sqlite3.c revision 322444
1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.20.0.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
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 embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25/************** Begin file ctime.c *******************************************/
26/*
27** 2010 February 23
28**
29** The author disclaims copyright to this source code.  In place of
30** a legal notice, here is a blessing:
31**
32**    May you do good and not evil.
33**    May you find forgiveness for yourself and forgive others.
34**    May you share freely, never taking more than you give.
35**
36*************************************************************************
37**
38** This file implements routines used to report what compile-time options
39** SQLite was built with.
40*/
41
42#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
43
44/*
45** Include the configuration header output by 'configure' if we're using the
46** autoconf-based build
47*/
48#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
49#include "config.h"
50#define SQLITECONFIG_H 1
51#endif
52
53/* These macros are provided to "stringify" the value of the define
54** for those options in which the value is meaningful. */
55#define CTIMEOPT_VAL_(opt) #opt
56#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
57
58/*
59** An array of names of all compile-time options.  This array should
60** be sorted A-Z.
61**
62** This array looks large, but in a typical installation actually uses
63** only a handful of compile-time options, so most times this array is usually
64** rather short and uses little memory space.
65*/
66static const char * const sqlite3azCompileOpt[] = {
67
68/*
69** BEGIN CODE GENERATED BY tool/mkctime.tcl
70*/
71#if SQLITE_32BIT_ROWID
72  "32BIT_ROWID",
73#endif
74#if SQLITE_4_BYTE_ALIGNED_MALLOC
75  "4_BYTE_ALIGNED_MALLOC",
76#endif
77#if SQLITE_64BIT_STATS
78  "64BIT_STATS",
79#endif
80#if SQLITE_ALLOW_COVERING_INDEX_SCAN
81  "ALLOW_COVERING_INDEX_SCAN",
82#endif
83#if SQLITE_ALLOW_URI_AUTHORITY
84  "ALLOW_URI_AUTHORITY",
85#endif
86#ifdef SQLITE_BITMASK_TYPE
87  "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
88#endif
89#if SQLITE_BUG_COMPATIBLE_20160819
90  "BUG_COMPATIBLE_20160819",
91#endif
92#if SQLITE_CASE_SENSITIVE_LIKE
93  "CASE_SENSITIVE_LIKE",
94#endif
95#if SQLITE_CHECK_PAGES
96  "CHECK_PAGES",
97#endif
98#if defined(__clang__) && defined(__clang_major__)
99  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
100                    CTIMEOPT_VAL(__clang_minor__) "."
101                    CTIMEOPT_VAL(__clang_patchlevel__),
102#elif defined(_MSC_VER)
103  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
104#elif defined(__GNUC__) && defined(__VERSION__)
105  "COMPILER=gcc-" __VERSION__,
106#endif
107#if SQLITE_COVERAGE_TEST
108  "COVERAGE_TEST",
109#endif
110#if SQLITE_DEBUG
111  "DEBUG",
112#endif
113#if SQLITE_DEFAULT_AUTOMATIC_INDEX
114  "DEFAULT_AUTOMATIC_INDEX",
115#endif
116#if SQLITE_DEFAULT_AUTOVACUUM
117  "DEFAULT_AUTOVACUUM",
118#endif
119#ifdef SQLITE_DEFAULT_CACHE_SIZE
120  "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
121#endif
122#if SQLITE_DEFAULT_CKPTFULLFSYNC
123  "DEFAULT_CKPTFULLFSYNC",
124#endif
125#ifdef SQLITE_DEFAULT_FILE_FORMAT
126  "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
127#endif
128#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
129  "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
130#endif
131#if SQLITE_DEFAULT_FOREIGN_KEYS
132  "DEFAULT_FOREIGN_KEYS",
133#endif
134#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
135  "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
136#endif
137#ifdef SQLITE_DEFAULT_LOCKING_MODE
138  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
139#endif
140#ifdef SQLITE_DEFAULT_LOOKASIDE
141  "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOOKASIDE),
142#endif
143#if SQLITE_DEFAULT_MEMSTATUS
144  "DEFAULT_MEMSTATUS",
145#endif
146#ifdef SQLITE_DEFAULT_MMAP_SIZE
147  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
148#endif
149#ifdef SQLITE_DEFAULT_PAGE_SIZE
150  "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
151#endif
152#ifdef SQLITE_DEFAULT_PCACHE_INITSZ
153  "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
154#endif
155#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
156  "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
157#endif
158#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
159  "DEFAULT_RECURSIVE_TRIGGERS",
160#endif
161#ifdef SQLITE_DEFAULT_ROWEST
162  "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
163#endif
164#ifdef SQLITE_DEFAULT_SECTOR_SIZE
165  "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
166#endif
167#ifdef SQLITE_DEFAULT_SYNCHRONOUS
168  "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
169#endif
170#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
171  "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
172#endif
173#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
174  "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
175#endif
176#ifdef SQLITE_DEFAULT_WORKER_THREADS
177  "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
178#endif
179#if SQLITE_DIRECT_OVERFLOW_READ
180  "DIRECT_OVERFLOW_READ",
181#endif
182#if SQLITE_DISABLE_DIRSYNC
183  "DISABLE_DIRSYNC",
184#endif
185#if SQLITE_DISABLE_FTS3_UNICODE
186  "DISABLE_FTS3_UNICODE",
187#endif
188#if SQLITE_DISABLE_FTS4_DEFERRED
189  "DISABLE_FTS4_DEFERRED",
190#endif
191#if SQLITE_DISABLE_INTRINSIC
192  "DISABLE_INTRINSIC",
193#endif
194#if SQLITE_DISABLE_LFS
195  "DISABLE_LFS",
196#endif
197#if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
198  "DISABLE_PAGECACHE_OVERFLOW_STATS",
199#endif
200#if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
201  "DISABLE_SKIPAHEAD_DISTINCT",
202#endif
203#ifdef SQLITE_ENABLE_8_3_NAMES
204  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
205#endif
206#if SQLITE_ENABLE_API_ARMOR
207  "ENABLE_API_ARMOR",
208#endif
209#if SQLITE_ENABLE_ATOMIC_WRITE
210  "ENABLE_ATOMIC_WRITE",
211#endif
212#if SQLITE_ENABLE_CEROD
213  "ENABLE_CEROD",
214#endif
215#if SQLITE_ENABLE_COLUMN_METADATA
216  "ENABLE_COLUMN_METADATA",
217#endif
218#if SQLITE_ENABLE_COLUMN_USED_MASK
219  "ENABLE_COLUMN_USED_MASK",
220#endif
221#if SQLITE_ENABLE_COSTMULT
222  "ENABLE_COSTMULT",
223#endif
224#if SQLITE_ENABLE_CURSOR_HINTS
225  "ENABLE_CURSOR_HINTS",
226#endif
227#if SQLITE_ENABLE_DBSTAT_VTAB
228  "ENABLE_DBSTAT_VTAB",
229#endif
230#if SQLITE_ENABLE_EXPENSIVE_ASSERT
231  "ENABLE_EXPENSIVE_ASSERT",
232#endif
233#if SQLITE_ENABLE_FTS1
234  "ENABLE_FTS1",
235#endif
236#if SQLITE_ENABLE_FTS2
237  "ENABLE_FTS2",
238#endif
239#if SQLITE_ENABLE_FTS3
240  "ENABLE_FTS3",
241#endif
242#if SQLITE_ENABLE_FTS3_PARENTHESIS
243  "ENABLE_FTS3_PARENTHESIS",
244#endif
245#if SQLITE_ENABLE_FTS3_TOKENIZER
246  "ENABLE_FTS3_TOKENIZER",
247#endif
248#if SQLITE_ENABLE_FTS4
249  "ENABLE_FTS4",
250#endif
251#if SQLITE_ENABLE_FTS5
252  "ENABLE_FTS5",
253#endif
254#if SQLITE_ENABLE_HIDDEN_COLUMNS
255  "ENABLE_HIDDEN_COLUMNS",
256#endif
257#if SQLITE_ENABLE_ICU
258  "ENABLE_ICU",
259#endif
260#if SQLITE_ENABLE_IOTRACE
261  "ENABLE_IOTRACE",
262#endif
263#if SQLITE_ENABLE_JSON1
264  "ENABLE_JSON1",
265#endif
266#if SQLITE_ENABLE_LOAD_EXTENSION
267  "ENABLE_LOAD_EXTENSION",
268#endif
269#ifdef SQLITE_ENABLE_LOCKING_STYLE
270  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
271#endif
272#if SQLITE_ENABLE_MEMORY_MANAGEMENT
273  "ENABLE_MEMORY_MANAGEMENT",
274#endif
275#if SQLITE_ENABLE_MEMSYS3
276  "ENABLE_MEMSYS3",
277#endif
278#if SQLITE_ENABLE_MEMSYS5
279  "ENABLE_MEMSYS5",
280#endif
281#if SQLITE_ENABLE_MULTIPLEX
282  "ENABLE_MULTIPLEX",
283#endif
284#if SQLITE_ENABLE_NULL_TRIM
285  "ENABLE_NULL_TRIM",
286#endif
287#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
288  "ENABLE_OVERSIZE_CELL_CHECK",
289#endif
290#if SQLITE_ENABLE_PREUPDATE_HOOK
291  "ENABLE_PREUPDATE_HOOK",
292#endif
293#if SQLITE_ENABLE_QPSG
294  "ENABLE_QPSG",
295#endif
296#if SQLITE_ENABLE_RBU
297  "ENABLE_RBU",
298#endif
299#if SQLITE_ENABLE_RTREE
300  "ENABLE_RTREE",
301#endif
302#if SQLITE_ENABLE_SELECTTRACE
303  "ENABLE_SELECTTRACE",
304#endif
305#if SQLITE_ENABLE_SESSION
306  "ENABLE_SESSION",
307#endif
308#if SQLITE_ENABLE_SNAPSHOT
309  "ENABLE_SNAPSHOT",
310#endif
311#if SQLITE_ENABLE_SQLLOG
312  "ENABLE_SQLLOG",
313#endif
314#if defined(SQLITE_ENABLE_STAT4)
315  "ENABLE_STAT4",
316#elif defined(SQLITE_ENABLE_STAT3)
317  "ENABLE_STAT3",
318#endif
319#if SQLITE_ENABLE_STMTVTAB
320  "ENABLE_STMTVTAB",
321#endif
322#if SQLITE_ENABLE_STMT_SCANSTATUS
323  "ENABLE_STMT_SCANSTATUS",
324#endif
325#if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
326  "ENABLE_UNKNOWN_SQL_FUNCTION",
327#endif
328#if SQLITE_ENABLE_UNLOCK_NOTIFY
329  "ENABLE_UNLOCK_NOTIFY",
330#endif
331#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
332  "ENABLE_UPDATE_DELETE_LIMIT",
333#endif
334#if SQLITE_ENABLE_URI_00_ERROR
335  "ENABLE_URI_00_ERROR",
336#endif
337#if SQLITE_ENABLE_VFSTRACE
338  "ENABLE_VFSTRACE",
339#endif
340#if SQLITE_ENABLE_WHERETRACE
341  "ENABLE_WHERETRACE",
342#endif
343#if SQLITE_ENABLE_ZIPVFS
344  "ENABLE_ZIPVFS",
345#endif
346#if SQLITE_EXPLAIN_ESTIMATED_ROWS
347  "EXPLAIN_ESTIMATED_ROWS",
348#endif
349#if SQLITE_EXTRA_IFNULLROW
350  "EXTRA_IFNULLROW",
351#endif
352#ifdef SQLITE_EXTRA_INIT
353  "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
354#endif
355#ifdef SQLITE_EXTRA_SHUTDOWN
356  "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
357#endif
358#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
359  "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
360#endif
361#if SQLITE_FTS5_ENABLE_TEST_MI
362  "FTS5_ENABLE_TEST_MI",
363#endif
364#if SQLITE_FTS5_NO_WITHOUT_ROWID
365  "FTS5_NO_WITHOUT_ROWID",
366#endif
367#if SQLITE_HAS_CODEC
368  "HAS_CODEC",
369#endif
370#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
371  "HAVE_ISNAN",
372#endif
373#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
374  "HOMEGROWN_RECURSIVE_MUTEX",
375#endif
376#if SQLITE_IGNORE_AFP_LOCK_ERRORS
377  "IGNORE_AFP_LOCK_ERRORS",
378#endif
379#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
380  "IGNORE_FLOCK_LOCK_ERRORS",
381#endif
382#if SQLITE_INLINE_MEMCPY
383  "INLINE_MEMCPY",
384#endif
385#if SQLITE_INT64_TYPE
386  "INT64_TYPE",
387#endif
388#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
389  "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
390#endif
391#if SQLITE_LIKE_DOESNT_MATCH_BLOBS
392  "LIKE_DOESNT_MATCH_BLOBS",
393#endif
394#if SQLITE_LOCK_TRACE
395  "LOCK_TRACE",
396#endif
397#if SQLITE_LOG_CACHE_SPILL
398  "LOG_CACHE_SPILL",
399#endif
400#ifdef SQLITE_MALLOC_SOFT_LIMIT
401  "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
402#endif
403#ifdef SQLITE_MAX_ATTACHED
404  "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
405#endif
406#ifdef SQLITE_MAX_COLUMN
407  "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
408#endif
409#ifdef SQLITE_MAX_COMPOUND_SELECT
410  "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
411#endif
412#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
413  "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
414#endif
415#ifdef SQLITE_MAX_EXPR_DEPTH
416  "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
417#endif
418#ifdef SQLITE_MAX_FUNCTION_ARG
419  "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
420#endif
421#ifdef SQLITE_MAX_LENGTH
422  "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
423#endif
424#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
425  "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
426#endif
427#ifdef SQLITE_MAX_MEMORY
428  "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
429#endif
430#ifdef SQLITE_MAX_MMAP_SIZE
431  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
432#endif
433#ifdef SQLITE_MAX_MMAP_SIZE_
434  "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
435#endif
436#ifdef SQLITE_MAX_PAGE_COUNT
437  "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
438#endif
439#ifdef SQLITE_MAX_PAGE_SIZE
440  "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
441#endif
442#ifdef SQLITE_MAX_SCHEMA_RETRY
443  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
444#endif
445#ifdef SQLITE_MAX_SQL_LENGTH
446  "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
447#endif
448#ifdef SQLITE_MAX_TRIGGER_DEPTH
449  "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
450#endif
451#ifdef SQLITE_MAX_VARIABLE_NUMBER
452  "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
453#endif
454#ifdef SQLITE_MAX_VDBE_OP
455  "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
456#endif
457#ifdef SQLITE_MAX_WORKER_THREADS
458  "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
459#endif
460#if SQLITE_MEMDEBUG
461  "MEMDEBUG",
462#endif
463#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
464  "MIXED_ENDIAN_64BIT_FLOAT",
465#endif
466#if SQLITE_MMAP_READWRITE
467  "MMAP_READWRITE",
468#endif
469#if SQLITE_MUTEX_NOOP
470  "MUTEX_NOOP",
471#endif
472#if SQLITE_MUTEX_NREF
473  "MUTEX_NREF",
474#endif
475#if SQLITE_MUTEX_OMIT
476  "MUTEX_OMIT",
477#endif
478#if SQLITE_MUTEX_PTHREADS
479  "MUTEX_PTHREADS",
480#endif
481#if SQLITE_MUTEX_W32
482  "MUTEX_W32",
483#endif
484#if SQLITE_NEED_ERR_NAME
485  "NEED_ERR_NAME",
486#endif
487#if SQLITE_NOINLINE
488  "NOINLINE",
489#endif
490#if SQLITE_NO_SYNC
491  "NO_SYNC",
492#endif
493#if SQLITE_OMIT_ALTERTABLE
494  "OMIT_ALTERTABLE",
495#endif
496#if SQLITE_OMIT_ANALYZE
497  "OMIT_ANALYZE",
498#endif
499#if SQLITE_OMIT_ATTACH
500  "OMIT_ATTACH",
501#endif
502#if SQLITE_OMIT_AUTHORIZATION
503  "OMIT_AUTHORIZATION",
504#endif
505#if SQLITE_OMIT_AUTOINCREMENT
506  "OMIT_AUTOINCREMENT",
507#endif
508#if SQLITE_OMIT_AUTOINIT
509  "OMIT_AUTOINIT",
510#endif
511#if SQLITE_OMIT_AUTOMATIC_INDEX
512  "OMIT_AUTOMATIC_INDEX",
513#endif
514#if SQLITE_OMIT_AUTORESET
515  "OMIT_AUTORESET",
516#endif
517#if SQLITE_OMIT_AUTOVACUUM
518  "OMIT_AUTOVACUUM",
519#endif
520#if SQLITE_OMIT_BETWEEN_OPTIMIZATION
521  "OMIT_BETWEEN_OPTIMIZATION",
522#endif
523#if SQLITE_OMIT_BLOB_LITERAL
524  "OMIT_BLOB_LITERAL",
525#endif
526#if SQLITE_OMIT_BTREECOUNT
527  "OMIT_BTREECOUNT",
528#endif
529#if SQLITE_OMIT_CAST
530  "OMIT_CAST",
531#endif
532#if SQLITE_OMIT_CHECK
533  "OMIT_CHECK",
534#endif
535#if SQLITE_OMIT_COMPLETE
536  "OMIT_COMPLETE",
537#endif
538#if SQLITE_OMIT_COMPOUND_SELECT
539  "OMIT_COMPOUND_SELECT",
540#endif
541#if SQLITE_OMIT_CONFLICT_CLAUSE
542  "OMIT_CONFLICT_CLAUSE",
543#endif
544#if SQLITE_OMIT_CTE
545  "OMIT_CTE",
546#endif
547#if SQLITE_OMIT_DATETIME_FUNCS
548  "OMIT_DATETIME_FUNCS",
549#endif
550#if SQLITE_OMIT_DECLTYPE
551  "OMIT_DECLTYPE",
552#endif
553#if SQLITE_OMIT_DEPRECATED
554  "OMIT_DEPRECATED",
555#endif
556#if SQLITE_OMIT_DISKIO
557  "OMIT_DISKIO",
558#endif
559#if SQLITE_OMIT_EXPLAIN
560  "OMIT_EXPLAIN",
561#endif
562#if SQLITE_OMIT_FLAG_PRAGMAS
563  "OMIT_FLAG_PRAGMAS",
564#endif
565#if SQLITE_OMIT_FLOATING_POINT
566  "OMIT_FLOATING_POINT",
567#endif
568#if SQLITE_OMIT_FOREIGN_KEY
569  "OMIT_FOREIGN_KEY",
570#endif
571#if SQLITE_OMIT_GET_TABLE
572  "OMIT_GET_TABLE",
573#endif
574#if SQLITE_OMIT_HEX_INTEGER
575  "OMIT_HEX_INTEGER",
576#endif
577#if SQLITE_OMIT_INCRBLOB
578  "OMIT_INCRBLOB",
579#endif
580#if SQLITE_OMIT_INTEGRITY_CHECK
581  "OMIT_INTEGRITY_CHECK",
582#endif
583#if SQLITE_OMIT_LIKE_OPTIMIZATION
584  "OMIT_LIKE_OPTIMIZATION",
585#endif
586#if SQLITE_OMIT_LOAD_EXTENSION
587  "OMIT_LOAD_EXTENSION",
588#endif
589#if SQLITE_OMIT_LOCALTIME
590  "OMIT_LOCALTIME",
591#endif
592#if SQLITE_OMIT_LOOKASIDE
593  "OMIT_LOOKASIDE",
594#endif
595#if SQLITE_OMIT_MEMORYDB
596  "OMIT_MEMORYDB",
597#endif
598#if SQLITE_OMIT_OR_OPTIMIZATION
599  "OMIT_OR_OPTIMIZATION",
600#endif
601#if SQLITE_OMIT_PAGER_PRAGMAS
602  "OMIT_PAGER_PRAGMAS",
603#endif
604#if SQLITE_OMIT_PARSER_TRACE
605  "OMIT_PARSER_TRACE",
606#endif
607#if SQLITE_OMIT_POPEN
608  "OMIT_POPEN",
609#endif
610#if SQLITE_OMIT_PRAGMA
611  "OMIT_PRAGMA",
612#endif
613#if SQLITE_OMIT_PROGRESS_CALLBACK
614  "OMIT_PROGRESS_CALLBACK",
615#endif
616#if SQLITE_OMIT_QUICKBALANCE
617  "OMIT_QUICKBALANCE",
618#endif
619#if SQLITE_OMIT_REINDEX
620  "OMIT_REINDEX",
621#endif
622#if SQLITE_OMIT_SCHEMA_PRAGMAS
623  "OMIT_SCHEMA_PRAGMAS",
624#endif
625#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
626  "OMIT_SCHEMA_VERSION_PRAGMAS",
627#endif
628#if SQLITE_OMIT_SHARED_CACHE
629  "OMIT_SHARED_CACHE",
630#endif
631#if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
632  "OMIT_SHUTDOWN_DIRECTORIES",
633#endif
634#if SQLITE_OMIT_SUBQUERY
635  "OMIT_SUBQUERY",
636#endif
637#if SQLITE_OMIT_TCL_VARIABLE
638  "OMIT_TCL_VARIABLE",
639#endif
640#if SQLITE_OMIT_TEMPDB
641  "OMIT_TEMPDB",
642#endif
643#if SQLITE_OMIT_TEST_CONTROL
644  "OMIT_TEST_CONTROL",
645#endif
646#if SQLITE_OMIT_TRACE
647  "OMIT_TRACE",
648#endif
649#if SQLITE_OMIT_TRIGGER
650  "OMIT_TRIGGER",
651#endif
652#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
653  "OMIT_TRUNCATE_OPTIMIZATION",
654#endif
655#if SQLITE_OMIT_UTF16
656  "OMIT_UTF16",
657#endif
658#if SQLITE_OMIT_VACUUM
659  "OMIT_VACUUM",
660#endif
661#if SQLITE_OMIT_VIEW
662  "OMIT_VIEW",
663#endif
664#if SQLITE_OMIT_VIRTUALTABLE
665  "OMIT_VIRTUALTABLE",
666#endif
667#if SQLITE_OMIT_WAL
668  "OMIT_WAL",
669#endif
670#if SQLITE_OMIT_WSD
671  "OMIT_WSD",
672#endif
673#if SQLITE_OMIT_XFER_OPT
674  "OMIT_XFER_OPT",
675#endif
676#if SQLITE_PCACHE_SEPARATE_HEADER
677  "PCACHE_SEPARATE_HEADER",
678#endif
679#if SQLITE_PERFORMANCE_TRACE
680  "PERFORMANCE_TRACE",
681#endif
682#if SQLITE_POWERSAFE_OVERWRITE
683  "POWERSAFE_OVERWRITE",
684#endif
685#if SQLITE_PREFER_PROXY_LOCKING
686  "PREFER_PROXY_LOCKING",
687#endif
688#if SQLITE_PROXY_DEBUG
689  "PROXY_DEBUG",
690#endif
691#if SQLITE_REVERSE_UNORDERED_SELECTS
692  "REVERSE_UNORDERED_SELECTS",
693#endif
694#if SQLITE_RTREE_INT_ONLY
695  "RTREE_INT_ONLY",
696#endif
697#if SQLITE_SECURE_DELETE
698  "SECURE_DELETE",
699#endif
700#if SQLITE_SMALL_STACK
701  "SMALL_STACK",
702#endif
703#ifdef SQLITE_SORTER_PMASZ
704  "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
705#endif
706#if SQLITE_SOUNDEX
707  "SOUNDEX",
708#endif
709#ifdef SQLITE_STAT4_SAMPLES
710  "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
711#endif
712#ifdef SQLITE_STMTJRNL_SPILL
713  "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
714#endif
715#if SQLITE_SUBSTR_COMPATIBILITY
716  "SUBSTR_COMPATIBILITY",
717#endif
718#if SQLITE_SYSTEM_MALLOC
719  "SYSTEM_MALLOC",
720#endif
721#if SQLITE_TCL
722  "TCL",
723#endif
724#ifdef SQLITE_TEMP_STORE
725  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
726#endif
727#if SQLITE_TEST
728  "TEST",
729#endif
730#if defined(SQLITE_THREADSAFE)
731  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
732#elif defined(THREADSAFE)
733  "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
734#else
735  "THREADSAFE=1",
736#endif
737#if SQLITE_UNLINK_AFTER_CLOSE
738  "UNLINK_AFTER_CLOSE",
739#endif
740#if SQLITE_UNTESTABLE
741  "UNTESTABLE",
742#endif
743#if SQLITE_USER_AUTHENTICATION
744  "USER_AUTHENTICATION",
745#endif
746#if SQLITE_USE_ALLOCA
747  "USE_ALLOCA",
748#endif
749#if SQLITE_USE_FCNTL_TRACE
750  "USE_FCNTL_TRACE",
751#endif
752#if SQLITE_USE_URI
753  "USE_URI",
754#endif
755#if SQLITE_VDBE_COVERAGE
756  "VDBE_COVERAGE",
757#endif
758#if SQLITE_WIN32_MALLOC
759  "WIN32_MALLOC",
760#endif
761#if SQLITE_ZERO_MALLOC
762  "ZERO_MALLOC",
763#endif
764/*
765** END CODE GENERATED BY tool/mkctime.tcl
766*/
767};
768
769SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
770  *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
771  return (const char**)sqlite3azCompileOpt;
772}
773
774#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
775
776/************** End of ctime.c ***********************************************/
777/************** Begin file sqliteInt.h ***************************************/
778/*
779** 2001 September 15
780**
781** The author disclaims copyright to this source code.  In place of
782** a legal notice, here is a blessing:
783**
784**    May you do good and not evil.
785**    May you find forgiveness for yourself and forgive others.
786**    May you share freely, never taking more than you give.
787**
788*************************************************************************
789** Internal interface definitions for SQLite.
790**
791*/
792#ifndef SQLITEINT_H
793#define SQLITEINT_H
794
795/* Special Comments:
796**
797** Some comments have special meaning to the tools that measure test
798** coverage:
799**
800**    NO_TEST                     - The branches on this line are not
801**                                  measured by branch coverage.  This is
802**                                  used on lines of code that actually
803**                                  implement parts of coverage testing.
804**
805**    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false
806**                                  and the correct answer is still obtained,
807**                                  though perhaps more slowly.
808**
809**    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true
810**                                  and the correct answer is still obtained,
811**                                  though perhaps more slowly.
812**
813**    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
814**                                  that would be harmless and undetectable
815**                                  if it did occur.
816**
817** In all cases, the special comment must be enclosed in the usual
818** slash-asterisk...asterisk-slash comment marks, with no spaces between the
819** asterisks and the comment text.
820*/
821
822/*
823** Make sure the Tcl calling convention macro is defined.  This macro is
824** only used by test code and Tcl integration code.
825*/
826#ifndef SQLITE_TCLAPI
827#  define SQLITE_TCLAPI
828#endif
829
830/*
831** Make sure that rand_s() is available on Windows systems with MSVC 2005
832** or higher.
833*/
834#if defined(_MSC_VER) && _MSC_VER>=1400
835#  define _CRT_RAND_S
836#endif
837
838/*
839** Include the header file used to customize the compiler options for MSVC.
840** This should be done first so that it can successfully prevent spurious
841** compiler warnings due to subsequent content in this file and other files
842** that are included by this file.
843*/
844/************** Include msvc.h in the middle of sqliteInt.h ******************/
845/************** Begin file msvc.h ********************************************/
846/*
847** 2015 January 12
848**
849** The author disclaims copyright to this source code.  In place of
850** a legal notice, here is a blessing:
851**
852**    May you do good and not evil.
853**    May you find forgiveness for yourself and forgive others.
854**    May you share freely, never taking more than you give.
855**
856******************************************************************************
857**
858** This file contains code that is specific to MSVC.
859*/
860#ifndef SQLITE_MSVC_H
861#define SQLITE_MSVC_H
862
863#if defined(_MSC_VER)
864#pragma warning(disable : 4054)
865#pragma warning(disable : 4055)
866#pragma warning(disable : 4100)
867#pragma warning(disable : 4127)
868#pragma warning(disable : 4130)
869#pragma warning(disable : 4152)
870#pragma warning(disable : 4189)
871#pragma warning(disable : 4206)
872#pragma warning(disable : 4210)
873#pragma warning(disable : 4232)
874#pragma warning(disable : 4244)
875#pragma warning(disable : 4305)
876#pragma warning(disable : 4306)
877#pragma warning(disable : 4702)
878#pragma warning(disable : 4706)
879#endif /* defined(_MSC_VER) */
880
881#endif /* SQLITE_MSVC_H */
882
883/************** End of msvc.h ************************************************/
884/************** Continuing where we left off in sqliteInt.h ******************/
885
886/*
887** Special setup for VxWorks
888*/
889/************** Include vxworks.h in the middle of sqliteInt.h ***************/
890/************** Begin file vxworks.h *****************************************/
891/*
892** 2015-03-02
893**
894** The author disclaims copyright to this source code.  In place of
895** a legal notice, here is a blessing:
896**
897**    May you do good and not evil.
898**    May you find forgiveness for yourself and forgive others.
899**    May you share freely, never taking more than you give.
900**
901******************************************************************************
902**
903** This file contains code that is specific to Wind River's VxWorks
904*/
905#if defined(__RTP__) || defined(_WRS_KERNEL)
906/* This is VxWorks.  Set up things specially for that OS
907*/
908#include <vxWorks.h>
909#include <pthread.h>  /* amalgamator: dontcache */
910#define OS_VXWORKS 1
911#define SQLITE_OS_OTHER 0
912#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
913#define SQLITE_OMIT_LOAD_EXTENSION 1
914#define SQLITE_ENABLE_LOCKING_STYLE 0
915#define HAVE_UTIME 1
916#else
917/* This is not VxWorks. */
918#define OS_VXWORKS 0
919#define HAVE_FCHOWN 1
920#define HAVE_READLINK 1
921#define HAVE_LSTAT 1
922#endif /* defined(_WRS_KERNEL) */
923
924/************** End of vxworks.h *********************************************/
925/************** Continuing where we left off in sqliteInt.h ******************/
926
927/*
928** These #defines should enable >2GB file support on POSIX if the
929** underlying operating system supports it.  If the OS lacks
930** large file support, or if the OS is windows, these should be no-ops.
931**
932** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
933** system #includes.  Hence, this block of code must be the very first
934** code in all source files.
935**
936** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
937** on the compiler command line.  This is necessary if you are compiling
938** on a recent machine (ex: Red Hat 7.2) but you want your code to work
939** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
940** without this option, LFS is enable.  But LFS does not exist in the kernel
941** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
942** portability you should omit LFS.
943**
944** The previous paragraph was written in 2005.  (This paragraph is written
945** on 2008-11-28.) These days, all Linux kernels support large files, so
946** you should probably leave LFS enabled.  But some embedded platforms might
947** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
948**
949** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
950*/
951#ifndef SQLITE_DISABLE_LFS
952# define _LARGE_FILE       1
953# ifndef _FILE_OFFSET_BITS
954#   define _FILE_OFFSET_BITS 64
955# endif
956# define _LARGEFILE_SOURCE 1
957#endif
958
959/* The GCC_VERSION and MSVC_VERSION macros are used to
960** conditionally include optimizations for each of these compilers.  A
961** value of 0 means that compiler is not being used.  The
962** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
963** optimizations, and hence set all compiler macros to 0
964**
965** There was once also a CLANG_VERSION macro.  However, we learn that the
966** version numbers in clang are for "marketing" only and are inconsistent
967** and unreliable.  Fortunately, all versions of clang also recognize the
968** gcc version numbers and have reasonable settings for gcc version numbers,
969** so the GCC_VERSION macro will be set to a correct non-zero value even
970** when compiling with clang.
971*/
972#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
973# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
974#else
975# define GCC_VERSION 0
976#endif
977#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
978# define MSVC_VERSION _MSC_VER
979#else
980# define MSVC_VERSION 0
981#endif
982
983/* Needed for various definitions... */
984#if defined(__GNUC__) && !defined(_GNU_SOURCE)
985# define _GNU_SOURCE
986#endif
987
988#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
989# define _BSD_SOURCE
990#endif
991
992/*
993** For MinGW, check to see if we can include the header file containing its
994** version information, among other things.  Normally, this internal MinGW
995** header file would [only] be included automatically by other MinGW header
996** files; however, the contained version information is now required by this
997** header file to work around binary compatibility issues (see below) and
998** this is the only known way to reliably obtain it.  This entire #if block
999** would be completely unnecessary if there was any other way of detecting
1000** MinGW via their preprocessor (e.g. if they customized their GCC to define
1001** some MinGW-specific macros).  When compiling for MinGW, either the
1002** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
1003** defined; otherwise, detection of conditions specific to MinGW will be
1004** disabled.
1005*/
1006#if defined(_HAVE_MINGW_H)
1007# include "mingw.h"
1008#elif defined(_HAVE__MINGW_H)
1009# include "_mingw.h"
1010#endif
1011
1012/*
1013** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
1014** define is required to maintain binary compatibility with the MSVC runtime
1015** library in use (e.g. for Windows XP).
1016*/
1017#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
1018    defined(_WIN32) && !defined(_WIN64) && \
1019    defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
1020    defined(__MSVCRT__)
1021# define _USE_32BIT_TIME_T
1022#endif
1023
1024/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
1025** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
1026** MinGW.
1027*/
1028/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
1029/************** Begin file sqlite3.h *****************************************/
1030/*
1031** 2001-09-15
1032**
1033** The author disclaims copyright to this source code.  In place of
1034** a legal notice, here is a blessing:
1035**
1036**    May you do good and not evil.
1037**    May you find forgiveness for yourself and forgive others.
1038**    May you share freely, never taking more than you give.
1039**
1040*************************************************************************
1041** This header file defines the interface that the SQLite library
1042** presents to client programs.  If a C-function, structure, datatype,
1043** or constant definition does not appear in this file, then it is
1044** not a published API of SQLite, is subject to change without
1045** notice, and should not be referenced by programs that use SQLite.
1046**
1047** Some of the definitions that are in this file are marked as
1048** "experimental".  Experimental interfaces are normally new
1049** features recently added to SQLite.  We do not anticipate changes
1050** to experimental interfaces but reserve the right to make minor changes
1051** if experience from use "in the wild" suggest such changes are prudent.
1052**
1053** The official C-language API documentation for SQLite is derived
1054** from comments in this file.  This file is the authoritative source
1055** on how SQLite interfaces are supposed to operate.
1056**
1057** The name of this file under configuration management is "sqlite.h.in".
1058** The makefile makes some minor changes to this file (such as inserting
1059** the version number) and changes its name to "sqlite3.h" as
1060** part of the build process.
1061*/
1062#ifndef SQLITE3_H
1063#define SQLITE3_H
1064#include <stdarg.h>     /* Needed for the definition of va_list */
1065
1066/*
1067** Make sure we can call this stuff from C++.
1068*/
1069#if 0
1070extern "C" {
1071#endif
1072
1073
1074/*
1075** Provide the ability to override linkage features of the interface.
1076*/
1077#ifndef SQLITE_EXTERN
1078# define SQLITE_EXTERN extern
1079#endif
1080#ifndef SQLITE_API
1081# define SQLITE_API
1082#endif
1083#ifndef SQLITE_CDECL
1084# define SQLITE_CDECL
1085#endif
1086#ifndef SQLITE_APICALL
1087# define SQLITE_APICALL
1088#endif
1089#ifndef SQLITE_STDCALL
1090# define SQLITE_STDCALL SQLITE_APICALL
1091#endif
1092#ifndef SQLITE_CALLBACK
1093# define SQLITE_CALLBACK
1094#endif
1095#ifndef SQLITE_SYSAPI
1096# define SQLITE_SYSAPI
1097#endif
1098
1099/*
1100** These no-op macros are used in front of interfaces to mark those
1101** interfaces as either deprecated or experimental.  New applications
1102** should not use deprecated interfaces - they are supported for backwards
1103** compatibility only.  Application writers should be aware that
1104** experimental interfaces are subject to change in point releases.
1105**
1106** These macros used to resolve to various kinds of compiler magic that
1107** would generate warning messages when they were used.  But that
1108** compiler magic ended up generating such a flurry of bug reports
1109** that we have taken it all out and gone back to using simple
1110** noop macros.
1111*/
1112#define SQLITE_DEPRECATED
1113#define SQLITE_EXPERIMENTAL
1114
1115/*
1116** Ensure these symbols were not defined by some previous header file.
1117*/
1118#ifdef SQLITE_VERSION
1119# undef SQLITE_VERSION
1120#endif
1121#ifdef SQLITE_VERSION_NUMBER
1122# undef SQLITE_VERSION_NUMBER
1123#endif
1124
1125/*
1126** CAPI3REF: Compile-Time Library Version Numbers
1127**
1128** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
1129** evaluates to a string literal that is the SQLite version in the
1130** format "X.Y.Z" where X is the major version number (always 3 for
1131** SQLite3) and Y is the minor version number and Z is the release number.)^
1132** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
1133** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
1134** numbers used in [SQLITE_VERSION].)^
1135** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
1136** be larger than the release from which it is derived.  Either Y will
1137** be held constant and Z will be incremented or else Y will be incremented
1138** and Z will be reset to zero.
1139**
1140** Since [version 3.6.18] ([dateof:3.6.18]),
1141** SQLite source code has been stored in the
1142** <a href="http://www.fossil-scm.org/">Fossil configuration management
1143** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
1144** a string which identifies a particular check-in of SQLite
1145** within its configuration management system.  ^The SQLITE_SOURCE_ID
1146** string contains the date and time of the check-in (UTC) and a SHA1
1147** or SHA3-256 hash of the entire source tree.
1148**
1149** See also: [sqlite3_libversion()],
1150** [sqlite3_libversion_number()], [sqlite3_sourceid()],
1151** [sqlite_version()] and [sqlite_source_id()].
1152*/
1153#define SQLITE_VERSION        "3.20.0"
1154#define SQLITE_VERSION_NUMBER 3020000
1155#define SQLITE_SOURCE_ID      "2017-08-01 13:24:15 9501e22dfeebdcefa783575e47c60b514d7c2e0cad73b2a496c0bc4b680900a8"
1156
1157/*
1158** CAPI3REF: Run-Time Library Version Numbers
1159** KEYWORDS: sqlite3_version sqlite3_sourceid
1160**
1161** These interfaces provide the same information as the [SQLITE_VERSION],
1162** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
1163** but are associated with the library instead of the header file.  ^(Cautious
1164** programmers might include assert() statements in their application to
1165** verify that values returned by these interfaces match the macros in
1166** the header, and thus ensure that the application is
1167** compiled with matching library and header files.
1168**
1169** <blockquote><pre>
1170** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
1171** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
1172** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
1173** </pre></blockquote>)^
1174**
1175** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
1176** macro.  ^The sqlite3_libversion() function returns a pointer to the
1177** to the sqlite3_version[] string constant.  The sqlite3_libversion()
1178** function is provided for use in DLLs since DLL users usually do not have
1179** direct access to string constants within the DLL.  ^The
1180** sqlite3_libversion_number() function returns an integer equal to
1181** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
1182** a pointer to a string constant whose value is the same as the
1183** [SQLITE_SOURCE_ID] C preprocessor macro.
1184**
1185** See also: [sqlite_version()] and [sqlite_source_id()].
1186*/
1187SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
1188SQLITE_API const char *sqlite3_libversion(void);
1189SQLITE_API const char *sqlite3_sourceid(void);
1190SQLITE_API int sqlite3_libversion_number(void);
1191
1192/*
1193** CAPI3REF: Run-Time Library Compilation Options Diagnostics
1194**
1195** ^The sqlite3_compileoption_used() function returns 0 or 1
1196** indicating whether the specified option was defined at
1197** compile time.  ^The SQLITE_ prefix may be omitted from the
1198** option name passed to sqlite3_compileoption_used().
1199**
1200** ^The sqlite3_compileoption_get() function allows iterating
1201** over the list of options that were defined at compile time by
1202** returning the N-th compile time option string.  ^If N is out of range,
1203** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
1204** prefix is omitted from any strings returned by
1205** sqlite3_compileoption_get().
1206**
1207** ^Support for the diagnostic functions sqlite3_compileoption_used()
1208** and sqlite3_compileoption_get() may be omitted by specifying the
1209** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
1210**
1211** See also: SQL functions [sqlite_compileoption_used()] and
1212** [sqlite_compileoption_get()] and the [compile_options pragma].
1213*/
1214#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1215SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
1216SQLITE_API const char *sqlite3_compileoption_get(int N);
1217#endif
1218
1219/*
1220** CAPI3REF: Test To See If The Library Is Threadsafe
1221**
1222** ^The sqlite3_threadsafe() function returns zero if and only if
1223** SQLite was compiled with mutexing code omitted due to the
1224** [SQLITE_THREADSAFE] compile-time option being set to 0.
1225**
1226** SQLite can be compiled with or without mutexes.  When
1227** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
1228** are enabled and SQLite is threadsafe.  When the
1229** [SQLITE_THREADSAFE] macro is 0,
1230** the mutexes are omitted.  Without the mutexes, it is not safe
1231** to use SQLite concurrently from more than one thread.
1232**
1233** Enabling mutexes incurs a measurable performance penalty.
1234** So if speed is of utmost importance, it makes sense to disable
1235** the mutexes.  But for maximum safety, mutexes should be enabled.
1236** ^The default behavior is for mutexes to be enabled.
1237**
1238** This interface can be used by an application to make sure that the
1239** version of SQLite that it is linking against was compiled with
1240** the desired setting of the [SQLITE_THREADSAFE] macro.
1241**
1242** This interface only reports on the compile-time mutex setting
1243** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
1244** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
1245** can be fully or partially disabled using a call to [sqlite3_config()]
1246** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
1247** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
1248** sqlite3_threadsafe() function shows only the compile-time setting of
1249** thread safety, not any run-time changes to that setting made by
1250** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
1251** is unchanged by calls to sqlite3_config().)^
1252**
1253** See the [threading mode] documentation for additional information.
1254*/
1255SQLITE_API int sqlite3_threadsafe(void);
1256
1257/*
1258** CAPI3REF: Database Connection Handle
1259** KEYWORDS: {database connection} {database connections}
1260**
1261** Each open SQLite database is represented by a pointer to an instance of
1262** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
1263** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
1264** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
1265** and [sqlite3_close_v2()] are its destructors.  There are many other
1266** interfaces (such as
1267** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
1268** [sqlite3_busy_timeout()] to name but three) that are methods on an
1269** sqlite3 object.
1270*/
1271typedef struct sqlite3 sqlite3;
1272
1273/*
1274** CAPI3REF: 64-Bit Integer Types
1275** KEYWORDS: sqlite_int64 sqlite_uint64
1276**
1277** Because there is no cross-platform way to specify 64-bit integer types
1278** SQLite includes typedefs for 64-bit signed and unsigned integers.
1279**
1280** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
1281** The sqlite_int64 and sqlite_uint64 types are supported for backwards
1282** compatibility only.
1283**
1284** ^The sqlite3_int64 and sqlite_int64 types can store integer values
1285** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
1286** sqlite3_uint64 and sqlite_uint64 types can store integer values
1287** between 0 and +18446744073709551615 inclusive.
1288*/
1289#ifdef SQLITE_INT64_TYPE
1290  typedef SQLITE_INT64_TYPE sqlite_int64;
1291# ifdef SQLITE_UINT64_TYPE
1292    typedef SQLITE_UINT64_TYPE sqlite_uint64;
1293# else
1294    typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
1295# endif
1296#elif defined(_MSC_VER) || defined(__BORLANDC__)
1297  typedef __int64 sqlite_int64;
1298  typedef unsigned __int64 sqlite_uint64;
1299#else
1300  typedef long long int sqlite_int64;
1301  typedef unsigned long long int sqlite_uint64;
1302#endif
1303typedef sqlite_int64 sqlite3_int64;
1304typedef sqlite_uint64 sqlite3_uint64;
1305
1306/*
1307** If compiling for a processor that lacks floating point support,
1308** substitute integer for floating-point.
1309*/
1310#ifdef SQLITE_OMIT_FLOATING_POINT
1311# define double sqlite3_int64
1312#endif
1313
1314/*
1315** CAPI3REF: Closing A Database Connection
1316** DESTRUCTOR: sqlite3
1317**
1318** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
1319** for the [sqlite3] object.
1320** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
1321** the [sqlite3] object is successfully destroyed and all associated
1322** resources are deallocated.
1323**
1324** ^If the database connection is associated with unfinalized prepared
1325** statements or unfinished sqlite3_backup objects then sqlite3_close()
1326** will leave the database connection open and return [SQLITE_BUSY].
1327** ^If sqlite3_close_v2() is called with unfinalized prepared statements
1328** and/or unfinished sqlite3_backups, then the database connection becomes
1329** an unusable "zombie" which will automatically be deallocated when the
1330** last prepared statement is finalized or the last sqlite3_backup is
1331** finished.  The sqlite3_close_v2() interface is intended for use with
1332** host languages that are garbage collected, and where the order in which
1333** destructors are called is arbitrary.
1334**
1335** Applications should [sqlite3_finalize | finalize] all [prepared statements],
1336** [sqlite3_blob_close | close] all [BLOB handles], and
1337** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
1338** with the [sqlite3] object prior to attempting to close the object.  ^If
1339** sqlite3_close_v2() is called on a [database connection] that still has
1340** outstanding [prepared statements], [BLOB handles], and/or
1341** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
1342** of resources is deferred until all [prepared statements], [BLOB handles],
1343** and [sqlite3_backup] objects are also destroyed.
1344**
1345** ^If an [sqlite3] object is destroyed while a transaction is open,
1346** the transaction is automatically rolled back.
1347**
1348** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
1349** must be either a NULL
1350** pointer or an [sqlite3] object pointer obtained
1351** from [sqlite3_open()], [sqlite3_open16()], or
1352** [sqlite3_open_v2()], and not previously closed.
1353** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
1354** argument is a harmless no-op.
1355*/
1356SQLITE_API int sqlite3_close(sqlite3*);
1357SQLITE_API int sqlite3_close_v2(sqlite3*);
1358
1359/*
1360** The type for a callback function.
1361** This is legacy and deprecated.  It is included for historical
1362** compatibility and is not documented.
1363*/
1364typedef int (*sqlite3_callback)(void*,int,char**, char**);
1365
1366/*
1367** CAPI3REF: One-Step Query Execution Interface
1368** METHOD: sqlite3
1369**
1370** The sqlite3_exec() interface is a convenience wrapper around
1371** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
1372** that allows an application to run multiple statements of SQL
1373** without having to use a lot of C code.
1374**
1375** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
1376** semicolon-separate SQL statements passed into its 2nd argument,
1377** in the context of the [database connection] passed in as its 1st
1378** argument.  ^If the callback function of the 3rd argument to
1379** sqlite3_exec() is not NULL, then it is invoked for each result row
1380** coming out of the evaluated SQL statements.  ^The 4th argument to
1381** sqlite3_exec() is relayed through to the 1st argument of each
1382** callback invocation.  ^If the callback pointer to sqlite3_exec()
1383** is NULL, then no callback is ever invoked and result rows are
1384** ignored.
1385**
1386** ^If an error occurs while evaluating the SQL statements passed into
1387** sqlite3_exec(), then execution of the current statement stops and
1388** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
1389** is not NULL then any error message is written into memory obtained
1390** from [sqlite3_malloc()] and passed back through the 5th parameter.
1391** To avoid memory leaks, the application should invoke [sqlite3_free()]
1392** on error message strings returned through the 5th parameter of
1393** sqlite3_exec() after the error message string is no longer needed.
1394** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
1395** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
1396** NULL before returning.
1397**
1398** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
1399** routine returns SQLITE_ABORT without invoking the callback again and
1400** without running any subsequent SQL statements.
1401**
1402** ^The 2nd argument to the sqlite3_exec() callback function is the
1403** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
1404** callback is an array of pointers to strings obtained as if from
1405** [sqlite3_column_text()], one for each column.  ^If an element of a
1406** result row is NULL then the corresponding string pointer for the
1407** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
1408** sqlite3_exec() callback is an array of pointers to strings where each
1409** entry represents the name of corresponding result column as obtained
1410** from [sqlite3_column_name()].
1411**
1412** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
1413** to an empty string, or a pointer that contains only whitespace and/or
1414** SQL comments, then no SQL statements are evaluated and the database
1415** is not changed.
1416**
1417** Restrictions:
1418**
1419** <ul>
1420** <li> The application must ensure that the 1st parameter to sqlite3_exec()
1421**      is a valid and open [database connection].
1422** <li> The application must not close the [database connection] specified by
1423**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
1424** <li> The application must not modify the SQL statement text passed into
1425**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
1426** </ul>
1427*/
1428SQLITE_API int sqlite3_exec(
1429  sqlite3*,                                  /* An open database */
1430  const char *sql,                           /* SQL to be evaluated */
1431  int (*callback)(void*,int,char**,char**),  /* Callback function */
1432  void *,                                    /* 1st argument to callback */
1433  char **errmsg                              /* Error msg written here */
1434);
1435
1436/*
1437** CAPI3REF: Result Codes
1438** KEYWORDS: {result code definitions}
1439**
1440** Many SQLite functions return an integer result code from the set shown
1441** here in order to indicate success or failure.
1442**
1443** New error codes may be added in future versions of SQLite.
1444**
1445** See also: [extended result code definitions]
1446*/
1447#define SQLITE_OK           0   /* Successful result */
1448/* beginning-of-error-codes */
1449#define SQLITE_ERROR        1   /* Generic error */
1450#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
1451#define SQLITE_PERM         3   /* Access permission denied */
1452#define SQLITE_ABORT        4   /* Callback routine requested an abort */
1453#define SQLITE_BUSY         5   /* The database file is locked */
1454#define SQLITE_LOCKED       6   /* A table in the database is locked */
1455#define SQLITE_NOMEM        7   /* A malloc() failed */
1456#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
1457#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
1458#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
1459#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
1460#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
1461#define SQLITE_FULL        13   /* Insertion failed because database is full */
1462#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
1463#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
1464#define SQLITE_EMPTY       16   /* Not used */
1465#define SQLITE_SCHEMA      17   /* The database schema changed */
1466#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
1467#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
1468#define SQLITE_MISMATCH    20   /* Data type mismatch */
1469#define SQLITE_MISUSE      21   /* Library used incorrectly */
1470#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
1471#define SQLITE_AUTH        23   /* Authorization denied */
1472#define SQLITE_FORMAT      24   /* Not used */
1473#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
1474#define SQLITE_NOTADB      26   /* File opened that is not a database file */
1475#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
1476#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
1477#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
1478#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
1479/* end-of-error-codes */
1480
1481/*
1482** CAPI3REF: Extended Result Codes
1483** KEYWORDS: {extended result code definitions}
1484**
1485** In its default configuration, SQLite API routines return one of 30 integer
1486** [result codes].  However, experience has shown that many of
1487** these result codes are too coarse-grained.  They do not provide as
1488** much information about problems as programmers might like.  In an effort to
1489** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
1490** and later) include
1491** support for additional result codes that provide more detailed information
1492** about errors. These [extended result codes] are enabled or disabled
1493** on a per database connection basis using the
1494** [sqlite3_extended_result_codes()] API.  Or, the extended code for
1495** the most recent error can be obtained using
1496** [sqlite3_extended_errcode()].
1497*/
1498#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
1499#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
1500#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
1501#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
1502#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
1503#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
1504#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1505#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1506#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1507#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1508#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1509#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1510#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1511#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1512#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1513#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1514#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1515#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1516#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1517#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1518#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1519#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1520#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
1521#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
1522#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
1523#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
1524#define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
1525#define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
1526#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1527#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1528#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
1529#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1530#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
1531#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
1532#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
1533#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1534#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1535#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1536#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
1537#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
1538#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1539#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
1540#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
1541#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
1542#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
1543#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
1544#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
1545#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
1546#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
1547#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
1548#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
1549#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
1550#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
1551#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
1552#define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
1553#define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
1554
1555/*
1556** CAPI3REF: Flags For File Open Operations
1557**
1558** These bit values are intended for use in the
1559** 3rd parameter to the [sqlite3_open_v2()] interface and
1560** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1561*/
1562#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1563#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1564#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1565#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1566#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1567#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1568#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1569#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
1570#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1571#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1572#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1573#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1574#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1575#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1576#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1577#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1578#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1579#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1580#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1581#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1582
1583/* Reserved:                         0x00F00000 */
1584
1585/*
1586** CAPI3REF: Device Characteristics
1587**
1588** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1589** object returns an integer which is a vector of these
1590** bit values expressing I/O characteristics of the mass storage
1591** device that holds the file that the [sqlite3_io_methods]
1592** refers to.
1593**
1594** The SQLITE_IOCAP_ATOMIC property means that all writes of
1595** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1596** mean that writes of blocks that are nnn bytes in size and
1597** are aligned to an address which is an integer multiple of
1598** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1599** that when data is appended to a file, the data is appended
1600** first then the size of the file is extended, never the other
1601** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1602** information is written to disk in the same order as calls
1603** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1604** after reboot following a crash or power loss, the only bytes in a
1605** file that were written at the application level might have changed
1606** and that adjacent bytes, even bytes within the same sector are
1607** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
1608** flag indicates that a file cannot be deleted when open.  The
1609** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
1610** read-only media and cannot be changed even by processes with
1611** elevated privileges.
1612*/
1613#define SQLITE_IOCAP_ATOMIC                 0x00000001
1614#define SQLITE_IOCAP_ATOMIC512              0x00000002
1615#define SQLITE_IOCAP_ATOMIC1K               0x00000004
1616#define SQLITE_IOCAP_ATOMIC2K               0x00000008
1617#define SQLITE_IOCAP_ATOMIC4K               0x00000010
1618#define SQLITE_IOCAP_ATOMIC8K               0x00000020
1619#define SQLITE_IOCAP_ATOMIC16K              0x00000040
1620#define SQLITE_IOCAP_ATOMIC32K              0x00000080
1621#define SQLITE_IOCAP_ATOMIC64K              0x00000100
1622#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1623#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1624#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1625#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1626#define SQLITE_IOCAP_IMMUTABLE              0x00002000
1627
1628/*
1629** CAPI3REF: File Locking Levels
1630**
1631** SQLite uses one of these integer values as the second
1632** argument to calls it makes to the xLock() and xUnlock() methods
1633** of an [sqlite3_io_methods] object.
1634*/
1635#define SQLITE_LOCK_NONE          0
1636#define SQLITE_LOCK_SHARED        1
1637#define SQLITE_LOCK_RESERVED      2
1638#define SQLITE_LOCK_PENDING       3
1639#define SQLITE_LOCK_EXCLUSIVE     4
1640
1641/*
1642** CAPI3REF: Synchronization Type Flags
1643**
1644** When SQLite invokes the xSync() method of an
1645** [sqlite3_io_methods] object it uses a combination of
1646** these integer values as the second argument.
1647**
1648** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1649** sync operation only needs to flush data to mass storage.  Inode
1650** information need not be flushed. If the lower four bits of the flag
1651** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1652** If the lower four bits equal SQLITE_SYNC_FULL, that means
1653** to use Mac OS X style fullsync instead of fsync().
1654**
1655** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1656** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1657** settings.  The [synchronous pragma] determines when calls to the
1658** xSync VFS method occur and applies uniformly across all platforms.
1659** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1660** energetic or rigorous or forceful the sync operations are and
1661** only make a difference on Mac OSX for the default SQLite code.
1662** (Third-party VFS implementations might also make the distinction
1663** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1664** operating systems natively supported by SQLite, only Mac OSX
1665** cares about the difference.)
1666*/
1667#define SQLITE_SYNC_NORMAL        0x00002
1668#define SQLITE_SYNC_FULL          0x00003
1669#define SQLITE_SYNC_DATAONLY      0x00010
1670
1671/*
1672** CAPI3REF: OS Interface Open File Handle
1673**
1674** An [sqlite3_file] object represents an open file in the
1675** [sqlite3_vfs | OS interface layer].  Individual OS interface
1676** implementations will
1677** want to subclass this object by appending additional fields
1678** for their own use.  The pMethods entry is a pointer to an
1679** [sqlite3_io_methods] object that defines methods for performing
1680** I/O operations on the open file.
1681*/
1682typedef struct sqlite3_file sqlite3_file;
1683struct sqlite3_file {
1684  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1685};
1686
1687/*
1688** CAPI3REF: OS Interface File Virtual Methods Object
1689**
1690** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1691** [sqlite3_file] object (or, more commonly, a subclass of the
1692** [sqlite3_file] object) with a pointer to an instance of this object.
1693** This object defines the methods used to perform various operations
1694** against the open file represented by the [sqlite3_file] object.
1695**
1696** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1697** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1698** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1699** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1700** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1701** to NULL.
1702**
1703** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1704** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1705** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1706** flag may be ORed in to indicate that only the data of the file
1707** and not its inode needs to be synced.
1708**
1709** The integer values to xLock() and xUnlock() are one of
1710** <ul>
1711** <li> [SQLITE_LOCK_NONE],
1712** <li> [SQLITE_LOCK_SHARED],
1713** <li> [SQLITE_LOCK_RESERVED],
1714** <li> [SQLITE_LOCK_PENDING], or
1715** <li> [SQLITE_LOCK_EXCLUSIVE].
1716** </ul>
1717** xLock() increases the lock. xUnlock() decreases the lock.
1718** The xCheckReservedLock() method checks whether any database connection,
1719** either in this process or in some other process, is holding a RESERVED,
1720** PENDING, or EXCLUSIVE lock on the file.  It returns true
1721** if such a lock exists and false otherwise.
1722**
1723** The xFileControl() method is a generic interface that allows custom
1724** VFS implementations to directly control an open file using the
1725** [sqlite3_file_control()] interface.  The second "op" argument is an
1726** integer opcode.  The third argument is a generic pointer intended to
1727** point to a structure that may contain arguments or space in which to
1728** write return values.  Potential uses for xFileControl() might be
1729** functions to enable blocking locks with timeouts, to change the
1730** locking strategy (for example to use dot-file locks), to inquire
1731** about the status of a lock, or to break stale locks.  The SQLite
1732** core reserves all opcodes less than 100 for its own use.
1733** A [file control opcodes | list of opcodes] less than 100 is available.
1734** Applications that define a custom xFileControl method should use opcodes
1735** greater than 100 to avoid conflicts.  VFS implementations should
1736** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1737** recognize.
1738**
1739** The xSectorSize() method returns the sector size of the
1740** device that underlies the file.  The sector size is the
1741** minimum write that can be performed without disturbing
1742** other bytes in the file.  The xDeviceCharacteristics()
1743** method returns a bit vector describing behaviors of the
1744** underlying device:
1745**
1746** <ul>
1747** <li> [SQLITE_IOCAP_ATOMIC]
1748** <li> [SQLITE_IOCAP_ATOMIC512]
1749** <li> [SQLITE_IOCAP_ATOMIC1K]
1750** <li> [SQLITE_IOCAP_ATOMIC2K]
1751** <li> [SQLITE_IOCAP_ATOMIC4K]
1752** <li> [SQLITE_IOCAP_ATOMIC8K]
1753** <li> [SQLITE_IOCAP_ATOMIC16K]
1754** <li> [SQLITE_IOCAP_ATOMIC32K]
1755** <li> [SQLITE_IOCAP_ATOMIC64K]
1756** <li> [SQLITE_IOCAP_SAFE_APPEND]
1757** <li> [SQLITE_IOCAP_SEQUENTIAL]
1758** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
1759** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
1760** <li> [SQLITE_IOCAP_IMMUTABLE]
1761** </ul>
1762**
1763** The SQLITE_IOCAP_ATOMIC property means that all writes of
1764** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1765** mean that writes of blocks that are nnn bytes in size and
1766** are aligned to an address which is an integer multiple of
1767** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1768** that when data is appended to a file, the data is appended
1769** first then the size of the file is extended, never the other
1770** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1771** information is written to disk in the same order as calls
1772** to xWrite().
1773**
1774** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1775** in the unread portions of the buffer with zeros.  A VFS that
1776** fails to zero-fill short reads might seem to work.  However,
1777** failure to zero-fill short reads will eventually lead to
1778** database corruption.
1779*/
1780typedef struct sqlite3_io_methods sqlite3_io_methods;
1781struct sqlite3_io_methods {
1782  int iVersion;
1783  int (*xClose)(sqlite3_file*);
1784  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1785  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1786  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1787  int (*xSync)(sqlite3_file*, int flags);
1788  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1789  int (*xLock)(sqlite3_file*, int);
1790  int (*xUnlock)(sqlite3_file*, int);
1791  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1792  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1793  int (*xSectorSize)(sqlite3_file*);
1794  int (*xDeviceCharacteristics)(sqlite3_file*);
1795  /* Methods above are valid for version 1 */
1796  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1797  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1798  void (*xShmBarrier)(sqlite3_file*);
1799  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1800  /* Methods above are valid for version 2 */
1801  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1802  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1803  /* Methods above are valid for version 3 */
1804  /* Additional methods may be added in future releases */
1805};
1806
1807/*
1808** CAPI3REF: Standard File Control Opcodes
1809** KEYWORDS: {file control opcodes} {file control opcode}
1810**
1811** These integer constants are opcodes for the xFileControl method
1812** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1813** interface.
1814**
1815** <ul>
1816** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1817** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1818** opcode causes the xFileControl method to write the current state of
1819** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1820** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1821** into an integer that the pArg argument points to. This capability
1822** is used during testing and is only available when the SQLITE_TEST
1823** compile-time option is used.
1824**
1825** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1826** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1827** layer a hint of how large the database file will grow to be during the
1828** current transaction.  This hint is not guaranteed to be accurate but it
1829** is often close.  The underlying VFS might choose to preallocate database
1830** file space based on this hint in order to help writes to the database
1831** file run faster.
1832**
1833** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1834** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1835** extends and truncates the database file in chunks of a size specified
1836** by the user. The fourth argument to [sqlite3_file_control()] should
1837** point to an integer (type int) containing the new chunk-size to use
1838** for the nominated database. Allocating database file space in large
1839** chunks (say 1MB at a time), may reduce file-system fragmentation and
1840** improve performance on some systems.
1841**
1842** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1843** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1844** to the [sqlite3_file] object associated with a particular database
1845** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].
1846**
1847** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1848** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1849** to the [sqlite3_file] object associated with the journal file (either
1850** the [rollback journal] or the [write-ahead log]) for a particular database
1851** connection.  See also [SQLITE_FCNTL_FILE_POINTER].
1852**
1853** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1854** No longer in use.
1855**
1856** <li>[[SQLITE_FCNTL_SYNC]]
1857** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1858** sent to the VFS immediately before the xSync method is invoked on a
1859** database file descriptor. Or, if the xSync method is not invoked
1860** because the user has configured SQLite with
1861** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1862** of the xSync method. In most cases, the pointer argument passed with
1863** this file-control is NULL. However, if the database file is being synced
1864** as part of a multi-database commit, the argument points to a nul-terminated
1865** string containing the transactions master-journal file name. VFSes that
1866** do not need this signal should silently ignore this opcode. Applications
1867** should not call [sqlite3_file_control()] with this opcode as doing so may
1868** disrupt the operation of the specialized VFSes that do require it.
1869**
1870** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1871** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1872** and sent to the VFS after a transaction has been committed immediately
1873** but before the database is unlocked. VFSes that do not need this signal
1874** should silently ignore this opcode. Applications should not call
1875** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1876** operation of the specialized VFSes that do require it.
1877**
1878** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1879** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1880** retry counts and intervals for certain disk I/O operations for the
1881** windows [VFS] in order to provide robustness in the presence of
1882** anti-virus programs.  By default, the windows VFS will retry file read,
1883** file write, and file delete operations up to 10 times, with a delay
1884** of 25 milliseconds before the first retry and with the delay increasing
1885** by an additional 25 milliseconds with each subsequent retry.  This
1886** opcode allows these two values (10 retries and 25 milliseconds of delay)
1887** to be adjusted.  The values are changed for all database connections
1888** within the same process.  The argument is a pointer to an array of two
1889** integers where the first integer is the new retry count and the second
1890** integer is the delay.  If either integer is negative, then the setting
1891** is not changed but instead the prior value of that setting is written
1892** into the array entry, allowing the current retry settings to be
1893** interrogated.  The zDbName parameter is ignored.
1894**
1895** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1896** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1897** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1898** write ahead log and shared memory files used for transaction control
1899** are automatically deleted when the latest connection to the database
1900** closes.  Setting persistent WAL mode causes those files to persist after
1901** close.  Persisting the files is useful when other processes that do not
1902** have write permission on the directory containing the database file want
1903** to read the database file, as the WAL and shared memory files must exist
1904** in order for the database to be readable.  The fourth parameter to
1905** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1906** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1907** WAL mode.  If the integer is -1, then it is overwritten with the current
1908** WAL persistence setting.
1909**
1910** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1911** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1912** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1913** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1914** xDeviceCharacteristics methods. The fourth parameter to
1915** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1916** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1917** mode.  If the integer is -1, then it is overwritten with the current
1918** zero-damage mode setting.
1919**
1920** <li>[[SQLITE_FCNTL_OVERWRITE]]
1921** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1922** a write transaction to indicate that, unless it is rolled back for some
1923** reason, the entire database file will be overwritten by the current
1924** transaction. This is used by VACUUM operations.
1925**
1926** <li>[[SQLITE_FCNTL_VFSNAME]]
1927** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1928** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1929** final bottom-level VFS are written into memory obtained from
1930** [sqlite3_malloc()] and the result is stored in the char* variable
1931** that the fourth parameter of [sqlite3_file_control()] points to.
1932** The caller is responsible for freeing the memory when done.  As with
1933** all file-control actions, there is no guarantee that this will actually
1934** do anything.  Callers should initialize the char* variable to a NULL
1935** pointer in case this file-control is not implemented.  This file-control
1936** is intended for diagnostic use only.
1937**
1938** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1939** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1940** [VFSes] currently in use.  ^(The argument X in
1941** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1942** of type "[sqlite3_vfs] **".  This opcodes will set *X
1943** to a pointer to the top-level VFS.)^
1944** ^When there are multiple VFS shims in the stack, this opcode finds the
1945** upper-most shim only.
1946**
1947** <li>[[SQLITE_FCNTL_PRAGMA]]
1948** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1949** file control is sent to the open [sqlite3_file] object corresponding
1950** to the database file to which the pragma statement refers. ^The argument
1951** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1952** pointers to strings (char**) in which the second element of the array
1953** is the name of the pragma and the third element is the argument to the
1954** pragma or NULL if the pragma has no argument.  ^The handler for an
1955** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1956** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1957** or the equivalent and that string will become the result of the pragma or
1958** the error message if the pragma fails. ^If the
1959** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1960** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1961** file control returns [SQLITE_OK], then the parser assumes that the
1962** VFS has handled the PRAGMA itself and the parser generates a no-op
1963** prepared statement if result string is NULL, or that returns a copy
1964** of the result string if the string is non-NULL.
1965** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1966** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1967** that the VFS encountered an error while handling the [PRAGMA] and the
1968** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1969** file control occurs at the beginning of pragma statement analysis and so
1970** it is able to override built-in [PRAGMA] statements.
1971**
1972** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1973** ^The [SQLITE_FCNTL_BUSYHANDLER]
1974** file-control may be invoked by SQLite on the database file handle
1975** shortly after it is opened in order to provide a custom VFS with access
1976** to the connections busy-handler callback. The argument is of type (void **)
1977** - an array of two (void *) values. The first (void *) actually points
1978** to a function of type (int (*)(void *)). In order to invoke the connections
1979** busy-handler, this function should be invoked with the second (void *) in
1980** the array as the only argument. If it returns non-zero, then the operation
1981** should be retried. If it returns zero, the custom VFS should abandon the
1982** current operation.
1983**
1984** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1985** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1986** to have SQLite generate a
1987** temporary filename using the same algorithm that is followed to generate
1988** temporary filenames for TEMP tables and other internal uses.  The
1989** argument should be a char** which will be filled with the filename
1990** written into memory obtained from [sqlite3_malloc()].  The caller should
1991** invoke [sqlite3_free()] on the result to avoid a memory leak.
1992**
1993** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1994** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1995** maximum number of bytes that will be used for memory-mapped I/O.
1996** The argument is a pointer to a value of type sqlite3_int64 that
1997** is an advisory maximum number of bytes in the file to memory map.  The
1998** pointer is overwritten with the old value.  The limit is not changed if
1999** the value originally pointed to is negative, and so the current limit
2000** can be queried by passing in a pointer to a negative number.  This
2001** file-control is used internally to implement [PRAGMA mmap_size].
2002**
2003** <li>[[SQLITE_FCNTL_TRACE]]
2004** The [SQLITE_FCNTL_TRACE] file control provides advisory information
2005** to the VFS about what the higher layers of the SQLite stack are doing.
2006** This file control is used by some VFS activity tracing [shims].
2007** The argument is a zero-terminated string.  Higher layers in the
2008** SQLite stack may generate instances of this file control if
2009** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
2010**
2011** <li>[[SQLITE_FCNTL_HAS_MOVED]]
2012** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
2013** pointer to an integer and it writes a boolean into that integer depending
2014** on whether or not the file has been renamed, moved, or deleted since it
2015** was first opened.
2016**
2017** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
2018** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
2019** underlying native file handle associated with a file handle.  This file
2020** control interprets its argument as a pointer to a native file handle and
2021** writes the resulting value there.
2022**
2023** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
2024** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
2025** opcode causes the xFileControl method to swap the file handle with the one
2026** pointed to by the pArg argument.  This capability is used during testing
2027** and only needs to be supported when SQLITE_TEST is defined.
2028**
2029** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
2030** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
2031** be advantageous to block on the next WAL lock if the lock is not immediately
2032** available.  The WAL subsystem issues this signal during rare
2033** circumstances in order to fix a problem with priority inversion.
2034** Applications should <em>not</em> use this file-control.
2035**
2036** <li>[[SQLITE_FCNTL_ZIPVFS]]
2037** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
2038** VFS should return SQLITE_NOTFOUND for this opcode.
2039**
2040** <li>[[SQLITE_FCNTL_RBU]]
2041** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
2042** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
2043** this opcode.
2044** </ul>
2045*/
2046#define SQLITE_FCNTL_LOCKSTATE               1
2047#define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
2048#define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
2049#define SQLITE_FCNTL_LAST_ERRNO              4
2050#define SQLITE_FCNTL_SIZE_HINT               5
2051#define SQLITE_FCNTL_CHUNK_SIZE              6
2052#define SQLITE_FCNTL_FILE_POINTER            7
2053#define SQLITE_FCNTL_SYNC_OMITTED            8
2054#define SQLITE_FCNTL_WIN32_AV_RETRY          9
2055#define SQLITE_FCNTL_PERSIST_WAL            10
2056#define SQLITE_FCNTL_OVERWRITE              11
2057#define SQLITE_FCNTL_VFSNAME                12
2058#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
2059#define SQLITE_FCNTL_PRAGMA                 14
2060#define SQLITE_FCNTL_BUSYHANDLER            15
2061#define SQLITE_FCNTL_TEMPFILENAME           16
2062#define SQLITE_FCNTL_MMAP_SIZE              18
2063#define SQLITE_FCNTL_TRACE                  19
2064#define SQLITE_FCNTL_HAS_MOVED              20
2065#define SQLITE_FCNTL_SYNC                   21
2066#define SQLITE_FCNTL_COMMIT_PHASETWO        22
2067#define SQLITE_FCNTL_WIN32_SET_HANDLE       23
2068#define SQLITE_FCNTL_WAL_BLOCK              24
2069#define SQLITE_FCNTL_ZIPVFS                 25
2070#define SQLITE_FCNTL_RBU                    26
2071#define SQLITE_FCNTL_VFS_POINTER            27
2072#define SQLITE_FCNTL_JOURNAL_POINTER        28
2073#define SQLITE_FCNTL_WIN32_GET_HANDLE       29
2074#define SQLITE_FCNTL_PDB                    30
2075
2076/* deprecated names */
2077#define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
2078#define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
2079#define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
2080
2081
2082/*
2083** CAPI3REF: Mutex Handle
2084**
2085** The mutex module within SQLite defines [sqlite3_mutex] to be an
2086** abstract type for a mutex object.  The SQLite core never looks
2087** at the internal representation of an [sqlite3_mutex].  It only
2088** deals with pointers to the [sqlite3_mutex] object.
2089**
2090** Mutexes are created using [sqlite3_mutex_alloc()].
2091*/
2092typedef struct sqlite3_mutex sqlite3_mutex;
2093
2094/*
2095** CAPI3REF: Loadable Extension Thunk
2096**
2097** A pointer to the opaque sqlite3_api_routines structure is passed as
2098** the third parameter to entry points of [loadable extensions].  This
2099** structure must be typedefed in order to work around compiler warnings
2100** on some platforms.
2101*/
2102typedef struct sqlite3_api_routines sqlite3_api_routines;
2103
2104/*
2105** CAPI3REF: OS Interface Object
2106**
2107** An instance of the sqlite3_vfs object defines the interface between
2108** the SQLite core and the underlying operating system.  The "vfs"
2109** in the name of the object stands for "virtual file system".  See
2110** the [VFS | VFS documentation] for further information.
2111**
2112** The value of the iVersion field is initially 1 but may be larger in
2113** future versions of SQLite.  Additional fields may be appended to this
2114** object when the iVersion value is increased.  Note that the structure
2115** of the sqlite3_vfs object changes in the transaction between
2116** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
2117** modified.
2118**
2119** The szOsFile field is the size of the subclassed [sqlite3_file]
2120** structure used by this VFS.  mxPathname is the maximum length of
2121** a pathname in this VFS.
2122**
2123** Registered sqlite3_vfs objects are kept on a linked list formed by
2124** the pNext pointer.  The [sqlite3_vfs_register()]
2125** and [sqlite3_vfs_unregister()] interfaces manage this list
2126** in a thread-safe way.  The [sqlite3_vfs_find()] interface
2127** searches the list.  Neither the application code nor the VFS
2128** implementation should use the pNext pointer.
2129**
2130** The pNext field is the only field in the sqlite3_vfs
2131** structure that SQLite will ever modify.  SQLite will only access
2132** or modify this field while holding a particular static mutex.
2133** The application should never modify anything within the sqlite3_vfs
2134** object once the object has been registered.
2135**
2136** The zName field holds the name of the VFS module.  The name must
2137** be unique across all VFS modules.
2138**
2139** [[sqlite3_vfs.xOpen]]
2140** ^SQLite guarantees that the zFilename parameter to xOpen
2141** is either a NULL pointer or string obtained
2142** from xFullPathname() with an optional suffix added.
2143** ^If a suffix is added to the zFilename parameter, it will
2144** consist of a single "-" character followed by no more than
2145** 11 alphanumeric and/or "-" characters.
2146** ^SQLite further guarantees that
2147** the string will be valid and unchanged until xClose() is
2148** called. Because of the previous sentence,
2149** the [sqlite3_file] can safely store a pointer to the
2150** filename if it needs to remember the filename for some reason.
2151** If the zFilename parameter to xOpen is a NULL pointer then xOpen
2152** must invent its own temporary name for the file.  ^Whenever the
2153** xFilename parameter is NULL it will also be the case that the
2154** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
2155**
2156** The flags argument to xOpen() includes all bits set in
2157** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
2158** or [sqlite3_open16()] is used, then flags includes at least
2159** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
2160** If xOpen() opens a file read-only then it sets *pOutFlags to
2161** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
2162**
2163** ^(SQLite will also add one of the following flags to the xOpen()
2164** call, depending on the object being opened:
2165**
2166** <ul>
2167** <li>  [SQLITE_OPEN_MAIN_DB]
2168** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
2169** <li>  [SQLITE_OPEN_TEMP_DB]
2170** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
2171** <li>  [SQLITE_OPEN_TRANSIENT_DB]
2172** <li>  [SQLITE_OPEN_SUBJOURNAL]
2173** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
2174** <li>  [SQLITE_OPEN_WAL]
2175** </ul>)^
2176**
2177** The file I/O implementation can use the object type flags to
2178** change the way it deals with files.  For example, an application
2179** that does not care about crash recovery or rollback might make
2180** the open of a journal file a no-op.  Writes to this journal would
2181** also be no-ops, and any attempt to read the journal would return
2182** SQLITE_IOERR.  Or the implementation might recognize that a database
2183** file will be doing page-aligned sector reads and writes in a random
2184** order and set up its I/O subsystem accordingly.
2185**
2186** SQLite might also add one of the following flags to the xOpen method:
2187**
2188** <ul>
2189** <li> [SQLITE_OPEN_DELETEONCLOSE]
2190** <li> [SQLITE_OPEN_EXCLUSIVE]
2191** </ul>
2192**
2193** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
2194** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
2195** will be set for TEMP databases and their journals, transient
2196** databases, and subjournals.
2197**
2198** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
2199** with the [SQLITE_OPEN_CREATE] flag, which are both directly
2200** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
2201** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
2202** SQLITE_OPEN_CREATE, is used to indicate that file should always
2203** be created, and that it is an error if it already exists.
2204** It is <i>not</i> used to indicate the file should be opened
2205** for exclusive access.
2206**
2207** ^At least szOsFile bytes of memory are allocated by SQLite
2208** to hold the  [sqlite3_file] structure passed as the third
2209** argument to xOpen.  The xOpen method does not have to
2210** allocate the structure; it should just fill it in.  Note that
2211** the xOpen method must set the sqlite3_file.pMethods to either
2212** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
2213** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
2214** element will be valid after xOpen returns regardless of the success
2215** or failure of the xOpen call.
2216**
2217** [[sqlite3_vfs.xAccess]]
2218** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
2219** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
2220** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
2221** to test whether a file is at least readable.   The file can be a
2222** directory.
2223**
2224** ^SQLite will always allocate at least mxPathname+1 bytes for the
2225** output buffer xFullPathname.  The exact size of the output buffer
2226** is also passed as a parameter to both  methods. If the output buffer
2227** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
2228** handled as a fatal error by SQLite, vfs implementations should endeavor
2229** to prevent this by setting mxPathname to a sufficiently large value.
2230**
2231** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
2232** interfaces are not strictly a part of the filesystem, but they are
2233** included in the VFS structure for completeness.
2234** The xRandomness() function attempts to return nBytes bytes
2235** of good-quality randomness into zOut.  The return value is
2236** the actual number of bytes of randomness obtained.
2237** The xSleep() method causes the calling thread to sleep for at
2238** least the number of microseconds given.  ^The xCurrentTime()
2239** method returns a Julian Day Number for the current date and time as
2240** a floating point value.
2241** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
2242** Day Number multiplied by 86400000 (the number of milliseconds in
2243** a 24-hour day).
2244** ^SQLite will use the xCurrentTimeInt64() method to get the current
2245** date and time if that method is available (if iVersion is 2 or
2246** greater and the function pointer is not NULL) and will fall back
2247** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
2248**
2249** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
2250** are not used by the SQLite core.  These optional interfaces are provided
2251** by some VFSes to facilitate testing of the VFS code. By overriding
2252** system calls with functions under its control, a test program can
2253** simulate faults and error conditions that would otherwise be difficult
2254** or impossible to induce.  The set of system calls that can be overridden
2255** varies from one VFS to another, and from one version of the same VFS to the
2256** next.  Applications that use these interfaces must be prepared for any
2257** or all of these interfaces to be NULL or for their behavior to change
2258** from one release to the next.  Applications must not attempt to access
2259** any of these methods if the iVersion of the VFS is less than 3.
2260*/
2261typedef struct sqlite3_vfs sqlite3_vfs;
2262typedef void (*sqlite3_syscall_ptr)(void);
2263struct sqlite3_vfs {
2264  int iVersion;            /* Structure version number (currently 3) */
2265  int szOsFile;            /* Size of subclassed sqlite3_file */
2266  int mxPathname;          /* Maximum file pathname length */
2267  sqlite3_vfs *pNext;      /* Next registered VFS */
2268  const char *zName;       /* Name of this virtual file system */
2269  void *pAppData;          /* Pointer to application-specific data */
2270  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
2271               int flags, int *pOutFlags);
2272  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
2273  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
2274  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
2275  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
2276  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
2277  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
2278  void (*xDlClose)(sqlite3_vfs*, void*);
2279  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
2280  int (*xSleep)(sqlite3_vfs*, int microseconds);
2281  int (*xCurrentTime)(sqlite3_vfs*, double*);
2282  int (*xGetLastError)(sqlite3_vfs*, int, char *);
2283  /*
2284  ** The methods above are in version 1 of the sqlite_vfs object
2285  ** definition.  Those that follow are added in version 2 or later
2286  */
2287  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
2288  /*
2289  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
2290  ** Those below are for version 3 and greater.
2291  */
2292  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
2293  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
2294  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
2295  /*
2296  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
2297  ** New fields may be appended in future versions.  The iVersion
2298  ** value will increment whenever this happens.
2299  */
2300};
2301
2302/*
2303** CAPI3REF: Flags for the xAccess VFS method
2304**
2305** These integer constants can be used as the third parameter to
2306** the xAccess method of an [sqlite3_vfs] object.  They determine
2307** what kind of permissions the xAccess method is looking for.
2308** With SQLITE_ACCESS_EXISTS, the xAccess method
2309** simply checks whether the file exists.
2310** With SQLITE_ACCESS_READWRITE, the xAccess method
2311** checks whether the named directory is both readable and writable
2312** (in other words, if files can be added, removed, and renamed within
2313** the directory).
2314** The SQLITE_ACCESS_READWRITE constant is currently used only by the
2315** [temp_store_directory pragma], though this could change in a future
2316** release of SQLite.
2317** With SQLITE_ACCESS_READ, the xAccess method
2318** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
2319** currently unused, though it might be used in a future release of
2320** SQLite.
2321*/
2322#define SQLITE_ACCESS_EXISTS    0
2323#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
2324#define SQLITE_ACCESS_READ      2   /* Unused */
2325
2326/*
2327** CAPI3REF: Flags for the xShmLock VFS method
2328**
2329** These integer constants define the various locking operations
2330** allowed by the xShmLock method of [sqlite3_io_methods].  The
2331** following are the only legal combinations of flags to the
2332** xShmLock method:
2333**
2334** <ul>
2335** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
2336** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
2337** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
2338** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
2339** </ul>
2340**
2341** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
2342** was given on the corresponding lock.
2343**
2344** The xShmLock method can transition between unlocked and SHARED or
2345** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
2346** and EXCLUSIVE.
2347*/
2348#define SQLITE_SHM_UNLOCK       1
2349#define SQLITE_SHM_LOCK         2
2350#define SQLITE_SHM_SHARED       4
2351#define SQLITE_SHM_EXCLUSIVE    8
2352
2353/*
2354** CAPI3REF: Maximum xShmLock index
2355**
2356** The xShmLock method on [sqlite3_io_methods] may use values
2357** between 0 and this upper bound as its "offset" argument.
2358** The SQLite core will never attempt to acquire or release a
2359** lock outside of this range
2360*/
2361#define SQLITE_SHM_NLOCK        8
2362
2363
2364/*
2365** CAPI3REF: Initialize The SQLite Library
2366**
2367** ^The sqlite3_initialize() routine initializes the
2368** SQLite library.  ^The sqlite3_shutdown() routine
2369** deallocates any resources that were allocated by sqlite3_initialize().
2370** These routines are designed to aid in process initialization and
2371** shutdown on embedded systems.  Workstation applications using
2372** SQLite normally do not need to invoke either of these routines.
2373**
2374** A call to sqlite3_initialize() is an "effective" call if it is
2375** the first time sqlite3_initialize() is invoked during the lifetime of
2376** the process, or if it is the first time sqlite3_initialize() is invoked
2377** following a call to sqlite3_shutdown().  ^(Only an effective call
2378** of sqlite3_initialize() does any initialization.  All other calls
2379** are harmless no-ops.)^
2380**
2381** A call to sqlite3_shutdown() is an "effective" call if it is the first
2382** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
2383** an effective call to sqlite3_shutdown() does any deinitialization.
2384** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
2385**
2386** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
2387** is not.  The sqlite3_shutdown() interface must only be called from a
2388** single thread.  All open [database connections] must be closed and all
2389** other SQLite resources must be deallocated prior to invoking
2390** sqlite3_shutdown().
2391**
2392** Among other things, ^sqlite3_initialize() will invoke
2393** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
2394** will invoke sqlite3_os_end().
2395**
2396** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
2397** ^If for some reason, sqlite3_initialize() is unable to initialize
2398** the library (perhaps it is unable to allocate a needed resource such
2399** as a mutex) it returns an [error code] other than [SQLITE_OK].
2400**
2401** ^The sqlite3_initialize() routine is called internally by many other
2402** SQLite interfaces so that an application usually does not need to
2403** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
2404** calls sqlite3_initialize() so the SQLite library will be automatically
2405** initialized when [sqlite3_open()] is called if it has not be initialized
2406** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
2407** compile-time option, then the automatic calls to sqlite3_initialize()
2408** are omitted and the application must call sqlite3_initialize() directly
2409** prior to using any other SQLite interface.  For maximum portability,
2410** it is recommended that applications always invoke sqlite3_initialize()
2411** directly prior to using any other SQLite interface.  Future releases
2412** of SQLite may require this.  In other words, the behavior exhibited
2413** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
2414** default behavior in some future release of SQLite.
2415**
2416** The sqlite3_os_init() routine does operating-system specific
2417** initialization of the SQLite library.  The sqlite3_os_end()
2418** routine undoes the effect of sqlite3_os_init().  Typical tasks
2419** performed by these routines include allocation or deallocation
2420** of static resources, initialization of global variables,
2421** setting up a default [sqlite3_vfs] module, or setting up
2422** a default configuration using [sqlite3_config()].
2423**
2424** The application should never invoke either sqlite3_os_init()
2425** or sqlite3_os_end() directly.  The application should only invoke
2426** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
2427** interface is called automatically by sqlite3_initialize() and
2428** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
2429** implementations for sqlite3_os_init() and sqlite3_os_end()
2430** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
2431** When [custom builds | built for other platforms]
2432** (using the [SQLITE_OS_OTHER=1] compile-time
2433** option) the application must supply a suitable implementation for
2434** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
2435** implementation of sqlite3_os_init() or sqlite3_os_end()
2436** must return [SQLITE_OK] on success and some other [error code] upon
2437** failure.
2438*/
2439SQLITE_API int sqlite3_initialize(void);
2440SQLITE_API int sqlite3_shutdown(void);
2441SQLITE_API int sqlite3_os_init(void);
2442SQLITE_API int sqlite3_os_end(void);
2443
2444/*
2445** CAPI3REF: Configuring The SQLite Library
2446**
2447** The sqlite3_config() interface is used to make global configuration
2448** changes to SQLite in order to tune SQLite to the specific needs of
2449** the application.  The default configuration is recommended for most
2450** applications and so this routine is usually not necessary.  It is
2451** provided to support rare applications with unusual needs.
2452**
2453** <b>The sqlite3_config() interface is not threadsafe. The application
2454** must ensure that no other SQLite interfaces are invoked by other
2455** threads while sqlite3_config() is running.</b>
2456**
2457** The sqlite3_config() interface
2458** may only be invoked prior to library initialization using
2459** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
2460** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
2461** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
2462** Note, however, that ^sqlite3_config() can be called as part of the
2463** implementation of an application-defined [sqlite3_os_init()].
2464**
2465** The first argument to sqlite3_config() is an integer
2466** [configuration option] that determines
2467** what property of SQLite is to be configured.  Subsequent arguments
2468** vary depending on the [configuration option]
2469** in the first argument.
2470**
2471** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
2472** ^If the option is unknown or SQLite is unable to set the option
2473** then this routine returns a non-zero [error code].
2474*/
2475SQLITE_API int sqlite3_config(int, ...);
2476
2477/*
2478** CAPI3REF: Configure database connections
2479** METHOD: sqlite3
2480**
2481** The sqlite3_db_config() interface is used to make configuration
2482** changes to a [database connection].  The interface is similar to
2483** [sqlite3_config()] except that the changes apply to a single
2484** [database connection] (specified in the first argument).
2485**
2486** The second argument to sqlite3_db_config(D,V,...)  is the
2487** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
2488** that indicates what aspect of the [database connection] is being configured.
2489** Subsequent arguments vary depending on the configuration verb.
2490**
2491** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
2492** the call is considered successful.
2493*/
2494SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
2495
2496/*
2497** CAPI3REF: Memory Allocation Routines
2498**
2499** An instance of this object defines the interface between SQLite
2500** and low-level memory allocation routines.
2501**
2502** This object is used in only one place in the SQLite interface.
2503** A pointer to an instance of this object is the argument to
2504** [sqlite3_config()] when the configuration option is
2505** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
2506** By creating an instance of this object
2507** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
2508** during configuration, an application can specify an alternative
2509** memory allocation subsystem for SQLite to use for all of its
2510** dynamic memory needs.
2511**
2512** Note that SQLite comes with several [built-in memory allocators]
2513** that are perfectly adequate for the overwhelming majority of applications
2514** and that this object is only useful to a tiny minority of applications
2515** with specialized memory allocation requirements.  This object is
2516** also used during testing of SQLite in order to specify an alternative
2517** memory allocator that simulates memory out-of-memory conditions in
2518** order to verify that SQLite recovers gracefully from such
2519** conditions.
2520**
2521** The xMalloc, xRealloc, and xFree methods must work like the
2522** malloc(), realloc() and free() functions from the standard C library.
2523** ^SQLite guarantees that the second argument to
2524** xRealloc is always a value returned by a prior call to xRoundup.
2525**
2526** xSize should return the allocated size of a memory allocation
2527** previously obtained from xMalloc or xRealloc.  The allocated size
2528** is always at least as big as the requested size but may be larger.
2529**
2530** The xRoundup method returns what would be the allocated size of
2531** a memory allocation given a particular requested size.  Most memory
2532** allocators round up memory allocations at least to the next multiple
2533** of 8.  Some allocators round up to a larger multiple or to a power of 2.
2534** Every memory allocation request coming in through [sqlite3_malloc()]
2535** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
2536** that causes the corresponding memory allocation to fail.
2537**
2538** The xInit method initializes the memory allocator.  For example,
2539** it might allocate any require mutexes or initialize internal data
2540** structures.  The xShutdown method is invoked (indirectly) by
2541** [sqlite3_shutdown()] and should deallocate any resources acquired
2542** by xInit.  The pAppData pointer is used as the only parameter to
2543** xInit and xShutdown.
2544**
2545** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
2546** the xInit method, so the xInit method need not be threadsafe.  The
2547** xShutdown method is only called from [sqlite3_shutdown()] so it does
2548** not need to be threadsafe either.  For all other methods, SQLite
2549** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
2550** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
2551** it is by default) and so the methods are automatically serialized.
2552** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
2553** methods must be threadsafe or else make their own arrangements for
2554** serialization.
2555**
2556** SQLite will never invoke xInit() more than once without an intervening
2557** call to xShutdown().
2558*/
2559typedef struct sqlite3_mem_methods sqlite3_mem_methods;
2560struct sqlite3_mem_methods {
2561  void *(*xMalloc)(int);         /* Memory allocation function */
2562  void (*xFree)(void*);          /* Free a prior allocation */
2563  void *(*xRealloc)(void*,int);  /* Resize an allocation */
2564  int (*xSize)(void*);           /* Return the size of an allocation */
2565  int (*xRoundup)(int);          /* Round up request size to allocation size */
2566  int (*xInit)(void*);           /* Initialize the memory allocator */
2567  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
2568  void *pAppData;                /* Argument to xInit() and xShutdown() */
2569};
2570
2571/*
2572** CAPI3REF: Configuration Options
2573** KEYWORDS: {configuration option}
2574**
2575** These constants are the available integer configuration options that
2576** can be passed as the first argument to the [sqlite3_config()] interface.
2577**
2578** New configuration options may be added in future releases of SQLite.
2579** Existing configuration options might be discontinued.  Applications
2580** should check the return code from [sqlite3_config()] to make sure that
2581** the call worked.  The [sqlite3_config()] interface will return a
2582** non-zero [error code] if a discontinued or unsupported configuration option
2583** is invoked.
2584**
2585** <dl>
2586** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
2587** <dd>There are no arguments to this option.  ^This option sets the
2588** [threading mode] to Single-thread.  In other words, it disables
2589** all mutexing and puts SQLite into a mode where it can only be used
2590** by a single thread.   ^If SQLite is compiled with
2591** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2592** it is not possible to change the [threading mode] from its default
2593** value of Single-thread and so [sqlite3_config()] will return
2594** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
2595** configuration option.</dd>
2596**
2597** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
2598** <dd>There are no arguments to this option.  ^This option sets the
2599** [threading mode] to Multi-thread.  In other words, it disables
2600** mutexing on [database connection] and [prepared statement] objects.
2601** The application is responsible for serializing access to
2602** [database connections] and [prepared statements].  But other mutexes
2603** are enabled so that SQLite will be safe to use in a multi-threaded
2604** environment as long as no two threads attempt to use the same
2605** [database connection] at the same time.  ^If SQLite is compiled with
2606** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2607** it is not possible to set the Multi-thread [threading mode] and
2608** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2609** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
2610**
2611** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
2612** <dd>There are no arguments to this option.  ^This option sets the
2613** [threading mode] to Serialized. In other words, this option enables
2614** all mutexes including the recursive
2615** mutexes on [database connection] and [prepared statement] objects.
2616** In this mode (which is the default when SQLite is compiled with
2617** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2618** to [database connections] and [prepared statements] so that the
2619** application is free to use the same [database connection] or the
2620** same [prepared statement] in different threads at the same time.
2621** ^If SQLite is compiled with
2622** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2623** it is not possible to set the Serialized [threading mode] and
2624** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2625** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2626**
2627** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2628** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
2629** a pointer to an instance of the [sqlite3_mem_methods] structure.
2630** The argument specifies
2631** alternative low-level memory allocation routines to be used in place of
2632** the memory allocation routines built into SQLite.)^ ^SQLite makes
2633** its own private copy of the content of the [sqlite3_mem_methods] structure
2634** before the [sqlite3_config()] call returns.</dd>
2635**
2636** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2637** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
2638** is a pointer to an instance of the [sqlite3_mem_methods] structure.
2639** The [sqlite3_mem_methods]
2640** structure is filled with the currently defined memory allocation routines.)^
2641** This option can be used to overload the default memory allocation
2642** routines with a wrapper that simulations memory allocation failure or
2643** tracks memory usage, for example. </dd>
2644**
2645** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2646** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
2647** interpreted as a boolean, which enables or disables the collection of
2648** memory allocation statistics. ^(When memory allocation statistics are
2649** disabled, the following SQLite interfaces become non-operational:
2650**   <ul>
2651**   <li> [sqlite3_memory_used()]
2652**   <li> [sqlite3_memory_highwater()]
2653**   <li> [sqlite3_soft_heap_limit64()]
2654**   <li> [sqlite3_status64()]
2655**   </ul>)^
2656** ^Memory allocation statistics are enabled by default unless SQLite is
2657** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2658** allocation statistics are disabled by default.
2659** </dd>
2660**
2661** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2662** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
2663** that SQLite can use for scratch memory.  ^(There are three arguments
2664** to SQLITE_CONFIG_SCRATCH:  A pointer an 8-byte
2665** aligned memory buffer from which the scratch allocations will be
2666** drawn, the size of each scratch allocation (sz),
2667** and the maximum number of scratch allocations (N).)^
2668** The first argument must be a pointer to an 8-byte aligned buffer
2669** of at least sz*N bytes of memory.
2670** ^SQLite will not use more than one scratch buffers per thread.
2671** ^SQLite will never request a scratch buffer that is more than 6
2672** times the database page size.
2673** ^If SQLite needs needs additional
2674** scratch memory beyond what is provided by this configuration option, then
2675** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
2676** ^When the application provides any amount of scratch memory using
2677** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
2678** [sqlite3_malloc|heap allocations].
2679** This can help [Robson proof|prevent memory allocation failures] due to heap
2680** fragmentation in low-memory embedded systems.
2681** </dd>
2682**
2683** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2684** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
2685** that SQLite can use for the database page cache with the default page
2686** cache implementation.
2687** This configuration option is a no-op if an application-define page
2688** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
2689** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
2690** 8-byte aligned memory (pMem), the size of each page cache line (sz),
2691** and the number of cache lines (N).
2692** The sz argument should be the size of the largest database page
2693** (a power of two between 512 and 65536) plus some extra bytes for each
2694** page header.  ^The number of extra bytes needed by the page header
2695** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
2696** ^It is harmless, apart from the wasted memory,
2697** for the sz parameter to be larger than necessary.  The pMem
2698** argument must be either a NULL pointer or a pointer to an 8-byte
2699** aligned block of memory of at least sz*N bytes, otherwise
2700** subsequent behavior is undefined.
2701** ^When pMem is not NULL, SQLite will strive to use the memory provided
2702** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
2703** a page cache line is larger than sz bytes or if all of the pMem buffer
2704** is exhausted.
2705** ^If pMem is NULL and N is non-zero, then each database connection
2706** does an initial bulk allocation for page cache memory
2707** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
2708** of -1024*N bytes if N is negative, . ^If additional
2709** page cache memory is needed beyond what is provided by the initial
2710** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
2711** additional cache line. </dd>
2712**
2713** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2714** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
2715** that SQLite will use for all of its dynamic memory allocation needs
2716** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
2717** [SQLITE_CONFIG_PAGECACHE].
2718** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
2719** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
2720** [SQLITE_ERROR] if invoked otherwise.
2721** ^There are three arguments to SQLITE_CONFIG_HEAP:
2722** An 8-byte aligned pointer to the memory,
2723** the number of bytes in the memory buffer, and the minimum allocation size.
2724** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2725** to using its default memory allocator (the system malloc() implementation),
2726** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2727** memory pointer is not NULL then the alternative memory
2728** allocator is engaged to handle all of SQLites memory allocation needs.
2729** The first pointer (the memory pointer) must be aligned to an 8-byte
2730** boundary or subsequent behavior of SQLite will be undefined.
2731** The minimum allocation size is capped at 2**12. Reasonable values
2732** for the minimum allocation size are 2**5 through 2**8.</dd>
2733**
2734** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2735** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
2736** pointer to an instance of the [sqlite3_mutex_methods] structure.
2737** The argument specifies alternative low-level mutex routines to be used
2738** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
2739** the content of the [sqlite3_mutex_methods] structure before the call to
2740** [sqlite3_config()] returns. ^If SQLite is compiled with
2741** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2742** the entire mutexing subsystem is omitted from the build and hence calls to
2743** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2744** return [SQLITE_ERROR].</dd>
2745**
2746** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2747** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
2748** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
2749** [sqlite3_mutex_methods]
2750** structure is filled with the currently defined mutex routines.)^
2751** This option can be used to overload the default mutex allocation
2752** routines with a wrapper used to track mutex usage for performance
2753** profiling or testing, for example.   ^If SQLite is compiled with
2754** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2755** the entire mutexing subsystem is omitted from the build and hence calls to
2756** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2757** return [SQLITE_ERROR].</dd>
2758**
2759** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2760** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
2761** the default size of lookaside memory on each [database connection].
2762** The first argument is the
2763** size of each lookaside buffer slot and the second is the number of
2764** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
2765** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2766** option to [sqlite3_db_config()] can be used to change the lookaside
2767** configuration on individual connections.)^ </dd>
2768**
2769** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2770** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
2771** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
2772** the interface to a custom page cache implementation.)^
2773** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
2774**
2775** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2776** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
2777** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
2778** the current page cache implementation into that object.)^ </dd>
2779**
2780** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2781** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2782** global [error log].
2783** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2784** function with a call signature of void(*)(void*,int,const char*),
2785** and a pointer to void. ^If the function pointer is not NULL, it is
2786** invoked by [sqlite3_log()] to process each logging event.  ^If the
2787** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2788** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2789** passed through as the first parameter to the application-defined logger
2790** function whenever that function is invoked.  ^The second parameter to
2791** the logger function is a copy of the first parameter to the corresponding
2792** [sqlite3_log()] call and is intended to be a [result code] or an
2793** [extended result code].  ^The third parameter passed to the logger is
2794** log message after formatting via [sqlite3_snprintf()].
2795** The SQLite logging interface is not reentrant; the logger function
2796** supplied by the application must not invoke any SQLite interface.
2797** In a multi-threaded application, the application-defined logger
2798** function must be threadsafe. </dd>
2799**
2800** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2801** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2802** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2803** then URI handling is globally disabled.)^ ^If URI handling is globally
2804** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2805** [sqlite3_open16()] or
2806** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2807** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2808** connection is opened. ^If it is globally disabled, filenames are
2809** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2810** database connection is opened. ^(By default, URI handling is globally
2811** disabled. The default value may be changed by compiling with the
2812** [SQLITE_USE_URI] symbol defined.)^
2813**
2814** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2815** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2816** argument which is interpreted as a boolean in order to enable or disable
2817** the use of covering indices for full table scans in the query optimizer.
2818** ^The default setting is determined
2819** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2820** if that compile-time option is omitted.
2821** The ability to disable the use of covering indices for full table scans
2822** is because some incorrectly coded legacy applications might malfunction
2823** when the optimization is enabled.  Providing the ability to
2824** disable the optimization allows the older, buggy application code to work
2825** without change even with newer versions of SQLite.
2826**
2827** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2828** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2829** <dd> These options are obsolete and should not be used by new code.
2830** They are retained for backwards compatibility but are now no-ops.
2831** </dd>
2832**
2833** [[SQLITE_CONFIG_SQLLOG]]
2834** <dt>SQLITE_CONFIG_SQLLOG
2835** <dd>This option is only available if sqlite is compiled with the
2836** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2837** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2838** The second should be of type (void*). The callback is invoked by the library
2839** in three separate circumstances, identified by the value passed as the
2840** fourth parameter. If the fourth parameter is 0, then the database connection
2841** passed as the second argument has just been opened. The third argument
2842** points to a buffer containing the name of the main database file. If the
2843** fourth parameter is 1, then the SQL statement that the third parameter
2844** points to has just been executed. Or, if the fourth parameter is 2, then
2845** the connection being passed as the second parameter is being closed. The
2846** third parameter is passed NULL In this case.  An example of using this
2847** configuration option can be seen in the "test_sqllog.c" source file in
2848** the canonical SQLite source tree.</dd>
2849**
2850** [[SQLITE_CONFIG_MMAP_SIZE]]
2851** <dt>SQLITE_CONFIG_MMAP_SIZE
2852** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2853** that are the default mmap size limit (the default setting for
2854** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2855** ^The default setting can be overridden by each database connection using
2856** either the [PRAGMA mmap_size] command, or by using the
2857** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
2858** will be silently truncated if necessary so that it does not exceed the
2859** compile-time maximum mmap size set by the
2860** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2861** ^If either argument to this option is negative, then that argument is
2862** changed to its compile-time default.
2863**
2864** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2865** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2866** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2867** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2868** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2869** that specifies the maximum size of the created heap.
2870**
2871** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2872** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2873** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2874** is a pointer to an integer and writes into that integer the number of extra
2875** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2876** The amount of extra space required can change depending on the compiler,
2877** target platform, and SQLite version.
2878**
2879** [[SQLITE_CONFIG_PMASZ]]
2880** <dt>SQLITE_CONFIG_PMASZ
2881** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2882** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2883** sorter to that integer.  The default minimum PMA Size is set by the
2884** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
2885** to help with sort operations when multithreaded sorting
2886** is enabled (using the [PRAGMA threads] command) and the amount of content
2887** to be sorted exceeds the page size times the minimum of the
2888** [PRAGMA cache_size] setting and this value.
2889**
2890** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2891** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2892** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2893** becomes the [statement journal] spill-to-disk threshold.
2894** [Statement journals] are held in memory until their size (in bytes)
2895** exceeds this threshold, at which point they are written to disk.
2896** Or if the threshold is -1, statement journals are always held
2897** exclusively in memory.
2898** Since many statement journals never become large, setting the spill
2899** threshold to a value such as 64KiB can greatly reduce the amount of
2900** I/O required to support statement rollback.
2901** The default value for this setting is controlled by the
2902** [SQLITE_STMTJRNL_SPILL] compile-time option.
2903** </dl>
2904*/
2905#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2906#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2907#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2908#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2909#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2910#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2911#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2912#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2913#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2914#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2915#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2916/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2917#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2918#define SQLITE_CONFIG_PCACHE       14  /* no-op */
2919#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2920#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2921#define SQLITE_CONFIG_URI          17  /* int */
2922#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2923#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2924#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2925#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2926#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
2927#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
2928#define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
2929#define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
2930#define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
2931
2932/*
2933** CAPI3REF: Database Connection Configuration Options
2934**
2935** These constants are the available integer configuration options that
2936** can be passed as the second argument to the [sqlite3_db_config()] interface.
2937**
2938** New configuration options may be added in future releases of SQLite.
2939** Existing configuration options might be discontinued.  Applications
2940** should check the return code from [sqlite3_db_config()] to make sure that
2941** the call worked.  ^The [sqlite3_db_config()] interface will return a
2942** non-zero [error code] if a discontinued or unsupported configuration option
2943** is invoked.
2944**
2945** <dl>
2946** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2947** <dd> ^This option takes three additional arguments that determine the
2948** [lookaside memory allocator] configuration for the [database connection].
2949** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2950** pointer to a memory buffer to use for lookaside memory.
2951** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2952** may be NULL in which case SQLite will allocate the
2953** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2954** size of each lookaside buffer slot.  ^The third argument is the number of
2955** slots.  The size of the buffer in the first argument must be greater than
2956** or equal to the product of the second and third arguments.  The buffer
2957** must be aligned to an 8-byte boundary.  ^If the second argument to
2958** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2959** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2960** configuration for a database connection can only be changed when that
2961** connection is not currently using lookaside memory, or in other words
2962** when the "current value" returned by
2963** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2964** Any attempt to change the lookaside memory configuration when lookaside
2965** memory is in use leaves the configuration unchanged and returns
2966** [SQLITE_BUSY].)^</dd>
2967**
2968** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2969** <dd> ^This option is used to enable or disable the enforcement of
2970** [foreign key constraints].  There should be two additional arguments.
2971** The first argument is an integer which is 0 to disable FK enforcement,
2972** positive to enable FK enforcement or negative to leave FK enforcement
2973** unchanged.  The second parameter is a pointer to an integer into which
2974** is written 0 or 1 to indicate whether FK enforcement is off or on
2975** following this call.  The second parameter may be a NULL pointer, in
2976** which case the FK enforcement setting is not reported back. </dd>
2977**
2978** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2979** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2980** There should be two additional arguments.
2981** The first argument is an integer which is 0 to disable triggers,
2982** positive to enable triggers or negative to leave the setting unchanged.
2983** The second parameter is a pointer to an integer into which
2984** is written 0 or 1 to indicate whether triggers are disabled or enabled
2985** following this call.  The second parameter may be a NULL pointer, in
2986** which case the trigger setting is not reported back. </dd>
2987**
2988** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2989** <dd> ^This option is used to enable or disable the two-argument
2990** version of the [fts3_tokenizer()] function which is part of the
2991** [FTS3] full-text search engine extension.
2992** There should be two additional arguments.
2993** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2994** positive to enable fts3_tokenizer() or negative to leave the setting
2995** unchanged.
2996** The second parameter is a pointer to an integer into which
2997** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2998** following this call.  The second parameter may be a NULL pointer, in
2999** which case the new setting is not reported back. </dd>
3000**
3001** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
3002** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
3003** interface independently of the [load_extension()] SQL function.
3004** The [sqlite3_enable_load_extension()] API enables or disables both the
3005** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
3006** There should be two additional arguments.
3007** When the first argument to this interface is 1, then only the C-API is
3008** enabled and the SQL function remains disabled.  If the first argument to
3009** this interface is 0, then both the C-API and the SQL function are disabled.
3010** If the first argument is -1, then no changes are made to state of either the
3011** C-API or the SQL function.
3012** The second parameter is a pointer to an integer into which
3013** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
3014** is disabled or enabled following this call.  The second parameter may
3015** be a NULL pointer, in which case the new setting is not reported back.
3016** </dd>
3017**
3018** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
3019** <dd> ^This option is used to change the name of the "main" database
3020** schema.  ^The sole argument is a pointer to a constant UTF8 string
3021** which will become the new schema name in place of "main".  ^SQLite
3022** does not make a copy of the new main schema name string, so the application
3023** must ensure that the argument passed into this DBCONFIG option is unchanged
3024** until after the database connection closes.
3025** </dd>
3026**
3027** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
3028** <dd> Usually, when a database in wal mode is closed or detached from a
3029** database handle, SQLite checks if this will mean that there are now no
3030** connections at all to the database. If so, it performs a checkpoint
3031** operation before closing the connection. This option may be used to
3032** override this behaviour. The first parameter passed to this operation
3033** is an integer - non-zero to disable checkpoints-on-close, or zero (the
3034** default) to enable them. The second parameter is a pointer to an integer
3035** into which is written 0 or 1 to indicate whether checkpoints-on-close
3036** have been disabled - 0 if they are not disabled, 1 if they are.
3037** </dd>
3038**
3039** <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
3040** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
3041** the [query planner stability guarantee] (QPSG).  When the QPSG is active,
3042** a single SQL query statement will always use the same algorithm regardless
3043** of values of [bound parameters].)^ The QPSG disables some query optimizations
3044** that look at the values of bound parameters, which can make some queries
3045** slower.  But the QPSG has the advantage of more predictable behavior.  With
3046** the QPSG active, SQLite will always use the same query plan in the field as
3047** was used during testing in the lab.
3048** </dd>
3049**
3050** </dl>
3051*/
3052#define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
3053#define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
3054#define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
3055#define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
3056#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
3057#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
3058#define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      1006 /* int int* */
3059#define SQLITE_DBCONFIG_ENABLE_QPSG           1007 /* int int* */
3060
3061
3062/*
3063** CAPI3REF: Enable Or Disable Extended Result Codes
3064** METHOD: sqlite3
3065**
3066** ^The sqlite3_extended_result_codes() routine enables or disables the
3067** [extended result codes] feature of SQLite. ^The extended result
3068** codes are disabled by default for historical compatibility.
3069*/
3070SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
3071
3072/*
3073** CAPI3REF: Last Insert Rowid
3074** METHOD: sqlite3
3075**
3076** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
3077** has a unique 64-bit signed
3078** integer key called the [ROWID | "rowid"]. ^The rowid is always available
3079** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
3080** names are not also used by explicitly declared columns. ^If
3081** the table has a column of type [INTEGER PRIMARY KEY] then that column
3082** is another alias for the rowid.
3083**
3084** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
3085** the most recent successful [INSERT] into a rowid table or [virtual table]
3086** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
3087** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
3088** on the database connection D, then sqlite3_last_insert_rowid(D) returns
3089** zero.
3090**
3091** As well as being set automatically as rows are inserted into database
3092** tables, the value returned by this function may be set explicitly by
3093** [sqlite3_set_last_insert_rowid()]
3094**
3095** Some virtual table implementations may INSERT rows into rowid tables as
3096** part of committing a transaction (e.g. to flush data accumulated in memory
3097** to disk). In this case subsequent calls to this function return the rowid
3098** associated with these internal INSERT operations, which leads to
3099** unintuitive results. Virtual table implementations that do write to rowid
3100** tables in this way can avoid this problem by restoring the original
3101** rowid value using [sqlite3_set_last_insert_rowid()] before returning
3102** control to the user.
3103**
3104** ^(If an [INSERT] occurs within a trigger then this routine will
3105** return the [rowid] of the inserted row as long as the trigger is
3106** running. Once the trigger program ends, the value returned
3107** by this routine reverts to what it was before the trigger was fired.)^
3108**
3109** ^An [INSERT] that fails due to a constraint violation is not a
3110** successful [INSERT] and does not change the value returned by this
3111** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
3112** and INSERT OR ABORT make no changes to the return value of this
3113** routine when their insertion fails.  ^(When INSERT OR REPLACE
3114** encounters a constraint violation, it does not fail.  The
3115** INSERT continues to completion after deleting rows that caused
3116** the constraint problem so INSERT OR REPLACE will always change
3117** the return value of this interface.)^
3118**
3119** ^For the purposes of this routine, an [INSERT] is considered to
3120** be successful even if it is subsequently rolled back.
3121**
3122** This function is accessible to SQL statements via the
3123** [last_insert_rowid() SQL function].
3124**
3125** If a separate thread performs a new [INSERT] on the same
3126** database connection while the [sqlite3_last_insert_rowid()]
3127** function is running and thus changes the last insert [rowid],
3128** then the value returned by [sqlite3_last_insert_rowid()] is
3129** unpredictable and might not equal either the old or the new
3130** last insert [rowid].
3131*/
3132SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
3133
3134/*
3135** CAPI3REF: Set the Last Insert Rowid value.
3136** METHOD: sqlite3
3137**
3138** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
3139** set the value returned by calling sqlite3_last_insert_rowid(D) to R
3140** without inserting a row into the database.
3141*/
3142SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
3143
3144/*
3145** CAPI3REF: Count The Number Of Rows Modified
3146** METHOD: sqlite3
3147**
3148** ^This function returns the number of rows modified, inserted or
3149** deleted by the most recently completed INSERT, UPDATE or DELETE
3150** statement on the database connection specified by the only parameter.
3151** ^Executing any other type of SQL statement does not modify the value
3152** returned by this function.
3153**
3154** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
3155** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
3156** [foreign key actions] or [REPLACE] constraint resolution are not counted.
3157**
3158** Changes to a view that are intercepted by
3159** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
3160** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
3161** DELETE statement run on a view is always zero. Only changes made to real
3162** tables are counted.
3163**
3164** Things are more complicated if the sqlite3_changes() function is
3165** executed while a trigger program is running. This may happen if the
3166** program uses the [changes() SQL function], or if some other callback
3167** function invokes sqlite3_changes() directly. Essentially:
3168**
3169** <ul>
3170**   <li> ^(Before entering a trigger program the value returned by
3171**        sqlite3_changes() function is saved. After the trigger program
3172**        has finished, the original value is restored.)^
3173**
3174**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
3175**        statement sets the value returned by sqlite3_changes()
3176**        upon completion as normal. Of course, this value will not include
3177**        any changes performed by sub-triggers, as the sqlite3_changes()
3178**        value will be saved and restored after each sub-trigger has run.)^
3179** </ul>
3180**
3181** ^This means that if the changes() SQL function (or similar) is used
3182** by the first INSERT, UPDATE or DELETE statement within a trigger, it
3183** returns the value as set when the calling statement began executing.
3184** ^If it is used by the second or subsequent such statement within a trigger
3185** program, the value returned reflects the number of rows modified by the
3186** previous INSERT, UPDATE or DELETE statement within the same trigger.
3187**
3188** See also the [sqlite3_total_changes()] interface, the
3189** [count_changes pragma], and the [changes() SQL function].
3190**
3191** If a separate thread makes changes on the same database connection
3192** while [sqlite3_changes()] is running then the value returned
3193** is unpredictable and not meaningful.
3194*/
3195SQLITE_API int sqlite3_changes(sqlite3*);
3196
3197/*
3198** CAPI3REF: Total Number Of Rows Modified
3199** METHOD: sqlite3
3200**
3201** ^This function returns the total number of rows inserted, modified or
3202** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
3203** since the database connection was opened, including those executed as
3204** part of trigger programs. ^Executing any other type of SQL statement
3205** does not affect the value returned by sqlite3_total_changes().
3206**
3207** ^Changes made as part of [foreign key actions] are included in the
3208** count, but those made as part of REPLACE constraint resolution are
3209** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
3210** are not counted.
3211**
3212** See also the [sqlite3_changes()] interface, the
3213** [count_changes pragma], and the [total_changes() SQL function].
3214**
3215** If a separate thread makes changes on the same database connection
3216** while [sqlite3_total_changes()] is running then the value
3217** returned is unpredictable and not meaningful.
3218*/
3219SQLITE_API int sqlite3_total_changes(sqlite3*);
3220
3221/*
3222** CAPI3REF: Interrupt A Long-Running Query
3223** METHOD: sqlite3
3224**
3225** ^This function causes any pending database operation to abort and
3226** return at its earliest opportunity. This routine is typically
3227** called in response to a user action such as pressing "Cancel"
3228** or Ctrl-C where the user wants a long query operation to halt
3229** immediately.
3230**
3231** ^It is safe to call this routine from a thread different from the
3232** thread that is currently running the database operation.  But it
3233** is not safe to call this routine with a [database connection] that
3234** is closed or might close before sqlite3_interrupt() returns.
3235**
3236** ^If an SQL operation is very nearly finished at the time when
3237** sqlite3_interrupt() is called, then it might not have an opportunity
3238** to be interrupted and might continue to completion.
3239**
3240** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
3241** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
3242** that is inside an explicit transaction, then the entire transaction
3243** will be rolled back automatically.
3244**
3245** ^The sqlite3_interrupt(D) call is in effect until all currently running
3246** SQL statements on [database connection] D complete.  ^Any new SQL statements
3247** that are started after the sqlite3_interrupt() call and before the
3248** running statements reaches zero are interrupted as if they had been
3249** running prior to the sqlite3_interrupt() call.  ^New SQL statements
3250** that are started after the running statement count reaches zero are
3251** not effected by the sqlite3_interrupt().
3252** ^A call to sqlite3_interrupt(D) that occurs when there are no running
3253** SQL statements is a no-op and has no effect on SQL statements
3254** that are started after the sqlite3_interrupt() call returns.
3255*/
3256SQLITE_API void sqlite3_interrupt(sqlite3*);
3257
3258/*
3259** CAPI3REF: Determine If An SQL Statement Is Complete
3260**
3261** These routines are useful during command-line input to determine if the
3262** currently entered text seems to form a complete SQL statement or
3263** if additional input is needed before sending the text into
3264** SQLite for parsing.  ^These routines return 1 if the input string
3265** appears to be a complete SQL statement.  ^A statement is judged to be
3266** complete if it ends with a semicolon token and is not a prefix of a
3267** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
3268** string literals or quoted identifier names or comments are not
3269** independent tokens (they are part of the token in which they are
3270** embedded) and thus do not count as a statement terminator.  ^Whitespace
3271** and comments that follow the final semicolon are ignored.
3272**
3273** ^These routines return 0 if the statement is incomplete.  ^If a
3274** memory allocation fails, then SQLITE_NOMEM is returned.
3275**
3276** ^These routines do not parse the SQL statements thus
3277** will not detect syntactically incorrect SQL.
3278**
3279** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
3280** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
3281** automatically by sqlite3_complete16().  If that initialization fails,
3282** then the return value from sqlite3_complete16() will be non-zero
3283** regardless of whether or not the input SQL is complete.)^
3284**
3285** The input to [sqlite3_complete()] must be a zero-terminated
3286** UTF-8 string.
3287**
3288** The input to [sqlite3_complete16()] must be a zero-terminated
3289** UTF-16 string in native byte order.
3290*/
3291SQLITE_API int sqlite3_complete(const char *sql);
3292SQLITE_API int sqlite3_complete16(const void *sql);
3293
3294/*
3295** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
3296** KEYWORDS: {busy-handler callback} {busy handler}
3297** METHOD: sqlite3
3298**
3299** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
3300** that might be invoked with argument P whenever
3301** an attempt is made to access a database table associated with
3302** [database connection] D when another thread
3303** or process has the table locked.
3304** The sqlite3_busy_handler() interface is used to implement
3305** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
3306**
3307** ^If the busy callback is NULL, then [SQLITE_BUSY]
3308** is returned immediately upon encountering the lock.  ^If the busy callback
3309** is not NULL, then the callback might be invoked with two arguments.
3310**
3311** ^The first argument to the busy handler is a copy of the void* pointer which
3312** is the third argument to sqlite3_busy_handler().  ^The second argument to
3313** the busy handler callback is the number of times that the busy handler has
3314** been invoked previously for the same locking event.  ^If the
3315** busy callback returns 0, then no additional attempts are made to
3316** access the database and [SQLITE_BUSY] is returned
3317** to the application.
3318** ^If the callback returns non-zero, then another attempt
3319** is made to access the database and the cycle repeats.
3320**
3321** The presence of a busy handler does not guarantee that it will be invoked
3322** when there is lock contention. ^If SQLite determines that invoking the busy
3323** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
3324** to the application instead of invoking the
3325** busy handler.
3326** Consider a scenario where one process is holding a read lock that
3327** it is trying to promote to a reserved lock and
3328** a second process is holding a reserved lock that it is trying
3329** to promote to an exclusive lock.  The first process cannot proceed
3330** because it is blocked by the second and the second process cannot
3331** proceed because it is blocked by the first.  If both processes
3332** invoke the busy handlers, neither will make any progress.  Therefore,
3333** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
3334** will induce the first process to release its read lock and allow
3335** the second process to proceed.
3336**
3337** ^The default busy callback is NULL.
3338**
3339** ^(There can only be a single busy handler defined for each
3340** [database connection].  Setting a new busy handler clears any
3341** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
3342** or evaluating [PRAGMA busy_timeout=N] will change the
3343** busy handler and thus clear any previously set busy handler.
3344**
3345** The busy callback should not take any actions which modify the
3346** database connection that invoked the busy handler.  In other words,
3347** the busy handler is not reentrant.  Any such actions
3348** result in undefined behavior.
3349**
3350** A busy handler must not close the database connection
3351** or [prepared statement] that invoked the busy handler.
3352*/
3353SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
3354
3355/*
3356** CAPI3REF: Set A Busy Timeout
3357** METHOD: sqlite3
3358**
3359** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
3360** for a specified amount of time when a table is locked.  ^The handler
3361** will sleep multiple times until at least "ms" milliseconds of sleeping
3362** have accumulated.  ^After at least "ms" milliseconds of sleeping,
3363** the handler returns 0 which causes [sqlite3_step()] to return
3364** [SQLITE_BUSY].
3365**
3366** ^Calling this routine with an argument less than or equal to zero
3367** turns off all busy handlers.
3368**
3369** ^(There can only be a single busy handler for a particular
3370** [database connection] at any given moment.  If another busy handler
3371** was defined  (using [sqlite3_busy_handler()]) prior to calling
3372** this routine, that other busy handler is cleared.)^
3373**
3374** See also:  [PRAGMA busy_timeout]
3375*/
3376SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
3377
3378/*
3379** CAPI3REF: Convenience Routines For Running Queries
3380** METHOD: sqlite3
3381**
3382** This is a legacy interface that is preserved for backwards compatibility.
3383** Use of this interface is not recommended.
3384**
3385** Definition: A <b>result table</b> is memory data structure created by the
3386** [sqlite3_get_table()] interface.  A result table records the
3387** complete query results from one or more queries.
3388**
3389** The table conceptually has a number of rows and columns.  But
3390** these numbers are not part of the result table itself.  These
3391** numbers are obtained separately.  Let N be the number of rows
3392** and M be the number of columns.
3393**
3394** A result table is an array of pointers to zero-terminated UTF-8 strings.
3395** There are (N+1)*M elements in the array.  The first M pointers point
3396** to zero-terminated strings that  contain the names of the columns.
3397** The remaining entries all point to query results.  NULL values result
3398** in NULL pointers.  All other values are in their UTF-8 zero-terminated
3399** string representation as returned by [sqlite3_column_text()].
3400**
3401** A result table might consist of one or more memory allocations.
3402** It is not safe to pass a result table directly to [sqlite3_free()].
3403** A result table should be deallocated using [sqlite3_free_table()].
3404**
3405** ^(As an example of the result table format, suppose a query result
3406** is as follows:
3407**
3408** <blockquote><pre>
3409**        Name        | Age
3410**        -----------------------
3411**        Alice       | 43
3412**        Bob         | 28
3413**        Cindy       | 21
3414** </pre></blockquote>
3415**
3416** There are two column (M==2) and three rows (N==3).  Thus the
3417** result table has 8 entries.  Suppose the result table is stored
3418** in an array names azResult.  Then azResult holds this content:
3419**
3420** <blockquote><pre>
3421**        azResult&#91;0] = "Name";
3422**        azResult&#91;1] = "Age";
3423**        azResult&#91;2] = "Alice";
3424**        azResult&#91;3] = "43";
3425**        azResult&#91;4] = "Bob";
3426**        azResult&#91;5] = "28";
3427**        azResult&#91;6] = "Cindy";
3428**        azResult&#91;7] = "21";
3429** </pre></blockquote>)^
3430**
3431** ^The sqlite3_get_table() function evaluates one or more
3432** semicolon-separated SQL statements in the zero-terminated UTF-8
3433** string of its 2nd parameter and returns a result table to the
3434** pointer given in its 3rd parameter.
3435**
3436** After the application has finished with the result from sqlite3_get_table(),
3437** it must pass the result table pointer to sqlite3_free_table() in order to
3438** release the memory that was malloced.  Because of the way the
3439** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
3440** function must not try to call [sqlite3_free()] directly.  Only
3441** [sqlite3_free_table()] is able to release the memory properly and safely.
3442**
3443** The sqlite3_get_table() interface is implemented as a wrapper around
3444** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
3445** to any internal data structures of SQLite.  It uses only the public
3446** interface defined here.  As a consequence, errors that occur in the
3447** wrapper layer outside of the internal [sqlite3_exec()] call are not
3448** reflected in subsequent calls to [sqlite3_errcode()] or
3449** [sqlite3_errmsg()].
3450*/
3451SQLITE_API int sqlite3_get_table(
3452  sqlite3 *db,          /* An open database */
3453  const char *zSql,     /* SQL to be evaluated */
3454  char ***pazResult,    /* Results of the query */
3455  int *pnRow,           /* Number of result rows written here */
3456  int *pnColumn,        /* Number of result columns written here */
3457  char **pzErrmsg       /* Error msg written here */
3458);
3459SQLITE_API void sqlite3_free_table(char **result);
3460
3461/*
3462** CAPI3REF: Formatted String Printing Functions
3463**
3464** These routines are work-alikes of the "printf()" family of functions
3465** from the standard C library.
3466** These routines understand most of the common K&R formatting options,
3467** plus some additional non-standard formats, detailed below.
3468** Note that some of the more obscure formatting options from recent
3469** C-library standards are omitted from this implementation.
3470**
3471** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
3472** results into memory obtained from [sqlite3_malloc()].
3473** The strings returned by these two routines should be
3474** released by [sqlite3_free()].  ^Both routines return a
3475** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
3476** memory to hold the resulting string.
3477**
3478** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
3479** the standard C library.  The result is written into the
3480** buffer supplied as the second parameter whose size is given by
3481** the first parameter. Note that the order of the
3482** first two parameters is reversed from snprintf().)^  This is an
3483** historical accident that cannot be fixed without breaking
3484** backwards compatibility.  ^(Note also that sqlite3_snprintf()
3485** returns a pointer to its buffer instead of the number of
3486** characters actually written into the buffer.)^  We admit that
3487** the number of characters written would be a more useful return
3488** value but we cannot change the implementation of sqlite3_snprintf()
3489** now without breaking compatibility.
3490**
3491** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
3492** guarantees that the buffer is always zero-terminated.  ^The first
3493** parameter "n" is the total size of the buffer, including space for
3494** the zero terminator.  So the longest string that can be completely
3495** written will be n-1 characters.
3496**
3497** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
3498**
3499** These routines all implement some additional formatting
3500** options that are useful for constructing SQL statements.
3501** All of the usual printf() formatting options apply.  In addition, there
3502** is are "%q", "%Q", "%w" and "%z" options.
3503**
3504** ^(The %q option works like %s in that it substitutes a nul-terminated
3505** string from the argument list.  But %q also doubles every '\'' character.
3506** %q is designed for use inside a string literal.)^  By doubling each '\''
3507** character it escapes that character and allows it to be inserted into
3508** the string.
3509**
3510** For example, assume the string variable zText contains text as follows:
3511**
3512** <blockquote><pre>
3513**  char *zText = "It's a happy day!";
3514** </pre></blockquote>
3515**
3516** One can use this text in an SQL statement as follows:
3517**
3518** <blockquote><pre>
3519**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
3520**  sqlite3_exec(db, zSQL, 0, 0, 0);
3521**  sqlite3_free(zSQL);
3522** </pre></blockquote>
3523**
3524** Because the %q format string is used, the '\'' character in zText
3525** is escaped and the SQL generated is as follows:
3526**
3527** <blockquote><pre>
3528**  INSERT INTO table1 VALUES('It''s a happy day!')
3529** </pre></blockquote>
3530**
3531** This is correct.  Had we used %s instead of %q, the generated SQL
3532** would have looked like this:
3533**
3534** <blockquote><pre>
3535**  INSERT INTO table1 VALUES('It's a happy day!');
3536** </pre></blockquote>
3537**
3538** This second example is an SQL syntax error.  As a general rule you should
3539** always use %q instead of %s when inserting text into a string literal.
3540**
3541** ^(The %Q option works like %q except it also adds single quotes around
3542** the outside of the total string.  Additionally, if the parameter in the
3543** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
3544** single quotes).)^  So, for example, one could say:
3545**
3546** <blockquote><pre>
3547**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
3548**  sqlite3_exec(db, zSQL, 0, 0, 0);
3549**  sqlite3_free(zSQL);
3550** </pre></blockquote>
3551**
3552** The code above will render a correct SQL statement in the zSQL
3553** variable even if the zText variable is a NULL pointer.
3554**
3555** ^(The "%w" formatting option is like "%q" except that it expects to
3556** be contained within double-quotes instead of single quotes, and it
3557** escapes the double-quote character instead of the single-quote
3558** character.)^  The "%w" formatting option is intended for safely inserting
3559** table and column names into a constructed SQL statement.
3560**
3561** ^(The "%z" formatting option works like "%s" but with the
3562** addition that after the string has been read and copied into
3563** the result, [sqlite3_free()] is called on the input string.)^
3564*/
3565SQLITE_API char *sqlite3_mprintf(const char*,...);
3566SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
3567SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
3568SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
3569
3570/*
3571** CAPI3REF: Memory Allocation Subsystem
3572**
3573** The SQLite core uses these three routines for all of its own
3574** internal memory allocation needs. "Core" in the previous sentence
3575** does not include operating-system specific VFS implementation.  The
3576** Windows VFS uses native malloc() and free() for some operations.
3577**
3578** ^The sqlite3_malloc() routine returns a pointer to a block
3579** of memory at least N bytes in length, where N is the parameter.
3580** ^If sqlite3_malloc() is unable to obtain sufficient free
3581** memory, it returns a NULL pointer.  ^If the parameter N to
3582** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
3583** a NULL pointer.
3584**
3585** ^The sqlite3_malloc64(N) routine works just like
3586** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
3587** of a signed 32-bit integer.
3588**
3589** ^Calling sqlite3_free() with a pointer previously returned
3590** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
3591** that it might be reused.  ^The sqlite3_free() routine is
3592** a no-op if is called with a NULL pointer.  Passing a NULL pointer
3593** to sqlite3_free() is harmless.  After being freed, memory
3594** should neither be read nor written.  Even reading previously freed
3595** memory might result in a segmentation fault or other severe error.
3596** Memory corruption, a segmentation fault, or other severe error
3597** might result if sqlite3_free() is called with a non-NULL pointer that
3598** was not obtained from sqlite3_malloc() or sqlite3_realloc().
3599**
3600** ^The sqlite3_realloc(X,N) interface attempts to resize a
3601** prior memory allocation X to be at least N bytes.
3602** ^If the X parameter to sqlite3_realloc(X,N)
3603** is a NULL pointer then its behavior is identical to calling
3604** sqlite3_malloc(N).
3605** ^If the N parameter to sqlite3_realloc(X,N) is zero or
3606** negative then the behavior is exactly the same as calling
3607** sqlite3_free(X).
3608** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
3609** of at least N bytes in size or NULL if insufficient memory is available.
3610** ^If M is the size of the prior allocation, then min(N,M) bytes
3611** of the prior allocation are copied into the beginning of buffer returned
3612** by sqlite3_realloc(X,N) and the prior allocation is freed.
3613** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
3614** prior allocation is not freed.
3615**
3616** ^The sqlite3_realloc64(X,N) interfaces works the same as
3617** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
3618** of a 32-bit signed integer.
3619**
3620** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
3621** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
3622** sqlite3_msize(X) returns the size of that memory allocation in bytes.
3623** ^The value returned by sqlite3_msize(X) might be larger than the number
3624** of bytes requested when X was allocated.  ^If X is a NULL pointer then
3625** sqlite3_msize(X) returns zero.  If X points to something that is not
3626** the beginning of memory allocation, or if it points to a formerly
3627** valid memory allocation that has now been freed, then the behavior
3628** of sqlite3_msize(X) is undefined and possibly harmful.
3629**
3630** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
3631** sqlite3_malloc64(), and sqlite3_realloc64()
3632** is always aligned to at least an 8 byte boundary, or to a
3633** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
3634** option is used.
3635**
3636** In SQLite version 3.5.0 and 3.5.1, it was possible to define
3637** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
3638** implementation of these routines to be omitted.  That capability
3639** is no longer provided.  Only built-in memory allocators can be used.
3640**
3641** Prior to SQLite version 3.7.10, the Windows OS interface layer called
3642** the system malloc() and free() directly when converting
3643** filenames between the UTF-8 encoding used by SQLite
3644** and whatever filename encoding is used by the particular Windows
3645** installation.  Memory allocation errors were detected, but
3646** they were reported back as [SQLITE_CANTOPEN] or
3647** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
3648**
3649** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
3650** must be either NULL or else pointers obtained from a prior
3651** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
3652** not yet been released.
3653**
3654** The application must not read or write any part of
3655** a block of memory after it has been released using
3656** [sqlite3_free()] or [sqlite3_realloc()].
3657*/
3658SQLITE_API void *sqlite3_malloc(int);
3659SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
3660SQLITE_API void *sqlite3_realloc(void*, int);
3661SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
3662SQLITE_API void sqlite3_free(void*);
3663SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
3664
3665/*
3666** CAPI3REF: Memory Allocator Statistics
3667**
3668** SQLite provides these two interfaces for reporting on the status
3669** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
3670** routines, which form the built-in memory allocation subsystem.
3671**
3672** ^The [sqlite3_memory_used()] routine returns the number of bytes
3673** of memory currently outstanding (malloced but not freed).
3674** ^The [sqlite3_memory_highwater()] routine returns the maximum
3675** value of [sqlite3_memory_used()] since the high-water mark
3676** was last reset.  ^The values returned by [sqlite3_memory_used()] and
3677** [sqlite3_memory_highwater()] include any overhead
3678** added by SQLite in its implementation of [sqlite3_malloc()],
3679** but not overhead added by the any underlying system library
3680** routines that [sqlite3_malloc()] may call.
3681**
3682** ^The memory high-water mark is reset to the current value of
3683** [sqlite3_memory_used()] if and only if the parameter to
3684** [sqlite3_memory_highwater()] is true.  ^The value returned
3685** by [sqlite3_memory_highwater(1)] is the high-water mark
3686** prior to the reset.
3687*/
3688SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
3689SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
3690
3691/*
3692** CAPI3REF: Pseudo-Random Number Generator
3693**
3694** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
3695** select random [ROWID | ROWIDs] when inserting new records into a table that
3696** already uses the largest possible [ROWID].  The PRNG is also used for
3697** the build-in random() and randomblob() SQL functions.  This interface allows
3698** applications to access the same PRNG for other purposes.
3699**
3700** ^A call to this routine stores N bytes of randomness into buffer P.
3701** ^The P parameter can be a NULL pointer.
3702**
3703** ^If this routine has not been previously called or if the previous
3704** call had N less than one or a NULL pointer for P, then the PRNG is
3705** seeded using randomness obtained from the xRandomness method of
3706** the default [sqlite3_vfs] object.
3707** ^If the previous call to this routine had an N of 1 or more and a
3708** non-NULL P then the pseudo-randomness is generated
3709** internally and without recourse to the [sqlite3_vfs] xRandomness
3710** method.
3711*/
3712SQLITE_API void sqlite3_randomness(int N, void *P);
3713
3714/*
3715** CAPI3REF: Compile-Time Authorization Callbacks
3716** METHOD: sqlite3
3717** KEYWORDS: {authorizer callback}
3718**
3719** ^This routine registers an authorizer callback with a particular
3720** [database connection], supplied in the first argument.
3721** ^The authorizer callback is invoked as SQL statements are being compiled
3722** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
3723** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
3724** and [sqlite3_prepare16_v3()].  ^At various
3725** points during the compilation process, as logic is being created
3726** to perform various actions, the authorizer callback is invoked to
3727** see if those actions are allowed.  ^The authorizer callback should
3728** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
3729** specific action but allow the SQL statement to continue to be
3730** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
3731** rejected with an error.  ^If the authorizer callback returns
3732** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
3733** then the [sqlite3_prepare_v2()] or equivalent call that triggered
3734** the authorizer will fail with an error message.
3735**
3736** When the callback returns [SQLITE_OK], that means the operation
3737** requested is ok.  ^When the callback returns [SQLITE_DENY], the
3738** [sqlite3_prepare_v2()] or equivalent call that triggered the
3739** authorizer will fail with an error message explaining that
3740** access is denied.
3741**
3742** ^The first parameter to the authorizer callback is a copy of the third
3743** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
3744** to the callback is an integer [SQLITE_COPY | action code] that specifies
3745** the particular action to be authorized. ^The third through sixth parameters
3746** to the callback are either NULL pointers or zero-terminated strings
3747** that contain additional details about the action to be authorized.
3748** Applications must always be prepared to encounter a NULL pointer in any
3749** of the third through the sixth parameters of the authorization callback.
3750**
3751** ^If the action code is [SQLITE_READ]
3752** and the callback returns [SQLITE_IGNORE] then the
3753** [prepared statement] statement is constructed to substitute
3754** a NULL value in place of the table column that would have
3755** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
3756** return can be used to deny an untrusted user access to individual
3757** columns of a table.
3758** ^When a table is referenced by a [SELECT] but no column values are
3759** extracted from that table (for example in a query like
3760** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
3761** is invoked once for that table with a column name that is an empty string.
3762** ^If the action code is [SQLITE_DELETE] and the callback returns
3763** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
3764** [truncate optimization] is disabled and all rows are deleted individually.
3765**
3766** An authorizer is used when [sqlite3_prepare | preparing]
3767** SQL statements from an untrusted source, to ensure that the SQL statements
3768** do not try to access data they are not allowed to see, or that they do not
3769** try to execute malicious statements that damage the database.  For
3770** example, an application may allow a user to enter arbitrary
3771** SQL queries for evaluation by a database.  But the application does
3772** not want the user to be able to make arbitrary changes to the
3773** database.  An authorizer could then be put in place while the
3774** user-entered SQL is being [sqlite3_prepare | prepared] that
3775** disallows everything except [SELECT] statements.
3776**
3777** Applications that need to process SQL from untrusted sources
3778** might also consider lowering resource limits using [sqlite3_limit()]
3779** and limiting database size using the [max_page_count] [PRAGMA]
3780** in addition to using an authorizer.
3781**
3782** ^(Only a single authorizer can be in place on a database connection
3783** at a time.  Each call to sqlite3_set_authorizer overrides the
3784** previous call.)^  ^Disable the authorizer by installing a NULL callback.
3785** The authorizer is disabled by default.
3786**
3787** The authorizer callback must not do anything that will modify
3788** the database connection that invoked the authorizer callback.
3789** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3790** database connections for the meaning of "modify" in this paragraph.
3791**
3792** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3793** statement might be re-prepared during [sqlite3_step()] due to a
3794** schema change.  Hence, the application should ensure that the
3795** correct authorizer callback remains in place during the [sqlite3_step()].
3796**
3797** ^Note that the authorizer callback is invoked only during
3798** [sqlite3_prepare()] or its variants.  Authorization is not
3799** performed during statement evaluation in [sqlite3_step()], unless
3800** as stated in the previous paragraph, sqlite3_step() invokes
3801** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3802*/
3803SQLITE_API int sqlite3_set_authorizer(
3804  sqlite3*,
3805  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3806  void *pUserData
3807);
3808
3809/*
3810** CAPI3REF: Authorizer Return Codes
3811**
3812** The [sqlite3_set_authorizer | authorizer callback function] must
3813** return either [SQLITE_OK] or one of these two constants in order
3814** to signal SQLite whether or not the action is permitted.  See the
3815** [sqlite3_set_authorizer | authorizer documentation] for additional
3816** information.
3817**
3818** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
3819** returned from the [sqlite3_vtab_on_conflict()] interface.
3820*/
3821#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
3822#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
3823
3824/*
3825** CAPI3REF: Authorizer Action Codes
3826**
3827** The [sqlite3_set_authorizer()] interface registers a callback function
3828** that is invoked to authorize certain SQL statement actions.  The
3829** second parameter to the callback is an integer code that specifies
3830** what action is being authorized.  These are the integer action codes that
3831** the authorizer callback may be passed.
3832**
3833** These action code values signify what kind of operation is to be
3834** authorized.  The 3rd and 4th parameters to the authorization
3835** callback function will be parameters or NULL depending on which of these
3836** codes is used as the second parameter.  ^(The 5th parameter to the
3837** authorizer callback is the name of the database ("main", "temp",
3838** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
3839** is the name of the inner-most trigger or view that is responsible for
3840** the access attempt or NULL if this access attempt is directly from
3841** top-level SQL code.
3842*/
3843/******************************************* 3rd ************ 4th ***********/
3844#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
3845#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3846#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3847#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3848#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3849#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3850#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3851#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3852#define SQLITE_DELETE                9   /* Table Name      NULL            */
3853#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3854#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3855#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3856#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3857#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3858#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3859#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3860#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3861#define SQLITE_INSERT               18   /* Table Name      NULL            */
3862#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3863#define SQLITE_READ                 20   /* Table Name      Column Name     */
3864#define SQLITE_SELECT               21   /* NULL            NULL            */
3865#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3866#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3867#define SQLITE_ATTACH               24   /* Filename        NULL            */
3868#define SQLITE_DETACH               25   /* Database Name   NULL            */
3869#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3870#define SQLITE_REINDEX              27   /* Index Name      NULL            */
3871#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3872#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3873#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3874#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3875#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3876#define SQLITE_COPY                  0   /* No longer used */
3877#define SQLITE_RECURSIVE            33   /* NULL            NULL            */
3878
3879/*
3880** CAPI3REF: Tracing And Profiling Functions
3881** METHOD: sqlite3
3882**
3883** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3884** instead of the routines described here.
3885**
3886** These routines register callback functions that can be used for
3887** tracing and profiling the execution of SQL statements.
3888**
3889** ^The callback function registered by sqlite3_trace() is invoked at
3890** various times when an SQL statement is being run by [sqlite3_step()].
3891** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3892** SQL statement text as the statement first begins executing.
3893** ^(Additional sqlite3_trace() callbacks might occur
3894** as each triggered subprogram is entered.  The callbacks for triggers
3895** contain a UTF-8 SQL comment that identifies the trigger.)^
3896**
3897** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3898** the length of [bound parameter] expansion in the output of sqlite3_trace().
3899**
3900** ^The callback function registered by sqlite3_profile() is invoked
3901** as each SQL statement finishes.  ^The profile callback contains
3902** the original statement text and an estimate of wall-clock time
3903** of how long that statement took to run.  ^The profile callback
3904** time is in units of nanoseconds, however the current implementation
3905** is only capable of millisecond resolution so the six least significant
3906** digits in the time are meaningless.  Future versions of SQLite
3907** might provide greater resolution on the profiler callback.  The
3908** sqlite3_profile() function is considered experimental and is
3909** subject to change in future versions of SQLite.
3910*/
3911SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
3912   void(*xTrace)(void*,const char*), void*);
3913SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
3914   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3915
3916/*
3917** CAPI3REF: SQL Trace Event Codes
3918** KEYWORDS: SQLITE_TRACE
3919**
3920** These constants identify classes of events that can be monitored
3921** using the [sqlite3_trace_v2()] tracing logic.  The third argument
3922** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
3923** the following constants.  ^The first argument to the trace callback
3924** is one of the following constants.
3925**
3926** New tracing constants may be added in future releases.
3927**
3928** ^A trace callback has four arguments: xCallback(T,C,P,X).
3929** ^The T argument is one of the integer type codes above.
3930** ^The C argument is a copy of the context pointer passed in as the
3931** fourth argument to [sqlite3_trace_v2()].
3932** The P and X arguments are pointers whose meanings depend on T.
3933**
3934** <dl>
3935** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3936** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3937** first begins running and possibly at other times during the
3938** execution of the prepared statement, such as at the start of each
3939** trigger subprogram. ^The P argument is a pointer to the
3940** [prepared statement]. ^The X argument is a pointer to a string which
3941** is the unexpanded SQL text of the prepared statement or an SQL comment
3942** that indicates the invocation of a trigger.  ^The callback can compute
3943** the same text that would have been returned by the legacy [sqlite3_trace()]
3944** interface by using the X argument when X begins with "--" and invoking
3945** [sqlite3_expanded_sql(P)] otherwise.
3946**
3947** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3948** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3949** information as is provided by the [sqlite3_profile()] callback.
3950** ^The P argument is a pointer to the [prepared statement] and the
3951** X argument points to a 64-bit integer which is the estimated of
3952** the number of nanosecond that the prepared statement took to run.
3953** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3954**
3955** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3956** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3957** statement generates a single row of result.
3958** ^The P argument is a pointer to the [prepared statement] and the
3959** X argument is unused.
3960**
3961** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3962** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3963** connection closes.
3964** ^The P argument is a pointer to the [database connection] object
3965** and the X argument is unused.
3966** </dl>
3967*/
3968#define SQLITE_TRACE_STMT       0x01
3969#define SQLITE_TRACE_PROFILE    0x02
3970#define SQLITE_TRACE_ROW        0x04
3971#define SQLITE_TRACE_CLOSE      0x08
3972
3973/*
3974** CAPI3REF: SQL Trace Hook
3975** METHOD: sqlite3
3976**
3977** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3978** function X against [database connection] D, using property mask M
3979** and context pointer P.  ^If the X callback is
3980** NULL or if the M mask is zero, then tracing is disabled.  The
3981** M argument should be the bitwise OR-ed combination of
3982** zero or more [SQLITE_TRACE] constants.
3983**
3984** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
3985** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
3986**
3987** ^The X callback is invoked whenever any of the events identified by
3988** mask M occur.  ^The integer return value from the callback is currently
3989** ignored, though this may change in future releases.  Callback
3990** implementations should return zero to ensure future compatibility.
3991**
3992** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3993** ^The T argument is one of the [SQLITE_TRACE]
3994** constants to indicate why the callback was invoked.
3995** ^The C argument is a copy of the context pointer.
3996** The P and X arguments are pointers whose meanings depend on T.
3997**
3998** The sqlite3_trace_v2() interface is intended to replace the legacy
3999** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
4000** are deprecated.
4001*/
4002SQLITE_API int sqlite3_trace_v2(
4003  sqlite3*,
4004  unsigned uMask,
4005  int(*xCallback)(unsigned,void*,void*,void*),
4006  void *pCtx
4007);
4008
4009/*
4010** CAPI3REF: Query Progress Callbacks
4011** METHOD: sqlite3
4012**
4013** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
4014** function X to be invoked periodically during long running calls to
4015** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
4016** database connection D.  An example use for this
4017** interface is to keep a GUI updated during a large query.
4018**
4019** ^The parameter P is passed through as the only parameter to the
4020** callback function X.  ^The parameter N is the approximate number of
4021** [virtual machine instructions] that are evaluated between successive
4022** invocations of the callback X.  ^If N is less than one then the progress
4023** handler is disabled.
4024**
4025** ^Only a single progress handler may be defined at one time per
4026** [database connection]; setting a new progress handler cancels the
4027** old one.  ^Setting parameter X to NULL disables the progress handler.
4028** ^The progress handler is also disabled by setting N to a value less
4029** than 1.
4030**
4031** ^If the progress callback returns non-zero, the operation is
4032** interrupted.  This feature can be used to implement a
4033** "Cancel" button on a GUI progress dialog box.
4034**
4035** The progress handler callback must not do anything that will modify
4036** the database connection that invoked the progress handler.
4037** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4038** database connections for the meaning of "modify" in this paragraph.
4039**
4040*/
4041SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
4042
4043/*
4044** CAPI3REF: Opening A New Database Connection
4045** CONSTRUCTOR: sqlite3
4046**
4047** ^These routines open an SQLite database file as specified by the
4048** filename argument. ^The filename argument is interpreted as UTF-8 for
4049** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
4050** order for sqlite3_open16(). ^(A [database connection] handle is usually
4051** returned in *ppDb, even if an error occurs.  The only exception is that
4052** if SQLite is unable to allocate memory to hold the [sqlite3] object,
4053** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
4054** object.)^ ^(If the database is opened (and/or created) successfully, then
4055** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
4056** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
4057** an English language description of the error following a failure of any
4058** of the sqlite3_open() routines.
4059**
4060** ^The default encoding will be UTF-8 for databases created using
4061** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
4062** created using sqlite3_open16() will be UTF-16 in the native byte order.
4063**
4064** Whether or not an error occurs when it is opened, resources
4065** associated with the [database connection] handle should be released by
4066** passing it to [sqlite3_close()] when it is no longer required.
4067**
4068** The sqlite3_open_v2() interface works like sqlite3_open()
4069** except that it accepts two additional parameters for additional control
4070** over the new database connection.  ^(The flags parameter to
4071** sqlite3_open_v2() can take one of
4072** the following three values, optionally combined with the
4073** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
4074** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
4075**
4076** <dl>
4077** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
4078** <dd>The database is opened in read-only mode.  If the database does not
4079** already exist, an error is returned.</dd>)^
4080**
4081** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
4082** <dd>The database is opened for reading and writing if possible, or reading
4083** only if the file is write protected by the operating system.  In either
4084** case the database must already exist, otherwise an error is returned.</dd>)^
4085**
4086** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
4087** <dd>The database is opened for reading and writing, and is created if
4088** it does not already exist. This is the behavior that is always used for
4089** sqlite3_open() and sqlite3_open16().</dd>)^
4090** </dl>
4091**
4092** If the 3rd parameter to sqlite3_open_v2() is not one of the
4093** combinations shown above optionally combined with other
4094** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
4095** then the behavior is undefined.
4096**
4097** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
4098** opens in the multi-thread [threading mode] as long as the single-thread
4099** mode has not been set at compile-time or start-time.  ^If the
4100** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
4101** in the serialized [threading mode] unless single-thread was
4102** previously selected at compile-time or start-time.
4103** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
4104** eligible to use [shared cache mode], regardless of whether or not shared
4105** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
4106** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
4107** participate in [shared cache mode] even if it is enabled.
4108**
4109** ^The fourth parameter to sqlite3_open_v2() is the name of the
4110** [sqlite3_vfs] object that defines the operating system interface that
4111** the new database connection should use.  ^If the fourth parameter is
4112** a NULL pointer then the default [sqlite3_vfs] object is used.
4113**
4114** ^If the filename is ":memory:", then a private, temporary in-memory database
4115** is created for the connection.  ^This in-memory database will vanish when
4116** the database connection is closed.  Future versions of SQLite might
4117** make use of additional special filenames that begin with the ":" character.
4118** It is recommended that when a database filename actually does begin with
4119** a ":" character you should prefix the filename with a pathname such as
4120** "./" to avoid ambiguity.
4121**
4122** ^If the filename is an empty string, then a private, temporary
4123** on-disk database will be created.  ^This private database will be
4124** automatically deleted as soon as the database connection is closed.
4125**
4126** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
4127**
4128** ^If [URI filename] interpretation is enabled, and the filename argument
4129** begins with "file:", then the filename is interpreted as a URI. ^URI
4130** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
4131** set in the fourth argument to sqlite3_open_v2(), or if it has
4132** been enabled globally using the [SQLITE_CONFIG_URI] option with the
4133** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
4134** As of SQLite version 3.7.7, URI filename interpretation is turned off
4135** by default, but future releases of SQLite might enable URI filename
4136** interpretation by default.  See "[URI filenames]" for additional
4137** information.
4138**
4139** URI filenames are parsed according to RFC 3986. ^If the URI contains an
4140** authority, then it must be either an empty string or the string
4141** "localhost". ^If the authority is not an empty string or "localhost", an
4142** error is returned to the caller. ^The fragment component of a URI, if
4143** present, is ignored.
4144**
4145** ^SQLite uses the path component of the URI as the name of the disk file
4146** which contains the database. ^If the path begins with a '/' character,
4147** then it is interpreted as an absolute path. ^If the path does not begin
4148** with a '/' (meaning that the authority section is omitted from the URI)
4149** then the path is interpreted as a relative path.
4150** ^(On windows, the first component of an absolute path
4151** is a drive specification (e.g. "C:").)^
4152**
4153** [[core URI query parameters]]
4154** The query component of a URI may contain parameters that are interpreted
4155** either by SQLite itself, or by a [VFS | custom VFS implementation].
4156** SQLite and its built-in [VFSes] interpret the
4157** following query parameters:
4158**
4159** <ul>
4160**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
4161**     a VFS object that provides the operating system interface that should
4162**     be used to access the database file on disk. ^If this option is set to
4163**     an empty string the default VFS object is used. ^Specifying an unknown
4164**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
4165**     present, then the VFS specified by the option takes precedence over
4166**     the value passed as the fourth parameter to sqlite3_open_v2().
4167**
4168**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
4169**     "rwc", or "memory". Attempting to set it to any other value is
4170**     an error)^.
4171**     ^If "ro" is specified, then the database is opened for read-only
4172**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
4173**     third argument to sqlite3_open_v2(). ^If the mode option is set to
4174**     "rw", then the database is opened for read-write (but not create)
4175**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
4176**     been set. ^Value "rwc" is equivalent to setting both
4177**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
4178**     set to "memory" then a pure [in-memory database] that never reads
4179**     or writes from disk is used. ^It is an error to specify a value for
4180**     the mode parameter that is less restrictive than that specified by
4181**     the flags passed in the third parameter to sqlite3_open_v2().
4182**
4183**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
4184**     "private". ^Setting it to "shared" is equivalent to setting the
4185**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
4186**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
4187**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
4188**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
4189**     a URI filename, its value overrides any behavior requested by setting
4190**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
4191**
4192**  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
4193**     [powersafe overwrite] property does or does not apply to the
4194**     storage media on which the database file resides.
4195**
4196**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
4197**     which if set disables file locking in rollback journal modes.  This
4198**     is useful for accessing a database on a filesystem that does not
4199**     support locking.  Caution:  Database corruption might result if two
4200**     or more processes write to the same database and any one of those
4201**     processes uses nolock=1.
4202**
4203**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
4204**     parameter that indicates that the database file is stored on
4205**     read-only media.  ^When immutable is set, SQLite assumes that the
4206**     database file cannot be changed, even by a process with higher
4207**     privilege, and so the database is opened read-only and all locking
4208**     and change detection is disabled.  Caution: Setting the immutable
4209**     property on a database file that does in fact change can result
4210**     in incorrect query results and/or [SQLITE_CORRUPT] errors.
4211**     See also: [SQLITE_IOCAP_IMMUTABLE].
4212**
4213** </ul>
4214**
4215** ^Specifying an unknown parameter in the query component of a URI is not an
4216** error.  Future versions of SQLite might understand additional query
4217** parameters.  See "[query parameters with special meaning to SQLite]" for
4218** additional information.
4219**
4220** [[URI filename examples]] <h3>URI filename examples</h3>
4221**
4222** <table border="1" align=center cellpadding=5>
4223** <tr><th> URI filenames <th> Results
4224** <tr><td> file:data.db <td>
4225**          Open the file "data.db" in the current directory.
4226** <tr><td> file:/home/fred/data.db<br>
4227**          file:///home/fred/data.db <br>
4228**          file://localhost/home/fred/data.db <br> <td>
4229**          Open the database file "/home/fred/data.db".
4230** <tr><td> file://darkstar/home/fred/data.db <td>
4231**          An error. "darkstar" is not a recognized authority.
4232** <tr><td style="white-space:nowrap">
4233**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
4234**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
4235**          C:. Note that the %20 escaping in this example is not strictly
4236**          necessary - space characters can be used literally
4237**          in URI filenames.
4238** <tr><td> file:data.db?mode=ro&cache=private <td>
4239**          Open file "data.db" in the current directory for read-only access.
4240**          Regardless of whether or not shared-cache mode is enabled by
4241**          default, use a private cache.
4242** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
4243**          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
4244**          that uses dot-files in place of posix advisory locking.
4245** <tr><td> file:data.db?mode=readonly <td>
4246**          An error. "readonly" is not a valid option for the "mode" parameter.
4247** </table>
4248**
4249** ^URI hexadecimal escape sequences (%HH) are supported within the path and
4250** query components of a URI. A hexadecimal escape sequence consists of a
4251** percent sign - "%" - followed by exactly two hexadecimal digits
4252** specifying an octet value. ^Before the path or query components of a
4253** URI filename are interpreted, they are encoded using UTF-8 and all
4254** hexadecimal escape sequences replaced by a single byte containing the
4255** corresponding octet. If this process generates an invalid UTF-8 encoding,
4256** the results are undefined.
4257**
4258** <b>Note to Windows users:</b>  The encoding used for the filename argument
4259** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
4260** codepage is currently defined.  Filenames containing international
4261** characters must be converted to UTF-8 prior to passing them into
4262** sqlite3_open() or sqlite3_open_v2().
4263**
4264** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
4265** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
4266** features that require the use of temporary files may fail.
4267**
4268** See also: [sqlite3_temp_directory]
4269*/
4270SQLITE_API int sqlite3_open(
4271  const char *filename,   /* Database filename (UTF-8) */
4272  sqlite3 **ppDb          /* OUT: SQLite db handle */
4273);
4274SQLITE_API int sqlite3_open16(
4275  const void *filename,   /* Database filename (UTF-16) */
4276  sqlite3 **ppDb          /* OUT: SQLite db handle */
4277);
4278SQLITE_API int sqlite3_open_v2(
4279  const char *filename,   /* Database filename (UTF-8) */
4280  sqlite3 **ppDb,         /* OUT: SQLite db handle */
4281  int flags,              /* Flags */
4282  const char *zVfs        /* Name of VFS module to use */
4283);
4284
4285/*
4286** CAPI3REF: Obtain Values For URI Parameters
4287**
4288** These are utility routines, useful to VFS implementations, that check
4289** to see if a database file was a URI that contained a specific query
4290** parameter, and if so obtains the value of that query parameter.
4291**
4292** If F is the database filename pointer passed into the xOpen() method of
4293** a VFS implementation when the flags parameter to xOpen() has one or
4294** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
4295** P is the name of the query parameter, then
4296** sqlite3_uri_parameter(F,P) returns the value of the P
4297** parameter if it exists or a NULL pointer if P does not appear as a
4298** query parameter on F.  If P is a query parameter of F
4299** has no explicit value, then sqlite3_uri_parameter(F,P) returns
4300** a pointer to an empty string.
4301**
4302** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
4303** parameter and returns true (1) or false (0) according to the value
4304** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
4305** value of query parameter P is one of "yes", "true", or "on" in any
4306** case or if the value begins with a non-zero number.  The
4307** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
4308** query parameter P is one of "no", "false", or "off" in any case or
4309** if the value begins with a numeric zero.  If P is not a query
4310** parameter on F or if the value of P is does not match any of the
4311** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
4312**
4313** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
4314** 64-bit signed integer and returns that integer, or D if P does not
4315** exist.  If the value of P is something other than an integer, then
4316** zero is returned.
4317**
4318** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
4319** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
4320** is not a database file pathname pointer that SQLite passed into the xOpen
4321** VFS method, then the behavior of this routine is undefined and probably
4322** undesirable.
4323*/
4324SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
4325SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
4326SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
4327
4328
4329/*
4330** CAPI3REF: Error Codes And Messages
4331** METHOD: sqlite3
4332**
4333** ^If the most recent sqlite3_* API call associated with
4334** [database connection] D failed, then the sqlite3_errcode(D) interface
4335** returns the numeric [result code] or [extended result code] for that
4336** API call.
4337** If the most recent API call was successful,
4338** then the return value from sqlite3_errcode() is undefined.
4339** ^The sqlite3_extended_errcode()
4340** interface is the same except that it always returns the
4341** [extended result code] even when extended result codes are
4342** disabled.
4343**
4344** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
4345** text that describes the error, as either UTF-8 or UTF-16 respectively.
4346** ^(Memory to hold the error message string is managed internally.
4347** The application does not need to worry about freeing the result.
4348** However, the error string might be overwritten or deallocated by
4349** subsequent calls to other SQLite interface functions.)^
4350**
4351** ^The sqlite3_errstr() interface returns the English-language text
4352** that describes the [result code], as UTF-8.
4353** ^(Memory to hold the error message string is managed internally
4354** and must not be freed by the application)^.
4355**
4356** When the serialized [threading mode] is in use, it might be the
4357** case that a second error occurs on a separate thread in between
4358** the time of the first error and the call to these interfaces.
4359** When that happens, the second error will be reported since these
4360** interfaces always report the most recent result.  To avoid
4361** this, each thread can obtain exclusive use of the [database connection] D
4362** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
4363** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
4364** all calls to the interfaces listed here are completed.
4365**
4366** If an interface fails with SQLITE_MISUSE, that means the interface
4367** was invoked incorrectly by the application.  In that case, the
4368** error code and message may or may not be set.
4369*/
4370SQLITE_API int sqlite3_errcode(sqlite3 *db);
4371SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
4372SQLITE_API const char *sqlite3_errmsg(sqlite3*);
4373SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
4374SQLITE_API const char *sqlite3_errstr(int);
4375
4376/*
4377** CAPI3REF: Prepared Statement Object
4378** KEYWORDS: {prepared statement} {prepared statements}
4379**
4380** An instance of this object represents a single SQL statement that
4381** has been compiled into binary form and is ready to be evaluated.
4382**
4383** Think of each SQL statement as a separate computer program.  The
4384** original SQL text is source code.  A prepared statement object
4385** is the compiled object code.  All SQL must be converted into a
4386** prepared statement before it can be run.
4387**
4388** The life-cycle of a prepared statement object usually goes like this:
4389**
4390** <ol>
4391** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
4392** <li> Bind values to [parameters] using the sqlite3_bind_*()
4393**      interfaces.
4394** <li> Run the SQL by calling [sqlite3_step()] one or more times.
4395** <li> Reset the prepared statement using [sqlite3_reset()] then go back
4396**      to step 2.  Do this zero or more times.
4397** <li> Destroy the object using [sqlite3_finalize()].
4398** </ol>
4399*/
4400typedef struct sqlite3_stmt sqlite3_stmt;
4401
4402/*
4403** CAPI3REF: Run-time Limits
4404** METHOD: sqlite3
4405**
4406** ^(This interface allows the size of various constructs to be limited
4407** on a connection by connection basis.  The first parameter is the
4408** [database connection] whose limit is to be set or queried.  The
4409** second parameter is one of the [limit categories] that define a
4410** class of constructs to be size limited.  The third parameter is the
4411** new limit for that construct.)^
4412**
4413** ^If the new limit is a negative number, the limit is unchanged.
4414** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
4415** [limits | hard upper bound]
4416** set at compile-time by a C preprocessor macro called
4417** [limits | SQLITE_MAX_<i>NAME</i>].
4418** (The "_LIMIT_" in the name is changed to "_MAX_".))^
4419** ^Attempts to increase a limit above its hard upper bound are
4420** silently truncated to the hard upper bound.
4421**
4422** ^Regardless of whether or not the limit was changed, the
4423** [sqlite3_limit()] interface returns the prior value of the limit.
4424** ^Hence, to find the current value of a limit without changing it,
4425** simply invoke this interface with the third parameter set to -1.
4426**
4427** Run-time limits are intended for use in applications that manage
4428** both their own internal database and also databases that are controlled
4429** by untrusted external sources.  An example application might be a
4430** web browser that has its own databases for storing history and
4431** separate databases controlled by JavaScript applications downloaded
4432** off the Internet.  The internal databases can be given the
4433** large, default limits.  Databases managed by external sources can
4434** be given much smaller limits designed to prevent a denial of service
4435** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
4436** interface to further control untrusted SQL.  The size of the database
4437** created by an untrusted script can be contained using the
4438** [max_page_count] [PRAGMA].
4439**
4440** New run-time limit categories may be added in future releases.
4441*/
4442SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
4443
4444/*
4445** CAPI3REF: Run-Time Limit Categories
4446** KEYWORDS: {limit category} {*limit categories}
4447**
4448** These constants define various performance limits
4449** that can be lowered at run-time using [sqlite3_limit()].
4450** The synopsis of the meanings of the various limits is shown below.
4451** Additional information is available at [limits | Limits in SQLite].
4452**
4453** <dl>
4454** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
4455** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
4456**
4457** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
4458** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
4459**
4460** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
4461** <dd>The maximum number of columns in a table definition or in the
4462** result set of a [SELECT] or the maximum number of columns in an index
4463** or in an ORDER BY or GROUP BY clause.</dd>)^
4464**
4465** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
4466** <dd>The maximum depth of the parse tree on any expression.</dd>)^
4467**
4468** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
4469** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
4470**
4471** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
4472** <dd>The maximum number of instructions in a virtual machine program
4473** used to implement an SQL statement.  If [sqlite3_prepare_v2()] or
4474** the equivalent tries to allocate space for more than this many opcodes
4475** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
4476**
4477** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
4478** <dd>The maximum number of arguments on a function.</dd>)^
4479**
4480** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
4481** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
4482**
4483** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
4484** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
4485** <dd>The maximum length of the pattern argument to the [LIKE] or
4486** [GLOB] operators.</dd>)^
4487**
4488** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
4489** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
4490** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4491**
4492** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
4493** <dd>The maximum depth of recursion for triggers.</dd>)^
4494**
4495** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
4496** <dd>The maximum number of auxiliary worker threads that a single
4497** [prepared statement] may start.</dd>)^
4498** </dl>
4499*/
4500#define SQLITE_LIMIT_LENGTH                    0
4501#define SQLITE_LIMIT_SQL_LENGTH                1
4502#define SQLITE_LIMIT_COLUMN                    2
4503#define SQLITE_LIMIT_EXPR_DEPTH                3
4504#define SQLITE_LIMIT_COMPOUND_SELECT           4
4505#define SQLITE_LIMIT_VDBE_OP                   5
4506#define SQLITE_LIMIT_FUNCTION_ARG              6
4507#define SQLITE_LIMIT_ATTACHED                  7
4508#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
4509#define SQLITE_LIMIT_VARIABLE_NUMBER           9
4510#define SQLITE_LIMIT_TRIGGER_DEPTH            10
4511#define SQLITE_LIMIT_WORKER_THREADS           11
4512
4513/*
4514** CAPI3REF: Prepare Flags
4515**
4516** These constants define various flags that can be passed into
4517** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
4518** [sqlite3_prepare16_v3()] interfaces.
4519**
4520** New flags may be added in future releases of SQLite.
4521**
4522** <dl>
4523** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
4524** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
4525** that the prepared statement will be retained for a long time and
4526** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
4527** and [sqlite3_prepare16_v3()] assume that the prepared statement will
4528** be used just once or at most a few times and then destroyed using
4529** [sqlite3_finalize()] relatively soon. The current implementation acts
4530** on this hint by avoiding the use of [lookaside memory] so as not to
4531** deplete the limited store of lookaside memory. Future versions of
4532** SQLite may act on this hint differently.
4533** </dl>
4534*/
4535#define SQLITE_PREPARE_PERSISTENT              0x01
4536
4537/*
4538** CAPI3REF: Compiling An SQL Statement
4539** KEYWORDS: {SQL statement compiler}
4540** METHOD: sqlite3
4541** CONSTRUCTOR: sqlite3_stmt
4542**
4543** To execute an SQL statement, it must first be compiled into a byte-code
4544** program using one of these routines.  Or, in other words, these routines
4545** are constructors for the [prepared statement] object.
4546**
4547** The preferred routine to use is [sqlite3_prepare_v2()].  The
4548** [sqlite3_prepare()] interface is legacy and should be avoided.
4549** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
4550** for special purposes.
4551**
4552** The use of the UTF-8 interfaces is preferred, as SQLite currently
4553** does all parsing using UTF-8.  The UTF-16 interfaces are provided
4554** as a convenience.  The UTF-16 interfaces work by converting the
4555** input text into UTF-8, then invoking the corresponding UTF-8 interface.
4556**
4557** The first argument, "db", is a [database connection] obtained from a
4558** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
4559** [sqlite3_open16()].  The database connection must not have been closed.
4560**
4561** The second argument, "zSql", is the statement to be compiled, encoded
4562** as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),
4563** and sqlite3_prepare_v3()
4564** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
4565** and sqlite3_prepare16_v3() use UTF-16.
4566**
4567** ^If the nByte argument is negative, then zSql is read up to the
4568** first zero terminator. ^If nByte is positive, then it is the
4569** number of bytes read from zSql.  ^If nByte is zero, then no prepared
4570** statement is generated.
4571** If the caller knows that the supplied string is nul-terminated, then
4572** there is a small performance advantage to passing an nByte parameter that
4573** is the number of bytes in the input string <i>including</i>
4574** the nul-terminator.
4575**
4576** ^If pzTail is not NULL then *pzTail is made to point to the first byte
4577** past the end of the first SQL statement in zSql.  These routines only
4578** compile the first statement in zSql, so *pzTail is left pointing to
4579** what remains uncompiled.
4580**
4581** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
4582** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
4583** to NULL.  ^If the input text contains no SQL (if the input is an empty
4584** string or a comment) then *ppStmt is set to NULL.
4585** The calling procedure is responsible for deleting the compiled
4586** SQL statement using [sqlite3_finalize()] after it has finished with it.
4587** ppStmt may not be NULL.
4588**
4589** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
4590** otherwise an [error code] is returned.
4591**
4592** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
4593** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
4594** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
4595** are retained for backwards compatibility, but their use is discouraged.
4596** ^In the "vX" interfaces, the prepared statement
4597** that is returned (the [sqlite3_stmt] object) contains a copy of the
4598** original SQL text. This causes the [sqlite3_step()] interface to
4599** behave differently in three ways:
4600**
4601** <ol>
4602** <li>
4603** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
4604** always used to do, [sqlite3_step()] will automatically recompile the SQL
4605** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
4606** retries will occur before sqlite3_step() gives up and returns an error.
4607** </li>
4608**
4609** <li>
4610** ^When an error occurs, [sqlite3_step()] will return one of the detailed
4611** [error codes] or [extended error codes].  ^The legacy behavior was that
4612** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
4613** and the application would have to make a second call to [sqlite3_reset()]
4614** in order to find the underlying cause of the problem. With the "v2" prepare
4615** interfaces, the underlying reason for the error is returned immediately.
4616** </li>
4617**
4618** <li>
4619** ^If the specific value bound to [parameter | host parameter] in the
4620** WHERE clause might influence the choice of query plan for a statement,
4621** then the statement will be automatically recompiled, as if there had been
4622** a schema change, on the first  [sqlite3_step()] call following any change
4623** to the [sqlite3_bind_text | bindings] of that [parameter].
4624** ^The specific value of WHERE-clause [parameter] might influence the
4625** choice of query plan if the parameter is the left-hand side of a [LIKE]
4626** or [GLOB] operator or if the parameter is compared to an indexed column
4627** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
4628** </li>
4629**
4630** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
4631** the extra prepFlags parameter, which is a bit array consisting of zero or
4632** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags.  ^The
4633** sqlite3_prepare_v2() interface works exactly the same as
4634** sqlite3_prepare_v3() with a zero prepFlags parameter.
4635** </ol>
4636*/
4637SQLITE_API int sqlite3_prepare(
4638  sqlite3 *db,            /* Database handle */
4639  const char *zSql,       /* SQL statement, UTF-8 encoded */
4640  int nByte,              /* Maximum length of zSql in bytes. */
4641  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4642  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
4643);
4644SQLITE_API int sqlite3_prepare_v2(
4645  sqlite3 *db,            /* Database handle */
4646  const char *zSql,       /* SQL statement, UTF-8 encoded */
4647  int nByte,              /* Maximum length of zSql in bytes. */
4648  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4649  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
4650);
4651SQLITE_API int sqlite3_prepare_v3(
4652  sqlite3 *db,            /* Database handle */
4653  const char *zSql,       /* SQL statement, UTF-8 encoded */
4654  int nByte,              /* Maximum length of zSql in bytes. */
4655  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4656  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4657  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
4658);
4659SQLITE_API int sqlite3_prepare16(
4660  sqlite3 *db,            /* Database handle */
4661  const void *zSql,       /* SQL statement, UTF-16 encoded */
4662  int nByte,              /* Maximum length of zSql in bytes. */
4663  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4664  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
4665);
4666SQLITE_API int sqlite3_prepare16_v2(
4667  sqlite3 *db,            /* Database handle */
4668  const void *zSql,       /* SQL statement, UTF-16 encoded */
4669  int nByte,              /* Maximum length of zSql in bytes. */
4670  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4671  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
4672);
4673SQLITE_API int sqlite3_prepare16_v3(
4674  sqlite3 *db,            /* Database handle */
4675  const void *zSql,       /* SQL statement, UTF-16 encoded */
4676  int nByte,              /* Maximum length of zSql in bytes. */
4677  unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
4678  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
4679  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
4680);
4681
4682/*
4683** CAPI3REF: Retrieving Statement SQL
4684** METHOD: sqlite3_stmt
4685**
4686** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
4687** SQL text used to create [prepared statement] P if P was
4688** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
4689** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
4690** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
4691** string containing the SQL text of prepared statement P with
4692** [bound parameters] expanded.
4693**
4694** ^(For example, if a prepared statement is created using the SQL
4695** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
4696** and parameter :xyz is unbound, then sqlite3_sql() will return
4697** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
4698** will return "SELECT 2345,NULL".)^
4699**
4700** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
4701** is available to hold the result, or if the result would exceed the
4702** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
4703**
4704** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
4705** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
4706** option causes sqlite3_expanded_sql() to always return NULL.
4707**
4708** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
4709** automatically freed when the prepared statement is finalized.
4710** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
4711** is obtained from [sqlite3_malloc()] and must be free by the application
4712** by passing it to [sqlite3_free()].
4713*/
4714SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
4715SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
4716
4717/*
4718** CAPI3REF: Determine If An SQL Statement Writes The Database
4719** METHOD: sqlite3_stmt
4720**
4721** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
4722** and only if the [prepared statement] X makes no direct changes to
4723** the content of the database file.
4724**
4725** Note that [application-defined SQL functions] or
4726** [virtual tables] might change the database indirectly as a side effect.
4727** ^(For example, if an application defines a function "eval()" that
4728** calls [sqlite3_exec()], then the following SQL statement would
4729** change the database file through side-effects:
4730**
4731** <blockquote><pre>
4732**    SELECT eval('DELETE FROM t1') FROM t2;
4733** </pre></blockquote>
4734**
4735** But because the [SELECT] statement does not change the database file
4736** directly, sqlite3_stmt_readonly() would still return true.)^
4737**
4738** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
4739** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
4740** since the statements themselves do not actually modify the database but
4741** rather they control the timing of when other statements modify the
4742** database.  ^The [ATTACH] and [DETACH] statements also cause
4743** sqlite3_stmt_readonly() to return true since, while those statements
4744** change the configuration of a database connection, they do not make
4745** changes to the content of the database files on disk.
4746** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
4747** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
4748** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
4749** sqlite3_stmt_readonly() returns false for those commands.
4750*/
4751SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
4752
4753/*
4754** CAPI3REF: Determine If A Prepared Statement Has Been Reset
4755** METHOD: sqlite3_stmt
4756**
4757** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
4758** [prepared statement] S has been stepped at least once using
4759** [sqlite3_step(S)] but has neither run to completion (returned
4760** [SQLITE_DONE] from [sqlite3_step(S)]) nor
4761** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
4762** interface returns false if S is a NULL pointer.  If S is not a
4763** NULL pointer and is not a pointer to a valid [prepared statement]
4764** object, then the behavior is undefined and probably undesirable.
4765**
4766** This interface can be used in combination [sqlite3_next_stmt()]
4767** to locate all prepared statements associated with a database
4768** connection that are in need of being reset.  This can be used,
4769** for example, in diagnostic routines to search for prepared
4770** statements that are holding a transaction open.
4771*/
4772SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
4773
4774/*
4775** CAPI3REF: Dynamically Typed Value Object
4776** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
4777**
4778** SQLite uses the sqlite3_value object to represent all values
4779** that can be stored in a database table. SQLite uses dynamic typing
4780** for the values it stores.  ^Values stored in sqlite3_value objects
4781** can be integers, floating point values, strings, BLOBs, or NULL.
4782**
4783** An sqlite3_value object may be either "protected" or "unprotected".
4784** Some interfaces require a protected sqlite3_value.  Other interfaces
4785** will accept either a protected or an unprotected sqlite3_value.
4786** Every interface that accepts sqlite3_value arguments specifies
4787** whether or not it requires a protected sqlite3_value.  The
4788** [sqlite3_value_dup()] interface can be used to construct a new
4789** protected sqlite3_value from an unprotected sqlite3_value.
4790**
4791** The terms "protected" and "unprotected" refer to whether or not
4792** a mutex is held.  An internal mutex is held for a protected
4793** sqlite3_value object but no mutex is held for an unprotected
4794** sqlite3_value object.  If SQLite is compiled to be single-threaded
4795** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
4796** or if SQLite is run in one of reduced mutex modes
4797** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
4798** then there is no distinction between protected and unprotected
4799** sqlite3_value objects and they can be used interchangeably.  However,
4800** for maximum code portability it is recommended that applications
4801** still make the distinction between protected and unprotected
4802** sqlite3_value objects even when not strictly required.
4803**
4804** ^The sqlite3_value objects that are passed as parameters into the
4805** implementation of [application-defined SQL functions] are protected.
4806** ^The sqlite3_value object returned by
4807** [sqlite3_column_value()] is unprotected.
4808** Unprotected sqlite3_value objects may only be used with
4809** [sqlite3_result_value()] and [sqlite3_bind_value()].
4810** The [sqlite3_value_blob | sqlite3_value_type()] family of
4811** interfaces require protected sqlite3_value objects.
4812*/
4813typedef struct sqlite3_value sqlite3_value;
4814
4815/*
4816** CAPI3REF: SQL Function Context Object
4817**
4818** The context in which an SQL function executes is stored in an
4819** sqlite3_context object.  ^A pointer to an sqlite3_context object
4820** is always first parameter to [application-defined SQL functions].
4821** The application-defined SQL function implementation will pass this
4822** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
4823** [sqlite3_aggregate_context()], [sqlite3_user_data()],
4824** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
4825** and/or [sqlite3_set_auxdata()].
4826*/
4827typedef struct sqlite3_context sqlite3_context;
4828
4829/*
4830** CAPI3REF: Binding Values To Prepared Statements
4831** KEYWORDS: {host parameter} {host parameters} {host parameter name}
4832** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
4833** METHOD: sqlite3_stmt
4834**
4835** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
4836** literals may be replaced by a [parameter] that matches one of following
4837** templates:
4838**
4839** <ul>
4840** <li>  ?
4841** <li>  ?NNN
4842** <li>  :VVV
4843** <li>  @VVV
4844** <li>  $VVV
4845** </ul>
4846**
4847** In the templates above, NNN represents an integer literal,
4848** and VVV represents an alphanumeric identifier.)^  ^The values of these
4849** parameters (also called "host parameter names" or "SQL parameters")
4850** can be set using the sqlite3_bind_*() routines defined here.
4851**
4852** ^The first argument to the sqlite3_bind_*() routines is always
4853** a pointer to the [sqlite3_stmt] object returned from
4854** [sqlite3_prepare_v2()] or its variants.
4855**
4856** ^The second argument is the index of the SQL parameter to be set.
4857** ^The leftmost SQL parameter has an index of 1.  ^When the same named
4858** SQL parameter is used more than once, second and subsequent
4859** occurrences have the same index as the first occurrence.
4860** ^The index for named parameters can be looked up using the
4861** [sqlite3_bind_parameter_index()] API if desired.  ^The index
4862** for "?NNN" parameters is the value of NNN.
4863** ^The NNN value must be between 1 and the [sqlite3_limit()]
4864** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
4865**
4866** ^The third argument is the value to bind to the parameter.
4867** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4868** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
4869** is ignored and the end result is the same as sqlite3_bind_null().
4870**
4871** ^(In those routines that have a fourth argument, its value is the
4872** number of bytes in the parameter.  To be clear: the value is the
4873** number of <u>bytes</u> in the value, not the number of characters.)^
4874** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
4875** is negative, then the length of the string is
4876** the number of bytes up to the first zero terminator.
4877** If the fourth parameter to sqlite3_bind_blob() is negative, then
4878** the behavior is undefined.
4879** If a non-negative fourth parameter is provided to sqlite3_bind_text()
4880** or sqlite3_bind_text16() or sqlite3_bind_text64() then
4881** that parameter must be the byte offset
4882** where the NUL terminator would occur assuming the string were NUL
4883** terminated.  If any NUL characters occur at byte offsets less than
4884** the value of the fourth parameter then the resulting string value will
4885** contain embedded NULs.  The result of expressions involving strings
4886** with embedded NULs is undefined.
4887**
4888** ^The fifth argument to the BLOB and string binding interfaces
4889** is a destructor used to dispose of the BLOB or
4890** string after SQLite has finished with it.  ^The destructor is called
4891** to dispose of the BLOB or string even if the call to bind API fails.
4892** ^If the fifth argument is
4893** the special value [SQLITE_STATIC], then SQLite assumes that the
4894** information is in static, unmanaged space and does not need to be freed.
4895** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
4896** SQLite makes its own private copy of the data immediately, before
4897** the sqlite3_bind_*() routine returns.
4898**
4899** ^The sixth argument to sqlite3_bind_text64() must be one of
4900** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
4901** to specify the encoding of the text in the third parameter.  If
4902** the sixth argument to sqlite3_bind_text64() is not one of the
4903** allowed values shown above, or if the text encoding is different
4904** from the encoding specified by the sixth parameter, then the behavior
4905** is undefined.
4906**
4907** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
4908** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
4909** (just an integer to hold its size) while it is being processed.
4910** Zeroblobs are intended to serve as placeholders for BLOBs whose
4911** content is later written using
4912** [sqlite3_blob_open | incremental BLOB I/O] routines.
4913** ^A negative value for the zeroblob results in a zero-length BLOB.
4914**
4915** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
4916** [prepared statement] S to have an SQL value of NULL, but to also be
4917** associated with the pointer P of type T.  ^D is either a NULL pointer or
4918** a pointer to a destructor function for P. ^SQLite will invoke the
4919** destructor D with a single argument of P when it is finished using
4920** P.  The T parameter should be a static string, preferably a string
4921** literal. The sqlite3_bind_pointer() routine is part of the
4922** [pointer passing interface] added for SQLite 3.20.0.
4923**
4924** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4925** for the [prepared statement] or with a prepared statement for which
4926** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4927** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
4928** routine is passed a [prepared statement] that has been finalized, the
4929** result is undefined and probably harmful.
4930**
4931** ^Bindings are not cleared by the [sqlite3_reset()] routine.
4932** ^Unbound parameters are interpreted as NULL.
4933**
4934** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
4935** [error code] if anything goes wrong.
4936** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
4937** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
4938** [SQLITE_MAX_LENGTH].
4939** ^[SQLITE_RANGE] is returned if the parameter
4940** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
4941**
4942** See also: [sqlite3_bind_parameter_count()],
4943** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
4944*/
4945SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
4946SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
4947                        void(*)(void*));
4948SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
4949SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
4950SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
4951SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
4952SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
4953SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
4954SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
4955                         void(*)(void*), unsigned char encoding);
4956SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
4957SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
4958SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
4959SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
4960
4961/*
4962** CAPI3REF: Number Of SQL Parameters
4963** METHOD: sqlite3_stmt
4964**
4965** ^This routine can be used to find the number of [SQL parameters]
4966** in a [prepared statement].  SQL parameters are tokens of the
4967** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
4968** placeholders for values that are [sqlite3_bind_blob | bound]
4969** to the parameters at a later time.
4970**
4971** ^(This routine actually returns the index of the largest (rightmost)
4972** parameter. For all forms except ?NNN, this will correspond to the
4973** number of unique parameters.  If parameters of the ?NNN form are used,
4974** there may be gaps in the list.)^
4975**
4976** See also: [sqlite3_bind_blob|sqlite3_bind()],
4977** [sqlite3_bind_parameter_name()], and
4978** [sqlite3_bind_parameter_index()].
4979*/
4980SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
4981
4982/*
4983** CAPI3REF: Name Of A Host Parameter
4984** METHOD: sqlite3_stmt
4985**
4986** ^The sqlite3_bind_parameter_name(P,N) interface returns
4987** the name of the N-th [SQL parameter] in the [prepared statement] P.
4988** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
4989** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
4990** respectively.
4991** In other words, the initial ":" or "$" or "@" or "?"
4992** is included as part of the name.)^
4993** ^Parameters of the form "?" without a following integer have no name
4994** and are referred to as "nameless" or "anonymous parameters".
4995**
4996** ^The first host parameter has an index of 1, not 0.
4997**
4998** ^If the value N is out of range or if the N-th parameter is
4999** nameless, then NULL is returned.  ^The returned string is
5000** always in UTF-8 encoding even if the named parameter was
5001** originally specified as UTF-16 in [sqlite3_prepare16()],
5002** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
5003**
5004** See also: [sqlite3_bind_blob|sqlite3_bind()],
5005** [sqlite3_bind_parameter_count()], and
5006** [sqlite3_bind_parameter_index()].
5007*/
5008SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
5009
5010/*
5011** CAPI3REF: Index Of A Parameter With A Given Name
5012** METHOD: sqlite3_stmt
5013**
5014** ^Return the index of an SQL parameter given its name.  ^The
5015** index value returned is suitable for use as the second
5016** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
5017** is returned if no matching parameter is found.  ^The parameter
5018** name must be given in UTF-8 even if the original statement
5019** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
5020** [sqlite3_prepare16_v3()].
5021**
5022** See also: [sqlite3_bind_blob|sqlite3_bind()],
5023** [sqlite3_bind_parameter_count()], and
5024** [sqlite3_bind_parameter_name()].
5025*/
5026SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
5027
5028/*
5029** CAPI3REF: Reset All Bindings On A Prepared Statement
5030** METHOD: sqlite3_stmt
5031**
5032** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
5033** the [sqlite3_bind_blob | bindings] on a [prepared statement].
5034** ^Use this routine to reset all host parameters to NULL.
5035*/
5036SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
5037
5038/*
5039** CAPI3REF: Number Of Columns In A Result Set
5040** METHOD: sqlite3_stmt
5041**
5042** ^Return the number of columns in the result set returned by the
5043** [prepared statement]. ^If this routine returns 0, that means the
5044** [prepared statement] returns no data (for example an [UPDATE]).
5045** ^However, just because this routine returns a positive number does not
5046** mean that one or more rows of data will be returned.  ^A SELECT statement
5047** will always have a positive sqlite3_column_count() but depending on the
5048** WHERE clause constraints and the table content, it might return no rows.
5049**
5050** See also: [sqlite3_data_count()]
5051*/
5052SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
5053
5054/*
5055** CAPI3REF: Column Names In A Result Set
5056** METHOD: sqlite3_stmt
5057**
5058** ^These routines return the name assigned to a particular column
5059** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
5060** interface returns a pointer to a zero-terminated UTF-8 string
5061** and sqlite3_column_name16() returns a pointer to a zero-terminated
5062** UTF-16 string.  ^The first parameter is the [prepared statement]
5063** that implements the [SELECT] statement. ^The second parameter is the
5064** column number.  ^The leftmost column is number 0.
5065**
5066** ^The returned string pointer is valid until either the [prepared statement]
5067** is destroyed by [sqlite3_finalize()] or until the statement is automatically
5068** reprepared by the first call to [sqlite3_step()] for a particular run
5069** or until the next call to
5070** sqlite3_column_name() or sqlite3_column_name16() on the same column.
5071**
5072** ^If sqlite3_malloc() fails during the processing of either routine
5073** (for example during a conversion from UTF-8 to UTF-16) then a
5074** NULL pointer is returned.
5075**
5076** ^The name of a result column is the value of the "AS" clause for
5077** that column, if there is an AS clause.  If there is no AS clause
5078** then the name of the column is unspecified and may change from
5079** one release of SQLite to the next.
5080*/
5081SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
5082SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
5083
5084/*
5085** CAPI3REF: Source Of Data In A Query Result
5086** METHOD: sqlite3_stmt
5087**
5088** ^These routines provide a means to determine the database, table, and
5089** table column that is the origin of a particular result column in
5090** [SELECT] statement.
5091** ^The name of the database or table or column can be returned as
5092** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
5093** the database name, the _table_ routines return the table name, and
5094** the origin_ routines return the column name.
5095** ^The returned string is valid until the [prepared statement] is destroyed
5096** using [sqlite3_finalize()] or until the statement is automatically
5097** reprepared by the first call to [sqlite3_step()] for a particular run
5098** or until the same information is requested
5099** again in a different encoding.
5100**
5101** ^The names returned are the original un-aliased names of the
5102** database, table, and column.
5103**
5104** ^The first argument to these interfaces is a [prepared statement].
5105** ^These functions return information about the Nth result column returned by
5106** the statement, where N is the second function argument.
5107** ^The left-most column is column 0 for these routines.
5108**
5109** ^If the Nth column returned by the statement is an expression or
5110** subquery and is not a column value, then all of these functions return
5111** NULL.  ^These routine might also return NULL if a memory allocation error
5112** occurs.  ^Otherwise, they return the name of the attached database, table,
5113** or column that query result column was extracted from.
5114**
5115** ^As with all other SQLite APIs, those whose names end with "16" return
5116** UTF-16 encoded strings and the other functions return UTF-8.
5117**
5118** ^These APIs are only available if the library was compiled with the
5119** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
5120**
5121** If two or more threads call one or more of these routines against the same
5122** prepared statement and column at the same time then the results are
5123** undefined.
5124**
5125** If two or more threads call one or more
5126** [sqlite3_column_database_name | column metadata interfaces]
5127** for the same [prepared statement] and result column
5128** at the same time then the results are undefined.
5129*/
5130SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
5131SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
5132SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
5133SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
5134SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
5135SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
5136
5137/*
5138** CAPI3REF: Declared Datatype Of A Query Result
5139** METHOD: sqlite3_stmt
5140**
5141** ^(The first parameter is a [prepared statement].
5142** If this statement is a [SELECT] statement and the Nth column of the
5143** returned result set of that [SELECT] is a table column (not an
5144** expression or subquery) then the declared type of the table
5145** column is returned.)^  ^If the Nth column of the result set is an
5146** expression or subquery, then a NULL pointer is returned.
5147** ^The returned string is always UTF-8 encoded.
5148**
5149** ^(For example, given the database schema:
5150**
5151** CREATE TABLE t1(c1 VARIANT);
5152**
5153** and the following statement to be compiled:
5154**
5155** SELECT c1 + 1, c1 FROM t1;
5156**
5157** this routine would return the string "VARIANT" for the second result
5158** column (i==1), and a NULL pointer for the first result column (i==0).)^
5159**
5160** ^SQLite uses dynamic run-time typing.  ^So just because a column
5161** is declared to contain a particular type does not mean that the
5162** data stored in that column is of the declared type.  SQLite is
5163** strongly typed, but the typing is dynamic not static.  ^Type
5164** is associated with individual values, not with the containers
5165** used to hold those values.
5166*/
5167SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
5168SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
5169
5170/*
5171** CAPI3REF: Evaluate An SQL Statement
5172** METHOD: sqlite3_stmt
5173**
5174** After a [prepared statement] has been prepared using any of
5175** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
5176** or [sqlite3_prepare16_v3()] or one of the legacy
5177** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
5178** must be called one or more times to evaluate the statement.
5179**
5180** The details of the behavior of the sqlite3_step() interface depend
5181** on whether the statement was prepared using the newer "vX" interfaces
5182** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
5183** [sqlite3_prepare16_v2()] or the older legacy
5184** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
5185** new "vX" interface is recommended for new applications but the legacy
5186** interface will continue to be supported.
5187**
5188** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
5189** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
5190** ^With the "v2" interface, any of the other [result codes] or
5191** [extended result codes] might be returned as well.
5192**
5193** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
5194** database locks it needs to do its job.  ^If the statement is a [COMMIT]
5195** or occurs outside of an explicit transaction, then you can retry the
5196** statement.  If the statement is not a [COMMIT] and occurs within an
5197** explicit transaction then you should rollback the transaction before
5198** continuing.
5199**
5200** ^[SQLITE_DONE] means that the statement has finished executing
5201** successfully.  sqlite3_step() should not be called again on this virtual
5202** machine without first calling [sqlite3_reset()] to reset the virtual
5203** machine back to its initial state.
5204**
5205** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
5206** is returned each time a new row of data is ready for processing by the
5207** caller. The values may be accessed using the [column access functions].
5208** sqlite3_step() is called again to retrieve the next row of data.
5209**
5210** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
5211** violation) has occurred.  sqlite3_step() should not be called again on
5212** the VM. More information may be found by calling [sqlite3_errmsg()].
5213** ^With the legacy interface, a more specific error code (for example,
5214** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
5215** can be obtained by calling [sqlite3_reset()] on the
5216** [prepared statement].  ^In the "v2" interface,
5217** the more specific error code is returned directly by sqlite3_step().
5218**
5219** [SQLITE_MISUSE] means that the this routine was called inappropriately.
5220** Perhaps it was called on a [prepared statement] that has
5221** already been [sqlite3_finalize | finalized] or on one that had
5222** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
5223** be the case that the same database connection is being used by two or
5224** more threads at the same moment in time.
5225**
5226** For all versions of SQLite up to and including 3.6.23.1, a call to
5227** [sqlite3_reset()] was required after sqlite3_step() returned anything
5228** other than [SQLITE_ROW] before any subsequent invocation of
5229** sqlite3_step().  Failure to reset the prepared statement using
5230** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
5231** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1]),
5232** sqlite3_step() began
5233** calling [sqlite3_reset()] automatically in this circumstance rather
5234** than returning [SQLITE_MISUSE].  This is not considered a compatibility
5235** break because any application that ever receives an SQLITE_MISUSE error
5236** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
5237** can be used to restore the legacy behavior.
5238**
5239** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
5240** API always returns a generic error code, [SQLITE_ERROR], following any
5241** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
5242** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
5243** specific [error codes] that better describes the error.
5244** We admit that this is a goofy design.  The problem has been fixed
5245** with the "v2" interface.  If you prepare all of your SQL statements
5246** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
5247** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
5248** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
5249** then the more specific [error codes] are returned directly
5250** by sqlite3_step().  The use of the "vX" interfaces is recommended.
5251*/
5252SQLITE_API int sqlite3_step(sqlite3_stmt*);
5253
5254/*
5255** CAPI3REF: Number of columns in a result set
5256** METHOD: sqlite3_stmt
5257**
5258** ^The sqlite3_data_count(P) interface returns the number of columns in the
5259** current row of the result set of [prepared statement] P.
5260** ^If prepared statement P does not have results ready to return
5261** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
5262** interfaces) then sqlite3_data_count(P) returns 0.
5263** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
5264** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
5265** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
5266** will return non-zero if previous call to [sqlite3_step](P) returned
5267** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
5268** where it always returns zero since each step of that multi-step
5269** pragma returns 0 columns of data.
5270**
5271** See also: [sqlite3_column_count()]
5272*/
5273SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
5274
5275/*
5276** CAPI3REF: Fundamental Datatypes
5277** KEYWORDS: SQLITE_TEXT
5278**
5279** ^(Every value in SQLite has one of five fundamental datatypes:
5280**
5281** <ul>
5282** <li> 64-bit signed integer
5283** <li> 64-bit IEEE floating point number
5284** <li> string
5285** <li> BLOB
5286** <li> NULL
5287** </ul>)^
5288**
5289** These constants are codes for each of those types.
5290**
5291** Note that the SQLITE_TEXT constant was also used in SQLite version 2
5292** for a completely different meaning.  Software that links against both
5293** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
5294** SQLITE_TEXT.
5295*/
5296#define SQLITE_INTEGER  1
5297#define SQLITE_FLOAT    2
5298#define SQLITE_BLOB     4
5299#define SQLITE_NULL     5
5300#ifdef SQLITE_TEXT
5301# undef SQLITE_TEXT
5302#else
5303# define SQLITE_TEXT     3
5304#endif
5305#define SQLITE3_TEXT     3
5306
5307/*
5308** CAPI3REF: Result Values From A Query
5309** KEYWORDS: {column access functions}
5310** METHOD: sqlite3_stmt
5311**
5312** <b>Summary:</b>
5313** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5314** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
5315** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
5316** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
5317** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
5318** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
5319** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
5320** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
5321** [sqlite3_value|unprotected sqlite3_value] object.
5322** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5323** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
5324** or a UTF-8 TEXT result in bytes
5325** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
5326** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5327** TEXT in bytes
5328** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
5329** datatype of the result
5330** </table></blockquote>
5331**
5332** <b>Details:</b>
5333**
5334** ^These routines return information about a single column of the current
5335** result row of a query.  ^In every case the first argument is a pointer
5336** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
5337** that was returned from [sqlite3_prepare_v2()] or one of its variants)
5338** and the second argument is the index of the column for which information
5339** should be returned. ^The leftmost column of the result set has the index 0.
5340** ^The number of columns in the result can be determined using
5341** [sqlite3_column_count()].
5342**
5343** If the SQL statement does not currently point to a valid row, or if the
5344** column index is out of range, the result is undefined.
5345** These routines may only be called when the most recent call to
5346** [sqlite3_step()] has returned [SQLITE_ROW] and neither
5347** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
5348** If any of these routines are called after [sqlite3_reset()] or
5349** [sqlite3_finalize()] or after [sqlite3_step()] has returned
5350** something other than [SQLITE_ROW], the results are undefined.
5351** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
5352** are called from a different thread while any of these routines
5353** are pending, then the results are undefined.
5354**
5355** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
5356** each return the value of a result column in a specific data format.  If
5357** the result column is not initially in the requested format (for example,
5358** if the query returns an integer but the sqlite3_column_text() interface
5359** is used to extract the value) then an automatic type conversion is performed.
5360**
5361** ^The sqlite3_column_type() routine returns the
5362** [SQLITE_INTEGER | datatype code] for the initial data type
5363** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
5364** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
5365** The return value of sqlite3_column_type() can be used to decide which
5366** of the first six interface should be used to extract the column value.
5367** The value returned by sqlite3_column_type() is only meaningful if no
5368** automatic type conversions have occurred for the value in question.
5369** After a type conversion, the result of calling sqlite3_column_type()
5370** is undefined, though harmless.  Future
5371** versions of SQLite may change the behavior of sqlite3_column_type()
5372** following a type conversion.
5373**
5374** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
5375** or sqlite3_column_bytes16() interfaces can be used to determine the size
5376** of that BLOB or string.
5377**
5378** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
5379** routine returns the number of bytes in that BLOB or string.
5380** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
5381** the string to UTF-8 and then returns the number of bytes.
5382** ^If the result is a numeric value then sqlite3_column_bytes() uses
5383** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
5384** the number of bytes in that string.
5385** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
5386**
5387** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
5388** routine returns the number of bytes in that BLOB or string.
5389** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
5390** the string to UTF-16 and then returns the number of bytes.
5391** ^If the result is a numeric value then sqlite3_column_bytes16() uses
5392** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
5393** the number of bytes in that string.
5394** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
5395**
5396** ^The values returned by [sqlite3_column_bytes()] and
5397** [sqlite3_column_bytes16()] do not include the zero terminators at the end
5398** of the string.  ^For clarity: the values returned by
5399** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
5400** bytes in the string, not the number of characters.
5401**
5402** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
5403** even empty strings, are always zero-terminated.  ^The return
5404** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
5405**
5406** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
5407** [unprotected sqlite3_value] object.  In a multithreaded environment,
5408** an unprotected sqlite3_value object may only be used safely with
5409** [sqlite3_bind_value()] and [sqlite3_result_value()].
5410** If the [unprotected sqlite3_value] object returned by
5411** [sqlite3_column_value()] is used in any other way, including calls
5412** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
5413** or [sqlite3_value_bytes()], the behavior is not threadsafe.
5414** Hence, the sqlite3_column_value() interface
5415** is normally only useful within the implementation of
5416** [application-defined SQL functions] or [virtual tables], not within
5417** top-level application code.
5418**
5419** The these routines may attempt to convert the datatype of the result.
5420** ^For example, if the internal representation is FLOAT and a text result
5421** is requested, [sqlite3_snprintf()] is used internally to perform the
5422** conversion automatically.  ^(The following table details the conversions
5423** that are applied:
5424**
5425** <blockquote>
5426** <table border="1">
5427** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
5428**
5429** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
5430** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
5431** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
5432** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
5433** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
5434** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
5435** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
5436** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
5437** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
5438** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
5439** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
5440** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
5441** <tr><td>  TEXT    <td>   BLOB    <td> No change
5442** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
5443** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
5444** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
5445** </table>
5446** </blockquote>)^
5447**
5448** Note that when type conversions occur, pointers returned by prior
5449** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
5450** sqlite3_column_text16() may be invalidated.
5451** Type conversions and pointer invalidations might occur
5452** in the following cases:
5453**
5454** <ul>
5455** <li> The initial content is a BLOB and sqlite3_column_text() or
5456**      sqlite3_column_text16() is called.  A zero-terminator might
5457**      need to be added to the string.</li>
5458** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
5459**      sqlite3_column_text16() is called.  The content must be converted
5460**      to UTF-16.</li>
5461** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
5462**      sqlite3_column_text() is called.  The content must be converted
5463**      to UTF-8.</li>
5464** </ul>
5465**
5466** ^Conversions between UTF-16be and UTF-16le are always done in place and do
5467** not invalidate a prior pointer, though of course the content of the buffer
5468** that the prior pointer references will have been modified.  Other kinds
5469** of conversion are done in place when it is possible, but sometimes they
5470** are not possible and in those cases prior pointers are invalidated.
5471**
5472** The safest policy is to invoke these routines
5473** in one of the following ways:
5474**
5475** <ul>
5476**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
5477**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
5478**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
5479** </ul>
5480**
5481** In other words, you should call sqlite3_column_text(),
5482** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
5483** into the desired format, then invoke sqlite3_column_bytes() or
5484** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
5485** to sqlite3_column_text() or sqlite3_column_blob() with calls to
5486** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
5487** with calls to sqlite3_column_bytes().
5488**
5489** ^The pointers returned are valid until a type conversion occurs as
5490** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
5491** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
5492** and BLOBs is freed automatically.  Do not pass the pointers returned
5493** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
5494** [sqlite3_free()].
5495**
5496** ^(If a memory allocation error occurs during the evaluation of any
5497** of these routines, a default value is returned.  The default value
5498** is either the integer 0, the floating point number 0.0, or a NULL
5499** pointer.  Subsequent calls to [sqlite3_errcode()] will return
5500** [SQLITE_NOMEM].)^
5501*/
5502SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
5503SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
5504SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
5505SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
5506SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
5507SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
5508SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
5509SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
5510SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
5511SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
5512
5513/*
5514** CAPI3REF: Destroy A Prepared Statement Object
5515** DESTRUCTOR: sqlite3_stmt
5516**
5517** ^The sqlite3_finalize() function is called to delete a [prepared statement].
5518** ^If the most recent evaluation of the statement encountered no errors
5519** or if the statement is never been evaluated, then sqlite3_finalize() returns
5520** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
5521** sqlite3_finalize(S) returns the appropriate [error code] or
5522** [extended error code].
5523**
5524** ^The sqlite3_finalize(S) routine can be called at any point during
5525** the life cycle of [prepared statement] S:
5526** before statement S is ever evaluated, after
5527** one or more calls to [sqlite3_reset()], or after any call
5528** to [sqlite3_step()] regardless of whether or not the statement has
5529** completed execution.
5530**
5531** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
5532**
5533** The application must finalize every [prepared statement] in order to avoid
5534** resource leaks.  It is a grievous error for the application to try to use
5535** a prepared statement after it has been finalized.  Any use of a prepared
5536** statement after it has been finalized can result in undefined and
5537** undesirable behavior such as segfaults and heap corruption.
5538*/
5539SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
5540
5541/*
5542** CAPI3REF: Reset A Prepared Statement Object
5543** METHOD: sqlite3_stmt
5544**
5545** The sqlite3_reset() function is called to reset a [prepared statement]
5546** object back to its initial state, ready to be re-executed.
5547** ^Any SQL statement variables that had values bound to them using
5548** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
5549** Use [sqlite3_clear_bindings()] to reset the bindings.
5550**
5551** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
5552** back to the beginning of its program.
5553**
5554** ^If the most recent call to [sqlite3_step(S)] for the
5555** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
5556** or if [sqlite3_step(S)] has never before been called on S,
5557** then [sqlite3_reset(S)] returns [SQLITE_OK].
5558**
5559** ^If the most recent call to [sqlite3_step(S)] for the
5560** [prepared statement] S indicated an error, then
5561** [sqlite3_reset(S)] returns an appropriate [error code].
5562**
5563** ^The [sqlite3_reset(S)] interface does not change the values
5564** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
5565*/
5566SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
5567
5568/*
5569** CAPI3REF: Create Or Redefine SQL Functions
5570** KEYWORDS: {function creation routines}
5571** KEYWORDS: {application-defined SQL function}
5572** KEYWORDS: {application-defined SQL functions}
5573** METHOD: sqlite3
5574**
5575** ^These functions (collectively known as "function creation routines")
5576** are used to add SQL functions or aggregates or to redefine the behavior
5577** of existing SQL functions or aggregates.  The only differences between
5578** these routines are the text encoding expected for
5579** the second parameter (the name of the function being created)
5580** and the presence or absence of a destructor callback for
5581** the application data pointer.
5582**
5583** ^The first parameter is the [database connection] to which the SQL
5584** function is to be added.  ^If an application uses more than one database
5585** connection then application-defined SQL functions must be added
5586** to each database connection separately.
5587**
5588** ^The second parameter is the name of the SQL function to be created or
5589** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
5590** representation, exclusive of the zero-terminator.  ^Note that the name
5591** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
5592** ^Any attempt to create a function with a longer name
5593** will result in [SQLITE_MISUSE] being returned.
5594**
5595** ^The third parameter (nArg)
5596** is the number of arguments that the SQL function or
5597** aggregate takes. ^If this parameter is -1, then the SQL function or
5598** aggregate may take any number of arguments between 0 and the limit
5599** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
5600** parameter is less than -1 or greater than 127 then the behavior is
5601** undefined.
5602**
5603** ^The fourth parameter, eTextRep, specifies what
5604** [SQLITE_UTF8 | text encoding] this SQL function prefers for
5605** its parameters.  The application should set this parameter to
5606** [SQLITE_UTF16LE] if the function implementation invokes
5607** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
5608** implementation invokes [sqlite3_value_text16be()] on an input, or
5609** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
5610** otherwise.  ^The same SQL function may be registered multiple times using
5611** different preferred text encodings, with different implementations for
5612** each encoding.
5613** ^When multiple implementations of the same function are available, SQLite
5614** will pick the one that involves the least amount of data conversion.
5615**
5616** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
5617** to signal that the function will always return the same result given
5618** the same inputs within a single SQL statement.  Most SQL functions are
5619** deterministic.  The built-in [random()] SQL function is an example of a
5620** function that is not deterministic.  The SQLite query planner is able to
5621** perform additional optimizations on deterministic functions, so use
5622** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
5623**
5624** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
5625** function can gain access to this pointer using [sqlite3_user_data()].)^
5626**
5627** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
5628** pointers to C-language functions that implement the SQL function or
5629** aggregate. ^A scalar SQL function requires an implementation of the xFunc
5630** callback only; NULL pointers must be passed as the xStep and xFinal
5631** parameters. ^An aggregate SQL function requires an implementation of xStep
5632** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
5633** SQL function or aggregate, pass NULL pointers for all three function
5634** callbacks.
5635**
5636** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
5637** then it is destructor for the application data pointer.
5638** The destructor is invoked when the function is deleted, either by being
5639** overloaded or when the database connection closes.)^
5640** ^The destructor is also invoked if the call to
5641** sqlite3_create_function_v2() fails.
5642** ^When the destructor callback of the tenth parameter is invoked, it
5643** is passed a single argument which is a copy of the application data
5644** pointer which was the fifth parameter to sqlite3_create_function_v2().
5645**
5646** ^It is permitted to register multiple implementations of the same
5647** functions with the same name but with either differing numbers of
5648** arguments or differing preferred text encodings.  ^SQLite will use
5649** the implementation that most closely matches the way in which the
5650** SQL function is used.  ^A function implementation with a non-negative
5651** nArg parameter is a better match than a function implementation with
5652** a negative nArg.  ^A function where the preferred text encoding
5653** matches the database encoding is a better
5654** match than a function where the encoding is different.
5655** ^A function where the encoding difference is between UTF16le and UTF16be
5656** is a closer match than a function where the encoding difference is
5657** between UTF8 and UTF16.
5658**
5659** ^Built-in functions may be overloaded by new application-defined functions.
5660**
5661** ^An application-defined function is permitted to call other
5662** SQLite interfaces.  However, such calls must not
5663** close the database connection nor finalize or reset the prepared
5664** statement in which the function is running.
5665*/
5666SQLITE_API int sqlite3_create_function(
5667  sqlite3 *db,
5668  const char *zFunctionName,
5669  int nArg,
5670  int eTextRep,
5671  void *pApp,
5672  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5673  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5674  void (*xFinal)(sqlite3_context*)
5675);
5676SQLITE_API int sqlite3_create_function16(
5677  sqlite3 *db,
5678  const void *zFunctionName,
5679  int nArg,
5680  int eTextRep,
5681  void *pApp,
5682  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5683  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5684  void (*xFinal)(sqlite3_context*)
5685);
5686SQLITE_API int sqlite3_create_function_v2(
5687  sqlite3 *db,
5688  const char *zFunctionName,
5689  int nArg,
5690  int eTextRep,
5691  void *pApp,
5692  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
5693  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
5694  void (*xFinal)(sqlite3_context*),
5695  void(*xDestroy)(void*)
5696);
5697
5698/*
5699** CAPI3REF: Text Encodings
5700**
5701** These constant define integer codes that represent the various
5702** text encodings supported by SQLite.
5703*/
5704#define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
5705#define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
5706#define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
5707#define SQLITE_UTF16          4    /* Use native byte order */
5708#define SQLITE_ANY            5    /* Deprecated */
5709#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
5710
5711/*
5712** CAPI3REF: Function Flags
5713**
5714** These constants may be ORed together with the
5715** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
5716** to [sqlite3_create_function()], [sqlite3_create_function16()], or
5717** [sqlite3_create_function_v2()].
5718*/
5719#define SQLITE_DETERMINISTIC    0x800
5720
5721/*
5722** CAPI3REF: Deprecated Functions
5723** DEPRECATED
5724**
5725** These functions are [deprecated].  In order to maintain
5726** backwards compatibility with older code, these functions continue
5727** to be supported.  However, new applications should avoid
5728** the use of these functions.  To encourage programmers to avoid
5729** these functions, we will not explain what they do.
5730*/
5731#ifndef SQLITE_OMIT_DEPRECATED
5732SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
5733SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
5734SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
5735SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
5736SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
5737SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
5738                      void*,sqlite3_int64);
5739#endif
5740
5741/*
5742** CAPI3REF: Obtaining SQL Values
5743** METHOD: sqlite3_value
5744**
5745** <b>Summary:</b>
5746** <blockquote><table border=0 cellpadding=0 cellspacing=0>
5747** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
5748** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
5749** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
5750** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
5751** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
5752** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
5753** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
5754** the native byteorder
5755** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
5756** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
5757** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
5758** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
5759** or a UTF-8 TEXT in bytes
5760** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
5761** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5762** TEXT in bytes
5763** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
5764** datatype of the value
5765** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
5766** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
5767** </table></blockquote>
5768**
5769** <b>Details:</b>
5770**
5771** These routines extract type, size, and content information from
5772** [protected sqlite3_value] objects.  Protected sqlite3_value objects
5773** are used to pass parameter information into implementation of
5774** [application-defined SQL functions] and [virtual tables].
5775**
5776** These routines work only with [protected sqlite3_value] objects.
5777** Any attempt to use these routines on an [unprotected sqlite3_value]
5778** is not threadsafe.
5779**
5780** ^These routines work just like the corresponding [column access functions]
5781** except that these routines take a single [protected sqlite3_value] object
5782** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
5783**
5784** ^The sqlite3_value_text16() interface extracts a UTF-16 string
5785** in the native byte-order of the host machine.  ^The
5786** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
5787** extract UTF-16 strings as big-endian and little-endian respectively.
5788**
5789** ^If [sqlite3_value] object V was initialized
5790** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
5791** and if X and Y are strings that compare equal according to strcmp(X,Y),
5792** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,
5793** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
5794** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
5795**
5796** ^(The sqlite3_value_type(V) interface returns the
5797** [SQLITE_INTEGER | datatype code] for the initial datatype of the
5798** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
5799** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
5800** Other interfaces might change the datatype for an sqlite3_value object.
5801** For example, if the datatype is initially SQLITE_INTEGER and
5802** sqlite3_value_text(V) is called to extract a text value for that
5803** integer, then subsequent calls to sqlite3_value_type(V) might return
5804** SQLITE_TEXT.  Whether or not a persistent internal datatype conversion
5805** occurs is undefined and may change from one release of SQLite to the next.
5806**
5807** ^(The sqlite3_value_numeric_type() interface attempts to apply
5808** numeric affinity to the value.  This means that an attempt is
5809** made to convert the value to an integer or floating point.  If
5810** such a conversion is possible without loss of information (in other
5811** words, if the value is a string that looks like a number)
5812** then the conversion is performed.  Otherwise no conversion occurs.
5813** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
5814**
5815** Please pay particular attention to the fact that the pointer returned
5816** from [sqlite3_value_blob()], [sqlite3_value_text()], or
5817** [sqlite3_value_text16()] can be invalidated by a subsequent call to
5818** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
5819** or [sqlite3_value_text16()].
5820**
5821** These routines must be called from the same thread as
5822** the SQL function that supplied the [sqlite3_value*] parameters.
5823*/
5824SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
5825SQLITE_API double sqlite3_value_double(sqlite3_value*);
5826SQLITE_API int sqlite3_value_int(sqlite3_value*);
5827SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
5828SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
5829SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
5830SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
5831SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
5832SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
5833SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
5834SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
5835SQLITE_API int sqlite3_value_type(sqlite3_value*);
5836SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
5837
5838/*
5839** CAPI3REF: Finding The Subtype Of SQL Values
5840** METHOD: sqlite3_value
5841**
5842** The sqlite3_value_subtype(V) function returns the subtype for
5843** an [application-defined SQL function] argument V.  The subtype
5844** information can be used to pass a limited amount of context from
5845** one SQL function to another.  Use the [sqlite3_result_subtype()]
5846** routine to set the subtype for the return value of an SQL function.
5847*/
5848SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
5849
5850/*
5851** CAPI3REF: Copy And Free SQL Values
5852** METHOD: sqlite3_value
5853**
5854** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
5855** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
5856** is a [protected sqlite3_value] object even if the input is not.
5857** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
5858** memory allocation fails.
5859**
5860** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
5861** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
5862** then sqlite3_value_free(V) is a harmless no-op.
5863*/
5864SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
5865SQLITE_API void sqlite3_value_free(sqlite3_value*);
5866
5867/*
5868** CAPI3REF: Obtain Aggregate Function Context
5869** METHOD: sqlite3_context
5870**
5871** Implementations of aggregate SQL functions use this
5872** routine to allocate memory for storing their state.
5873**
5874** ^The first time the sqlite3_aggregate_context(C,N) routine is called
5875** for a particular aggregate function, SQLite
5876** allocates N of memory, zeroes out that memory, and returns a pointer
5877** to the new memory. ^On second and subsequent calls to
5878** sqlite3_aggregate_context() for the same aggregate function instance,
5879** the same buffer is returned.  Sqlite3_aggregate_context() is normally
5880** called once for each invocation of the xStep callback and then one
5881** last time when the xFinal callback is invoked.  ^(When no rows match
5882** an aggregate query, the xStep() callback of the aggregate function
5883** implementation is never called and xFinal() is called exactly once.
5884** In those cases, sqlite3_aggregate_context() might be called for the
5885** first time from within xFinal().)^
5886**
5887** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
5888** when first called if N is less than or equal to zero or if a memory
5889** allocate error occurs.
5890**
5891** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
5892** determined by the N parameter on first successful call.  Changing the
5893** value of N in subsequent call to sqlite3_aggregate_context() within
5894** the same aggregate function instance will not resize the memory
5895** allocation.)^  Within the xFinal callback, it is customary to set
5896** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
5897** pointless memory allocations occur.
5898**
5899** ^SQLite automatically frees the memory allocated by
5900** sqlite3_aggregate_context() when the aggregate query concludes.
5901**
5902** The first parameter must be a copy of the
5903** [sqlite3_context | SQL function context] that is the first parameter
5904** to the xStep or xFinal callback routine that implements the aggregate
5905** function.
5906**
5907** This routine must be called from the same thread in which
5908** the aggregate SQL function is running.
5909*/
5910SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
5911
5912/*
5913** CAPI3REF: User Data For Functions
5914** METHOD: sqlite3_context
5915**
5916** ^The sqlite3_user_data() interface returns a copy of
5917** the pointer that was the pUserData parameter (the 5th parameter)
5918** of the [sqlite3_create_function()]
5919** and [sqlite3_create_function16()] routines that originally
5920** registered the application defined function.
5921**
5922** This routine must be called from the same thread in which
5923** the application-defined function is running.
5924*/
5925SQLITE_API void *sqlite3_user_data(sqlite3_context*);
5926
5927/*
5928** CAPI3REF: Database Connection For Functions
5929** METHOD: sqlite3_context
5930**
5931** ^The sqlite3_context_db_handle() interface returns a copy of
5932** the pointer to the [database connection] (the 1st parameter)
5933** of the [sqlite3_create_function()]
5934** and [sqlite3_create_function16()] routines that originally
5935** registered the application defined function.
5936*/
5937SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
5938
5939/*
5940** CAPI3REF: Function Auxiliary Data
5941** METHOD: sqlite3_context
5942**
5943** These functions may be used by (non-aggregate) SQL functions to
5944** associate metadata with argument values. If the same value is passed to
5945** multiple invocations of the same SQL function during query execution, under
5946** some circumstances the associated metadata may be preserved.  An example
5947** of where this might be useful is in a regular-expression matching
5948** function. The compiled version of the regular expression can be stored as
5949** metadata associated with the pattern string.
5950** Then as long as the pattern string remains the same,
5951** the compiled regular expression can be reused on multiple
5952** invocations of the same function.
5953**
5954** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
5955** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
5956** value to the application-defined function.  ^N is zero for the left-most
5957** function argument.  ^If there is no metadata
5958** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
5959** returns a NULL pointer.
5960**
5961** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
5962** argument of the application-defined function.  ^Subsequent
5963** calls to sqlite3_get_auxdata(C,N) return P from the most recent
5964** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
5965** NULL if the metadata has been discarded.
5966** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
5967** SQLite will invoke the destructor function X with parameter P exactly
5968** once, when the metadata is discarded.
5969** SQLite is free to discard the metadata at any time, including: <ul>
5970** <li> ^(when the corresponding function parameter changes)^, or
5971** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
5972**      SQL statement)^, or
5973** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
5974**       parameter)^, or
5975** <li> ^(during the original sqlite3_set_auxdata() call when a memory
5976**      allocation error occurs.)^ </ul>
5977**
5978** Note the last bullet in particular.  The destructor X in
5979** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
5980** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
5981** should be called near the end of the function implementation and the
5982** function implementation should not make any use of P after
5983** sqlite3_set_auxdata() has been called.
5984**
5985** ^(In practice, metadata is preserved between function calls for
5986** function parameters that are compile-time constants, including literal
5987** values and [parameters] and expressions composed from the same.)^
5988**
5989** The value of the N parameter to these interfaces should be non-negative.
5990** Future enhancements may make use of negative N values to define new
5991** kinds of function caching behavior.
5992**
5993** These routines must be called from the same thread in which
5994** the SQL function is running.
5995*/
5996SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
5997SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
5998
5999
6000/*
6001** CAPI3REF: Constants Defining Special Destructor Behavior
6002**
6003** These are special values for the destructor that is passed in as the
6004** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
6005** argument is SQLITE_STATIC, it means that the content pointer is constant
6006** and will never change.  It does not need to be destroyed.  ^The
6007** SQLITE_TRANSIENT value means that the content will likely change in
6008** the near future and that SQLite should make its own private copy of
6009** the content before returning.
6010**
6011** The typedef is necessary to work around problems in certain
6012** C++ compilers.
6013*/
6014typedef void (*sqlite3_destructor_type)(void*);
6015#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
6016#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
6017
6018/*
6019** CAPI3REF: Setting The Result Of An SQL Function
6020** METHOD: sqlite3_context
6021**
6022** These routines are used by the xFunc or xFinal callbacks that
6023** implement SQL functions and aggregates.  See
6024** [sqlite3_create_function()] and [sqlite3_create_function16()]
6025** for additional information.
6026**
6027** These functions work very much like the [parameter binding] family of
6028** functions used to bind values to host parameters in prepared statements.
6029** Refer to the [SQL parameter] documentation for additional information.
6030**
6031** ^The sqlite3_result_blob() interface sets the result from
6032** an application-defined function to be the BLOB whose content is pointed
6033** to by the second parameter and which is N bytes long where N is the
6034** third parameter.
6035**
6036** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
6037** interfaces set the result of the application-defined function to be
6038** a BLOB containing all zero bytes and N bytes in size.
6039**
6040** ^The sqlite3_result_double() interface sets the result from
6041** an application-defined function to be a floating point value specified
6042** by its 2nd argument.
6043**
6044** ^The sqlite3_result_error() and sqlite3_result_error16() functions
6045** cause the implemented SQL function to throw an exception.
6046** ^SQLite uses the string pointed to by the
6047** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
6048** as the text of an error message.  ^SQLite interprets the error
6049** message string from sqlite3_result_error() as UTF-8. ^SQLite
6050** interprets the string from sqlite3_result_error16() as UTF-16 in native
6051** byte order.  ^If the third parameter to sqlite3_result_error()
6052** or sqlite3_result_error16() is negative then SQLite takes as the error
6053** message all text up through the first zero character.
6054** ^If the third parameter to sqlite3_result_error() or
6055** sqlite3_result_error16() is non-negative then SQLite takes that many
6056** bytes (not characters) from the 2nd parameter as the error message.
6057** ^The sqlite3_result_error() and sqlite3_result_error16()
6058** routines make a private copy of the error message text before
6059** they return.  Hence, the calling function can deallocate or
6060** modify the text after they return without harm.
6061** ^The sqlite3_result_error_code() function changes the error code
6062** returned by SQLite as a result of an error in a function.  ^By default,
6063** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
6064** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
6065**
6066** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
6067** error indicating that a string or BLOB is too long to represent.
6068**
6069** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
6070** error indicating that a memory allocation failed.
6071**
6072** ^The sqlite3_result_int() interface sets the return value
6073** of the application-defined function to be the 32-bit signed integer
6074** value given in the 2nd argument.
6075** ^The sqlite3_result_int64() interface sets the return value
6076** of the application-defined function to be the 64-bit signed integer
6077** value given in the 2nd argument.
6078**
6079** ^The sqlite3_result_null() interface sets the return value
6080** of the application-defined function to be NULL.
6081**
6082** ^The sqlite3_result_text(), sqlite3_result_text16(),
6083** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
6084** set the return value of the application-defined function to be
6085** a text string which is represented as UTF-8, UTF-16 native byte order,
6086** UTF-16 little endian, or UTF-16 big endian, respectively.
6087** ^The sqlite3_result_text64() interface sets the return value of an
6088** application-defined function to be a text string in an encoding
6089** specified by the fifth (and last) parameter, which must be one
6090** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
6091** ^SQLite takes the text result from the application from
6092** the 2nd parameter of the sqlite3_result_text* interfaces.
6093** ^If the 3rd parameter to the sqlite3_result_text* interfaces
6094** is negative, then SQLite takes result text from the 2nd parameter
6095** through the first zero character.
6096** ^If the 3rd parameter to the sqlite3_result_text* interfaces
6097** is non-negative, then as many bytes (not characters) of the text
6098** pointed to by the 2nd parameter are taken as the application-defined
6099** function result.  If the 3rd parameter is non-negative, then it
6100** must be the byte offset into the string where the NUL terminator would
6101** appear if the string where NUL terminated.  If any NUL characters occur
6102** in the string at a byte offset that is less than the value of the 3rd
6103** parameter, then the resulting string will contain embedded NULs and the
6104** result of expressions operating on strings with embedded NULs is undefined.
6105** ^If the 4th parameter to the sqlite3_result_text* interfaces
6106** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
6107** function as the destructor on the text or BLOB result when it has
6108** finished using that result.
6109** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
6110** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
6111** assumes that the text or BLOB result is in constant space and does not
6112** copy the content of the parameter nor call a destructor on the content
6113** when it has finished using that result.
6114** ^If the 4th parameter to the sqlite3_result_text* interfaces
6115** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
6116** then SQLite makes a copy of the result into space obtained
6117** from [sqlite3_malloc()] before it returns.
6118**
6119** ^The sqlite3_result_value() interface sets the result of
6120** the application-defined function to be a copy of the
6121** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
6122** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
6123** so that the [sqlite3_value] specified in the parameter may change or
6124** be deallocated after sqlite3_result_value() returns without harm.
6125** ^A [protected sqlite3_value] object may always be used where an
6126** [unprotected sqlite3_value] object is required, so either
6127** kind of [sqlite3_value] object can be used with this interface.
6128**
6129** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
6130** SQL NULL value, just like [sqlite3_result_null(C)], except that it
6131** also associates the host-language pointer P or type T with that
6132** NULL value such that the pointer can be retrieved within an
6133** [application-defined SQL function] using [sqlite3_value_pointer()].
6134** ^If the D parameter is not NULL, then it is a pointer to a destructor
6135** for the P parameter.  ^SQLite invokes D with P as its only argument
6136** when SQLite is finished with P.  The T parameter should be a static
6137** string and preferably a string literal. The sqlite3_result_pointer()
6138** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
6139**
6140** If these routines are called from within the different thread
6141** than the one containing the application-defined function that received
6142** the [sqlite3_context] pointer, the results are undefined.
6143*/
6144SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
6145SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
6146                           sqlite3_uint64,void(*)(void*));
6147SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
6148SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
6149SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
6150SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
6151SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
6152SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
6153SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
6154SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
6155SQLITE_API void sqlite3_result_null(sqlite3_context*);
6156SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
6157SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
6158                           void(*)(void*), unsigned char encoding);
6159SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
6160SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
6161SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
6162SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
6163SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
6164SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
6165SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
6166
6167
6168/*
6169** CAPI3REF: Setting The Subtype Of An SQL Function
6170** METHOD: sqlite3_context
6171**
6172** The sqlite3_result_subtype(C,T) function causes the subtype of
6173** the result from the [application-defined SQL function] with
6174** [sqlite3_context] C to be the value T.  Only the lower 8 bits
6175** of the subtype T are preserved in current versions of SQLite;
6176** higher order bits are discarded.
6177** The number of subtype bytes preserved by SQLite might increase
6178** in future releases of SQLite.
6179*/
6180SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
6181
6182/*
6183** CAPI3REF: Define New Collating Sequences
6184** METHOD: sqlite3
6185**
6186** ^These functions add, remove, or modify a [collation] associated
6187** with the [database connection] specified as the first argument.
6188**
6189** ^The name of the collation is a UTF-8 string
6190** for sqlite3_create_collation() and sqlite3_create_collation_v2()
6191** and a UTF-16 string in native byte order for sqlite3_create_collation16().
6192** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
6193** considered to be the same name.
6194**
6195** ^(The third argument (eTextRep) must be one of the constants:
6196** <ul>
6197** <li> [SQLITE_UTF8],
6198** <li> [SQLITE_UTF16LE],
6199** <li> [SQLITE_UTF16BE],
6200** <li> [SQLITE_UTF16], or
6201** <li> [SQLITE_UTF16_ALIGNED].
6202** </ul>)^
6203** ^The eTextRep argument determines the encoding of strings passed
6204** to the collating function callback, xCallback.
6205** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
6206** force strings to be UTF16 with native byte order.
6207** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
6208** on an even byte address.
6209**
6210** ^The fourth argument, pArg, is an application data pointer that is passed
6211** through as the first argument to the collating function callback.
6212**
6213** ^The fifth argument, xCallback, is a pointer to the collating function.
6214** ^Multiple collating functions can be registered using the same name but
6215** with different eTextRep parameters and SQLite will use whichever
6216** function requires the least amount of data transformation.
6217** ^If the xCallback argument is NULL then the collating function is
6218** deleted.  ^When all collating functions having the same name are deleted,
6219** that collation is no longer usable.
6220**
6221** ^The collating function callback is invoked with a copy of the pArg
6222** application data pointer and with two strings in the encoding specified
6223** by the eTextRep argument.  The collating function must return an
6224** integer that is negative, zero, or positive
6225** if the first string is less than, equal to, or greater than the second,
6226** respectively.  A collating function must always return the same answer
6227** given the same inputs.  If two or more collating functions are registered
6228** to the same collation name (using different eTextRep values) then all
6229** must give an equivalent answer when invoked with equivalent strings.
6230** The collating function must obey the following properties for all
6231** strings A, B, and C:
6232**
6233** <ol>
6234** <li> If A==B then B==A.
6235** <li> If A==B and B==C then A==C.
6236** <li> If A&lt;B THEN B&gt;A.
6237** <li> If A&lt;B and B&lt;C then A&lt;C.
6238** </ol>
6239**
6240** If a collating function fails any of the above constraints and that
6241** collating function is  registered and used, then the behavior of SQLite
6242** is undefined.
6243**
6244** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
6245** with the addition that the xDestroy callback is invoked on pArg when
6246** the collating function is deleted.
6247** ^Collating functions are deleted when they are overridden by later
6248** calls to the collation creation functions or when the
6249** [database connection] is closed using [sqlite3_close()].
6250**
6251** ^The xDestroy callback is <u>not</u> called if the
6252** sqlite3_create_collation_v2() function fails.  Applications that invoke
6253** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
6254** check the return code and dispose of the application data pointer
6255** themselves rather than expecting SQLite to deal with it for them.
6256** This is different from every other SQLite interface.  The inconsistency
6257** is unfortunate but cannot be changed without breaking backwards
6258** compatibility.
6259**
6260** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
6261*/
6262SQLITE_API int sqlite3_create_collation(
6263  sqlite3*,
6264  const char *zName,
6265  int eTextRep,
6266  void *pArg,
6267  int(*xCompare)(void*,int,const void*,int,const void*)
6268);
6269SQLITE_API int sqlite3_create_collation_v2(
6270  sqlite3*,
6271  const char *zName,
6272  int eTextRep,
6273  void *pArg,
6274  int(*xCompare)(void*,int,const void*,int,const void*),
6275  void(*xDestroy)(void*)
6276);
6277SQLITE_API int sqlite3_create_collation16(
6278  sqlite3*,
6279  const void *zName,
6280  int eTextRep,
6281  void *pArg,
6282  int(*xCompare)(void*,int,const void*,int,const void*)
6283);
6284
6285/*
6286** CAPI3REF: Collation Needed Callbacks
6287** METHOD: sqlite3
6288**
6289** ^To avoid having to register all collation sequences before a database
6290** can be used, a single callback function may be registered with the
6291** [database connection] to be invoked whenever an undefined collation
6292** sequence is required.
6293**
6294** ^If the function is registered using the sqlite3_collation_needed() API,
6295** then it is passed the names of undefined collation sequences as strings
6296** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
6297** the names are passed as UTF-16 in machine native byte order.
6298** ^A call to either function replaces the existing collation-needed callback.
6299**
6300** ^(When the callback is invoked, the first argument passed is a copy
6301** of the second argument to sqlite3_collation_needed() or
6302** sqlite3_collation_needed16().  The second argument is the database
6303** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
6304** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
6305** sequence function required.  The fourth parameter is the name of the
6306** required collation sequence.)^
6307**
6308** The callback function should register the desired collation using
6309** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
6310** [sqlite3_create_collation_v2()].
6311*/
6312SQLITE_API int sqlite3_collation_needed(
6313  sqlite3*,
6314  void*,
6315  void(*)(void*,sqlite3*,int eTextRep,const char*)
6316);
6317SQLITE_API int sqlite3_collation_needed16(
6318  sqlite3*,
6319  void*,
6320  void(*)(void*,sqlite3*,int eTextRep,const void*)
6321);
6322
6323#ifdef SQLITE_HAS_CODEC
6324/*
6325** Specify the key for an encrypted database.  This routine should be
6326** called right after sqlite3_open().
6327**
6328** The code to implement this API is not available in the public release
6329** of SQLite.
6330*/
6331SQLITE_API int sqlite3_key(
6332  sqlite3 *db,                   /* Database to be rekeyed */
6333  const void *pKey, int nKey     /* The key */
6334);
6335SQLITE_API int sqlite3_key_v2(
6336  sqlite3 *db,                   /* Database to be rekeyed */
6337  const char *zDbName,           /* Name of the database */
6338  const void *pKey, int nKey     /* The key */
6339);
6340
6341/*
6342** Change the key on an open database.  If the current database is not
6343** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
6344** database is decrypted.
6345**
6346** The code to implement this API is not available in the public release
6347** of SQLite.
6348*/
6349SQLITE_API int sqlite3_rekey(
6350  sqlite3 *db,                   /* Database to be rekeyed */
6351  const void *pKey, int nKey     /* The new key */
6352);
6353SQLITE_API int sqlite3_rekey_v2(
6354  sqlite3 *db,                   /* Database to be rekeyed */
6355  const char *zDbName,           /* Name of the database */
6356  const void *pKey, int nKey     /* The new key */
6357);
6358
6359/*
6360** Specify the activation key for a SEE database.  Unless
6361** activated, none of the SEE routines will work.
6362*/
6363SQLITE_API void sqlite3_activate_see(
6364  const char *zPassPhrase        /* Activation phrase */
6365);
6366#endif
6367
6368#ifdef SQLITE_ENABLE_CEROD
6369/*
6370** Specify the activation key for a CEROD database.  Unless
6371** activated, none of the CEROD routines will work.
6372*/
6373SQLITE_API void sqlite3_activate_cerod(
6374  const char *zPassPhrase        /* Activation phrase */
6375);
6376#endif
6377
6378/*
6379** CAPI3REF: Suspend Execution For A Short Time
6380**
6381** The sqlite3_sleep() function causes the current thread to suspend execution
6382** for at least a number of milliseconds specified in its parameter.
6383**
6384** If the operating system does not support sleep requests with
6385** millisecond time resolution, then the time will be rounded up to
6386** the nearest second. The number of milliseconds of sleep actually
6387** requested from the operating system is returned.
6388**
6389** ^SQLite implements this interface by calling the xSleep()
6390** method of the default [sqlite3_vfs] object.  If the xSleep() method
6391** of the default VFS is not implemented correctly, or not implemented at
6392** all, then the behavior of sqlite3_sleep() may deviate from the description
6393** in the previous paragraphs.
6394*/
6395SQLITE_API int sqlite3_sleep(int);
6396
6397/*
6398** CAPI3REF: Name Of The Folder Holding Temporary Files
6399**
6400** ^(If this global variable is made to point to a string which is
6401** the name of a folder (a.k.a. directory), then all temporary files
6402** created by SQLite when using a built-in [sqlite3_vfs | VFS]
6403** will be placed in that directory.)^  ^If this variable
6404** is a NULL pointer, then SQLite performs a search for an appropriate
6405** temporary file directory.
6406**
6407** Applications are strongly discouraged from using this global variable.
6408** It is required to set a temporary folder on Windows Runtime (WinRT).
6409** But for all other platforms, it is highly recommended that applications
6410** neither read nor write this variable.  This global variable is a relic
6411** that exists for backwards compatibility of legacy applications and should
6412** be avoided in new projects.
6413**
6414** It is not safe to read or modify this variable in more than one
6415** thread at a time.  It is not safe to read or modify this variable
6416** if a [database connection] is being used at the same time in a separate
6417** thread.
6418** It is intended that this variable be set once
6419** as part of process initialization and before any SQLite interface
6420** routines have been called and that this variable remain unchanged
6421** thereafter.
6422**
6423** ^The [temp_store_directory pragma] may modify this variable and cause
6424** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
6425** the [temp_store_directory pragma] always assumes that any string
6426** that this variable points to is held in memory obtained from
6427** [sqlite3_malloc] and the pragma may attempt to free that memory
6428** using [sqlite3_free].
6429** Hence, if this variable is modified directly, either it should be
6430** made NULL or made to point to memory obtained from [sqlite3_malloc]
6431** or else the use of the [temp_store_directory pragma] should be avoided.
6432** Except when requested by the [temp_store_directory pragma], SQLite
6433** does not free the memory that sqlite3_temp_directory points to.  If
6434** the application wants that memory to be freed, it must do
6435** so itself, taking care to only do so after all [database connection]
6436** objects have been destroyed.
6437**
6438** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
6439** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
6440** features that require the use of temporary files may fail.  Here is an
6441** example of how to do this using C++ with the Windows Runtime:
6442**
6443** <blockquote><pre>
6444** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
6445** &nbsp;     TemporaryFolder->Path->Data();
6446** char zPathBuf&#91;MAX_PATH + 1&#93;;
6447** memset(zPathBuf, 0, sizeof(zPathBuf));
6448** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
6449** &nbsp;     NULL, NULL);
6450** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
6451** </pre></blockquote>
6452*/
6453SQLITE_API char *sqlite3_temp_directory;
6454
6455/*
6456** CAPI3REF: Name Of The Folder Holding Database Files
6457**
6458** ^(If this global variable is made to point to a string which is
6459** the name of a folder (a.k.a. directory), then all database files
6460** specified with a relative pathname and created or accessed by
6461** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
6462** to be relative to that directory.)^ ^If this variable is a NULL
6463** pointer, then SQLite assumes that all database files specified
6464** with a relative pathname are relative to the current directory
6465** for the process.  Only the windows VFS makes use of this global
6466** variable; it is ignored by the unix VFS.
6467**
6468** Changing the value of this variable while a database connection is
6469** open can result in a corrupt database.
6470**
6471** It is not safe to read or modify this variable in more than one
6472** thread at a time.  It is not safe to read or modify this variable
6473** if a [database connection] is being used at the same time in a separate
6474** thread.
6475** It is intended that this variable be set once
6476** as part of process initialization and before any SQLite interface
6477** routines have been called and that this variable remain unchanged
6478** thereafter.
6479**
6480** ^The [data_store_directory pragma] may modify this variable and cause
6481** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
6482** the [data_store_directory pragma] always assumes that any string
6483** that this variable points to is held in memory obtained from
6484** [sqlite3_malloc] and the pragma may attempt to free that memory
6485** using [sqlite3_free].
6486** Hence, if this variable is modified directly, either it should be
6487** made NULL or made to point to memory obtained from [sqlite3_malloc]
6488** or else the use of the [data_store_directory pragma] should be avoided.
6489*/
6490SQLITE_API char *sqlite3_data_directory;
6491
6492/*
6493** CAPI3REF: Test For Auto-Commit Mode
6494** KEYWORDS: {autocommit mode}
6495** METHOD: sqlite3
6496**
6497** ^The sqlite3_get_autocommit() interface returns non-zero or
6498** zero if the given database connection is or is not in autocommit mode,
6499** respectively.  ^Autocommit mode is on by default.
6500** ^Autocommit mode is disabled by a [BEGIN] statement.
6501** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
6502**
6503** If certain kinds of errors occur on a statement within a multi-statement
6504** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
6505** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
6506** transaction might be rolled back automatically.  The only way to
6507** find out whether SQLite automatically rolled back the transaction after
6508** an error is to use this function.
6509**
6510** If another thread changes the autocommit status of the database
6511** connection while this routine is running, then the return value
6512** is undefined.
6513*/
6514SQLITE_API int sqlite3_get_autocommit(sqlite3*);
6515
6516/*
6517** CAPI3REF: Find The Database Handle Of A Prepared Statement
6518** METHOD: sqlite3_stmt
6519**
6520** ^The sqlite3_db_handle interface returns the [database connection] handle
6521** to which a [prepared statement] belongs.  ^The [database connection]
6522** returned by sqlite3_db_handle is the same [database connection]
6523** that was the first argument
6524** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
6525** create the statement in the first place.
6526*/
6527SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
6528
6529/*
6530** CAPI3REF: Return The Filename For A Database Connection
6531** METHOD: sqlite3
6532**
6533** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
6534** associated with database N of connection D.  ^The main database file
6535** has the name "main".  If there is no attached database N on the database
6536** connection D, or if database N is a temporary or in-memory database, then
6537** a NULL pointer is returned.
6538**
6539** ^The filename returned by this function is the output of the
6540** xFullPathname method of the [VFS].  ^In other words, the filename
6541** will be an absolute pathname, even if the filename used
6542** to open the database originally was a URI or relative pathname.
6543*/
6544SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
6545
6546/*
6547** CAPI3REF: Determine if a database is read-only
6548** METHOD: sqlite3
6549**
6550** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
6551** of connection D is read-only, 0 if it is read/write, or -1 if N is not
6552** the name of a database on connection D.
6553*/
6554SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
6555
6556/*
6557** CAPI3REF: Find the next prepared statement
6558** METHOD: sqlite3
6559**
6560** ^This interface returns a pointer to the next [prepared statement] after
6561** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
6562** then this interface returns a pointer to the first prepared statement
6563** associated with the database connection pDb.  ^If no prepared statement
6564** satisfies the conditions of this routine, it returns NULL.
6565**
6566** The [database connection] pointer D in a call to
6567** [sqlite3_next_stmt(D,S)] must refer to an open database
6568** connection and in particular must not be a NULL pointer.
6569*/
6570SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
6571
6572/*
6573** CAPI3REF: Commit And Rollback Notification Callbacks
6574** METHOD: sqlite3
6575**
6576** ^The sqlite3_commit_hook() interface registers a callback
6577** function to be invoked whenever a transaction is [COMMIT | committed].
6578** ^Any callback set by a previous call to sqlite3_commit_hook()
6579** for the same database connection is overridden.
6580** ^The sqlite3_rollback_hook() interface registers a callback
6581** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
6582** ^Any callback set by a previous call to sqlite3_rollback_hook()
6583** for the same database connection is overridden.
6584** ^The pArg argument is passed through to the callback.
6585** ^If the callback on a commit hook function returns non-zero,
6586** then the commit is converted into a rollback.
6587**
6588** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
6589** return the P argument from the previous call of the same function
6590** on the same [database connection] D, or NULL for
6591** the first call for each function on D.
6592**
6593** The commit and rollback hook callbacks are not reentrant.
6594** The callback implementation must not do anything that will modify
6595** the database connection that invoked the callback.  Any actions
6596** to modify the database connection must be deferred until after the
6597** completion of the [sqlite3_step()] call that triggered the commit
6598** or rollback hook in the first place.
6599** Note that running any other SQL statements, including SELECT statements,
6600** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
6601** the database connections for the meaning of "modify" in this paragraph.
6602**
6603** ^Registering a NULL function disables the callback.
6604**
6605** ^When the commit hook callback routine returns zero, the [COMMIT]
6606** operation is allowed to continue normally.  ^If the commit hook
6607** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
6608** ^The rollback hook is invoked on a rollback that results from a commit
6609** hook returning non-zero, just as it would be with any other rollback.
6610**
6611** ^For the purposes of this API, a transaction is said to have been
6612** rolled back if an explicit "ROLLBACK" statement is executed, or
6613** an error or constraint causes an implicit rollback to occur.
6614** ^The rollback callback is not invoked if a transaction is
6615** automatically rolled back because the database connection is closed.
6616**
6617** See also the [sqlite3_update_hook()] interface.
6618*/
6619SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
6620SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
6621
6622/*
6623** CAPI3REF: Data Change Notification Callbacks
6624** METHOD: sqlite3
6625**
6626** ^The sqlite3_update_hook() interface registers a callback function
6627** with the [database connection] identified by the first argument
6628** to be invoked whenever a row is updated, inserted or deleted in
6629** a [rowid table].
6630** ^Any callback set by a previous call to this function
6631** for the same database connection is overridden.
6632**
6633** ^The second argument is a pointer to the function to invoke when a
6634** row is updated, inserted or deleted in a rowid table.
6635** ^The first argument to the callback is a copy of the third argument
6636** to sqlite3_update_hook().
6637** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
6638** or [SQLITE_UPDATE], depending on the operation that caused the callback
6639** to be invoked.
6640** ^The third and fourth arguments to the callback contain pointers to the
6641** database and table name containing the affected row.
6642** ^The final callback parameter is the [rowid] of the row.
6643** ^In the case of an update, this is the [rowid] after the update takes place.
6644**
6645** ^(The update hook is not invoked when internal system tables are
6646** modified (i.e. sqlite_master and sqlite_sequence).)^
6647** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
6648**
6649** ^In the current implementation, the update hook
6650** is not invoked when conflicting rows are deleted because of an
6651** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
6652** invoked when rows are deleted using the [truncate optimization].
6653** The exceptions defined in this paragraph might change in a future
6654** release of SQLite.
6655**
6656** The update hook implementation must not do anything that will modify
6657** the database connection that invoked the update hook.  Any actions
6658** to modify the database connection must be deferred until after the
6659** completion of the [sqlite3_step()] call that triggered the update hook.
6660** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
6661** database connections for the meaning of "modify" in this paragraph.
6662**
6663** ^The sqlite3_update_hook(D,C,P) function
6664** returns the P argument from the previous call
6665** on the same [database connection] D, or NULL for
6666** the first call on D.
6667**
6668** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
6669** and [sqlite3_preupdate_hook()] interfaces.
6670*/
6671SQLITE_API void *sqlite3_update_hook(
6672  sqlite3*,
6673  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
6674  void*
6675);
6676
6677/*
6678** CAPI3REF: Enable Or Disable Shared Pager Cache
6679**
6680** ^(This routine enables or disables the sharing of the database cache
6681** and schema data structures between [database connection | connections]
6682** to the same database. Sharing is enabled if the argument is true
6683** and disabled if the argument is false.)^
6684**
6685** ^Cache sharing is enabled and disabled for an entire process.
6686** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
6687** In prior versions of SQLite,
6688** sharing was enabled or disabled for each thread separately.
6689**
6690** ^(The cache sharing mode set by this interface effects all subsequent
6691** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
6692** Existing database connections continue use the sharing mode
6693** that was in effect at the time they were opened.)^
6694**
6695** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
6696** successfully.  An [error code] is returned otherwise.)^
6697**
6698** ^Shared cache is disabled by default. But this might change in
6699** future releases of SQLite.  Applications that care about shared
6700** cache setting should set it explicitly.
6701**
6702** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
6703** and will always return SQLITE_MISUSE. On those systems,
6704** shared cache mode should be enabled per-database connection via
6705** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
6706**
6707** This interface is threadsafe on processors where writing a
6708** 32-bit integer is atomic.
6709**
6710** See Also:  [SQLite Shared-Cache Mode]
6711*/
6712SQLITE_API int sqlite3_enable_shared_cache(int);
6713
6714/*
6715** CAPI3REF: Attempt To Free Heap Memory
6716**
6717** ^The sqlite3_release_memory() interface attempts to free N bytes
6718** of heap memory by deallocating non-essential memory allocations
6719** held by the database library.   Memory used to cache database
6720** pages to improve performance is an example of non-essential memory.
6721** ^sqlite3_release_memory() returns the number of bytes actually freed,
6722** which might be more or less than the amount requested.
6723** ^The sqlite3_release_memory() routine is a no-op returning zero
6724** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
6725**
6726** See also: [sqlite3_db_release_memory()]
6727*/
6728SQLITE_API int sqlite3_release_memory(int);
6729
6730/*
6731** CAPI3REF: Free Memory Used By A Database Connection
6732** METHOD: sqlite3
6733**
6734** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
6735** memory as possible from database connection D. Unlike the
6736** [sqlite3_release_memory()] interface, this interface is in effect even
6737** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
6738** omitted.
6739**
6740** See also: [sqlite3_release_memory()]
6741*/
6742SQLITE_API int sqlite3_db_release_memory(sqlite3*);
6743
6744/*
6745** CAPI3REF: Impose A Limit On Heap Size
6746**
6747** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
6748** soft limit on the amount of heap memory that may be allocated by SQLite.
6749** ^SQLite strives to keep heap memory utilization below the soft heap
6750** limit by reducing the number of pages held in the page cache
6751** as heap memory usages approaches the limit.
6752** ^The soft heap limit is "soft" because even though SQLite strives to stay
6753** below the limit, it will exceed the limit rather than generate
6754** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
6755** is advisory only.
6756**
6757** ^The return value from sqlite3_soft_heap_limit64() is the size of
6758** the soft heap limit prior to the call, or negative in the case of an
6759** error.  ^If the argument N is negative
6760** then no change is made to the soft heap limit.  Hence, the current
6761** size of the soft heap limit can be determined by invoking
6762** sqlite3_soft_heap_limit64() with a negative argument.
6763**
6764** ^If the argument N is zero then the soft heap limit is disabled.
6765**
6766** ^(The soft heap limit is not enforced in the current implementation
6767** if one or more of following conditions are true:
6768**
6769** <ul>
6770** <li> The soft heap limit is set to zero.
6771** <li> Memory accounting is disabled using a combination of the
6772**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
6773**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
6774** <li> An alternative page cache implementation is specified using
6775**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
6776** <li> The page cache allocates from its own memory pool supplied
6777**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
6778**      from the heap.
6779** </ul>)^
6780**
6781** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
6782** the soft heap limit is enforced
6783** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
6784** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
6785** the soft heap limit is enforced on every memory allocation.  Without
6786** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
6787** when memory is allocated by the page cache.  Testing suggests that because
6788** the page cache is the predominate memory user in SQLite, most
6789** applications will achieve adequate soft heap limit enforcement without
6790** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
6791**
6792** The circumstances under which SQLite will enforce the soft heap limit may
6793** changes in future releases of SQLite.
6794*/
6795SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
6796
6797/*
6798** CAPI3REF: Deprecated Soft Heap Limit Interface
6799** DEPRECATED
6800**
6801** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
6802** interface.  This routine is provided for historical compatibility
6803** only.  All new applications should use the
6804** [sqlite3_soft_heap_limit64()] interface rather than this one.
6805*/
6806SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
6807
6808
6809/*
6810** CAPI3REF: Extract Metadata About A Column Of A Table
6811** METHOD: sqlite3
6812**
6813** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
6814** information about column C of table T in database D
6815** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
6816** interface returns SQLITE_OK and fills in the non-NULL pointers in
6817** the final five arguments with appropriate values if the specified
6818** column exists.  ^The sqlite3_table_column_metadata() interface returns
6819** SQLITE_ERROR and if the specified column does not exist.
6820** ^If the column-name parameter to sqlite3_table_column_metadata() is a
6821** NULL pointer, then this routine simply checks for the existence of the
6822** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
6823** does not.  If the table name parameter T in a call to
6824** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
6825** undefined behavior.
6826**
6827** ^The column is identified by the second, third and fourth parameters to
6828** this function. ^(The second parameter is either the name of the database
6829** (i.e. "main", "temp", or an attached database) containing the specified
6830** table or NULL.)^ ^If it is NULL, then all attached databases are searched
6831** for the table using the same algorithm used by the database engine to
6832** resolve unqualified table references.
6833**
6834** ^The third and fourth parameters to this function are the table and column
6835** name of the desired column, respectively.
6836**
6837** ^Metadata is returned by writing to the memory locations passed as the 5th
6838** and subsequent parameters to this function. ^Any of these arguments may be
6839** NULL, in which case the corresponding element of metadata is omitted.
6840**
6841** ^(<blockquote>
6842** <table border="1">
6843** <tr><th> Parameter <th> Output<br>Type <th>  Description
6844**
6845** <tr><td> 5th <td> const char* <td> Data type
6846** <tr><td> 6th <td> const char* <td> Name of default collation sequence
6847** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
6848** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
6849** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
6850** </table>
6851** </blockquote>)^
6852**
6853** ^The memory pointed to by the character pointers returned for the
6854** declaration type and collation sequence is valid until the next
6855** call to any SQLite API function.
6856**
6857** ^If the specified table is actually a view, an [error code] is returned.
6858**
6859** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
6860** is not a [WITHOUT ROWID] table and an
6861** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
6862** parameters are set for the explicitly declared column. ^(If there is no
6863** [INTEGER PRIMARY KEY] column, then the outputs
6864** for the [rowid] are set as follows:
6865**
6866** <pre>
6867**     data type: "INTEGER"
6868**     collation sequence: "BINARY"
6869**     not null: 0
6870**     primary key: 1
6871**     auto increment: 0
6872** </pre>)^
6873**
6874** ^This function causes all database schemas to be read from disk and
6875** parsed, if that has not already been done, and returns an error if
6876** any errors are encountered while loading the schema.
6877*/
6878SQLITE_API int sqlite3_table_column_metadata(
6879  sqlite3 *db,                /* Connection handle */
6880  const char *zDbName,        /* Database name or NULL */
6881  const char *zTableName,     /* Table name */
6882  const char *zColumnName,    /* Column name */
6883  char const **pzDataType,    /* OUTPUT: Declared data type */
6884  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
6885  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
6886  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
6887  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
6888);
6889
6890/*
6891** CAPI3REF: Load An Extension
6892** METHOD: sqlite3
6893**
6894** ^This interface loads an SQLite extension library from the named file.
6895**
6896** ^The sqlite3_load_extension() interface attempts to load an
6897** [SQLite extension] library contained in the file zFile.  If
6898** the file cannot be loaded directly, attempts are made to load
6899** with various operating-system specific extensions added.
6900** So for example, if "samplelib" cannot be loaded, then names like
6901** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
6902** be tried also.
6903**
6904** ^The entry point is zProc.
6905** ^(zProc may be 0, in which case SQLite will try to come up with an
6906** entry point name on its own.  It first tries "sqlite3_extension_init".
6907** If that does not work, it constructs a name "sqlite3_X_init" where the
6908** X is consists of the lower-case equivalent of all ASCII alphabetic
6909** characters in the filename from the last "/" to the first following
6910** "." and omitting any initial "lib".)^
6911** ^The sqlite3_load_extension() interface returns
6912** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
6913** ^If an error occurs and pzErrMsg is not 0, then the
6914** [sqlite3_load_extension()] interface shall attempt to
6915** fill *pzErrMsg with error message text stored in memory
6916** obtained from [sqlite3_malloc()]. The calling function
6917** should free this memory by calling [sqlite3_free()].
6918**
6919** ^Extension loading must be enabled using
6920** [sqlite3_enable_load_extension()] or
6921** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
6922** prior to calling this API,
6923** otherwise an error will be returned.
6924**
6925** <b>Security warning:</b> It is recommended that the
6926** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
6927** interface.  The use of the [sqlite3_enable_load_extension()] interface
6928** should be avoided.  This will keep the SQL function [load_extension()]
6929** disabled and prevent SQL injections from giving attackers
6930** access to extension loading capabilities.
6931**
6932** See also the [load_extension() SQL function].
6933*/
6934SQLITE_API int sqlite3_load_extension(
6935  sqlite3 *db,          /* Load the extension into this database connection */
6936  const char *zFile,    /* Name of the shared library containing extension */
6937  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
6938  char **pzErrMsg       /* Put error message here if not 0 */
6939);
6940
6941/*
6942** CAPI3REF: Enable Or Disable Extension Loading
6943** METHOD: sqlite3
6944**
6945** ^So as not to open security holes in older applications that are
6946** unprepared to deal with [extension loading], and as a means of disabling
6947** [extension loading] while evaluating user-entered SQL, the following API
6948** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
6949**
6950** ^Extension loading is off by default.
6951** ^Call the sqlite3_enable_load_extension() routine with onoff==1
6952** to turn extension loading on and call it with onoff==0 to turn
6953** it back off again.
6954**
6955** ^This interface enables or disables both the C-API
6956** [sqlite3_load_extension()] and the SQL function [load_extension()].
6957** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
6958** to enable or disable only the C-API.)^
6959**
6960** <b>Security warning:</b> It is recommended that extension loading
6961** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
6962** rather than this interface, so the [load_extension()] SQL function
6963** remains disabled. This will prevent SQL injections from giving attackers
6964** access to extension loading capabilities.
6965*/
6966SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
6967
6968/*
6969** CAPI3REF: Automatically Load Statically Linked Extensions
6970**
6971** ^This interface causes the xEntryPoint() function to be invoked for
6972** each new [database connection] that is created.  The idea here is that
6973** xEntryPoint() is the entry point for a statically linked [SQLite extension]
6974** that is to be automatically loaded into all new database connections.
6975**
6976** ^(Even though the function prototype shows that xEntryPoint() takes
6977** no arguments and returns void, SQLite invokes xEntryPoint() with three
6978** arguments and expects an integer result as if the signature of the
6979** entry point where as follows:
6980**
6981** <blockquote><pre>
6982** &nbsp;  int xEntryPoint(
6983** &nbsp;    sqlite3 *db,
6984** &nbsp;    const char **pzErrMsg,
6985** &nbsp;    const struct sqlite3_api_routines *pThunk
6986** &nbsp;  );
6987** </pre></blockquote>)^
6988**
6989** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
6990** point to an appropriate error message (obtained from [sqlite3_mprintf()])
6991** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
6992** is NULL before calling the xEntryPoint().  ^SQLite will invoke
6993** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
6994** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
6995** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
6996**
6997** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
6998** on the list of automatic extensions is a harmless no-op. ^No entry point
6999** will be called more than once for each database connection that is opened.
7000**
7001** See also: [sqlite3_reset_auto_extension()]
7002** and [sqlite3_cancel_auto_extension()]
7003*/
7004SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
7005
7006/*
7007** CAPI3REF: Cancel Automatic Extension Loading
7008**
7009** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
7010** initialization routine X that was registered using a prior call to
7011** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
7012** routine returns 1 if initialization routine X was successfully
7013** unregistered and it returns 0 if X was not on the list of initialization
7014** routines.
7015*/
7016SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
7017
7018/*
7019** CAPI3REF: Reset Automatic Extension Loading
7020**
7021** ^This interface disables all automatic extensions previously
7022** registered using [sqlite3_auto_extension()].
7023*/
7024SQLITE_API void sqlite3_reset_auto_extension(void);
7025
7026/*
7027** The interface to the virtual-table mechanism is currently considered
7028** to be experimental.  The interface might change in incompatible ways.
7029** If this is a problem for you, do not use the interface at this time.
7030**
7031** When the virtual-table mechanism stabilizes, we will declare the
7032** interface fixed, support it indefinitely, and remove this comment.
7033*/
7034
7035/*
7036** Structures used by the virtual table interface
7037*/
7038typedef struct sqlite3_vtab sqlite3_vtab;
7039typedef struct sqlite3_index_info sqlite3_index_info;
7040typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
7041typedef struct sqlite3_module sqlite3_module;
7042
7043/*
7044** CAPI3REF: Virtual Table Object
7045** KEYWORDS: sqlite3_module {virtual table module}
7046**
7047** This structure, sometimes called a "virtual table module",
7048** defines the implementation of a [virtual tables].
7049** This structure consists mostly of methods for the module.
7050**
7051** ^A virtual table module is created by filling in a persistent
7052** instance of this structure and passing a pointer to that instance
7053** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
7054** ^The registration remains valid until it is replaced by a different
7055** module or until the [database connection] closes.  The content
7056** of this structure must not change while it is registered with
7057** any database connection.
7058*/
7059struct sqlite3_module {
7060  int iVersion;
7061  int (*xCreate)(sqlite3*, void *pAux,
7062               int argc, const char *const*argv,
7063               sqlite3_vtab **ppVTab, char**);
7064  int (*xConnect)(sqlite3*, void *pAux,
7065               int argc, const char *const*argv,
7066               sqlite3_vtab **ppVTab, char**);
7067  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
7068  int (*xDisconnect)(sqlite3_vtab *pVTab);
7069  int (*xDestroy)(sqlite3_vtab *pVTab);
7070  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
7071  int (*xClose)(sqlite3_vtab_cursor*);
7072  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
7073                int argc, sqlite3_value **argv);
7074  int (*xNext)(sqlite3_vtab_cursor*);
7075  int (*xEof)(sqlite3_vtab_cursor*);
7076  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
7077  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
7078  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
7079  int (*xBegin)(sqlite3_vtab *pVTab);
7080  int (*xSync)(sqlite3_vtab *pVTab);
7081  int (*xCommit)(sqlite3_vtab *pVTab);
7082  int (*xRollback)(sqlite3_vtab *pVTab);
7083  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
7084                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
7085                       void **ppArg);
7086  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
7087  /* The methods above are in version 1 of the sqlite_module object. Those
7088  ** below are for version 2 and greater. */
7089  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
7090  int (*xRelease)(sqlite3_vtab *pVTab, int);
7091  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
7092};
7093
7094/*
7095** CAPI3REF: Virtual Table Indexing Information
7096** KEYWORDS: sqlite3_index_info
7097**
7098** The sqlite3_index_info structure and its substructures is used as part
7099** of the [virtual table] interface to
7100** pass information into and receive the reply from the [xBestIndex]
7101** method of a [virtual table module].  The fields under **Inputs** are the
7102** inputs to xBestIndex and are read-only.  xBestIndex inserts its
7103** results into the **Outputs** fields.
7104**
7105** ^(The aConstraint[] array records WHERE clause constraints of the form:
7106**
7107** <blockquote>column OP expr</blockquote>
7108**
7109** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
7110** stored in aConstraint[].op using one of the
7111** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
7112** ^(The index of the column is stored in
7113** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
7114** expr on the right-hand side can be evaluated (and thus the constraint
7115** is usable) and false if it cannot.)^
7116**
7117** ^The optimizer automatically inverts terms of the form "expr OP column"
7118** and makes other simplifications to the WHERE clause in an attempt to
7119** get as many WHERE clause terms into the form shown above as possible.
7120** ^The aConstraint[] array only reports WHERE clause terms that are
7121** relevant to the particular virtual table being queried.
7122**
7123** ^Information about the ORDER BY clause is stored in aOrderBy[].
7124** ^Each term of aOrderBy records a column of the ORDER BY clause.
7125**
7126** The colUsed field indicates which columns of the virtual table may be
7127** required by the current scan. Virtual table columns are numbered from
7128** zero in the order in which they appear within the CREATE TABLE statement
7129** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
7130** the corresponding bit is set within the colUsed mask if the column may be
7131** required by SQLite. If the table has at least 64 columns and any column
7132** to the right of the first 63 is required, then bit 63 of colUsed is also
7133** set. In other words, column iCol may be required if the expression
7134** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
7135** non-zero.
7136**
7137** The [xBestIndex] method must fill aConstraintUsage[] with information
7138** about what parameters to pass to xFilter.  ^If argvIndex>0 then
7139** the right-hand side of the corresponding aConstraint[] is evaluated
7140** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
7141** is true, then the constraint is assumed to be fully handled by the
7142** virtual table and is not checked again by SQLite.)^
7143**
7144** ^The idxNum and idxPtr values are recorded and passed into the
7145** [xFilter] method.
7146** ^[sqlite3_free()] is used to free idxPtr if and only if
7147** needToFreeIdxPtr is true.
7148**
7149** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
7150** the correct order to satisfy the ORDER BY clause so that no separate
7151** sorting step is required.
7152**
7153** ^The estimatedCost value is an estimate of the cost of a particular
7154** strategy. A cost of N indicates that the cost of the strategy is similar
7155** to a linear scan of an SQLite table with N rows. A cost of log(N)
7156** indicates that the expense of the operation is similar to that of a
7157** binary search on a unique indexed field of an SQLite table with N rows.
7158**
7159** ^The estimatedRows value is an estimate of the number of rows that
7160** will be returned by the strategy.
7161**
7162** The xBestIndex method may optionally populate the idxFlags field with a
7163** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
7164** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
7165** assumes that the strategy may visit at most one row.
7166**
7167** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
7168** SQLite also assumes that if a call to the xUpdate() method is made as
7169** part of the same statement to delete or update a virtual table row and the
7170** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
7171** any database changes. In other words, if the xUpdate() returns
7172** SQLITE_CONSTRAINT, the database contents must be exactly as they were
7173** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
7174** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
7175** the xUpdate method are automatically rolled back by SQLite.
7176**
7177** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
7178** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
7179** If a virtual table extension is
7180** used with an SQLite version earlier than 3.8.2, the results of attempting
7181** to read or write the estimatedRows field are undefined (but are likely
7182** to included crashing the application). The estimatedRows field should
7183** therefore only be used if [sqlite3_libversion_number()] returns a
7184** value greater than or equal to 3008002. Similarly, the idxFlags field
7185** was added for [version 3.9.0] ([dateof:3.9.0]).
7186** It may therefore only be used if
7187** sqlite3_libversion_number() returns a value greater than or equal to
7188** 3009000.
7189*/
7190struct sqlite3_index_info {
7191  /* Inputs */
7192  int nConstraint;           /* Number of entries in aConstraint */
7193  struct sqlite3_index_constraint {
7194     int iColumn;              /* Column constrained.  -1 for ROWID */
7195     unsigned char op;         /* Constraint operator */
7196     unsigned char usable;     /* True if this constraint is usable */
7197     int iTermOffset;          /* Used internally - xBestIndex should ignore */
7198  } *aConstraint;            /* Table of WHERE clause constraints */
7199  int nOrderBy;              /* Number of terms in the ORDER BY clause */
7200  struct sqlite3_index_orderby {
7201     int iColumn;              /* Column number */
7202     unsigned char desc;       /* True for DESC.  False for ASC. */
7203  } *aOrderBy;               /* The ORDER BY clause */
7204  /* Outputs */
7205  struct sqlite3_index_constraint_usage {
7206    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
7207    unsigned char omit;      /* Do not code a test for this constraint */
7208  } *aConstraintUsage;
7209  int idxNum;                /* Number used to identify the index */
7210  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
7211  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
7212  int orderByConsumed;       /* True if output is already ordered */
7213  double estimatedCost;           /* Estimated cost of using this index */
7214  /* Fields below are only available in SQLite 3.8.2 and later */
7215  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
7216  /* Fields below are only available in SQLite 3.9.0 and later */
7217  int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
7218  /* Fields below are only available in SQLite 3.10.0 and later */
7219  sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
7220};
7221
7222/*
7223** CAPI3REF: Virtual Table Scan Flags
7224*/
7225#define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
7226
7227/*
7228** CAPI3REF: Virtual Table Constraint Operator Codes
7229**
7230** These macros defined the allowed values for the
7231** [sqlite3_index_info].aConstraint[].op field.  Each value represents
7232** an operator that is part of a constraint term in the wHERE clause of
7233** a query that uses a [virtual table].
7234*/
7235#define SQLITE_INDEX_CONSTRAINT_EQ      2
7236#define SQLITE_INDEX_CONSTRAINT_GT      4
7237#define SQLITE_INDEX_CONSTRAINT_LE      8
7238#define SQLITE_INDEX_CONSTRAINT_LT     16
7239#define SQLITE_INDEX_CONSTRAINT_GE     32
7240#define SQLITE_INDEX_CONSTRAINT_MATCH  64
7241#define SQLITE_INDEX_CONSTRAINT_LIKE   65
7242#define SQLITE_INDEX_CONSTRAINT_GLOB   66
7243#define SQLITE_INDEX_CONSTRAINT_REGEXP 67
7244
7245/*
7246** CAPI3REF: Register A Virtual Table Implementation
7247** METHOD: sqlite3
7248**
7249** ^These routines are used to register a new [virtual table module] name.
7250** ^Module names must be registered before
7251** creating a new [virtual table] using the module and before using a
7252** preexisting [virtual table] for the module.
7253**
7254** ^The module name is registered on the [database connection] specified
7255** by the first parameter.  ^The name of the module is given by the
7256** second parameter.  ^The third parameter is a pointer to
7257** the implementation of the [virtual table module].   ^The fourth
7258** parameter is an arbitrary client data pointer that is passed through
7259** into the [xCreate] and [xConnect] methods of the virtual table module
7260** when a new virtual table is be being created or reinitialized.
7261**
7262** ^The sqlite3_create_module_v2() interface has a fifth parameter which
7263** is a pointer to a destructor for the pClientData.  ^SQLite will
7264** invoke the destructor function (if it is not NULL) when SQLite
7265** no longer needs the pClientData pointer.  ^The destructor will also
7266** be invoked if the call to sqlite3_create_module_v2() fails.
7267** ^The sqlite3_create_module()
7268** interface is equivalent to sqlite3_create_module_v2() with a NULL
7269** destructor.
7270*/
7271SQLITE_API int sqlite3_create_module(
7272  sqlite3 *db,               /* SQLite connection to register module with */
7273  const char *zName,         /* Name of the module */
7274  const sqlite3_module *p,   /* Methods for the module */
7275  void *pClientData          /* Client data for xCreate/xConnect */
7276);
7277SQLITE_API int sqlite3_create_module_v2(
7278  sqlite3 *db,               /* SQLite connection to register module with */
7279  const char *zName,         /* Name of the module */
7280  const sqlite3_module *p,   /* Methods for the module */
7281  void *pClientData,         /* Client data for xCreate/xConnect */
7282  void(*xDestroy)(void*)     /* Module destructor function */
7283);
7284
7285/*
7286** CAPI3REF: Virtual Table Instance Object
7287** KEYWORDS: sqlite3_vtab
7288**
7289** Every [virtual table module] implementation uses a subclass
7290** of this object to describe a particular instance
7291** of the [virtual table].  Each subclass will
7292** be tailored to the specific needs of the module implementation.
7293** The purpose of this superclass is to define certain fields that are
7294** common to all module implementations.
7295**
7296** ^Virtual tables methods can set an error message by assigning a
7297** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
7298** take care that any prior string is freed by a call to [sqlite3_free()]
7299** prior to assigning a new string to zErrMsg.  ^After the error message
7300** is delivered up to the client application, the string will be automatically
7301** freed by sqlite3_free() and the zErrMsg field will be zeroed.
7302*/
7303struct sqlite3_vtab {
7304  const sqlite3_module *pModule;  /* The module for this virtual table */
7305  int nRef;                       /* Number of open cursors */
7306  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
7307  /* Virtual table implementations will typically add additional fields */
7308};
7309
7310/*
7311** CAPI3REF: Virtual Table Cursor Object
7312** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
7313**
7314** Every [virtual table module] implementation uses a subclass of the
7315** following structure to describe cursors that point into the
7316** [virtual table] and are used
7317** to loop through the virtual table.  Cursors are created using the
7318** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
7319** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
7320** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
7321** of the module.  Each module implementation will define
7322** the content of a cursor structure to suit its own needs.
7323**
7324** This superclass exists in order to define fields of the cursor that
7325** are common to all implementations.
7326*/
7327struct sqlite3_vtab_cursor {
7328  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
7329  /* Virtual table implementations will typically add additional fields */
7330};
7331
7332/*
7333** CAPI3REF: Declare The Schema Of A Virtual Table
7334**
7335** ^The [xCreate] and [xConnect] methods of a
7336** [virtual table module] call this interface
7337** to declare the format (the names and datatypes of the columns) of
7338** the virtual tables they implement.
7339*/
7340SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
7341
7342/*
7343** CAPI3REF: Overload A Function For A Virtual Table
7344** METHOD: sqlite3
7345**
7346** ^(Virtual tables can provide alternative implementations of functions
7347** using the [xFindFunction] method of the [virtual table module].
7348** But global versions of those functions
7349** must exist in order to be overloaded.)^
7350**
7351** ^(This API makes sure a global version of a function with a particular
7352** name and number of parameters exists.  If no such function exists
7353** before this API is called, a new function is created.)^  ^The implementation
7354** of the new function always causes an exception to be thrown.  So
7355** the new function is not good for anything by itself.  Its only
7356** purpose is to be a placeholder function that can be overloaded
7357** by a [virtual table].
7358*/
7359SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
7360
7361/*
7362** The interface to the virtual-table mechanism defined above (back up
7363** to a comment remarkably similar to this one) is currently considered
7364** to be experimental.  The interface might change in incompatible ways.
7365** If this is a problem for you, do not use the interface at this time.
7366**
7367** When the virtual-table mechanism stabilizes, we will declare the
7368** interface fixed, support it indefinitely, and remove this comment.
7369*/
7370
7371/*
7372** CAPI3REF: A Handle To An Open BLOB
7373** KEYWORDS: {BLOB handle} {BLOB handles}
7374**
7375** An instance of this object represents an open BLOB on which
7376** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
7377** ^Objects of this type are created by [sqlite3_blob_open()]
7378** and destroyed by [sqlite3_blob_close()].
7379** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
7380** can be used to read or write small subsections of the BLOB.
7381** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
7382*/
7383typedef struct sqlite3_blob sqlite3_blob;
7384
7385/*
7386** CAPI3REF: Open A BLOB For Incremental I/O
7387** METHOD: sqlite3
7388** CONSTRUCTOR: sqlite3_blob
7389**
7390** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
7391** in row iRow, column zColumn, table zTable in database zDb;
7392** in other words, the same BLOB that would be selected by:
7393**
7394** <pre>
7395**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
7396** </pre>)^
7397**
7398** ^(Parameter zDb is not the filename that contains the database, but
7399** rather the symbolic name of the database. For attached databases, this is
7400** the name that appears after the AS keyword in the [ATTACH] statement.
7401** For the main database file, the database name is "main". For TEMP
7402** tables, the database name is "temp".)^
7403**
7404** ^If the flags parameter is non-zero, then the BLOB is opened for read
7405** and write access. ^If the flags parameter is zero, the BLOB is opened for
7406** read-only access.
7407**
7408** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
7409** in *ppBlob. Otherwise an [error code] is returned and, unless the error
7410** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
7411** the API is not misused, it is always safe to call [sqlite3_blob_close()]
7412** on *ppBlob after this function it returns.
7413**
7414** This function fails with SQLITE_ERROR if any of the following are true:
7415** <ul>
7416**   <li> ^(Database zDb does not exist)^,
7417**   <li> ^(Table zTable does not exist within database zDb)^,
7418**   <li> ^(Table zTable is a WITHOUT ROWID table)^,
7419**   <li> ^(Column zColumn does not exist)^,
7420**   <li> ^(Row iRow is not present in the table)^,
7421**   <li> ^(The specified column of row iRow contains a value that is not
7422**         a TEXT or BLOB value)^,
7423**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
7424**         constraint and the blob is being opened for read/write access)^,
7425**   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
7426**         column zColumn is part of a [child key] definition and the blob is
7427**         being opened for read/write access)^.
7428** </ul>
7429**
7430** ^Unless it returns SQLITE_MISUSE, this function sets the
7431** [database connection] error code and message accessible via
7432** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
7433**
7434** A BLOB referenced by sqlite3_blob_open() may be read using the
7435** [sqlite3_blob_read()] interface and modified by using
7436** [sqlite3_blob_write()].  The [BLOB handle] can be moved to a
7437** different row of the same table using the [sqlite3_blob_reopen()]
7438** interface.  However, the column, table, or database of a [BLOB handle]
7439** cannot be changed after the [BLOB handle] is opened.
7440**
7441** ^(If the row that a BLOB handle points to is modified by an
7442** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
7443** then the BLOB handle is marked as "expired".
7444** This is true if any column of the row is changed, even a column
7445** other than the one the BLOB handle is open on.)^
7446** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
7447** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
7448** ^(Changes written into a BLOB prior to the BLOB expiring are not
7449** rolled back by the expiration of the BLOB.  Such changes will eventually
7450** commit if the transaction continues to completion.)^
7451**
7452** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
7453** the opened blob.  ^The size of a blob may not be changed by this
7454** interface.  Use the [UPDATE] SQL command to change the size of a
7455** blob.
7456**
7457** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
7458** and the built-in [zeroblob] SQL function may be used to create a
7459** zero-filled blob to read or write using the incremental-blob interface.
7460**
7461** To avoid a resource leak, every open [BLOB handle] should eventually
7462** be released by a call to [sqlite3_blob_close()].
7463**
7464** See also: [sqlite3_blob_close()],
7465** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
7466** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
7467*/
7468SQLITE_API int sqlite3_blob_open(
7469  sqlite3*,
7470  const char *zDb,
7471  const char *zTable,
7472  const char *zColumn,
7473  sqlite3_int64 iRow,
7474  int flags,
7475  sqlite3_blob **ppBlob
7476);
7477
7478/*
7479** CAPI3REF: Move a BLOB Handle to a New Row
7480** METHOD: sqlite3_blob
7481**
7482** ^This function is used to move an existing [BLOB handle] so that it points
7483** to a different row of the same database table. ^The new row is identified
7484** by the rowid value passed as the second argument. Only the row can be
7485** changed. ^The database, table and column on which the blob handle is open
7486** remain the same. Moving an existing [BLOB handle] to a new row is
7487** faster than closing the existing handle and opening a new one.
7488**
7489** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
7490** it must exist and there must be either a blob or text value stored in
7491** the nominated column.)^ ^If the new row is not present in the table, or if
7492** it does not contain a blob or text value, or if another error occurs, an
7493** SQLite error code is returned and the blob handle is considered aborted.
7494** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
7495** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
7496** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
7497** always returns zero.
7498**
7499** ^This function sets the database handle error code and message.
7500*/
7501SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
7502
7503/*
7504** CAPI3REF: Close A BLOB Handle
7505** DESTRUCTOR: sqlite3_blob
7506**
7507** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
7508** unconditionally.  Even if this routine returns an error code, the
7509** handle is still closed.)^
7510**
7511** ^If the blob handle being closed was opened for read-write access, and if
7512** the database is in auto-commit mode and there are no other open read-write
7513** blob handles or active write statements, the current transaction is
7514** committed. ^If an error occurs while committing the transaction, an error
7515** code is returned and the transaction rolled back.
7516**
7517** Calling this function with an argument that is not a NULL pointer or an
7518** open blob handle results in undefined behaviour. ^Calling this routine
7519** with a null pointer (such as would be returned by a failed call to
7520** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
7521** is passed a valid open blob handle, the values returned by the
7522** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
7523*/
7524SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
7525
7526/*
7527** CAPI3REF: Return The Size Of An Open BLOB
7528** METHOD: sqlite3_blob
7529**
7530** ^Returns the size in bytes of the BLOB accessible via the
7531** successfully opened [BLOB handle] in its only argument.  ^The
7532** incremental blob I/O routines can only read or overwriting existing
7533** blob content; they cannot change the size of a blob.
7534**
7535** This routine only works on a [BLOB handle] which has been created
7536** by a prior successful call to [sqlite3_blob_open()] and which has not
7537** been closed by [sqlite3_blob_close()].  Passing any other pointer in
7538** to this routine results in undefined and probably undesirable behavior.
7539*/
7540SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
7541
7542/*
7543** CAPI3REF: Read Data From A BLOB Incrementally
7544** METHOD: sqlite3_blob
7545**
7546** ^(This function is used to read data from an open [BLOB handle] into a
7547** caller-supplied buffer. N bytes of data are copied into buffer Z
7548** from the open BLOB, starting at offset iOffset.)^
7549**
7550** ^If offset iOffset is less than N bytes from the end of the BLOB,
7551** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
7552** less than zero, [SQLITE_ERROR] is returned and no data is read.
7553** ^The size of the blob (and hence the maximum value of N+iOffset)
7554** can be determined using the [sqlite3_blob_bytes()] interface.
7555**
7556** ^An attempt to read from an expired [BLOB handle] fails with an
7557** error code of [SQLITE_ABORT].
7558**
7559** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
7560** Otherwise, an [error code] or an [extended error code] is returned.)^
7561**
7562** This routine only works on a [BLOB handle] which has been created
7563** by a prior successful call to [sqlite3_blob_open()] and which has not
7564** been closed by [sqlite3_blob_close()].  Passing any other pointer in
7565** to this routine results in undefined and probably undesirable behavior.
7566**
7567** See also: [sqlite3_blob_write()].
7568*/
7569SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
7570
7571/*
7572** CAPI3REF: Write Data Into A BLOB Incrementally
7573** METHOD: sqlite3_blob
7574**
7575** ^(This function is used to write data into an open [BLOB handle] from a
7576** caller-supplied buffer. N bytes of data are copied from the buffer Z
7577** into the open BLOB, starting at offset iOffset.)^
7578**
7579** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
7580** Otherwise, an  [error code] or an [extended error code] is returned.)^
7581** ^Unless SQLITE_MISUSE is returned, this function sets the
7582** [database connection] error code and message accessible via
7583** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
7584**
7585** ^If the [BLOB handle] passed as the first argument was not opened for
7586** writing (the flags parameter to [sqlite3_blob_open()] was zero),
7587** this function returns [SQLITE_READONLY].
7588**
7589** This function may only modify the contents of the BLOB; it is
7590** not possible to increase the size of a BLOB using this API.
7591** ^If offset iOffset is less than N bytes from the end of the BLOB,
7592** [SQLITE_ERROR] is returned and no data is written. The size of the
7593** BLOB (and hence the maximum value of N+iOffset) can be determined
7594** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
7595** than zero [SQLITE_ERROR] is returned and no data is written.
7596**
7597** ^An attempt to write to an expired [BLOB handle] fails with an
7598** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
7599** before the [BLOB handle] expired are not rolled back by the
7600** expiration of the handle, though of course those changes might
7601** have been overwritten by the statement that expired the BLOB handle
7602** or by other independent statements.
7603**
7604** This routine only works on a [BLOB handle] which has been created
7605** by a prior successful call to [sqlite3_blob_open()] and which has not
7606** been closed by [sqlite3_blob_close()].  Passing any other pointer in
7607** to this routine results in undefined and probably undesirable behavior.
7608**
7609** See also: [sqlite3_blob_read()].
7610*/
7611SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
7612
7613/*
7614** CAPI3REF: Virtual File System Objects
7615**
7616** A virtual filesystem (VFS) is an [sqlite3_vfs] object
7617** that SQLite uses to interact
7618** with the underlying operating system.  Most SQLite builds come with a
7619** single default VFS that is appropriate for the host computer.
7620** New VFSes can be registered and existing VFSes can be unregistered.
7621** The following interfaces are provided.
7622**
7623** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
7624** ^Names are case sensitive.
7625** ^Names are zero-terminated UTF-8 strings.
7626** ^If there is no match, a NULL pointer is returned.
7627** ^If zVfsName is NULL then the default VFS is returned.
7628**
7629** ^New VFSes are registered with sqlite3_vfs_register().
7630** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
7631** ^The same VFS can be registered multiple times without injury.
7632** ^To make an existing VFS into the default VFS, register it again
7633** with the makeDflt flag set.  If two different VFSes with the
7634** same name are registered, the behavior is undefined.  If a
7635** VFS is registered with a name that is NULL or an empty string,
7636** then the behavior is undefined.
7637**
7638** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
7639** ^(If the default VFS is unregistered, another VFS is chosen as
7640** the default.  The choice for the new VFS is arbitrary.)^
7641*/
7642SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
7643SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
7644SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
7645
7646/*
7647** CAPI3REF: Mutexes
7648**
7649** The SQLite core uses these routines for thread
7650** synchronization. Though they are intended for internal
7651** use by SQLite, code that links against SQLite is
7652** permitted to use any of these routines.
7653**
7654** The SQLite source code contains multiple implementations
7655** of these mutex routines.  An appropriate implementation
7656** is selected automatically at compile-time.  The following
7657** implementations are available in the SQLite core:
7658**
7659** <ul>
7660** <li>   SQLITE_MUTEX_PTHREADS
7661** <li>   SQLITE_MUTEX_W32
7662** <li>   SQLITE_MUTEX_NOOP
7663** </ul>
7664**
7665** The SQLITE_MUTEX_NOOP implementation is a set of routines
7666** that does no real locking and is appropriate for use in
7667** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
7668** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
7669** and Windows.
7670**
7671** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
7672** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
7673** implementation is included with the library. In this case the
7674** application must supply a custom mutex implementation using the
7675** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
7676** before calling sqlite3_initialize() or any other public sqlite3_
7677** function that calls sqlite3_initialize().
7678**
7679** ^The sqlite3_mutex_alloc() routine allocates a new
7680** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
7681** routine returns NULL if it is unable to allocate the requested
7682** mutex.  The argument to sqlite3_mutex_alloc() must one of these
7683** integer constants:
7684**
7685** <ul>
7686** <li>  SQLITE_MUTEX_FAST
7687** <li>  SQLITE_MUTEX_RECURSIVE
7688** <li>  SQLITE_MUTEX_STATIC_MASTER
7689** <li>  SQLITE_MUTEX_STATIC_MEM
7690** <li>  SQLITE_MUTEX_STATIC_OPEN
7691** <li>  SQLITE_MUTEX_STATIC_PRNG
7692** <li>  SQLITE_MUTEX_STATIC_LRU
7693** <li>  SQLITE_MUTEX_STATIC_PMEM
7694** <li>  SQLITE_MUTEX_STATIC_APP1
7695** <li>  SQLITE_MUTEX_STATIC_APP2
7696** <li>  SQLITE_MUTEX_STATIC_APP3
7697** <li>  SQLITE_MUTEX_STATIC_VFS1
7698** <li>  SQLITE_MUTEX_STATIC_VFS2
7699** <li>  SQLITE_MUTEX_STATIC_VFS3
7700** </ul>
7701**
7702** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
7703** cause sqlite3_mutex_alloc() to create
7704** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
7705** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
7706** The mutex implementation does not need to make a distinction
7707** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
7708** not want to.  SQLite will only request a recursive mutex in
7709** cases where it really needs one.  If a faster non-recursive mutex
7710** implementation is available on the host platform, the mutex subsystem
7711** might return such a mutex in response to SQLITE_MUTEX_FAST.
7712**
7713** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
7714** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
7715** a pointer to a static preexisting mutex.  ^Nine static mutexes are
7716** used by the current version of SQLite.  Future versions of SQLite
7717** may add additional static mutexes.  Static mutexes are for internal
7718** use by SQLite only.  Applications that use SQLite mutexes should
7719** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
7720** SQLITE_MUTEX_RECURSIVE.
7721**
7722** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
7723** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
7724** returns a different mutex on every call.  ^For the static
7725** mutex types, the same mutex is returned on every call that has
7726** the same type number.
7727**
7728** ^The sqlite3_mutex_free() routine deallocates a previously
7729** allocated dynamic mutex.  Attempting to deallocate a static
7730** mutex results in undefined behavior.
7731**
7732** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
7733** to enter a mutex.  ^If another thread is already within the mutex,
7734** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
7735** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
7736** upon successful entry.  ^(Mutexes created using
7737** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
7738** In such cases, the
7739** mutex must be exited an equal number of times before another thread
7740** can enter.)^  If the same thread tries to enter any mutex other
7741** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
7742**
7743** ^(Some systems (for example, Windows 95) do not support the operation
7744** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
7745** will always return SQLITE_BUSY. The SQLite core only ever uses
7746** sqlite3_mutex_try() as an optimization so this is acceptable
7747** behavior.)^
7748**
7749** ^The sqlite3_mutex_leave() routine exits a mutex that was
7750** previously entered by the same thread.   The behavior
7751** is undefined if the mutex is not currently entered by the
7752** calling thread or is not currently allocated.
7753**
7754** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
7755** sqlite3_mutex_leave() is a NULL pointer, then all three routines
7756** behave as no-ops.
7757**
7758** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
7759*/
7760SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
7761SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
7762SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
7763SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
7764SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
7765
7766/*
7767** CAPI3REF: Mutex Methods Object
7768**
7769** An instance of this structure defines the low-level routines
7770** used to allocate and use mutexes.
7771**
7772** Usually, the default mutex implementations provided by SQLite are
7773** sufficient, however the application has the option of substituting a custom
7774** implementation for specialized deployments or systems for which SQLite
7775** does not provide a suitable implementation. In this case, the application
7776** creates and populates an instance of this structure to pass
7777** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
7778** Additionally, an instance of this structure can be used as an
7779** output variable when querying the system for the current mutex
7780** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
7781**
7782** ^The xMutexInit method defined by this structure is invoked as
7783** part of system initialization by the sqlite3_initialize() function.
7784** ^The xMutexInit routine is called by SQLite exactly once for each
7785** effective call to [sqlite3_initialize()].
7786**
7787** ^The xMutexEnd method defined by this structure is invoked as
7788** part of system shutdown by the sqlite3_shutdown() function. The
7789** implementation of this method is expected to release all outstanding
7790** resources obtained by the mutex methods implementation, especially
7791** those obtained by the xMutexInit method.  ^The xMutexEnd()
7792** interface is invoked exactly once for each call to [sqlite3_shutdown()].
7793**
7794** ^(The remaining seven methods defined by this structure (xMutexAlloc,
7795** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
7796** xMutexNotheld) implement the following interfaces (respectively):
7797**
7798** <ul>
7799**   <li>  [sqlite3_mutex_alloc()] </li>
7800**   <li>  [sqlite3_mutex_free()] </li>
7801**   <li>  [sqlite3_mutex_enter()] </li>
7802**   <li>  [sqlite3_mutex_try()] </li>
7803**   <li>  [sqlite3_mutex_leave()] </li>
7804**   <li>  [sqlite3_mutex_held()] </li>
7805**   <li>  [sqlite3_mutex_notheld()] </li>
7806** </ul>)^
7807**
7808** The only difference is that the public sqlite3_XXX functions enumerated
7809** above silently ignore any invocations that pass a NULL pointer instead
7810** of a valid mutex handle. The implementations of the methods defined
7811** by this structure are not required to handle this case, the results
7812** of passing a NULL pointer instead of a valid mutex handle are undefined
7813** (i.e. it is acceptable to provide an implementation that segfaults if
7814** it is passed a NULL pointer).
7815**
7816** The xMutexInit() method must be threadsafe.  It must be harmless to
7817** invoke xMutexInit() multiple times within the same process and without
7818** intervening calls to xMutexEnd().  Second and subsequent calls to
7819** xMutexInit() must be no-ops.
7820**
7821** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
7822** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
7823** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
7824** memory allocation for a fast or recursive mutex.
7825**
7826** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
7827** called, but only if the prior call to xMutexInit returned SQLITE_OK.
7828** If xMutexInit fails in any way, it is expected to clean up after itself
7829** prior to returning.
7830*/
7831typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
7832struct sqlite3_mutex_methods {
7833  int (*xMutexInit)(void);
7834  int (*xMutexEnd)(void);
7835  sqlite3_mutex *(*xMutexAlloc)(int);
7836  void (*xMutexFree)(sqlite3_mutex *);
7837  void (*xMutexEnter)(sqlite3_mutex *);
7838  int (*xMutexTry)(sqlite3_mutex *);
7839  void (*xMutexLeave)(sqlite3_mutex *);
7840  int (*xMutexHeld)(sqlite3_mutex *);
7841  int (*xMutexNotheld)(sqlite3_mutex *);
7842};
7843
7844/*
7845** CAPI3REF: Mutex Verification Routines
7846**
7847** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
7848** are intended for use inside assert() statements.  The SQLite core
7849** never uses these routines except inside an assert() and applications
7850** are advised to follow the lead of the core.  The SQLite core only
7851** provides implementations for these routines when it is compiled
7852** with the SQLITE_DEBUG flag.  External mutex implementations
7853** are only required to provide these routines if SQLITE_DEBUG is
7854** defined and if NDEBUG is not defined.
7855**
7856** These routines should return true if the mutex in their argument
7857** is held or not held, respectively, by the calling thread.
7858**
7859** The implementation is not required to provide versions of these
7860** routines that actually work. If the implementation does not provide working
7861** versions of these routines, it should at least provide stubs that always
7862** return true so that one does not get spurious assertion failures.
7863**
7864** If the argument to sqlite3_mutex_held() is a NULL pointer then
7865** the routine should return 1.   This seems counter-intuitive since
7866** clearly the mutex cannot be held if it does not exist.  But
7867** the reason the mutex does not exist is because the build is not
7868** using mutexes.  And we do not want the assert() containing the
7869** call to sqlite3_mutex_held() to fail, so a non-zero return is
7870** the appropriate thing to do.  The sqlite3_mutex_notheld()
7871** interface should also return 1 when given a NULL pointer.
7872*/
7873#ifndef NDEBUG
7874SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
7875SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
7876#endif
7877
7878/*
7879** CAPI3REF: Mutex Types
7880**
7881** The [sqlite3_mutex_alloc()] interface takes a single argument
7882** which is one of these integer constants.
7883**
7884** The set of static mutexes may change from one SQLite release to the
7885** next.  Applications that override the built-in mutex logic must be
7886** prepared to accommodate additional static mutexes.
7887*/
7888#define SQLITE_MUTEX_FAST             0
7889#define SQLITE_MUTEX_RECURSIVE        1
7890#define SQLITE_MUTEX_STATIC_MASTER    2
7891#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
7892#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
7893#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
7894#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_randomness() */
7895#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
7896#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
7897#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
7898#define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
7899#define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
7900#define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
7901#define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
7902#define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
7903#define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
7904
7905/*
7906** CAPI3REF: Retrieve the mutex for a database connection
7907** METHOD: sqlite3
7908**
7909** ^This interface returns a pointer the [sqlite3_mutex] object that
7910** serializes access to the [database connection] given in the argument
7911** when the [threading mode] is Serialized.
7912** ^If the [threading mode] is Single-thread or Multi-thread then this
7913** routine returns a NULL pointer.
7914*/
7915SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
7916
7917/*
7918** CAPI3REF: Low-Level Control Of Database Files
7919** METHOD: sqlite3
7920**
7921** ^The [sqlite3_file_control()] interface makes a direct call to the
7922** xFileControl method for the [sqlite3_io_methods] object associated
7923** with a particular database identified by the second argument. ^The
7924** name of the database is "main" for the main database or "temp" for the
7925** TEMP database, or the name that appears after the AS keyword for
7926** databases that are added using the [ATTACH] SQL command.
7927** ^A NULL pointer can be used in place of "main" to refer to the
7928** main database file.
7929** ^The third and fourth parameters to this routine
7930** are passed directly through to the second and third parameters of
7931** the xFileControl method.  ^The return value of the xFileControl
7932** method becomes the return value of this routine.
7933**
7934** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
7935** a pointer to the underlying [sqlite3_file] object to be written into
7936** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
7937** case is a short-circuit path which does not actually invoke the
7938** underlying sqlite3_io_methods.xFileControl method.
7939**
7940** ^If the second parameter (zDbName) does not match the name of any
7941** open database file, then SQLITE_ERROR is returned.  ^This error
7942** code is not remembered and will not be recalled by [sqlite3_errcode()]
7943** or [sqlite3_errmsg()].  The underlying xFileControl method might
7944** also return SQLITE_ERROR.  There is no way to distinguish between
7945** an incorrect zDbName and an SQLITE_ERROR return from the underlying
7946** xFileControl method.
7947**
7948** See also: [SQLITE_FCNTL_LOCKSTATE]
7949*/
7950SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
7951
7952/*
7953** CAPI3REF: Testing Interface
7954**
7955** ^The sqlite3_test_control() interface is used to read out internal
7956** state of SQLite and to inject faults into SQLite for testing
7957** purposes.  ^The first parameter is an operation code that determines
7958** the number, meaning, and operation of all subsequent parameters.
7959**
7960** This interface is not for use by applications.  It exists solely
7961** for verifying the correct operation of the SQLite library.  Depending
7962** on how the SQLite library is compiled, this interface might not exist.
7963**
7964** The details of the operation codes, their meanings, the parameters
7965** they take, and what they do are all subject to change without notice.
7966** Unlike most of the SQLite API, this function is not guaranteed to
7967** operate consistently from one release to the next.
7968*/
7969SQLITE_API int sqlite3_test_control(int op, ...);
7970
7971/*
7972** CAPI3REF: Testing Interface Operation Codes
7973**
7974** These constants are the valid operation code parameters used
7975** as the first argument to [sqlite3_test_control()].
7976**
7977** These parameters and their meanings are subject to change
7978** without notice.  These values are for testing purposes only.
7979** Applications should not use any of these parameters or the
7980** [sqlite3_test_control()] interface.
7981*/
7982#define SQLITE_TESTCTRL_FIRST                    5
7983#define SQLITE_TESTCTRL_PRNG_SAVE                5
7984#define SQLITE_TESTCTRL_PRNG_RESTORE             6
7985#define SQLITE_TESTCTRL_PRNG_RESET               7
7986#define SQLITE_TESTCTRL_BITVEC_TEST              8
7987#define SQLITE_TESTCTRL_FAULT_INSTALL            9
7988#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
7989#define SQLITE_TESTCTRL_PENDING_BYTE            11
7990#define SQLITE_TESTCTRL_ASSERT                  12
7991#define SQLITE_TESTCTRL_ALWAYS                  13
7992#define SQLITE_TESTCTRL_RESERVE                 14
7993#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
7994#define SQLITE_TESTCTRL_ISKEYWORD               16
7995#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
7996#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
7997#define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
7998#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD    19
7999#define SQLITE_TESTCTRL_NEVER_CORRUPT           20
8000#define SQLITE_TESTCTRL_VDBE_COVERAGE           21
8001#define SQLITE_TESTCTRL_BYTEORDER               22
8002#define SQLITE_TESTCTRL_ISINIT                  23
8003#define SQLITE_TESTCTRL_SORTER_MMAP             24
8004#define SQLITE_TESTCTRL_IMPOSTER                25
8005#define SQLITE_TESTCTRL_LAST                    25
8006
8007/*
8008** CAPI3REF: SQLite Runtime Status
8009**
8010** ^These interfaces are used to retrieve runtime status information
8011** about the performance of SQLite, and optionally to reset various
8012** highwater marks.  ^The first argument is an integer code for
8013** the specific parameter to measure.  ^(Recognized integer codes
8014** are of the form [status parameters | SQLITE_STATUS_...].)^
8015** ^The current value of the parameter is returned into *pCurrent.
8016** ^The highest recorded value is returned in *pHighwater.  ^If the
8017** resetFlag is true, then the highest record value is reset after
8018** *pHighwater is written.  ^(Some parameters do not record the highest
8019** value.  For those parameters
8020** nothing is written into *pHighwater and the resetFlag is ignored.)^
8021** ^(Other parameters record only the highwater mark and not the current
8022** value.  For these latter parameters nothing is written into *pCurrent.)^
8023**
8024** ^The sqlite3_status() and sqlite3_status64() routines return
8025** SQLITE_OK on success and a non-zero [error code] on failure.
8026**
8027** If either the current value or the highwater mark is too large to
8028** be represented by a 32-bit integer, then the values returned by
8029** sqlite3_status() are undefined.
8030**
8031** See also: [sqlite3_db_status()]
8032*/
8033SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
8034SQLITE_API int sqlite3_status64(
8035  int op,
8036  sqlite3_int64 *pCurrent,
8037  sqlite3_int64 *pHighwater,
8038  int resetFlag
8039);
8040
8041
8042/*
8043** CAPI3REF: Status Parameters
8044** KEYWORDS: {status parameters}
8045**
8046** These integer constants designate various run-time status parameters
8047** that can be returned by [sqlite3_status()].
8048**
8049** <dl>
8050** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
8051** <dd>This parameter is the current amount of memory checked out
8052** using [sqlite3_malloc()], either directly or indirectly.  The
8053** figure includes calls made to [sqlite3_malloc()] by the application
8054** and internal memory usage by the SQLite library.  Scratch memory
8055** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
8056** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
8057** this parameter.  The amount returned is the sum of the allocation
8058** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
8059**
8060** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
8061** <dd>This parameter records the largest memory allocation request
8062** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
8063** internal equivalents).  Only the value returned in the
8064** *pHighwater parameter to [sqlite3_status()] is of interest.
8065** The value written into the *pCurrent parameter is undefined.</dd>)^
8066**
8067** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
8068** <dd>This parameter records the number of separate memory allocations
8069** currently checked out.</dd>)^
8070**
8071** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
8072** <dd>This parameter returns the number of pages used out of the
8073** [pagecache memory allocator] that was configured using
8074** [SQLITE_CONFIG_PAGECACHE].  The
8075** value returned is in pages, not in bytes.</dd>)^
8076**
8077** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
8078** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
8079** <dd>This parameter returns the number of bytes of page cache
8080** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
8081** buffer and where forced to overflow to [sqlite3_malloc()].  The
8082** returned value includes allocations that overflowed because they
8083** where too large (they were larger than the "sz" parameter to
8084** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
8085** no space was left in the page cache.</dd>)^
8086**
8087** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
8088** <dd>This parameter records the largest memory allocation request
8089** handed to [pagecache memory allocator].  Only the value returned in the
8090** *pHighwater parameter to [sqlite3_status()] is of interest.
8091** The value written into the *pCurrent parameter is undefined.</dd>)^
8092**
8093** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
8094** <dd>This parameter returns the number of allocations used out of the
8095** [scratch memory allocator] configured using
8096** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
8097** in bytes.  Since a single thread may only have one scratch allocation
8098** outstanding at time, this parameter also reports the number of threads
8099** using scratch memory at the same time.</dd>)^
8100**
8101** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
8102** <dd>This parameter returns the number of bytes of scratch memory
8103** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
8104** buffer and where forced to overflow to [sqlite3_malloc()].  The values
8105** returned include overflows because the requested allocation was too
8106** larger (that is, because the requested allocation was larger than the
8107** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
8108** slots were available.
8109** </dd>)^
8110**
8111** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
8112** <dd>This parameter records the largest memory allocation request
8113** handed to [scratch memory allocator].  Only the value returned in the
8114** *pHighwater parameter to [sqlite3_status()] is of interest.
8115** The value written into the *pCurrent parameter is undefined.</dd>)^
8116**
8117** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
8118** <dd>The *pHighwater parameter records the deepest parser stack.
8119** The *pCurrent value is undefined.  The *pHighwater value is only
8120** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
8121** </dl>
8122**
8123** New status parameters may be added from time to time.
8124*/
8125#define SQLITE_STATUS_MEMORY_USED          0
8126#define SQLITE_STATUS_PAGECACHE_USED       1
8127#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
8128#define SQLITE_STATUS_SCRATCH_USED         3
8129#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
8130#define SQLITE_STATUS_MALLOC_SIZE          5
8131#define SQLITE_STATUS_PARSER_STACK         6
8132#define SQLITE_STATUS_PAGECACHE_SIZE       7
8133#define SQLITE_STATUS_SCRATCH_SIZE         8
8134#define SQLITE_STATUS_MALLOC_COUNT         9
8135
8136/*
8137** CAPI3REF: Database Connection Status
8138** METHOD: sqlite3
8139**
8140** ^This interface is used to retrieve runtime status information
8141** about a single [database connection].  ^The first argument is the
8142** database connection object to be interrogated.  ^The second argument
8143** is an integer constant, taken from the set of
8144** [SQLITE_DBSTATUS options], that
8145** determines the parameter to interrogate.  The set of
8146** [SQLITE_DBSTATUS options] is likely
8147** to grow in future releases of SQLite.
8148**
8149** ^The current value of the requested parameter is written into *pCur
8150** and the highest instantaneous value is written into *pHiwtr.  ^If
8151** the resetFlg is true, then the highest instantaneous value is
8152** reset back down to the current value.
8153**
8154** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
8155** non-zero [error code] on failure.
8156**
8157** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
8158*/
8159SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
8160
8161/*
8162** CAPI3REF: Status Parameters for database connections
8163** KEYWORDS: {SQLITE_DBSTATUS options}
8164**
8165** These constants are the available integer "verbs" that can be passed as
8166** the second argument to the [sqlite3_db_status()] interface.
8167**
8168** New verbs may be added in future releases of SQLite. Existing verbs
8169** might be discontinued. Applications should check the return code from
8170** [sqlite3_db_status()] to make sure that the call worked.
8171** The [sqlite3_db_status()] interface will return a non-zero error code
8172** if a discontinued or unsupported verb is invoked.
8173**
8174** <dl>
8175** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
8176** <dd>This parameter returns the number of lookaside memory slots currently
8177** checked out.</dd>)^
8178**
8179** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
8180** <dd>This parameter returns the number malloc attempts that were
8181** satisfied using lookaside memory. Only the high-water value is meaningful;
8182** the current value is always zero.)^
8183**
8184** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
8185** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
8186** <dd>This parameter returns the number malloc attempts that might have
8187** been satisfied using lookaside memory but failed due to the amount of
8188** memory requested being larger than the lookaside slot size.
8189** Only the high-water value is meaningful;
8190** the current value is always zero.)^
8191**
8192** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
8193** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
8194** <dd>This parameter returns the number malloc attempts that might have
8195** been satisfied using lookaside memory but failed due to all lookaside
8196** memory already being in use.
8197** Only the high-water value is meaningful;
8198** the current value is always zero.)^
8199**
8200** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
8201** <dd>This parameter returns the approximate number of bytes of heap
8202** memory used by all pager caches associated with the database connection.)^
8203** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
8204**
8205** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
8206** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
8207** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
8208** pager cache is shared between two or more connections the bytes of heap
8209** memory used by that pager cache is divided evenly between the attached
8210** connections.)^  In other words, if none of the pager caches associated
8211** with the database connection are shared, this request returns the same
8212** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
8213** shared, the value returned by this call will be smaller than that returned
8214** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
8215** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
8216**
8217** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
8218** <dd>This parameter returns the approximate number of bytes of heap
8219** memory used to store the schema for all databases associated
8220** with the connection - main, temp, and any [ATTACH]-ed databases.)^
8221** ^The full amount of memory used by the schemas is reported, even if the
8222** schema memory is shared with other database connections due to
8223** [shared cache mode] being enabled.
8224** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
8225**
8226** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
8227** <dd>This parameter returns the approximate number of bytes of heap
8228** and lookaside memory used by all prepared statements associated with
8229** the database connection.)^
8230** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
8231** </dd>
8232**
8233** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
8234** <dd>This parameter returns the number of pager cache hits that have
8235** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
8236** is always 0.
8237** </dd>
8238**
8239** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
8240** <dd>This parameter returns the number of pager cache misses that have
8241** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
8242** is always 0.
8243** </dd>
8244**
8245** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
8246** <dd>This parameter returns the number of dirty cache entries that have
8247** been written to disk. Specifically, the number of pages written to the
8248** wal file in wal mode databases, or the number of pages written to the
8249** database file in rollback mode databases. Any pages written as part of
8250** transaction rollback or database recovery operations are not included.
8251** If an IO or other error occurs while writing a page to disk, the effect
8252** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
8253** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
8254** </dd>
8255**
8256** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
8257** <dd>This parameter returns zero for the current value if and only if
8258** all foreign key constraints (deferred or immediate) have been
8259** resolved.)^  ^The highwater mark is always 0.
8260** </dd>
8261** </dl>
8262*/
8263#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
8264#define SQLITE_DBSTATUS_CACHE_USED           1
8265#define SQLITE_DBSTATUS_SCHEMA_USED          2
8266#define SQLITE_DBSTATUS_STMT_USED            3
8267#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
8268#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
8269#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
8270#define SQLITE_DBSTATUS_CACHE_HIT            7
8271#define SQLITE_DBSTATUS_CACHE_MISS           8
8272#define SQLITE_DBSTATUS_CACHE_WRITE          9
8273#define SQLITE_DBSTATUS_DEFERRED_FKS        10
8274#define SQLITE_DBSTATUS_CACHE_USED_SHARED   11
8275#define SQLITE_DBSTATUS_MAX                 11   /* Largest defined DBSTATUS */
8276
8277
8278/*
8279** CAPI3REF: Prepared Statement Status
8280** METHOD: sqlite3_stmt
8281**
8282** ^(Each prepared statement maintains various
8283** [SQLITE_STMTSTATUS counters] that measure the number
8284** of times it has performed specific operations.)^  These counters can
8285** be used to monitor the performance characteristics of the prepared
8286** statements.  For example, if the number of table steps greatly exceeds
8287** the number of table searches or result rows, that would tend to indicate
8288** that the prepared statement is using a full table scan rather than
8289** an index.
8290**
8291** ^(This interface is used to retrieve and reset counter values from
8292** a [prepared statement].  The first argument is the prepared statement
8293** object to be interrogated.  The second argument
8294** is an integer code for a specific [SQLITE_STMTSTATUS counter]
8295** to be interrogated.)^
8296** ^The current value of the requested counter is returned.
8297** ^If the resetFlg is true, then the counter is reset to zero after this
8298** interface call returns.
8299**
8300** See also: [sqlite3_status()] and [sqlite3_db_status()].
8301*/
8302SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
8303
8304/*
8305** CAPI3REF: Status Parameters for prepared statements
8306** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
8307**
8308** These preprocessor macros define integer codes that name counter
8309** values associated with the [sqlite3_stmt_status()] interface.
8310** The meanings of the various counters are as follows:
8311**
8312** <dl>
8313** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
8314** <dd>^This is the number of times that SQLite has stepped forward in
8315** a table as part of a full table scan.  Large numbers for this counter
8316** may indicate opportunities for performance improvement through
8317** careful use of indices.</dd>
8318**
8319** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
8320** <dd>^This is the number of sort operations that have occurred.
8321** A non-zero value in this counter may indicate an opportunity to
8322** improvement performance through careful use of indices.</dd>
8323**
8324** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
8325** <dd>^This is the number of rows inserted into transient indices that
8326** were created automatically in order to help joins run faster.
8327** A non-zero value in this counter may indicate an opportunity to
8328** improvement performance by adding permanent indices that do not
8329** need to be reinitialized each time the statement is run.</dd>
8330**
8331** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
8332** <dd>^This is the number of virtual machine operations executed
8333** by the prepared statement if that number is less than or equal
8334** to 2147483647.  The number of virtual machine operations can be
8335** used as a proxy for the total work done by the prepared statement.
8336** If the number of virtual machine operations exceeds 2147483647
8337** then the value returned by this statement status code is undefined.
8338**
8339** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
8340** <dd>^This is the number of times that the prepare statement has been
8341** automatically regenerated due to schema changes or change to
8342** [bound parameters] that might affect the query plan.
8343**
8344** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
8345** <dd>^This is the number of times that the prepared statement has
8346** been run.  A single "run" for the purposes of this counter is one
8347** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
8348** The counter is incremented on the first [sqlite3_step()] call of each
8349** cycle.
8350**
8351** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
8352** <dd>^This is the approximate number of bytes of heap memory
8353** used to store the prepared statement.  ^This value is not actually
8354** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
8355** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
8356** </dd>
8357** </dl>
8358*/
8359#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
8360#define SQLITE_STMTSTATUS_SORT              2
8361#define SQLITE_STMTSTATUS_AUTOINDEX         3
8362#define SQLITE_STMTSTATUS_VM_STEP           4
8363#define SQLITE_STMTSTATUS_REPREPARE         5
8364#define SQLITE_STMTSTATUS_RUN               6
8365#define SQLITE_STMTSTATUS_MEMUSED           99
8366
8367/*
8368** CAPI3REF: Custom Page Cache Object
8369**
8370** The sqlite3_pcache type is opaque.  It is implemented by
8371** the pluggable module.  The SQLite core has no knowledge of
8372** its size or internal structure and never deals with the
8373** sqlite3_pcache object except by holding and passing pointers
8374** to the object.
8375**
8376** See [sqlite3_pcache_methods2] for additional information.
8377*/
8378typedef struct sqlite3_pcache sqlite3_pcache;
8379
8380/*
8381** CAPI3REF: Custom Page Cache Object
8382**
8383** The sqlite3_pcache_page object represents a single page in the
8384** page cache.  The page cache will allocate instances of this
8385** object.  Various methods of the page cache use pointers to instances
8386** of this object as parameters or as their return value.
8387**
8388** See [sqlite3_pcache_methods2] for additional information.
8389*/
8390typedef struct sqlite3_pcache_page sqlite3_pcache_page;
8391struct sqlite3_pcache_page {
8392  void *pBuf;        /* The content of the page */
8393  void *pExtra;      /* Extra information associated with the page */
8394};
8395
8396/*
8397** CAPI3REF: Application Defined Page Cache.
8398** KEYWORDS: {page cache}
8399**
8400** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
8401** register an alternative page cache implementation by passing in an
8402** instance of the sqlite3_pcache_methods2 structure.)^
8403** In many applications, most of the heap memory allocated by
8404** SQLite is used for the page cache.
8405** By implementing a
8406** custom page cache using this API, an application can better control
8407** the amount of memory consumed by SQLite, the way in which
8408** that memory is allocated and released, and the policies used to
8409** determine exactly which parts of a database file are cached and for
8410** how long.
8411**
8412** The alternative page cache mechanism is an
8413** extreme measure that is only needed by the most demanding applications.
8414** The built-in page cache is recommended for most uses.
8415**
8416** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
8417** internal buffer by SQLite within the call to [sqlite3_config].  Hence
8418** the application may discard the parameter after the call to
8419** [sqlite3_config()] returns.)^
8420**
8421** [[the xInit() page cache method]]
8422** ^(The xInit() method is called once for each effective
8423** call to [sqlite3_initialize()])^
8424** (usually only once during the lifetime of the process). ^(The xInit()
8425** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
8426** The intent of the xInit() method is to set up global data structures
8427** required by the custom page cache implementation.
8428** ^(If the xInit() method is NULL, then the
8429** built-in default page cache is used instead of the application defined
8430** page cache.)^
8431**
8432** [[the xShutdown() page cache method]]
8433** ^The xShutdown() method is called by [sqlite3_shutdown()].
8434** It can be used to clean up
8435** any outstanding resources before process shutdown, if required.
8436** ^The xShutdown() method may be NULL.
8437**
8438** ^SQLite automatically serializes calls to the xInit method,
8439** so the xInit method need not be threadsafe.  ^The
8440** xShutdown method is only called from [sqlite3_shutdown()] so it does
8441** not need to be threadsafe either.  All other methods must be threadsafe
8442** in multithreaded applications.
8443**
8444** ^SQLite will never invoke xInit() more than once without an intervening
8445** call to xShutdown().
8446**
8447** [[the xCreate() page cache methods]]
8448** ^SQLite invokes the xCreate() method to construct a new cache instance.
8449** SQLite will typically create one cache instance for each open database file,
8450** though this is not guaranteed. ^The
8451** first parameter, szPage, is the size in bytes of the pages that must
8452** be allocated by the cache.  ^szPage will always a power of two.  ^The
8453** second parameter szExtra is a number of bytes of extra storage
8454** associated with each page cache entry.  ^The szExtra parameter will
8455** a number less than 250.  SQLite will use the
8456** extra szExtra bytes on each page to store metadata about the underlying
8457** database page on disk.  The value passed into szExtra depends
8458** on the SQLite version, the target platform, and how SQLite was compiled.
8459** ^The third argument to xCreate(), bPurgeable, is true if the cache being
8460** created will be used to cache database pages of a file stored on disk, or
8461** false if it is used for an in-memory database. The cache implementation
8462** does not have to do anything special based with the value of bPurgeable;
8463** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
8464** never invoke xUnpin() except to deliberately delete a page.
8465** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
8466** false will always have the "discard" flag set to true.
8467** ^Hence, a cache created with bPurgeable false will
8468** never contain any unpinned pages.
8469**
8470** [[the xCachesize() page cache method]]
8471** ^(The xCachesize() method may be called at any time by SQLite to set the
8472** suggested maximum cache-size (number of pages stored by) the cache
8473** instance passed as the first argument. This is the value configured using
8474** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
8475** parameter, the implementation is not required to do anything with this
8476** value; it is advisory only.
8477**
8478** [[the xPagecount() page cache methods]]
8479** The xPagecount() method must return the number of pages currently
8480** stored in the cache, both pinned and unpinned.
8481**
8482** [[the xFetch() page cache methods]]
8483** The xFetch() method locates a page in the cache and returns a pointer to
8484** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
8485** The pBuf element of the returned sqlite3_pcache_page object will be a
8486** pointer to a buffer of szPage bytes used to store the content of a
8487** single database page.  The pExtra element of sqlite3_pcache_page will be
8488** a pointer to the szExtra bytes of extra storage that SQLite has requested
8489** for each entry in the page cache.
8490**
8491** The page to be fetched is determined by the key. ^The minimum key value
8492** is 1.  After it has been retrieved using xFetch, the page is considered
8493** to be "pinned".
8494**
8495** If the requested page is already in the page cache, then the page cache
8496** implementation must return a pointer to the page buffer with its content
8497** intact.  If the requested page is not already in the cache, then the
8498** cache implementation should use the value of the createFlag
8499** parameter to help it determined what action to take:
8500**
8501** <table border=1 width=85% align=center>
8502** <tr><th> createFlag <th> Behavior when page is not already in cache
8503** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
8504** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
8505**                 Otherwise return NULL.
8506** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
8507**                 NULL if allocating a new page is effectively impossible.
8508** </table>
8509**
8510** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
8511** will only use a createFlag of 2 after a prior call with a createFlag of 1
8512** failed.)^  In between the to xFetch() calls, SQLite may
8513** attempt to unpin one or more cache pages by spilling the content of
8514** pinned pages to disk and synching the operating system disk cache.
8515**
8516** [[the xUnpin() page cache method]]
8517** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
8518** as its second argument.  If the third parameter, discard, is non-zero,
8519** then the page must be evicted from the cache.
8520** ^If the discard parameter is
8521** zero, then the page may be discarded or retained at the discretion of
8522** page cache implementation. ^The page cache implementation
8523** may choose to evict unpinned pages at any time.
8524**
8525** The cache must not perform any reference counting. A single
8526** call to xUnpin() unpins the page regardless of the number of prior calls
8527** to xFetch().
8528**
8529** [[the xRekey() page cache methods]]
8530** The xRekey() method is used to change the key value associated with the
8531** page passed as the second argument. If the cache
8532** previously contains an entry associated with newKey, it must be
8533** discarded. ^Any prior cache entry associated with newKey is guaranteed not
8534** to be pinned.
8535**
8536** When SQLite calls the xTruncate() method, the cache must discard all
8537** existing cache entries with page numbers (keys) greater than or equal
8538** to the value of the iLimit parameter passed to xTruncate(). If any
8539** of these pages are pinned, they are implicitly unpinned, meaning that
8540** they can be safely discarded.
8541**
8542** [[the xDestroy() page cache method]]
8543** ^The xDestroy() method is used to delete a cache allocated by xCreate().
8544** All resources associated with the specified cache should be freed. ^After
8545** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
8546** handle invalid, and will not use it with any other sqlite3_pcache_methods2
8547** functions.
8548**
8549** [[the xShrink() page cache method]]
8550** ^SQLite invokes the xShrink() method when it wants the page cache to
8551** free up as much of heap memory as possible.  The page cache implementation
8552** is not obligated to free any memory, but well-behaved implementations should
8553** do their best.
8554*/
8555typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
8556struct sqlite3_pcache_methods2 {
8557  int iVersion;
8558  void *pArg;
8559  int (*xInit)(void*);
8560  void (*xShutdown)(void*);
8561  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
8562  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
8563  int (*xPagecount)(sqlite3_pcache*);
8564  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
8565  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
8566  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
8567      unsigned oldKey, unsigned newKey);
8568  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
8569  void (*xDestroy)(sqlite3_pcache*);
8570  void (*xShrink)(sqlite3_pcache*);
8571};
8572
8573/*
8574** This is the obsolete pcache_methods object that has now been replaced
8575** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
8576** retained in the header file for backwards compatibility only.
8577*/
8578typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
8579struct sqlite3_pcache_methods {
8580  void *pArg;
8581  int (*xInit)(void*);
8582  void (*xShutdown)(void*);
8583  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
8584  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
8585  int (*xPagecount)(sqlite3_pcache*);
8586  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
8587  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
8588  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
8589  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
8590  void (*xDestroy)(sqlite3_pcache*);
8591};
8592
8593
8594/*
8595** CAPI3REF: Online Backup Object
8596**
8597** The sqlite3_backup object records state information about an ongoing
8598** online backup operation.  ^The sqlite3_backup object is created by
8599** a call to [sqlite3_backup_init()] and is destroyed by a call to
8600** [sqlite3_backup_finish()].
8601**
8602** See Also: [Using the SQLite Online Backup API]
8603*/
8604typedef struct sqlite3_backup sqlite3_backup;
8605
8606/*
8607** CAPI3REF: Online Backup API.
8608**
8609** The backup API copies the content of one database into another.
8610** It is useful either for creating backups of databases or
8611** for copying in-memory databases to or from persistent files.
8612**
8613** See Also: [Using the SQLite Online Backup API]
8614**
8615** ^SQLite holds a write transaction open on the destination database file
8616** for the duration of the backup operation.
8617** ^The source database is read-locked only while it is being read;
8618** it is not locked continuously for the entire backup operation.
8619** ^Thus, the backup may be performed on a live source database without
8620** preventing other database connections from
8621** reading or writing to the source database while the backup is underway.
8622**
8623** ^(To perform a backup operation:
8624**   <ol>
8625**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
8626**         backup,
8627**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
8628**         the data between the two databases, and finally
8629**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
8630**         associated with the backup operation.
8631**   </ol>)^
8632** There should be exactly one call to sqlite3_backup_finish() for each
8633** successful call to sqlite3_backup_init().
8634**
8635** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
8636**
8637** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
8638** [database connection] associated with the destination database
8639** and the database name, respectively.
8640** ^The database name is "main" for the main database, "temp" for the
8641** temporary database, or the name specified after the AS keyword in
8642** an [ATTACH] statement for an attached database.
8643** ^The S and M arguments passed to
8644** sqlite3_backup_init(D,N,S,M) identify the [database connection]
8645** and database name of the source database, respectively.
8646** ^The source and destination [database connections] (parameters S and D)
8647** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
8648** an error.
8649**
8650** ^A call to sqlite3_backup_init() will fail, returning NULL, if
8651** there is already a read or read-write transaction open on the
8652** destination database.
8653**
8654** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
8655** returned and an error code and error message are stored in the
8656** destination [database connection] D.
8657** ^The error code and message for the failed call to sqlite3_backup_init()
8658** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
8659** [sqlite3_errmsg16()] functions.
8660** ^A successful call to sqlite3_backup_init() returns a pointer to an
8661** [sqlite3_backup] object.
8662** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
8663** sqlite3_backup_finish() functions to perform the specified backup
8664** operation.
8665**
8666** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
8667**
8668** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
8669** the source and destination databases specified by [sqlite3_backup] object B.
8670** ^If N is negative, all remaining source pages are copied.
8671** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
8672** are still more pages to be copied, then the function returns [SQLITE_OK].
8673** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
8674** from source to destination, then it returns [SQLITE_DONE].
8675** ^If an error occurs while running sqlite3_backup_step(B,N),
8676** then an [error code] is returned. ^As well as [SQLITE_OK] and
8677** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
8678** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
8679** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
8680**
8681** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
8682** <ol>
8683** <li> the destination database was opened read-only, or
8684** <li> the destination database is using write-ahead-log journaling
8685** and the destination and source page sizes differ, or
8686** <li> the destination database is an in-memory database and the
8687** destination and source page sizes differ.
8688** </ol>)^
8689**
8690** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
8691** the [sqlite3_busy_handler | busy-handler function]
8692** is invoked (if one is specified). ^If the
8693** busy-handler returns non-zero before the lock is available, then
8694** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
8695** sqlite3_backup_step() can be retried later. ^If the source
8696** [database connection]
8697** is being used to write to the source database when sqlite3_backup_step()
8698** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
8699** case the call to sqlite3_backup_step() can be retried later on. ^(If
8700** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
8701** [SQLITE_READONLY] is returned, then
8702** there is no point in retrying the call to sqlite3_backup_step(). These
8703** errors are considered fatal.)^  The application must accept
8704** that the backup operation has failed and pass the backup operation handle
8705** to the sqlite3_backup_finish() to release associated resources.
8706**
8707** ^The first call to sqlite3_backup_step() obtains an exclusive lock
8708** on the destination file. ^The exclusive lock is not released until either
8709** sqlite3_backup_finish() is called or the backup operation is complete
8710** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
8711** sqlite3_backup_step() obtains a [shared lock] on the source database that
8712** lasts for the duration of the sqlite3_backup_step() call.
8713** ^Because the source database is not locked between calls to
8714** sqlite3_backup_step(), the source database may be modified mid-way
8715** through the backup process.  ^If the source database is modified by an
8716** external process or via a database connection other than the one being
8717** used by the backup operation, then the backup will be automatically
8718** restarted by the next call to sqlite3_backup_step(). ^If the source
8719** database is modified by the using the same database connection as is used
8720** by the backup operation, then the backup database is automatically
8721** updated at the same time.
8722**
8723** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
8724**
8725** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
8726** application wishes to abandon the backup operation, the application
8727** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
8728** ^The sqlite3_backup_finish() interfaces releases all
8729** resources associated with the [sqlite3_backup] object.
8730** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
8731** active write-transaction on the destination database is rolled back.
8732** The [sqlite3_backup] object is invalid
8733** and may not be used following a call to sqlite3_backup_finish().
8734**
8735** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
8736** sqlite3_backup_step() errors occurred, regardless or whether or not
8737** sqlite3_backup_step() completed.
8738** ^If an out-of-memory condition or IO error occurred during any prior
8739** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
8740** sqlite3_backup_finish() returns the corresponding [error code].
8741**
8742** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
8743** is not a permanent error and does not affect the return value of
8744** sqlite3_backup_finish().
8745**
8746** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
8747** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
8748**
8749** ^The sqlite3_backup_remaining() routine returns the number of pages still
8750** to be backed up at the conclusion of the most recent sqlite3_backup_step().
8751** ^The sqlite3_backup_pagecount() routine returns the total number of pages
8752** in the source database at the conclusion of the most recent
8753** sqlite3_backup_step().
8754** ^(The values returned by these functions are only updated by
8755** sqlite3_backup_step(). If the source database is modified in a way that
8756** changes the size of the source database or the number of pages remaining,
8757** those changes are not reflected in the output of sqlite3_backup_pagecount()
8758** and sqlite3_backup_remaining() until after the next
8759** sqlite3_backup_step().)^
8760**
8761** <b>Concurrent Usage of Database Handles</b>
8762**
8763** ^The source [database connection] may be used by the application for other
8764** purposes while a backup operation is underway or being initialized.
8765** ^If SQLite is compiled and configured to support threadsafe database
8766** connections, then the source database connection may be used concurrently
8767** from within other threads.
8768**
8769** However, the application must guarantee that the destination
8770** [database connection] is not passed to any other API (by any thread) after
8771** sqlite3_backup_init() is called and before the corresponding call to
8772** sqlite3_backup_finish().  SQLite does not currently check to see
8773** if the application incorrectly accesses the destination [database connection]
8774** and so no error code is reported, but the operations may malfunction
8775** nevertheless.  Use of the destination database connection while a
8776** backup is in progress might also also cause a mutex deadlock.
8777**
8778** If running in [shared cache mode], the application must
8779** guarantee that the shared cache used by the destination database
8780** is not accessed while the backup is running. In practice this means
8781** that the application must guarantee that the disk file being
8782** backed up to is not accessed by any connection within the process,
8783** not just the specific connection that was passed to sqlite3_backup_init().
8784**
8785** The [sqlite3_backup] object itself is partially threadsafe. Multiple
8786** threads may safely make multiple concurrent calls to sqlite3_backup_step().
8787** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
8788** APIs are not strictly speaking threadsafe. If they are invoked at the
8789** same time as another thread is invoking sqlite3_backup_step() it is
8790** possible that they return invalid values.
8791*/
8792SQLITE_API sqlite3_backup *sqlite3_backup_init(
8793  sqlite3 *pDest,                        /* Destination database handle */
8794  const char *zDestName,                 /* Destination database name */
8795  sqlite3 *pSource,                      /* Source database handle */
8796  const char *zSourceName                /* Source database name */
8797);
8798SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
8799SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
8800SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
8801SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
8802
8803/*
8804** CAPI3REF: Unlock Notification
8805** METHOD: sqlite3
8806**
8807** ^When running in shared-cache mode, a database operation may fail with
8808** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
8809** individual tables within the shared-cache cannot be obtained. See
8810** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
8811** ^This API may be used to register a callback that SQLite will invoke
8812** when the connection currently holding the required lock relinquishes it.
8813** ^This API is only available if the library was compiled with the
8814** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
8815**
8816** See Also: [Using the SQLite Unlock Notification Feature].
8817**
8818** ^Shared-cache locks are released when a database connection concludes
8819** its current transaction, either by committing it or rolling it back.
8820**
8821** ^When a connection (known as the blocked connection) fails to obtain a
8822** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
8823** identity of the database connection (the blocking connection) that
8824** has locked the required resource is stored internally. ^After an
8825** application receives an SQLITE_LOCKED error, it may call the
8826** sqlite3_unlock_notify() method with the blocked connection handle as
8827** the first argument to register for a callback that will be invoked
8828** when the blocking connections current transaction is concluded. ^The
8829** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
8830** call that concludes the blocking connections transaction.
8831**
8832** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
8833** there is a chance that the blocking connection will have already
8834** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
8835** If this happens, then the specified callback is invoked immediately,
8836** from within the call to sqlite3_unlock_notify().)^
8837**
8838** ^If the blocked connection is attempting to obtain a write-lock on a
8839** shared-cache table, and more than one other connection currently holds
8840** a read-lock on the same table, then SQLite arbitrarily selects one of
8841** the other connections to use as the blocking connection.
8842**
8843** ^(There may be at most one unlock-notify callback registered by a
8844** blocked connection. If sqlite3_unlock_notify() is called when the
8845** blocked connection already has a registered unlock-notify callback,
8846** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
8847** called with a NULL pointer as its second argument, then any existing
8848** unlock-notify callback is canceled. ^The blocked connections
8849** unlock-notify callback may also be canceled by closing the blocked
8850** connection using [sqlite3_close()].
8851**
8852** The unlock-notify callback is not reentrant. If an application invokes
8853** any sqlite3_xxx API functions from within an unlock-notify callback, a
8854** crash or deadlock may be the result.
8855**
8856** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
8857** returns SQLITE_OK.
8858**
8859** <b>Callback Invocation Details</b>
8860**
8861** When an unlock-notify callback is registered, the application provides a
8862** single void* pointer that is passed to the callback when it is invoked.
8863** However, the signature of the callback function allows SQLite to pass
8864** it an array of void* context pointers. The first argument passed to
8865** an unlock-notify callback is a pointer to an array of void* pointers,
8866** and the second is the number of entries in the array.
8867**
8868** When a blocking connections transaction is concluded, there may be
8869** more than one blocked connection that has registered for an unlock-notify
8870** callback. ^If two or more such blocked connections have specified the
8871** same callback function, then instead of invoking the callback function
8872** multiple times, it is invoked once with the set of void* context pointers
8873** specified by the blocked connections bundled together into an array.
8874** This gives the application an opportunity to prioritize any actions
8875** related to the set of unblocked database connections.
8876**
8877** <b>Deadlock Detection</b>
8878**
8879** Assuming that after registering for an unlock-notify callback a
8880** database waits for the callback to be issued before taking any further
8881** action (a reasonable assumption), then using this API may cause the
8882** application to deadlock. For example, if connection X is waiting for
8883** connection Y's transaction to be concluded, and similarly connection
8884** Y is waiting on connection X's transaction, then neither connection
8885** will proceed and the system may remain deadlocked indefinitely.
8886**
8887** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
8888** detection. ^If a given call to sqlite3_unlock_notify() would put the
8889** system in a deadlocked state, then SQLITE_LOCKED is returned and no
8890** unlock-notify callback is registered. The system is said to be in
8891** a deadlocked state if connection A has registered for an unlock-notify
8892** callback on the conclusion of connection B's transaction, and connection
8893** B has itself registered for an unlock-notify callback when connection
8894** A's transaction is concluded. ^Indirect deadlock is also detected, so
8895** the system is also considered to be deadlocked if connection B has
8896** registered for an unlock-notify callback on the conclusion of connection
8897** C's transaction, where connection C is waiting on connection A. ^Any
8898** number of levels of indirection are allowed.
8899**
8900** <b>The "DROP TABLE" Exception</b>
8901**
8902** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
8903** always appropriate to call sqlite3_unlock_notify(). There is however,
8904** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
8905** SQLite checks if there are any currently executing SELECT statements
8906** that belong to the same connection. If there are, SQLITE_LOCKED is
8907** returned. In this case there is no "blocking connection", so invoking
8908** sqlite3_unlock_notify() results in the unlock-notify callback being
8909** invoked immediately. If the application then re-attempts the "DROP TABLE"
8910** or "DROP INDEX" query, an infinite loop might be the result.
8911**
8912** One way around this problem is to check the extended error code returned
8913** by an sqlite3_step() call. ^(If there is a blocking connection, then the
8914** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
8915** the special "DROP TABLE/INDEX" case, the extended error code is just
8916** SQLITE_LOCKED.)^
8917*/
8918SQLITE_API int sqlite3_unlock_notify(
8919  sqlite3 *pBlocked,                          /* Waiting connection */
8920  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
8921  void *pNotifyArg                            /* Argument to pass to xNotify */
8922);
8923
8924
8925/*
8926** CAPI3REF: String Comparison
8927**
8928** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
8929** and extensions to compare the contents of two buffers containing UTF-8
8930** strings in a case-independent fashion, using the same definition of "case
8931** independence" that SQLite uses internally when comparing identifiers.
8932*/
8933SQLITE_API int sqlite3_stricmp(const char *, const char *);
8934SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
8935
8936/*
8937** CAPI3REF: String Globbing
8938*
8939** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
8940** string X matches the [GLOB] pattern P.
8941** ^The definition of [GLOB] pattern matching used in
8942** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
8943** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function
8944** is case sensitive.
8945**
8946** Note that this routine returns zero on a match and non-zero if the strings
8947** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
8948**
8949** See also: [sqlite3_strlike()].
8950*/
8951SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
8952
8953/*
8954** CAPI3REF: String LIKE Matching
8955*
8956** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
8957** string X matches the [LIKE] pattern P with escape character E.
8958** ^The definition of [LIKE] pattern matching used in
8959** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
8960** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without
8961** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
8962** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
8963** insensitive - equivalent upper and lower case ASCII characters match
8964** one another.
8965**
8966** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
8967** only ASCII characters are case folded.
8968**
8969** Note that this routine returns zero on a match and non-zero if the strings
8970** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
8971**
8972** See also: [sqlite3_strglob()].
8973*/
8974SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
8975
8976/*
8977** CAPI3REF: Error Logging Interface
8978**
8979** ^The [sqlite3_log()] interface writes a message into the [error log]
8980** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
8981** ^If logging is enabled, the zFormat string and subsequent arguments are
8982** used with [sqlite3_snprintf()] to generate the final output string.
8983**
8984** The sqlite3_log() interface is intended for use by extensions such as
8985** virtual tables, collating functions, and SQL functions.  While there is
8986** nothing to prevent an application from calling sqlite3_log(), doing so
8987** is considered bad form.
8988**
8989** The zFormat string must not be NULL.
8990**
8991** To avoid deadlocks and other threading problems, the sqlite3_log() routine
8992** will not use dynamically allocated memory.  The log message is stored in
8993** a fixed-length buffer on the stack.  If the log message is longer than
8994** a few hundred characters, it will be truncated to the length of the
8995** buffer.
8996*/
8997SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
8998
8999/*
9000** CAPI3REF: Write-Ahead Log Commit Hook
9001** METHOD: sqlite3
9002**
9003** ^The [sqlite3_wal_hook()] function is used to register a callback that
9004** is invoked each time data is committed to a database in wal mode.
9005**
9006** ^(The callback is invoked by SQLite after the commit has taken place and
9007** the associated write-lock on the database released)^, so the implementation
9008** may read, write or [checkpoint] the database as required.
9009**
9010** ^The first parameter passed to the callback function when it is invoked
9011** is a copy of the third parameter passed to sqlite3_wal_hook() when
9012** registering the callback. ^The second is a copy of the database handle.
9013** ^The third parameter is the name of the database that was written to -
9014** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
9015** is the number of pages currently in the write-ahead log file,
9016** including those that were just committed.
9017**
9018** The callback function should normally return [SQLITE_OK].  ^If an error
9019** code is returned, that error will propagate back up through the
9020** SQLite code base to cause the statement that provoked the callback
9021** to report an error, though the commit will have still occurred. If the
9022** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
9023** that does not correspond to any valid SQLite error code, the results
9024** are undefined.
9025**
9026** A single database handle may have at most a single write-ahead log callback
9027** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
9028** previously registered write-ahead log callback. ^Note that the
9029** [sqlite3_wal_autocheckpoint()] interface and the
9030** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
9031** overwrite any prior [sqlite3_wal_hook()] settings.
9032*/
9033SQLITE_API void *sqlite3_wal_hook(
9034  sqlite3*,
9035  int(*)(void *,sqlite3*,const char*,int),
9036  void*
9037);
9038
9039/*
9040** CAPI3REF: Configure an auto-checkpoint
9041** METHOD: sqlite3
9042**
9043** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
9044** [sqlite3_wal_hook()] that causes any database on [database connection] D
9045** to automatically [checkpoint]
9046** after committing a transaction if there are N or
9047** more frames in the [write-ahead log] file.  ^Passing zero or
9048** a negative value as the nFrame parameter disables automatic
9049** checkpoints entirely.
9050**
9051** ^The callback registered by this function replaces any existing callback
9052** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
9053** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
9054** configured by this function.
9055**
9056** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
9057** from SQL.
9058**
9059** ^Checkpoints initiated by this mechanism are
9060** [sqlite3_wal_checkpoint_v2|PASSIVE].
9061**
9062** ^Every new [database connection] defaults to having the auto-checkpoint
9063** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
9064** pages.  The use of this interface
9065** is only necessary if the default setting is found to be suboptimal
9066** for a particular application.
9067*/
9068SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
9069
9070/*
9071** CAPI3REF: Checkpoint a database
9072** METHOD: sqlite3
9073**
9074** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
9075** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
9076**
9077** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
9078** [write-ahead log] for database X on [database connection] D to be
9079** transferred into the database file and for the write-ahead log to
9080** be reset.  See the [checkpointing] documentation for addition
9081** information.
9082**
9083** This interface used to be the only way to cause a checkpoint to
9084** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
9085** interface was added.  This interface is retained for backwards
9086** compatibility and as a convenience for applications that need to manually
9087** start a callback but which do not need the full power (and corresponding
9088** complication) of [sqlite3_wal_checkpoint_v2()].
9089*/
9090SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
9091
9092/*
9093** CAPI3REF: Checkpoint a database
9094** METHOD: sqlite3
9095**
9096** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
9097** operation on database X of [database connection] D in mode M.  Status
9098** information is written back into integers pointed to by L and C.)^
9099** ^(The M parameter must be a valid [checkpoint mode]:)^
9100**
9101** <dl>
9102** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
9103**   ^Checkpoint as many frames as possible without waiting for any database
9104**   readers or writers to finish, then sync the database file if all frames
9105**   in the log were checkpointed. ^The [busy-handler callback]
9106**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
9107**   ^On the other hand, passive mode might leave the checkpoint unfinished
9108**   if there are concurrent readers or writers.
9109**
9110** <dt>SQLITE_CHECKPOINT_FULL<dd>
9111**   ^This mode blocks (it invokes the
9112**   [sqlite3_busy_handler|busy-handler callback]) until there is no
9113**   database writer and all readers are reading from the most recent database
9114**   snapshot. ^It then checkpoints all frames in the log file and syncs the
9115**   database file. ^This mode blocks new database writers while it is pending,
9116**   but new database readers are allowed to continue unimpeded.
9117**
9118** <dt>SQLITE_CHECKPOINT_RESTART<dd>
9119**   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
9120**   that after checkpointing the log file it blocks (calls the
9121**   [busy-handler callback])
9122**   until all readers are reading from the database file only. ^This ensures
9123**   that the next writer will restart the log file from the beginning.
9124**   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
9125**   database writer attempts while it is pending, but does not impede readers.
9126**
9127** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
9128**   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
9129**   addition that it also truncates the log file to zero bytes just prior
9130**   to a successful return.
9131** </dl>
9132**
9133** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
9134** the log file or to -1 if the checkpoint could not run because
9135** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
9136** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
9137** log file (including any that were already checkpointed before the function
9138** was called) or to -1 if the checkpoint could not run due to an error or
9139** because the database is not in WAL mode. ^Note that upon successful
9140** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
9141** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
9142**
9143** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
9144** any other process is running a checkpoint operation at the same time, the
9145** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
9146** busy-handler configured, it will not be invoked in this case.
9147**
9148** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
9149** exclusive "writer" lock on the database file. ^If the writer lock cannot be
9150** obtained immediately, and a busy-handler is configured, it is invoked and
9151** the writer lock retried until either the busy-handler returns 0 or the lock
9152** is successfully obtained. ^The busy-handler is also invoked while waiting for
9153** database readers as described above. ^If the busy-handler returns 0 before
9154** the writer lock is obtained or while waiting for database readers, the
9155** checkpoint operation proceeds from that point in the same way as
9156** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
9157** without blocking any further. ^SQLITE_BUSY is returned in this case.
9158**
9159** ^If parameter zDb is NULL or points to a zero length string, then the
9160** specified operation is attempted on all WAL databases [attached] to
9161** [database connection] db.  In this case the
9162** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
9163** an SQLITE_BUSY error is encountered when processing one or more of the
9164** attached WAL databases, the operation is still attempted on any remaining
9165** attached databases and SQLITE_BUSY is returned at the end. ^If any other
9166** error occurs while processing an attached database, processing is abandoned
9167** and the error code is returned to the caller immediately. ^If no error
9168** (SQLITE_BUSY or otherwise) is encountered while processing the attached
9169** databases, SQLITE_OK is returned.
9170**
9171** ^If database zDb is the name of an attached database that is not in WAL
9172** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
9173** zDb is not NULL (or a zero length string) and is not the name of any
9174** attached database, SQLITE_ERROR is returned to the caller.
9175**
9176** ^Unless it returns SQLITE_MISUSE,
9177** the sqlite3_wal_checkpoint_v2() interface
9178** sets the error information that is queried by
9179** [sqlite3_errcode()] and [sqlite3_errmsg()].
9180**
9181** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
9182** from SQL.
9183*/
9184SQLITE_API int sqlite3_wal_checkpoint_v2(
9185  sqlite3 *db,                    /* Database handle */
9186  const char *zDb,                /* Name of attached database (or NULL) */
9187  int eMode,                      /* SQLITE_CHECKPOINT_* value */
9188  int *pnLog,                     /* OUT: Size of WAL log in frames */
9189  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
9190);
9191
9192/*
9193** CAPI3REF: Checkpoint Mode Values
9194** KEYWORDS: {checkpoint mode}
9195**
9196** These constants define all valid values for the "checkpoint mode" passed
9197** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
9198** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
9199** meaning of each of these checkpoint modes.
9200*/
9201#define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
9202#define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
9203#define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
9204#define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
9205
9206/*
9207** CAPI3REF: Virtual Table Interface Configuration
9208**
9209** This function may be called by either the [xConnect] or [xCreate] method
9210** of a [virtual table] implementation to configure
9211** various facets of the virtual table interface.
9212**
9213** If this interface is invoked outside the context of an xConnect or
9214** xCreate virtual table method then the behavior is undefined.
9215**
9216** At present, there is only one option that may be configured using
9217** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
9218** may be added in the future.
9219*/
9220SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
9221
9222/*
9223** CAPI3REF: Virtual Table Configuration Options
9224**
9225** These macros define the various options to the
9226** [sqlite3_vtab_config()] interface that [virtual table] implementations
9227** can use to customize and optimize their behavior.
9228**
9229** <dl>
9230** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
9231** <dd>Calls of the form
9232** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
9233** where X is an integer.  If X is zero, then the [virtual table] whose
9234** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
9235** support constraints.  In this configuration (which is the default) if
9236** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
9237** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
9238** specified as part of the users SQL statement, regardless of the actual
9239** ON CONFLICT mode specified.
9240**
9241** If X is non-zero, then the virtual table implementation guarantees
9242** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
9243** any modifications to internal or persistent data structures have been made.
9244** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
9245** is able to roll back a statement or database transaction, and abandon
9246** or continue processing the current SQL statement as appropriate.
9247** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
9248** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
9249** had been ABORT.
9250**
9251** Virtual table implementations that are required to handle OR REPLACE
9252** must do so within the [xUpdate] method. If a call to the
9253** [sqlite3_vtab_on_conflict()] function indicates that the current ON
9254** CONFLICT policy is REPLACE, the virtual table implementation should
9255** silently replace the appropriate rows within the xUpdate callback and
9256** return SQLITE_OK. Or, if this is not possible, it may return
9257** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
9258** constraint handling.
9259** </dl>
9260*/
9261#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
9262
9263/*
9264** CAPI3REF: Determine The Virtual Table Conflict Policy
9265**
9266** This function may only be called from within a call to the [xUpdate] method
9267** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
9268** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
9269** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
9270** of the SQL statement that triggered the call to the [xUpdate] method of the
9271** [virtual table].
9272*/
9273SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
9274
9275/*
9276** CAPI3REF: Conflict resolution modes
9277** KEYWORDS: {conflict resolution mode}
9278**
9279** These constants are returned by [sqlite3_vtab_on_conflict()] to
9280** inform a [virtual table] implementation what the [ON CONFLICT] mode
9281** is for the SQL statement being evaluated.
9282**
9283** Note that the [SQLITE_IGNORE] constant is also used as a potential
9284** return value from the [sqlite3_set_authorizer()] callback and that
9285** [SQLITE_ABORT] is also a [result code].
9286*/
9287#define SQLITE_ROLLBACK 1
9288/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
9289#define SQLITE_FAIL     3
9290/* #define SQLITE_ABORT 4  // Also an error code */
9291#define SQLITE_REPLACE  5
9292
9293/*
9294** CAPI3REF: Prepared Statement Scan Status Opcodes
9295** KEYWORDS: {scanstatus options}
9296**
9297** The following constants can be used for the T parameter to the
9298** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
9299** different metric for sqlite3_stmt_scanstatus() to return.
9300**
9301** When the value returned to V is a string, space to hold that string is
9302** managed by the prepared statement S and will be automatically freed when
9303** S is finalized.
9304**
9305** <dl>
9306** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
9307** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
9308** set to the total number of times that the X-th loop has run.</dd>
9309**
9310** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
9311** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
9312** to the total number of rows examined by all iterations of the X-th loop.</dd>
9313**
9314** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
9315** <dd>^The "double" variable pointed to by the T parameter will be set to the
9316** query planner's estimate for the average number of rows output from each
9317** iteration of the X-th loop.  If the query planner's estimates was accurate,
9318** then this value will approximate the quotient NVISIT/NLOOP and the
9319** product of this value for all prior loops with the same SELECTID will
9320** be the NLOOP value for the current loop.
9321**
9322** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
9323** <dd>^The "const char *" variable pointed to by the T parameter will be set
9324** to a zero-terminated UTF-8 string containing the name of the index or table
9325** used for the X-th loop.
9326**
9327** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
9328** <dd>^The "const char *" variable pointed to by the T parameter will be set
9329** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
9330** description for the X-th loop.
9331**
9332** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
9333** <dd>^The "int" variable pointed to by the T parameter will be set to the
9334** "select-id" for the X-th loop.  The select-id identifies which query or
9335** subquery the loop is part of.  The main query has a select-id of zero.
9336** The select-id is the same value as is output in the first column
9337** of an [EXPLAIN QUERY PLAN] query.
9338** </dl>
9339*/
9340#define SQLITE_SCANSTAT_NLOOP    0
9341#define SQLITE_SCANSTAT_NVISIT   1
9342#define SQLITE_SCANSTAT_EST      2
9343#define SQLITE_SCANSTAT_NAME     3
9344#define SQLITE_SCANSTAT_EXPLAIN  4
9345#define SQLITE_SCANSTAT_SELECTID 5
9346
9347/*
9348** CAPI3REF: Prepared Statement Scan Status
9349** METHOD: sqlite3_stmt
9350**
9351** This interface returns information about the predicted and measured
9352** performance for pStmt.  Advanced applications can use this
9353** interface to compare the predicted and the measured performance and
9354** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
9355**
9356** Since this interface is expected to be rarely used, it is only
9357** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
9358** compile-time option.
9359**
9360** The "iScanStatusOp" parameter determines which status information to return.
9361** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
9362** of this interface is undefined.
9363** ^The requested measurement is written into a variable pointed to by
9364** the "pOut" parameter.
9365** Parameter "idx" identifies the specific loop to retrieve statistics for.
9366** Loops are numbered starting from zero. ^If idx is out of range - less than
9367** zero or greater than or equal to the total number of loops used to implement
9368** the statement - a non-zero value is returned and the variable that pOut
9369** points to is unchanged.
9370**
9371** ^Statistics might not be available for all loops in all statements. ^In cases
9372** where there exist loops with no available statistics, this function behaves
9373** as if the loop did not exist - it returns non-zero and leave the variable
9374** that pOut points to unchanged.
9375**
9376** See also: [sqlite3_stmt_scanstatus_reset()]
9377*/
9378SQLITE_API int sqlite3_stmt_scanstatus(
9379  sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
9380  int idx,                  /* Index of loop to report on */
9381  int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
9382  void *pOut                /* Result written here */
9383);
9384
9385/*
9386** CAPI3REF: Zero Scan-Status Counters
9387** METHOD: sqlite3_stmt
9388**
9389** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
9390**
9391** This API is only available if the library is built with pre-processor
9392** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
9393*/
9394SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
9395
9396/*
9397** CAPI3REF: Flush caches to disk mid-transaction
9398**
9399** ^If a write-transaction is open on [database connection] D when the
9400** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
9401** pages in the pager-cache that are not currently in use are written out
9402** to disk. A dirty page may be in use if a database cursor created by an
9403** active SQL statement is reading from it, or if it is page 1 of a database
9404** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
9405** interface flushes caches for all schemas - "main", "temp", and
9406** any [attached] databases.
9407**
9408** ^If this function needs to obtain extra database locks before dirty pages
9409** can be flushed to disk, it does so. ^If those locks cannot be obtained
9410** immediately and there is a busy-handler callback configured, it is invoked
9411** in the usual manner. ^If the required lock still cannot be obtained, then
9412** the database is skipped and an attempt made to flush any dirty pages
9413** belonging to the next (if any) database. ^If any databases are skipped
9414** because locks cannot be obtained, but no other error occurs, this
9415** function returns SQLITE_BUSY.
9416**
9417** ^If any other error occurs while flushing dirty pages to disk (for
9418** example an IO error or out-of-memory condition), then processing is
9419** abandoned and an SQLite [error code] is returned to the caller immediately.
9420**
9421** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
9422**
9423** ^This function does not set the database handle error code or message
9424** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
9425*/
9426SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
9427
9428/*
9429** CAPI3REF: The pre-update hook.
9430**
9431** ^These interfaces are only available if SQLite is compiled using the
9432** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
9433**
9434** ^The [sqlite3_preupdate_hook()] interface registers a callback function
9435** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
9436** on a database table.
9437** ^At most one preupdate hook may be registered at a time on a single
9438** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
9439** the previous setting.
9440** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
9441** with a NULL pointer as the second parameter.
9442** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
9443** the first parameter to callbacks.
9444**
9445** ^The preupdate hook only fires for changes to real database tables; the
9446** preupdate hook is not invoked for changes to [virtual tables] or to
9447** system tables like sqlite_master or sqlite_stat1.
9448**
9449** ^The second parameter to the preupdate callback is a pointer to
9450** the [database connection] that registered the preupdate hook.
9451** ^The third parameter to the preupdate callback is one of the constants
9452** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
9453** kind of update operation that is about to occur.
9454** ^(The fourth parameter to the preupdate callback is the name of the
9455** database within the database connection that is being modified.  This
9456** will be "main" for the main database or "temp" for TEMP tables or
9457** the name given after the AS keyword in the [ATTACH] statement for attached
9458** databases.)^
9459** ^The fifth parameter to the preupdate callback is the name of the
9460** table that is being modified.
9461**
9462** For an UPDATE or DELETE operation on a [rowid table], the sixth
9463** parameter passed to the preupdate callback is the initial [rowid] of the
9464** row being modified or deleted. For an INSERT operation on a rowid table,
9465** or any operation on a WITHOUT ROWID table, the value of the sixth
9466** parameter is undefined. For an INSERT or UPDATE on a rowid table the
9467** seventh parameter is the final rowid value of the row being inserted
9468** or updated. The value of the seventh parameter passed to the callback
9469** function is not defined for operations on WITHOUT ROWID tables, or for
9470** INSERT operations on rowid tables.
9471**
9472** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
9473** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
9474** provide additional information about a preupdate event. These routines
9475** may only be called from within a preupdate callback.  Invoking any of
9476** these routines from outside of a preupdate callback or with a
9477** [database connection] pointer that is different from the one supplied
9478** to the preupdate callback results in undefined and probably undesirable
9479** behavior.
9480**
9481** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
9482** in the row that is being inserted, updated, or deleted.
9483**
9484** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
9485** a [protected sqlite3_value] that contains the value of the Nth column of
9486** the table row before it is updated.  The N parameter must be between 0
9487** and one less than the number of columns or the behavior will be
9488** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
9489** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
9490** behavior is undefined.  The [sqlite3_value] that P points to
9491** will be destroyed when the preupdate callback returns.
9492**
9493** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
9494** a [protected sqlite3_value] that contains the value of the Nth column of
9495** the table row after it is updated.  The N parameter must be between 0
9496** and one less than the number of columns or the behavior will be
9497** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
9498** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
9499** behavior is undefined.  The [sqlite3_value] that P points to
9500** will be destroyed when the preupdate callback returns.
9501**
9502** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
9503** callback was invoked as a result of a direct insert, update, or delete
9504** operation; or 1 for inserts, updates, or deletes invoked by top-level
9505** triggers; or 2 for changes resulting from triggers called by top-level
9506** triggers; and so forth.
9507**
9508** See also:  [sqlite3_update_hook()]
9509*/
9510#if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
9511SQLITE_API void *sqlite3_preupdate_hook(
9512  sqlite3 *db,
9513  void(*xPreUpdate)(
9514    void *pCtx,                   /* Copy of third arg to preupdate_hook() */
9515    sqlite3 *db,                  /* Database handle */
9516    int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
9517    char const *zDb,              /* Database name */
9518    char const *zName,            /* Table name */
9519    sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
9520    sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
9521  ),
9522  void*
9523);
9524SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
9525SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
9526SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
9527SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
9528#endif
9529
9530/*
9531** CAPI3REF: Low-level system error code
9532**
9533** ^Attempt to return the underlying operating system error code or error
9534** number that caused the most recent I/O error or failure to open a file.
9535** The return value is OS-dependent.  For example, on unix systems, after
9536** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
9537** called to get back the underlying "errno" that caused the problem, such
9538** as ENOSPC, EAUTH, EISDIR, and so forth.
9539*/
9540SQLITE_API int sqlite3_system_errno(sqlite3*);
9541
9542/*
9543** CAPI3REF: Database Snapshot
9544** KEYWORDS: {snapshot} {sqlite3_snapshot}
9545** EXPERIMENTAL
9546**
9547** An instance of the snapshot object records the state of a [WAL mode]
9548** database for some specific point in history.
9549**
9550** In [WAL mode], multiple [database connections] that are open on the
9551** same database file can each be reading a different historical version
9552** of the database file.  When a [database connection] begins a read
9553** transaction, that connection sees an unchanging copy of the database
9554** as it existed for the point in time when the transaction first started.
9555** Subsequent changes to the database from other connections are not seen
9556** by the reader until a new read transaction is started.
9557**
9558** The sqlite3_snapshot object records state information about an historical
9559** version of the database file so that it is possible to later open a new read
9560** transaction that sees that historical version of the database rather than
9561** the most recent version.
9562**
9563** The constructor for this object is [sqlite3_snapshot_get()].  The
9564** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
9565** to an historical snapshot (if possible).  The destructor for
9566** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
9567*/
9568typedef struct sqlite3_snapshot {
9569  unsigned char hidden[48];
9570} sqlite3_snapshot;
9571
9572/*
9573** CAPI3REF: Record A Database Snapshot
9574** EXPERIMENTAL
9575**
9576** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
9577** new [sqlite3_snapshot] object that records the current state of
9578** schema S in database connection D.  ^On success, the
9579** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
9580** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
9581** If there is not already a read-transaction open on schema S when
9582** this function is called, one is opened automatically.
9583**
9584** The following must be true for this function to succeed. If any of
9585** the following statements are false when sqlite3_snapshot_get() is
9586** called, SQLITE_ERROR is returned. The final value of *P is undefined
9587** in this case.
9588**
9589** <ul>
9590**   <li> The database handle must be in [autocommit mode].
9591**
9592**   <li> Schema S of [database connection] D must be a [WAL mode] database.
9593**
9594**   <li> There must not be a write transaction open on schema S of database
9595**        connection D.
9596**
9597**   <li> One or more transactions must have been written to the current wal
9598**        file since it was created on disk (by any connection). This means
9599**        that a snapshot cannot be taken on a wal mode database with no wal
9600**        file immediately after it is first opened. At least one transaction
9601**        must be written to it first.
9602** </ul>
9603**
9604** This function may also return SQLITE_NOMEM.  If it is called with the
9605** database handle in autocommit mode but fails for some other reason,
9606** whether or not a read transaction is opened on schema S is undefined.
9607**
9608** The [sqlite3_snapshot] object returned from a successful call to
9609** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
9610** to avoid a memory leak.
9611**
9612** The [sqlite3_snapshot_get()] interface is only available when the
9613** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
9614*/
9615SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
9616  sqlite3 *db,
9617  const char *zSchema,
9618  sqlite3_snapshot **ppSnapshot
9619);
9620
9621/*
9622** CAPI3REF: Start a read transaction on an historical snapshot
9623** EXPERIMENTAL
9624**
9625** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
9626** read transaction for schema S of
9627** [database connection] D such that the read transaction
9628** refers to historical [snapshot] P, rather than the most
9629** recent change to the database.
9630** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
9631** or an appropriate [error code] if it fails.
9632**
9633** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
9634** the first operation following the [BEGIN] that takes the schema S
9635** out of [autocommit mode].
9636** ^In other words, schema S must not currently be in
9637** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
9638** database connection D must be out of [autocommit mode].
9639** ^A [snapshot] will fail to open if it has been overwritten by a
9640** [checkpoint].
9641** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
9642** database connection D does not know that the database file for
9643** schema S is in [WAL mode].  A database connection might not know
9644** that the database file is in [WAL mode] if there has been no prior
9645** I/O on that database connection, or if the database entered [WAL mode]
9646** after the most recent I/O on the database connection.)^
9647** (Hint: Run "[PRAGMA application_id]" against a newly opened
9648** database connection in order to make it ready to use snapshots.)
9649**
9650** The [sqlite3_snapshot_open()] interface is only available when the
9651** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
9652*/
9653SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
9654  sqlite3 *db,
9655  const char *zSchema,
9656  sqlite3_snapshot *pSnapshot
9657);
9658
9659/*
9660** CAPI3REF: Destroy a snapshot
9661** EXPERIMENTAL
9662**
9663** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
9664** The application must eventually free every [sqlite3_snapshot] object
9665** using this routine to avoid a memory leak.
9666**
9667** The [sqlite3_snapshot_free()] interface is only available when the
9668** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
9669*/
9670SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
9671
9672/*
9673** CAPI3REF: Compare the ages of two snapshot handles.
9674** EXPERIMENTAL
9675**
9676** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
9677** of two valid snapshot handles.
9678**
9679** If the two snapshot handles are not associated with the same database
9680** file, the result of the comparison is undefined.
9681**
9682** Additionally, the result of the comparison is only valid if both of the
9683** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
9684** last time the wal file was deleted. The wal file is deleted when the
9685** database is changed back to rollback mode or when the number of database
9686** clients drops to zero. If either snapshot handle was obtained before the
9687** wal file was last deleted, the value returned by this function
9688** is undefined.
9689**
9690** Otherwise, this API returns a negative value if P1 refers to an older
9691** snapshot than P2, zero if the two handles refer to the same database
9692** snapshot, and a positive value if P1 is a newer snapshot than P2.
9693*/
9694SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
9695  sqlite3_snapshot *p1,
9696  sqlite3_snapshot *p2
9697);
9698
9699/*
9700** CAPI3REF: Recover snapshots from a wal file
9701** EXPERIMENTAL
9702**
9703** If all connections disconnect from a database file but do not perform
9704** a checkpoint, the existing wal file is opened along with the database
9705** file the next time the database is opened. At this point it is only
9706** possible to successfully call sqlite3_snapshot_open() to open the most
9707** recent snapshot of the database (the one at the head of the wal file),
9708** even though the wal file may contain other valid snapshots for which
9709** clients have sqlite3_snapshot handles.
9710**
9711** This function attempts to scan the wal file associated with database zDb
9712** of database handle db and make all valid snapshots available to
9713** sqlite3_snapshot_open(). It is an error if there is already a read
9714** transaction open on the database, or if the database is not a wal mode
9715** database.
9716**
9717** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9718*/
9719SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
9720
9721/*
9722** Undo the hack that converts floating point types to integer for
9723** builds on processors without floating point support.
9724*/
9725#ifdef SQLITE_OMIT_FLOATING_POINT
9726# undef double
9727#endif
9728
9729#if 0
9730}  /* End of the 'extern "C"' block */
9731#endif
9732#endif /* SQLITE3_H */
9733
9734/******** Begin file sqlite3rtree.h *********/
9735/*
9736** 2010 August 30
9737**
9738** The author disclaims copyright to this source code.  In place of
9739** a legal notice, here is a blessing:
9740**
9741**    May you do good and not evil.
9742**    May you find forgiveness for yourself and forgive others.
9743**    May you share freely, never taking more than you give.
9744**
9745*************************************************************************
9746*/
9747
9748#ifndef _SQLITE3RTREE_H_
9749#define _SQLITE3RTREE_H_
9750
9751
9752#if 0
9753extern "C" {
9754#endif
9755
9756typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
9757typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
9758
9759/* The double-precision datatype used by RTree depends on the
9760** SQLITE_RTREE_INT_ONLY compile-time option.
9761*/
9762#ifdef SQLITE_RTREE_INT_ONLY
9763  typedef sqlite3_int64 sqlite3_rtree_dbl;
9764#else
9765  typedef double sqlite3_rtree_dbl;
9766#endif
9767
9768/*
9769** Register a geometry callback named zGeom that can be used as part of an
9770** R-Tree geometry query as follows:
9771**
9772**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
9773*/
9774SQLITE_API int sqlite3_rtree_geometry_callback(
9775  sqlite3 *db,
9776  const char *zGeom,
9777  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
9778  void *pContext
9779);
9780
9781
9782/*
9783** A pointer to a structure of the following type is passed as the first
9784** argument to callbacks registered using rtree_geometry_callback().
9785*/
9786struct sqlite3_rtree_geometry {
9787  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
9788  int nParam;                     /* Size of array aParam[] */
9789  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
9790  void *pUser;                    /* Callback implementation user data */
9791  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
9792};
9793
9794/*
9795** Register a 2nd-generation geometry callback named zScore that can be
9796** used as part of an R-Tree geometry query as follows:
9797**
9798**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
9799*/
9800SQLITE_API int sqlite3_rtree_query_callback(
9801  sqlite3 *db,
9802  const char *zQueryFunc,
9803  int (*xQueryFunc)(sqlite3_rtree_query_info*),
9804  void *pContext,
9805  void (*xDestructor)(void*)
9806);
9807
9808
9809/*
9810** A pointer to a structure of the following type is passed as the
9811** argument to scored geometry callback registered using
9812** sqlite3_rtree_query_callback().
9813**
9814** Note that the first 5 fields of this structure are identical to
9815** sqlite3_rtree_geometry.  This structure is a subclass of
9816** sqlite3_rtree_geometry.
9817*/
9818struct sqlite3_rtree_query_info {
9819  void *pContext;                   /* pContext from when function registered */
9820  int nParam;                       /* Number of function parameters */
9821  sqlite3_rtree_dbl *aParam;        /* value of function parameters */
9822  void *pUser;                      /* callback can use this, if desired */
9823  void (*xDelUser)(void*);          /* function to free pUser */
9824  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
9825  unsigned int *anQueue;            /* Number of pending entries in the queue */
9826  int nCoord;                       /* Number of coordinates */
9827  int iLevel;                       /* Level of current node or entry */
9828  int mxLevel;                      /* The largest iLevel value in the tree */
9829  sqlite3_int64 iRowid;             /* Rowid for current entry */
9830  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
9831  int eParentWithin;                /* Visibility of parent node */
9832  int eWithin;                      /* OUT: Visiblity */
9833  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
9834  /* The following fields are only available in 3.8.11 and later */
9835  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
9836};
9837
9838/*
9839** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
9840*/
9841#define NOT_WITHIN       0   /* Object completely outside of query region */
9842#define PARTLY_WITHIN    1   /* Object partially overlaps query region */
9843#define FULLY_WITHIN     2   /* Object fully contained within query region */
9844
9845
9846#if 0
9847}  /* end of the 'extern "C"' block */
9848#endif
9849
9850#endif  /* ifndef _SQLITE3RTREE_H_ */
9851
9852/******** End of sqlite3rtree.h *********/
9853/******** Begin file sqlite3session.h *********/
9854
9855#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
9856#define __SQLITESESSION_H_ 1
9857
9858/*
9859** Make sure we can call this stuff from C++.
9860*/
9861#if 0
9862extern "C" {
9863#endif
9864
9865
9866/*
9867** CAPI3REF: Session Object Handle
9868*/
9869typedef struct sqlite3_session sqlite3_session;
9870
9871/*
9872** CAPI3REF: Changeset Iterator Handle
9873*/
9874typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
9875
9876/*
9877** CAPI3REF: Create A New Session Object
9878**
9879** Create a new session object attached to database handle db. If successful,
9880** a pointer to the new object is written to *ppSession and SQLITE_OK is
9881** returned. If an error occurs, *ppSession is set to NULL and an SQLite
9882** error code (e.g. SQLITE_NOMEM) is returned.
9883**
9884** It is possible to create multiple session objects attached to a single
9885** database handle.
9886**
9887** Session objects created using this function should be deleted using the
9888** [sqlite3session_delete()] function before the database handle that they
9889** are attached to is itself closed. If the database handle is closed before
9890** the session object is deleted, then the results of calling any session
9891** module function, including [sqlite3session_delete()] on the session object
9892** are undefined.
9893**
9894** Because the session module uses the [sqlite3_preupdate_hook()] API, it
9895** is not possible for an application to register a pre-update hook on a
9896** database handle that has one or more session objects attached. Nor is
9897** it possible to create a session object attached to a database handle for
9898** which a pre-update hook is already defined. The results of attempting
9899** either of these things are undefined.
9900**
9901** The session object will be used to create changesets for tables in
9902** database zDb, where zDb is either "main", or "temp", or the name of an
9903** attached database. It is not an error if database zDb is not attached
9904** to the database when the session object is created.
9905*/
9906SQLITE_API int sqlite3session_create(
9907  sqlite3 *db,                    /* Database handle */
9908  const char *zDb,                /* Name of db (e.g. "main") */
9909  sqlite3_session **ppSession     /* OUT: New session object */
9910);
9911
9912/*
9913** CAPI3REF: Delete A Session Object
9914**
9915** Delete a session object previously allocated using
9916** [sqlite3session_create()]. Once a session object has been deleted, the
9917** results of attempting to use pSession with any other session module
9918** function are undefined.
9919**
9920** Session objects must be deleted before the database handle to which they
9921** are attached is closed. Refer to the documentation for
9922** [sqlite3session_create()] for details.
9923*/
9924SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
9925
9926
9927/*
9928** CAPI3REF: Enable Or Disable A Session Object
9929**
9930** Enable or disable the recording of changes by a session object. When
9931** enabled, a session object records changes made to the database. When
9932** disabled - it does not. A newly created session object is enabled.
9933** Refer to the documentation for [sqlite3session_changeset()] for further
9934** details regarding how enabling and disabling a session object affects
9935** the eventual changesets.
9936**
9937** Passing zero to this function disables the session. Passing a value
9938** greater than zero enables it. Passing a value less than zero is a
9939** no-op, and may be used to query the current state of the session.
9940**
9941** The return value indicates the final state of the session object: 0 if
9942** the session is disabled, or 1 if it is enabled.
9943*/
9944SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
9945
9946/*
9947** CAPI3REF: Set Or Clear the Indirect Change Flag
9948**
9949** Each change recorded by a session object is marked as either direct or
9950** indirect. A change is marked as indirect if either:
9951**
9952** <ul>
9953**   <li> The session object "indirect" flag is set when the change is
9954**        made, or
9955**   <li> The change is made by an SQL trigger or foreign key action
9956**        instead of directly as a result of a users SQL statement.
9957** </ul>
9958**
9959** If a single row is affected by more than one operation within a session,
9960** then the change is considered indirect if all operations meet the criteria
9961** for an indirect change above, or direct otherwise.
9962**
9963** This function is used to set, clear or query the session object indirect
9964** flag.  If the second argument passed to this function is zero, then the
9965** indirect flag is cleared. If it is greater than zero, the indirect flag
9966** is set. Passing a value less than zero does not modify the current value
9967** of the indirect flag, and may be used to query the current state of the
9968** indirect flag for the specified session object.
9969**
9970** The return value indicates the final state of the indirect flag: 0 if
9971** it is clear, or 1 if it is set.
9972*/
9973SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
9974
9975/*
9976** CAPI3REF: Attach A Table To A Session Object
9977**
9978** If argument zTab is not NULL, then it is the name of a table to attach
9979** to the session object passed as the first argument. All subsequent changes
9980** made to the table while the session object is enabled will be recorded. See
9981** documentation for [sqlite3session_changeset()] for further details.
9982**
9983** Or, if argument zTab is NULL, then changes are recorded for all tables
9984** in the database. If additional tables are added to the database (by
9985** executing "CREATE TABLE" statements) after this call is made, changes for
9986** the new tables are also recorded.
9987**
9988** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
9989** defined as part of their CREATE TABLE statement. It does not matter if the
9990** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
9991** KEY may consist of a single column, or may be a composite key.
9992**
9993** It is not an error if the named table does not exist in the database. Nor
9994** is it an error if the named table does not have a PRIMARY KEY. However,
9995** no changes will be recorded in either of these scenarios.
9996**
9997** Changes are not recorded for individual rows that have NULL values stored
9998** in one or more of their PRIMARY KEY columns.
9999**
10000** SQLITE_OK is returned if the call completes without error. Or, if an error
10001** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
10002*/
10003SQLITE_API int sqlite3session_attach(
10004  sqlite3_session *pSession,      /* Session object */
10005  const char *zTab                /* Table name */
10006);
10007
10008/*
10009** CAPI3REF: Set a table filter on a Session Object.
10010**
10011** The second argument (xFilter) is the "filter callback". For changes to rows
10012** in tables that are not attached to the Session object, the filter is called
10013** to determine whether changes to the table's rows should be tracked or not.
10014** If xFilter returns 0, changes is not tracked. Note that once a table is
10015** attached, xFilter will not be called again.
10016*/
10017SQLITE_API void sqlite3session_table_filter(
10018  sqlite3_session *pSession,      /* Session object */
10019  int(*xFilter)(
10020    void *pCtx,                   /* Copy of third arg to _filter_table() */
10021    const char *zTab              /* Table name */
10022  ),
10023  void *pCtx                      /* First argument passed to xFilter */
10024);
10025
10026/*
10027** CAPI3REF: Generate A Changeset From A Session Object
10028**
10029** Obtain a changeset containing changes to the tables attached to the
10030** session object passed as the first argument. If successful,
10031** set *ppChangeset to point to a buffer containing the changeset
10032** and *pnChangeset to the size of the changeset in bytes before returning
10033** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
10034** zero and return an SQLite error code.
10035**
10036** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
10037** each representing a change to a single row of an attached table. An INSERT
10038** change contains the values of each field of a new database row. A DELETE
10039** contains the original values of each field of a deleted database row. An
10040** UPDATE change contains the original values of each field of an updated
10041** database row along with the updated values for each updated non-primary-key
10042** column. It is not possible for an UPDATE change to represent a change that
10043** modifies the values of primary key columns. If such a change is made, it
10044** is represented in a changeset as a DELETE followed by an INSERT.
10045**
10046** Changes are not recorded for rows that have NULL values stored in one or
10047** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
10048** no corresponding change is present in the changesets returned by this
10049** function. If an existing row with one or more NULL values stored in
10050** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
10051** only an INSERT is appears in the changeset. Similarly, if an existing row
10052** with non-NULL PRIMARY KEY values is updated so that one or more of its
10053** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
10054** DELETE change only.
10055**
10056** The contents of a changeset may be traversed using an iterator created
10057** using the [sqlite3changeset_start()] API. A changeset may be applied to
10058** a database with a compatible schema using the [sqlite3changeset_apply()]
10059** API.
10060**
10061** Within a changeset generated by this function, all changes related to a
10062** single table are grouped together. In other words, when iterating through
10063** a changeset or when applying a changeset to a database, all changes related
10064** to a single table are processed before moving on to the next table. Tables
10065** are sorted in the same order in which they were attached (or auto-attached)
10066** to the sqlite3_session object. The order in which the changes related to
10067** a single table are stored is undefined.
10068**
10069** Following a successful call to this function, it is the responsibility of
10070** the caller to eventually free the buffer that *ppChangeset points to using
10071** [sqlite3_free()].
10072**
10073** <h3>Changeset Generation</h3>
10074**
10075** Once a table has been attached to a session object, the session object
10076** records the primary key values of all new rows inserted into the table.
10077** It also records the original primary key and other column values of any
10078** deleted or updated rows. For each unique primary key value, data is only
10079** recorded once - the first time a row with said primary key is inserted,
10080** updated or deleted in the lifetime of the session.
10081**
10082** There is one exception to the previous paragraph: when a row is inserted,
10083** updated or deleted, if one or more of its primary key columns contain a
10084** NULL value, no record of the change is made.
10085**
10086** The session object therefore accumulates two types of records - those
10087** that consist of primary key values only (created when the user inserts
10088** a new record) and those that consist of the primary key values and the
10089** original values of other table columns (created when the users deletes
10090** or updates a record).
10091**
10092** When this function is called, the requested changeset is created using
10093** both the accumulated records and the current contents of the database
10094** file. Specifically:
10095**
10096** <ul>
10097**   <li> For each record generated by an insert, the database is queried
10098**        for a row with a matching primary key. If one is found, an INSERT
10099**        change is added to the changeset. If no such row is found, no change
10100**        is added to the changeset.
10101**
10102**   <li> For each record generated by an update or delete, the database is
10103**        queried for a row with a matching primary key. If such a row is
10104**        found and one or more of the non-primary key fields have been
10105**        modified from their original values, an UPDATE change is added to
10106**        the changeset. Or, if no such row is found in the table, a DELETE
10107**        change is added to the changeset. If there is a row with a matching
10108**        primary key in the database, but all fields contain their original
10109**        values, no change is added to the changeset.
10110** </ul>
10111**
10112** This means, amongst other things, that if a row is inserted and then later
10113** deleted while a session object is active, neither the insert nor the delete
10114** will be present in the changeset. Or if a row is deleted and then later a
10115** row with the same primary key values inserted while a session object is
10116** active, the resulting changeset will contain an UPDATE change instead of
10117** a DELETE and an INSERT.
10118**
10119** When a session object is disabled (see the [sqlite3session_enable()] API),
10120** it does not accumulate records when rows are inserted, updated or deleted.
10121** This may appear to have some counter-intuitive effects if a single row
10122** is written to more than once during a session. For example, if a row
10123** is inserted while a session object is enabled, then later deleted while
10124** the same session object is disabled, no INSERT record will appear in the
10125** changeset, even though the delete took place while the session was disabled.
10126** Or, if one field of a row is updated while a session is disabled, and
10127** another field of the same row is updated while the session is enabled, the
10128** resulting changeset will contain an UPDATE change that updates both fields.
10129*/
10130SQLITE_API int sqlite3session_changeset(
10131  sqlite3_session *pSession,      /* Session object */
10132  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
10133  void **ppChangeset              /* OUT: Buffer containing changeset */
10134);
10135
10136/*
10137** CAPI3REF: Load The Difference Between Tables Into A Session
10138**
10139** If it is not already attached to the session object passed as the first
10140** argument, this function attaches table zTbl in the same manner as the
10141** [sqlite3session_attach()] function. If zTbl does not exist, or if it
10142** does not have a primary key, this function is a no-op (but does not return
10143** an error).
10144**
10145** Argument zFromDb must be the name of a database ("main", "temp" etc.)
10146** attached to the same database handle as the session object that contains
10147** a table compatible with the table attached to the session by this function.
10148** A table is considered compatible if it:
10149**
10150** <ul>
10151**   <li> Has the same name,
10152**   <li> Has the same set of columns declared in the same order, and
10153**   <li> Has the same PRIMARY KEY definition.
10154** </ul>
10155**
10156** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
10157** are compatible but do not have any PRIMARY KEY columns, it is not an error
10158** but no changes are added to the session object. As with other session
10159** APIs, tables without PRIMARY KEYs are simply ignored.
10160**
10161** This function adds a set of changes to the session object that could be
10162** used to update the table in database zFrom (call this the "from-table")
10163** so that its content is the same as the table attached to the session
10164** object (call this the "to-table"). Specifically:
10165**
10166** <ul>
10167**   <li> For each row (primary key) that exists in the to-table but not in
10168**     the from-table, an INSERT record is added to the session object.
10169**
10170**   <li> For each row (primary key) that exists in the to-table but not in
10171**     the from-table, a DELETE record is added to the session object.
10172**
10173**   <li> For each row (primary key) that exists in both tables, but features
10174**     different non-PK values in each, an UPDATE record is added to the
10175**     session.
10176** </ul>
10177**
10178** To clarify, if this function is called and then a changeset constructed
10179** using [sqlite3session_changeset()], then after applying that changeset to
10180** database zFrom the contents of the two compatible tables would be
10181** identical.
10182**
10183** It an error if database zFrom does not exist or does not contain the
10184** required compatible table.
10185**
10186** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
10187** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
10188** may be set to point to a buffer containing an English language error
10189** message. It is the responsibility of the caller to free this buffer using
10190** sqlite3_free().
10191*/
10192SQLITE_API int sqlite3session_diff(
10193  sqlite3_session *pSession,
10194  const char *zFromDb,
10195  const char *zTbl,
10196  char **pzErrMsg
10197);
10198
10199
10200/*
10201** CAPI3REF: Generate A Patchset From A Session Object
10202**
10203** The differences between a patchset and a changeset are that:
10204**
10205** <ul>
10206**   <li> DELETE records consist of the primary key fields only. The
10207**        original values of other fields are omitted.
10208**   <li> The original values of any modified fields are omitted from
10209**        UPDATE records.
10210** </ul>
10211**
10212** A patchset blob may be used with up to date versions of all
10213** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
10214** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
10215** attempting to use a patchset blob with old versions of the
10216** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
10217**
10218** Because the non-primary key "old.*" fields are omitted, no
10219** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
10220** is passed to the sqlite3changeset_apply() API. Other conflict types work
10221** in the same way as for changesets.
10222**
10223** Changes within a patchset are ordered in the same way as for changesets
10224** generated by the sqlite3session_changeset() function (i.e. all changes for
10225** a single table are grouped together, tables appear in the order in which
10226** they were attached to the session object).
10227*/
10228SQLITE_API int sqlite3session_patchset(
10229  sqlite3_session *pSession,      /* Session object */
10230  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
10231  void **ppPatchset               /* OUT: Buffer containing changeset */
10232);
10233
10234/*
10235** CAPI3REF: Test if a changeset has recorded any changes.
10236**
10237** Return non-zero if no changes to attached tables have been recorded by
10238** the session object passed as the first argument. Otherwise, if one or
10239** more changes have been recorded, return zero.
10240**
10241** Even if this function returns zero, it is possible that calling
10242** [sqlite3session_changeset()] on the session handle may still return a
10243** changeset that contains no changes. This can happen when a row in
10244** an attached table is modified and then later on the original values
10245** are restored. However, if this function returns non-zero, then it is
10246** guaranteed that a call to sqlite3session_changeset() will return a
10247** changeset containing zero changes.
10248*/
10249SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
10250
10251/*
10252** CAPI3REF: Create An Iterator To Traverse A Changeset
10253**
10254** Create an iterator used to iterate through the contents of a changeset.
10255** If successful, *pp is set to point to the iterator handle and SQLITE_OK
10256** is returned. Otherwise, if an error occurs, *pp is set to zero and an
10257** SQLite error code is returned.
10258**
10259** The following functions can be used to advance and query a changeset
10260** iterator created by this function:
10261**
10262** <ul>
10263**   <li> [sqlite3changeset_next()]
10264**   <li> [sqlite3changeset_op()]
10265**   <li> [sqlite3changeset_new()]
10266**   <li> [sqlite3changeset_old()]
10267** </ul>
10268**
10269** It is the responsibility of the caller to eventually destroy the iterator
10270** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
10271** changeset (pChangeset) must remain valid until after the iterator is
10272** destroyed.
10273**
10274** Assuming the changeset blob was created by one of the
10275** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
10276** [sqlite3changeset_invert()] functions, all changes within the changeset
10277** that apply to a single table are grouped together. This means that when
10278** an application iterates through a changeset using an iterator created by
10279** this function, all changes that relate to a single table are visited
10280** consecutively. There is no chance that the iterator will visit a change
10281** the applies to table X, then one for table Y, and then later on visit
10282** another change for table X.
10283*/
10284SQLITE_API int sqlite3changeset_start(
10285  sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
10286  int nChangeset,                 /* Size of changeset blob in bytes */
10287  void *pChangeset                /* Pointer to blob containing changeset */
10288);
10289
10290
10291/*
10292** CAPI3REF: Advance A Changeset Iterator
10293**
10294** This function may only be used with iterators created by function
10295** [sqlite3changeset_start()]. If it is called on an iterator passed to
10296** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
10297** is returned and the call has no effect.
10298**
10299** Immediately after an iterator is created by sqlite3changeset_start(), it
10300** does not point to any change in the changeset. Assuming the changeset
10301** is not empty, the first call to this function advances the iterator to
10302** point to the first change in the changeset. Each subsequent call advances
10303** the iterator to point to the next change in the changeset (if any). If
10304** no error occurs and the iterator points to a valid change after a call
10305** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
10306** Otherwise, if all changes in the changeset have already been visited,
10307** SQLITE_DONE is returned.
10308**
10309** If an error occurs, an SQLite error code is returned. Possible error
10310** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
10311** SQLITE_NOMEM.
10312*/
10313SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
10314
10315/*
10316** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
10317**
10318** The pIter argument passed to this function may either be an iterator
10319** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
10320** created by [sqlite3changeset_start()]. In the latter case, the most recent
10321** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
10322** is not the case, this function returns [SQLITE_MISUSE].
10323**
10324** If argument pzTab is not NULL, then *pzTab is set to point to a
10325** nul-terminated utf-8 encoded string containing the name of the table
10326** affected by the current change. The buffer remains valid until either
10327** sqlite3changeset_next() is called on the iterator or until the
10328** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
10329** set to the number of columns in the table affected by the change. If
10330** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
10331** is an indirect change, or false (0) otherwise. See the documentation for
10332** [sqlite3session_indirect()] for a description of direct and indirect
10333** changes. Finally, if pOp is not NULL, then *pOp is set to one of
10334** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
10335** type of change that the iterator currently points to.
10336**
10337** If no error occurs, SQLITE_OK is returned. If an error does occur, an
10338** SQLite error code is returned. The values of the output variables may not
10339** be trusted in this case.
10340*/
10341SQLITE_API int sqlite3changeset_op(
10342  sqlite3_changeset_iter *pIter,  /* Iterator object */
10343  const char **pzTab,             /* OUT: Pointer to table name */
10344  int *pnCol,                     /* OUT: Number of columns in table */
10345  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
10346  int *pbIndirect                 /* OUT: True for an 'indirect' change */
10347);
10348
10349/*
10350** CAPI3REF: Obtain The Primary Key Definition Of A Table
10351**
10352** For each modified table, a changeset includes the following:
10353**
10354** <ul>
10355**   <li> The number of columns in the table, and
10356**   <li> Which of those columns make up the tables PRIMARY KEY.
10357** </ul>
10358**
10359** This function is used to find which columns comprise the PRIMARY KEY of
10360** the table modified by the change that iterator pIter currently points to.
10361** If successful, *pabPK is set to point to an array of nCol entries, where
10362** nCol is the number of columns in the table. Elements of *pabPK are set to
10363** 0x01 if the corresponding column is part of the tables primary key, or
10364** 0x00 if it is not.
10365**
10366** If argument pnCol is not NULL, then *pnCol is set to the number of columns
10367** in the table.
10368**
10369** If this function is called when the iterator does not point to a valid
10370** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
10371** SQLITE_OK is returned and the output variables populated as described
10372** above.
10373*/
10374SQLITE_API int sqlite3changeset_pk(
10375  sqlite3_changeset_iter *pIter,  /* Iterator object */
10376  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
10377  int *pnCol                      /* OUT: Number of entries in output array */
10378);
10379
10380/*
10381** CAPI3REF: Obtain old.* Values From A Changeset Iterator
10382**
10383** The pIter argument passed to this function may either be an iterator
10384** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
10385** created by [sqlite3changeset_start()]. In the latter case, the most recent
10386** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
10387** Furthermore, it may only be called if the type of change that the iterator
10388** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
10389** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
10390**
10391** Argument iVal must be greater than or equal to 0, and less than the number
10392** of columns in the table affected by the current change. Otherwise,
10393** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
10394**
10395** If successful, this function sets *ppValue to point to a protected
10396** sqlite3_value object containing the iVal'th value from the vector of
10397** original row values stored as part of the UPDATE or DELETE change and
10398** returns SQLITE_OK. The name of the function comes from the fact that this
10399** is similar to the "old.*" columns available to update or delete triggers.
10400**
10401** If some other error occurs (e.g. an OOM condition), an SQLite error code
10402** is returned and *ppValue is set to NULL.
10403*/
10404SQLITE_API int sqlite3changeset_old(
10405  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
10406  int iVal,                       /* Column number */
10407  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
10408);
10409
10410/*
10411** CAPI3REF: Obtain new.* Values From A Changeset Iterator
10412**
10413** The pIter argument passed to this function may either be an iterator
10414** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
10415** created by [sqlite3changeset_start()]. In the latter case, the most recent
10416** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
10417** Furthermore, it may only be called if the type of change that the iterator
10418** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
10419** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
10420**
10421** Argument iVal must be greater than or equal to 0, and less than the number
10422** of columns in the table affected by the current change. Otherwise,
10423** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
10424**
10425** If successful, this function sets *ppValue to point to a protected
10426** sqlite3_value object containing the iVal'th value from the vector of
10427** new row values stored as part of the UPDATE or INSERT change and
10428** returns SQLITE_OK. If the change is an UPDATE and does not include
10429** a new value for the requested column, *ppValue is set to NULL and
10430** SQLITE_OK returned. The name of the function comes from the fact that
10431** this is similar to the "new.*" columns available to update or delete
10432** triggers.
10433**
10434** If some other error occurs (e.g. an OOM condition), an SQLite error code
10435** is returned and *ppValue is set to NULL.
10436*/
10437SQLITE_API int sqlite3changeset_new(
10438  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
10439  int iVal,                       /* Column number */
10440  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
10441);
10442
10443/*
10444** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
10445**
10446** This function should only be used with iterator objects passed to a
10447** conflict-handler callback by [sqlite3changeset_apply()] with either
10448** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
10449** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
10450** is set to NULL.
10451**
10452** Argument iVal must be greater than or equal to 0, and less than the number
10453** of columns in the table affected by the current change. Otherwise,
10454** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
10455**
10456** If successful, this function sets *ppValue to point to a protected
10457** sqlite3_value object containing the iVal'th value from the
10458** "conflicting row" associated with the current conflict-handler callback
10459** and returns SQLITE_OK.
10460**
10461** If some other error occurs (e.g. an OOM condition), an SQLite error code
10462** is returned and *ppValue is set to NULL.
10463*/
10464SQLITE_API int sqlite3changeset_conflict(
10465  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
10466  int iVal,                       /* Column number */
10467  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
10468);
10469
10470/*
10471** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
10472**
10473** This function may only be called with an iterator passed to an
10474** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
10475** it sets the output variable to the total number of known foreign key
10476** violations in the destination database and returns SQLITE_OK.
10477**
10478** In all other cases this function returns SQLITE_MISUSE.
10479*/
10480SQLITE_API int sqlite3changeset_fk_conflicts(
10481  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
10482  int *pnOut                      /* OUT: Number of FK violations */
10483);
10484
10485
10486/*
10487** CAPI3REF: Finalize A Changeset Iterator
10488**
10489** This function is used to finalize an iterator allocated with
10490** [sqlite3changeset_start()].
10491**
10492** This function should only be called on iterators created using the
10493** [sqlite3changeset_start()] function. If an application calls this
10494** function with an iterator passed to a conflict-handler by
10495** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
10496** call has no effect.
10497**
10498** If an error was encountered within a call to an sqlite3changeset_xxx()
10499** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
10500** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
10501** to that error is returned by this function. Otherwise, SQLITE_OK is
10502** returned. This is to allow the following pattern (pseudo-code):
10503**
10504**   sqlite3changeset_start();
10505**   while( SQLITE_ROW==sqlite3changeset_next() ){
10506**     // Do something with change.
10507**   }
10508**   rc = sqlite3changeset_finalize();
10509**   if( rc!=SQLITE_OK ){
10510**     // An error has occurred
10511**   }
10512*/
10513SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
10514
10515/*
10516** CAPI3REF: Invert A Changeset
10517**
10518** This function is used to "invert" a changeset object. Applying an inverted
10519** changeset to a database reverses the effects of applying the uninverted
10520** changeset. Specifically:
10521**
10522** <ul>
10523**   <li> Each DELETE change is changed to an INSERT, and
10524**   <li> Each INSERT change is changed to a DELETE, and
10525**   <li> For each UPDATE change, the old.* and new.* values are exchanged.
10526** </ul>
10527**
10528** This function does not change the order in which changes appear within
10529** the changeset. It merely reverses the sense of each individual change.
10530**
10531** If successful, a pointer to a buffer containing the inverted changeset
10532** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
10533** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
10534** zeroed and an SQLite error code returned.
10535**
10536** It is the responsibility of the caller to eventually call sqlite3_free()
10537** on the *ppOut pointer to free the buffer allocation following a successful
10538** call to this function.
10539**
10540** WARNING/TODO: This function currently assumes that the input is a valid
10541** changeset. If it is not, the results are undefined.
10542*/
10543SQLITE_API int sqlite3changeset_invert(
10544  int nIn, const void *pIn,       /* Input changeset */
10545  int *pnOut, void **ppOut        /* OUT: Inverse of input */
10546);
10547
10548/*
10549** CAPI3REF: Concatenate Two Changeset Objects
10550**
10551** This function is used to concatenate two changesets, A and B, into a
10552** single changeset. The result is a changeset equivalent to applying
10553** changeset A followed by changeset B.
10554**
10555** This function combines the two input changesets using an
10556** sqlite3_changegroup object. Calling it produces similar results as the
10557** following code fragment:
10558**
10559**   sqlite3_changegroup *pGrp;
10560**   rc = sqlite3_changegroup_new(&pGrp);
10561**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
10562**   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
10563**   if( rc==SQLITE_OK ){
10564**     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
10565**   }else{
10566**     *ppOut = 0;
10567**     *pnOut = 0;
10568**   }
10569**
10570** Refer to the sqlite3_changegroup documentation below for details.
10571*/
10572SQLITE_API int sqlite3changeset_concat(
10573  int nA,                         /* Number of bytes in buffer pA */
10574  void *pA,                       /* Pointer to buffer containing changeset A */
10575  int nB,                         /* Number of bytes in buffer pB */
10576  void *pB,                       /* Pointer to buffer containing changeset B */
10577  int *pnOut,                     /* OUT: Number of bytes in output changeset */
10578  void **ppOut                    /* OUT: Buffer containing output changeset */
10579);
10580
10581
10582/*
10583** CAPI3REF: Changegroup Handle
10584*/
10585typedef struct sqlite3_changegroup sqlite3_changegroup;
10586
10587/*
10588** CAPI3REF: Create A New Changegroup Object
10589**
10590** An sqlite3_changegroup object is used to combine two or more changesets
10591** (or patchsets) into a single changeset (or patchset). A single changegroup
10592** object may combine changesets or patchsets, but not both. The output is
10593** always in the same format as the input.
10594**
10595** If successful, this function returns SQLITE_OK and populates (*pp) with
10596** a pointer to a new sqlite3_changegroup object before returning. The caller
10597** should eventually free the returned object using a call to
10598** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
10599** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
10600**
10601** The usual usage pattern for an sqlite3_changegroup object is as follows:
10602**
10603** <ul>
10604**   <li> It is created using a call to sqlite3changegroup_new().
10605**
10606**   <li> Zero or more changesets (or patchsets) are added to the object
10607**        by calling sqlite3changegroup_add().
10608**
10609**   <li> The result of combining all input changesets together is obtained
10610**        by the application via a call to sqlite3changegroup_output().
10611**
10612**   <li> The object is deleted using a call to sqlite3changegroup_delete().
10613** </ul>
10614**
10615** Any number of calls to add() and output() may be made between the calls to
10616** new() and delete(), and in any order.
10617**
10618** As well as the regular sqlite3changegroup_add() and
10619** sqlite3changegroup_output() functions, also available are the streaming
10620** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
10621*/
10622SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
10623
10624/*
10625** CAPI3REF: Add A Changeset To A Changegroup
10626**
10627** Add all changes within the changeset (or patchset) in buffer pData (size
10628** nData bytes) to the changegroup.
10629**
10630** If the buffer contains a patchset, then all prior calls to this function
10631** on the same changegroup object must also have specified patchsets. Or, if
10632** the buffer contains a changeset, so must have the earlier calls to this
10633** function. Otherwise, SQLITE_ERROR is returned and no changes are added
10634** to the changegroup.
10635**
10636** Rows within the changeset and changegroup are identified by the values in
10637** their PRIMARY KEY columns. A change in the changeset is considered to
10638** apply to the same row as a change already present in the changegroup if
10639** the two rows have the same primary key.
10640**
10641** Changes to rows that do not already appear in the changegroup are
10642** simply copied into it. Or, if both the new changeset and the changegroup
10643** contain changes that apply to a single row, the final contents of the
10644** changegroup depends on the type of each change, as follows:
10645**
10646** <table border=1 style="margin-left:8ex;margin-right:8ex">
10647**   <tr><th style="white-space:pre">Existing Change  </th>
10648**       <th style="white-space:pre">New Change       </th>
10649**       <th>Output Change
10650**   <tr><td>INSERT <td>INSERT <td>
10651**       The new change is ignored. This case does not occur if the new
10652**       changeset was recorded immediately after the changesets already
10653**       added to the changegroup.
10654**   <tr><td>INSERT <td>UPDATE <td>
10655**       The INSERT change remains in the changegroup. The values in the
10656**       INSERT change are modified as if the row was inserted by the
10657**       existing change and then updated according to the new change.
10658**   <tr><td>INSERT <td>DELETE <td>
10659**       The existing INSERT is removed from the changegroup. The DELETE is
10660**       not added.
10661**   <tr><td>UPDATE <td>INSERT <td>
10662**       The new change is ignored. This case does not occur if the new
10663**       changeset was recorded immediately after the changesets already
10664**       added to the changegroup.
10665**   <tr><td>UPDATE <td>UPDATE <td>
10666**       The existing UPDATE remains within the changegroup. It is amended
10667**       so that the accompanying values are as if the row was updated once
10668**       by the existing change and then again by the new change.
10669**   <tr><td>UPDATE <td>DELETE <td>
10670**       The existing UPDATE is replaced by the new DELETE within the
10671**       changegroup.
10672**   <tr><td>DELETE <td>INSERT <td>
10673**       If one or more of the column values in the row inserted by the
10674**       new change differ from those in the row deleted by the existing
10675**       change, the existing DELETE is replaced by an UPDATE within the
10676**       changegroup. Otherwise, if the inserted row is exactly the same
10677**       as the deleted row, the existing DELETE is simply discarded.
10678**   <tr><td>DELETE <td>UPDATE <td>
10679**       The new change is ignored. This case does not occur if the new
10680**       changeset was recorded immediately after the changesets already
10681**       added to the changegroup.
10682**   <tr><td>DELETE <td>DELETE <td>
10683**       The new change is ignored. This case does not occur if the new
10684**       changeset was recorded immediately after the changesets already
10685**       added to the changegroup.
10686** </table>
10687**
10688** If the new changeset contains changes to a table that is already present
10689** in the changegroup, then the number of columns and the position of the
10690** primary key columns for the table must be consistent. If this is not the
10691** case, this function fails with SQLITE_SCHEMA. If the input changeset
10692** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
10693** returned. Or, if an out-of-memory condition occurs during processing, this
10694** function returns SQLITE_NOMEM. In all cases, if an error occurs the
10695** final contents of the changegroup is undefined.
10696**
10697** If no error occurs, SQLITE_OK is returned.
10698*/
10699SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
10700
10701/*
10702** CAPI3REF: Obtain A Composite Changeset From A Changegroup
10703**
10704** Obtain a buffer containing a changeset (or patchset) representing the
10705** current contents of the changegroup. If the inputs to the changegroup
10706** were themselves changesets, the output is a changeset. Or, if the
10707** inputs were patchsets, the output is also a patchset.
10708**
10709** As with the output of the sqlite3session_changeset() and
10710** sqlite3session_patchset() functions, all changes related to a single
10711** table are grouped together in the output of this function. Tables appear
10712** in the same order as for the very first changeset added to the changegroup.
10713** If the second or subsequent changesets added to the changegroup contain
10714** changes for tables that do not appear in the first changeset, they are
10715** appended onto the end of the output changeset, again in the order in
10716** which they are first encountered.
10717**
10718** If an error occurs, an SQLite error code is returned and the output
10719** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
10720** is returned and the output variables are set to the size of and a
10721** pointer to the output buffer, respectively. In this case it is the
10722** responsibility of the caller to eventually free the buffer using a
10723** call to sqlite3_free().
10724*/
10725SQLITE_API int sqlite3changegroup_output(
10726  sqlite3_changegroup*,
10727  int *pnData,                    /* OUT: Size of output buffer in bytes */
10728  void **ppData                   /* OUT: Pointer to output buffer */
10729);
10730
10731/*
10732** CAPI3REF: Delete A Changegroup Object
10733*/
10734SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
10735
10736/*
10737** CAPI3REF: Apply A Changeset To A Database
10738**
10739** Apply a changeset to a database. This function attempts to update the
10740** "main" database attached to handle db with the changes found in the
10741** changeset passed via the second and third arguments.
10742**
10743** The fourth argument (xFilter) passed to this function is the "filter
10744** callback". If it is not NULL, then for each table affected by at least one
10745** change in the changeset, the filter callback is invoked with
10746** the table name as the second argument, and a copy of the context pointer
10747** passed as the sixth argument to this function as the first. If the "filter
10748** callback" returns zero, then no attempt is made to apply any changes to
10749** the table. Otherwise, if the return value is non-zero or the xFilter
10750** argument to this function is NULL, all changes related to the table are
10751** attempted.
10752**
10753** For each table that is not excluded by the filter callback, this function
10754** tests that the target database contains a compatible table. A table is
10755** considered compatible if all of the following are true:
10756**
10757** <ul>
10758**   <li> The table has the same name as the name recorded in the
10759**        changeset, and
10760**   <li> The table has at least as many columns as recorded in the
10761**        changeset, and
10762**   <li> The table has primary key columns in the same position as
10763**        recorded in the changeset.
10764** </ul>
10765**
10766** If there is no compatible table, it is not an error, but none of the
10767** changes associated with the table are applied. A warning message is issued
10768** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
10769** one such warning is issued for each table in the changeset.
10770**
10771** For each change for which there is a compatible table, an attempt is made
10772** to modify the table contents according to the UPDATE, INSERT or DELETE
10773** change. If a change cannot be applied cleanly, the conflict handler
10774** function passed as the fifth argument to sqlite3changeset_apply() may be
10775** invoked. A description of exactly when the conflict handler is invoked for
10776** each type of change is below.
10777**
10778** Unlike the xFilter argument, xConflict may not be passed NULL. The results
10779** of passing anything other than a valid function pointer as the xConflict
10780** argument are undefined.
10781**
10782** Each time the conflict handler function is invoked, it must return one
10783** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
10784** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
10785** if the second argument passed to the conflict handler is either
10786** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
10787** returns an illegal value, any changes already made are rolled back and
10788** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
10789** actions are taken by sqlite3changeset_apply() depending on the value
10790** returned by each invocation of the conflict-handler function. Refer to
10791** the documentation for the three
10792** [SQLITE_CHANGESET_OMIT|available return values] for details.
10793**
10794** <dl>
10795** <dt>DELETE Changes<dd>
10796**   For each DELETE change, this function checks if the target database
10797**   contains a row with the same primary key value (or values) as the
10798**   original row values stored in the changeset. If it does, and the values
10799**   stored in all non-primary key columns also match the values stored in
10800**   the changeset the row is deleted from the target database.
10801**
10802**   If a row with matching primary key values is found, but one or more of
10803**   the non-primary key fields contains a value different from the original
10804**   row value stored in the changeset, the conflict-handler function is
10805**   invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
10806**   database table has more columns than are recorded in the changeset,
10807**   only the values of those non-primary key fields are compared against
10808**   the current database contents - any trailing database table columns
10809**   are ignored.
10810**
10811**   If no row with matching primary key values is found in the database,
10812**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
10813**   passed as the second argument.
10814**
10815**   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
10816**   (which can only happen if a foreign key constraint is violated), the
10817**   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
10818**   passed as the second argument. This includes the case where the DELETE
10819**   operation is attempted because an earlier call to the conflict handler
10820**   function returned [SQLITE_CHANGESET_REPLACE].
10821**
10822** <dt>INSERT Changes<dd>
10823**   For each INSERT change, an attempt is made to insert the new row into
10824**   the database. If the changeset row contains fewer fields than the
10825**   database table, the trailing fields are populated with their default
10826**   values.
10827**
10828**   If the attempt to insert the row fails because the database already
10829**   contains a row with the same primary key values, the conflict handler
10830**   function is invoked with the second argument set to
10831**   [SQLITE_CHANGESET_CONFLICT].
10832**
10833**   If the attempt to insert the row fails because of some other constraint
10834**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
10835**   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
10836**   This includes the case where the INSERT operation is re-attempted because
10837**   an earlier call to the conflict handler function returned
10838**   [SQLITE_CHANGESET_REPLACE].
10839**
10840** <dt>UPDATE Changes<dd>
10841**   For each UPDATE change, this function checks if the target database
10842**   contains a row with the same primary key value (or values) as the
10843**   original row values stored in the changeset. If it does, and the values
10844**   stored in all modified non-primary key columns also match the values
10845**   stored in the changeset the row is updated within the target database.
10846**
10847**   If a row with matching primary key values is found, but one or more of
10848**   the modified non-primary key fields contains a value different from an
10849**   original row value stored in the changeset, the conflict-handler function
10850**   is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
10851**   UPDATE changes only contain values for non-primary key fields that are
10852**   to be modified, only those fields need to match the original values to
10853**   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
10854**
10855**   If no row with matching primary key values is found in the database,
10856**   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
10857**   passed as the second argument.
10858**
10859**   If the UPDATE operation is attempted, but SQLite returns
10860**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with
10861**   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
10862**   This includes the case where the UPDATE operation is attempted after
10863**   an earlier call to the conflict handler function returned
10864**   [SQLITE_CHANGESET_REPLACE].
10865** </dl>
10866**
10867** It is safe to execute SQL statements, including those that write to the
10868** table that the callback related to, from within the xConflict callback.
10869** This can be used to further customize the applications conflict
10870** resolution strategy.
10871**
10872** All changes made by this function are enclosed in a savepoint transaction.
10873** If any other error (aside from a constraint failure when attempting to
10874** write to the target database) occurs, then the savepoint transaction is
10875** rolled back, restoring the target database to its original state, and an
10876** SQLite error code returned.
10877*/
10878SQLITE_API int sqlite3changeset_apply(
10879  sqlite3 *db,                    /* Apply change to "main" db of this handle */
10880  int nChangeset,                 /* Size of changeset in bytes */
10881  void *pChangeset,               /* Changeset blob */
10882  int(*xFilter)(
10883    void *pCtx,                   /* Copy of sixth arg to _apply() */
10884    const char *zTab              /* Table name */
10885  ),
10886  int(*xConflict)(
10887    void *pCtx,                   /* Copy of sixth arg to _apply() */
10888    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
10889    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
10890  ),
10891  void *pCtx                      /* First argument passed to xConflict */
10892);
10893
10894/*
10895** CAPI3REF: Constants Passed To The Conflict Handler
10896**
10897** Values that may be passed as the second argument to a conflict-handler.
10898**
10899** <dl>
10900** <dt>SQLITE_CHANGESET_DATA<dd>
10901**   The conflict handler is invoked with CHANGESET_DATA as the second argument
10902**   when processing a DELETE or UPDATE change if a row with the required
10903**   PRIMARY KEY fields is present in the database, but one or more other
10904**   (non primary-key) fields modified by the update do not contain the
10905**   expected "before" values.
10906**
10907**   The conflicting row, in this case, is the database row with the matching
10908**   primary key.
10909**
10910** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
10911**   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
10912**   argument when processing a DELETE or UPDATE change if a row with the
10913**   required PRIMARY KEY fields is not present in the database.
10914**
10915**   There is no conflicting row in this case. The results of invoking the
10916**   sqlite3changeset_conflict() API are undefined.
10917**
10918** <dt>SQLITE_CHANGESET_CONFLICT<dd>
10919**   CHANGESET_CONFLICT is passed as the second argument to the conflict
10920**   handler while processing an INSERT change if the operation would result
10921**   in duplicate primary key values.
10922**
10923**   The conflicting row in this case is the database row with the matching
10924**   primary key.
10925**
10926** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
10927**   If foreign key handling is enabled, and applying a changeset leaves the
10928**   database in a state containing foreign key violations, the conflict
10929**   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
10930**   exactly once before the changeset is committed. If the conflict handler
10931**   returns CHANGESET_OMIT, the changes, including those that caused the
10932**   foreign key constraint violation, are committed. Or, if it returns
10933**   CHANGESET_ABORT, the changeset is rolled back.
10934**
10935**   No current or conflicting row information is provided. The only function
10936**   it is possible to call on the supplied sqlite3_changeset_iter handle
10937**   is sqlite3changeset_fk_conflicts().
10938**
10939** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
10940**   If any other constraint violation occurs while applying a change (i.e.
10941**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
10942**   invoked with CHANGESET_CONSTRAINT as the second argument.
10943**
10944**   There is no conflicting row in this case. The results of invoking the
10945**   sqlite3changeset_conflict() API are undefined.
10946**
10947** </dl>
10948*/
10949#define SQLITE_CHANGESET_DATA        1
10950#define SQLITE_CHANGESET_NOTFOUND    2
10951#define SQLITE_CHANGESET_CONFLICT    3
10952#define SQLITE_CHANGESET_CONSTRAINT  4
10953#define SQLITE_CHANGESET_FOREIGN_KEY 5
10954
10955/*
10956** CAPI3REF: Constants Returned By The Conflict Handler
10957**
10958** A conflict handler callback must return one of the following three values.
10959**
10960** <dl>
10961** <dt>SQLITE_CHANGESET_OMIT<dd>
10962**   If a conflict handler returns this value no special action is taken. The
10963**   change that caused the conflict is not applied. The session module
10964**   continues to the next change in the changeset.
10965**
10966** <dt>SQLITE_CHANGESET_REPLACE<dd>
10967**   This value may only be returned if the second argument to the conflict
10968**   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
10969**   is not the case, any changes applied so far are rolled back and the
10970**   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
10971**
10972**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
10973**   handler, then the conflicting row is either updated or deleted, depending
10974**   on the type of change.
10975**
10976**   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
10977**   handler, then the conflicting row is removed from the database and a
10978**   second attempt to apply the change is made. If this second attempt fails,
10979**   the original row is restored to the database before continuing.
10980**
10981** <dt>SQLITE_CHANGESET_ABORT<dd>
10982**   If this value is returned, any changes applied so far are rolled back
10983**   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
10984** </dl>
10985*/
10986#define SQLITE_CHANGESET_OMIT       0
10987#define SQLITE_CHANGESET_REPLACE    1
10988#define SQLITE_CHANGESET_ABORT      2
10989
10990/*
10991** CAPI3REF: Streaming Versions of API functions.
10992**
10993** The six streaming API xxx_strm() functions serve similar purposes to the
10994** corresponding non-streaming API functions:
10995**
10996** <table border=1 style="margin-left:8ex;margin-right:8ex">
10997**   <tr><th>Streaming function<th>Non-streaming equivalent</th>
10998**   <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
10999**   <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
11000**   <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
11001**   <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
11002**   <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
11003**   <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
11004** </table>
11005**
11006** Non-streaming functions that accept changesets (or patchsets) as input
11007** require that the entire changeset be stored in a single buffer in memory.
11008** Similarly, those that return a changeset or patchset do so by returning
11009** a pointer to a single large buffer allocated using sqlite3_malloc().
11010** Normally this is convenient. However, if an application running in a
11011** low-memory environment is required to handle very large changesets, the
11012** large contiguous memory allocations required can become onerous.
11013**
11014** In order to avoid this problem, instead of a single large buffer, input
11015** is passed to a streaming API functions by way of a callback function that
11016** the sessions module invokes to incrementally request input data as it is
11017** required. In all cases, a pair of API function parameters such as
11018**
11019**  <pre>
11020**  &nbsp;     int nChangeset,
11021**  &nbsp;     void *pChangeset,
11022**  </pre>
11023**
11024** Is replaced by:
11025**
11026**  <pre>
11027**  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),
11028**  &nbsp;     void *pIn,
11029**  </pre>
11030**
11031** Each time the xInput callback is invoked by the sessions module, the first
11032** argument passed is a copy of the supplied pIn context pointer. The second
11033** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
11034** error occurs the xInput method should copy up to (*pnData) bytes of data
11035** into the buffer and set (*pnData) to the actual number of bytes copied
11036** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
11037** should be set to zero to indicate this. Or, if an error occurs, an SQLite
11038** error code should be returned. In all cases, if an xInput callback returns
11039** an error, all processing is abandoned and the streaming API function
11040** returns a copy of the error code to the caller.
11041**
11042** In the case of sqlite3changeset_start_strm(), the xInput callback may be
11043** invoked by the sessions module at any point during the lifetime of the
11044** iterator. If such an xInput callback returns an error, the iterator enters
11045** an error state, whereby all subsequent calls to iterator functions
11046** immediately fail with the same error code as returned by xInput.
11047**
11048** Similarly, streaming API functions that return changesets (or patchsets)
11049** return them in chunks by way of a callback function instead of via a
11050** pointer to a single large buffer. In this case, a pair of parameters such
11051** as:
11052**
11053**  <pre>
11054**  &nbsp;     int *pnChangeset,
11055**  &nbsp;     void **ppChangeset,
11056**  </pre>
11057**
11058** Is replaced by:
11059**
11060**  <pre>
11061**  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),
11062**  &nbsp;     void *pOut
11063**  </pre>
11064**
11065** The xOutput callback is invoked zero or more times to return data to
11066** the application. The first parameter passed to each call is a copy of the
11067** pOut pointer supplied by the application. The second parameter, pData,
11068** points to a buffer nData bytes in size containing the chunk of output
11069** data being returned. If the xOutput callback successfully processes the
11070** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
11071** it should return some other SQLite error code. In this case processing
11072** is immediately abandoned and the streaming API function returns a copy
11073** of the xOutput error code to the application.
11074**
11075** The sessions module never invokes an xOutput callback with the third
11076** parameter set to a value less than or equal to zero. Other than this,
11077** no guarantees are made as to the size of the chunks of data returned.
11078*/
11079SQLITE_API int sqlite3changeset_apply_strm(
11080  sqlite3 *db,                    /* Apply change to "main" db of this handle */
11081  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
11082  void *pIn,                                          /* First arg for xInput */
11083  int(*xFilter)(
11084    void *pCtx,                   /* Copy of sixth arg to _apply() */
11085    const char *zTab              /* Table name */
11086  ),
11087  int(*xConflict)(
11088    void *pCtx,                   /* Copy of sixth arg to _apply() */
11089    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
11090    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
11091  ),
11092  void *pCtx                      /* First argument passed to xConflict */
11093);
11094SQLITE_API int sqlite3changeset_concat_strm(
11095  int (*xInputA)(void *pIn, void *pData, int *pnData),
11096  void *pInA,
11097  int (*xInputB)(void *pIn, void *pData, int *pnData),
11098  void *pInB,
11099  int (*xOutput)(void *pOut, const void *pData, int nData),
11100  void *pOut
11101);
11102SQLITE_API int sqlite3changeset_invert_strm(
11103  int (*xInput)(void *pIn, void *pData, int *pnData),
11104  void *pIn,
11105  int (*xOutput)(void *pOut, const void *pData, int nData),
11106  void *pOut
11107);
11108SQLITE_API int sqlite3changeset_start_strm(
11109  sqlite3_changeset_iter **pp,
11110  int (*xInput)(void *pIn, void *pData, int *pnData),
11111  void *pIn
11112);
11113SQLITE_API int sqlite3session_changeset_strm(
11114  sqlite3_session *pSession,
11115  int (*xOutput)(void *pOut, const void *pData, int nData),
11116  void *pOut
11117);
11118SQLITE_API int sqlite3session_patchset_strm(
11119  sqlite3_session *pSession,
11120  int (*xOutput)(void *pOut, const void *pData, int nData),
11121  void *pOut
11122);
11123SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
11124    int (*xInput)(void *pIn, void *pData, int *pnData),
11125    void *pIn
11126);
11127SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
11128    int (*xOutput)(void *pOut, const void *pData, int nData),
11129    void *pOut
11130);
11131
11132
11133/*
11134** Make sure we can call this stuff from C++.
11135*/
11136#if 0
11137}
11138#endif
11139
11140#endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
11141
11142/******** End of sqlite3session.h *********/
11143/******** Begin file fts5.h *********/
11144/*
11145** 2014 May 31
11146**
11147** The author disclaims copyright to this source code.  In place of
11148** a legal notice, here is a blessing:
11149**
11150**    May you do good and not evil.
11151**    May you find forgiveness for yourself and forgive others.
11152**    May you share freely, never taking more than you give.
11153**
11154******************************************************************************
11155**
11156** Interfaces to extend FTS5. Using the interfaces defined in this file,
11157** FTS5 may be extended with:
11158**
11159**     * custom tokenizers, and
11160**     * custom auxiliary functions.
11161*/
11162
11163
11164#ifndef _FTS5_H
11165#define _FTS5_H
11166
11167
11168#if 0
11169extern "C" {
11170#endif
11171
11172/*************************************************************************
11173** CUSTOM AUXILIARY FUNCTIONS
11174**
11175** Virtual table implementations may overload SQL functions by implementing
11176** the sqlite3_module.xFindFunction() method.
11177*/
11178
11179typedef struct Fts5ExtensionApi Fts5ExtensionApi;
11180typedef struct Fts5Context Fts5Context;
11181typedef struct Fts5PhraseIter Fts5PhraseIter;
11182
11183typedef void (*fts5_extension_function)(
11184  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
11185  Fts5Context *pFts,              /* First arg to pass to pApi functions */
11186  sqlite3_context *pCtx,          /* Context for returning result/error */
11187  int nVal,                       /* Number of values in apVal[] array */
11188  sqlite3_value **apVal           /* Array of trailing arguments */
11189);
11190
11191struct Fts5PhraseIter {
11192  const unsigned char *a;
11193  const unsigned char *b;
11194};
11195
11196/*
11197** EXTENSION API FUNCTIONS
11198**
11199** xUserData(pFts):
11200**   Return a copy of the context pointer the extension function was
11201**   registered with.
11202**
11203** xColumnTotalSize(pFts, iCol, pnToken):
11204**   If parameter iCol is less than zero, set output variable *pnToken
11205**   to the total number of tokens in the FTS5 table. Or, if iCol is
11206**   non-negative but less than the number of columns in the table, return
11207**   the total number of tokens in column iCol, considering all rows in
11208**   the FTS5 table.
11209**
11210**   If parameter iCol is greater than or equal to the number of columns
11211**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
11212**   an OOM condition or IO error), an appropriate SQLite error code is
11213**   returned.
11214**
11215** xColumnCount(pFts):
11216**   Return the number of columns in the table.
11217**
11218** xColumnSize(pFts, iCol, pnToken):
11219**   If parameter iCol is less than zero, set output variable *pnToken
11220**   to the total number of tokens in the current row. Or, if iCol is
11221**   non-negative but less than the number of columns in the table, set
11222**   *pnToken to the number of tokens in column iCol of the current row.
11223**
11224**   If parameter iCol is greater than or equal to the number of columns
11225**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
11226**   an OOM condition or IO error), an appropriate SQLite error code is
11227**   returned.
11228**
11229**   This function may be quite inefficient if used with an FTS5 table
11230**   created with the "columnsize=0" option.
11231**
11232** xColumnText:
11233**   This function attempts to retrieve the text of column iCol of the
11234**   current document. If successful, (*pz) is set to point to a buffer
11235**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
11236**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
11237**   if an error occurs, an SQLite error code is returned and the final values
11238**   of (*pz) and (*pn) are undefined.
11239**
11240** xPhraseCount:
11241**   Returns the number of phrases in the current query expression.
11242**
11243** xPhraseSize:
11244**   Returns the number of tokens in phrase iPhrase of the query. Phrases
11245**   are numbered starting from zero.
11246**
11247** xInstCount:
11248**   Set *pnInst to the total number of occurrences of all phrases within
11249**   the query within the current row. Return SQLITE_OK if successful, or
11250**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
11251**
11252**   This API can be quite slow if used with an FTS5 table created with the
11253**   "detail=none" or "detail=column" option. If the FTS5 table is created
11254**   with either "detail=none" or "detail=column" and "content=" option
11255**   (i.e. if it is a contentless table), then this API always returns 0.
11256**
11257** xInst:
11258**   Query for the details of phrase match iIdx within the current row.
11259**   Phrase matches are numbered starting from zero, so the iIdx argument
11260**   should be greater than or equal to zero and smaller than the value
11261**   output by xInstCount().
11262**
11263**   Usually, output parameter *piPhrase is set to the phrase number, *piCol
11264**   to the column in which it occurs and *piOff the token offset of the
11265**   first token of the phrase. The exception is if the table was created
11266**   with the offsets=0 option specified. In this case *piOff is always
11267**   set to -1.
11268**
11269**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
11270**   if an error occurs.
11271**
11272**   This API can be quite slow if used with an FTS5 table created with the
11273**   "detail=none" or "detail=column" option.
11274**
11275** xRowid:
11276**   Returns the rowid of the current row.
11277**
11278** xTokenize:
11279**   Tokenize text using the tokenizer belonging to the FTS5 table.
11280**
11281** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
11282**   This API function is used to query the FTS table for phrase iPhrase
11283**   of the current query. Specifically, a query equivalent to:
11284**
11285**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
11286**
11287**   with $p set to a phrase equivalent to the phrase iPhrase of the
11288**   current query is executed. Any column filter that applies to
11289**   phrase iPhrase of the current query is included in $p. For each
11290**   row visited, the callback function passed as the fourth argument
11291**   is invoked. The context and API objects passed to the callback
11292**   function may be used to access the properties of each matched row.
11293**   Invoking Api.xUserData() returns a copy of the pointer passed as
11294**   the third argument to pUserData.
11295**
11296**   If the callback function returns any value other than SQLITE_OK, the
11297**   query is abandoned and the xQueryPhrase function returns immediately.
11298**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
11299**   Otherwise, the error code is propagated upwards.
11300**
11301**   If the query runs to completion without incident, SQLITE_OK is returned.
11302**   Or, if some error occurs before the query completes or is aborted by
11303**   the callback, an SQLite error code is returned.
11304**
11305**
11306** xSetAuxdata(pFts5, pAux, xDelete)
11307**
11308**   Save the pointer passed as the second argument as the extension functions
11309**   "auxiliary data". The pointer may then be retrieved by the current or any
11310**   future invocation of the same fts5 extension function made as part of
11311**   of the same MATCH query using the xGetAuxdata() API.
11312**
11313**   Each extension function is allocated a single auxiliary data slot for
11314**   each FTS query (MATCH expression). If the extension function is invoked
11315**   more than once for a single FTS query, then all invocations share a
11316**   single auxiliary data context.
11317**
11318**   If there is already an auxiliary data pointer when this function is
11319**   invoked, then it is replaced by the new pointer. If an xDelete callback
11320**   was specified along with the original pointer, it is invoked at this
11321**   point.
11322**
11323**   The xDelete callback, if one is specified, is also invoked on the
11324**   auxiliary data pointer after the FTS5 query has finished.
11325**
11326**   If an error (e.g. an OOM condition) occurs within this function, an
11327**   the auxiliary data is set to NULL and an error code returned. If the
11328**   xDelete parameter was not NULL, it is invoked on the auxiliary data
11329**   pointer before returning.
11330**
11331**
11332** xGetAuxdata(pFts5, bClear)
11333**
11334**   Returns the current auxiliary data pointer for the fts5 extension
11335**   function. See the xSetAuxdata() method for details.
11336**
11337**   If the bClear argument is non-zero, then the auxiliary data is cleared
11338**   (set to NULL) before this function returns. In this case the xDelete,
11339**   if any, is not invoked.
11340**
11341**
11342** xRowCount(pFts5, pnRow)
11343**
11344**   This function is used to retrieve the total number of rows in the table.
11345**   In other words, the same value that would be returned by:
11346**
11347**        SELECT count(*) FROM ftstable;
11348**
11349** xPhraseFirst()
11350**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
11351**   method, to iterate through all instances of a single query phrase within
11352**   the current row. This is the same information as is accessible via the
11353**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
11354**   to use, this API may be faster under some circumstances. To iterate
11355**   through instances of phrase iPhrase, use the following code:
11356**
11357**       Fts5PhraseIter iter;
11358**       int iCol, iOff;
11359**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
11360**           iCol>=0;
11361**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
11362**       ){
11363**         // An instance of phrase iPhrase at offset iOff of column iCol
11364**       }
11365**
11366**   The Fts5PhraseIter structure is defined above. Applications should not
11367**   modify this structure directly - it should only be used as shown above
11368**   with the xPhraseFirst() and xPhraseNext() API methods (and by
11369**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
11370**
11371**   This API can be quite slow if used with an FTS5 table created with the
11372**   "detail=none" or "detail=column" option. If the FTS5 table is created
11373**   with either "detail=none" or "detail=column" and "content=" option
11374**   (i.e. if it is a contentless table), then this API always iterates
11375**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
11376**
11377** xPhraseNext()
11378**   See xPhraseFirst above.
11379**
11380** xPhraseFirstColumn()
11381**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
11382**   and xPhraseNext() APIs described above. The difference is that instead
11383**   of iterating through all instances of a phrase in the current row, these
11384**   APIs are used to iterate through the set of columns in the current row
11385**   that contain one or more instances of a specified phrase. For example:
11386**
11387**       Fts5PhraseIter iter;
11388**       int iCol;
11389**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
11390**           iCol>=0;
11391**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
11392**       ){
11393**         // Column iCol contains at least one instance of phrase iPhrase
11394**       }
11395**
11396**   This API can be quite slow if used with an FTS5 table created with the
11397**   "detail=none" option. If the FTS5 table is created with either
11398**   "detail=none" "content=" option (i.e. if it is a contentless table),
11399**   then this API always iterates through an empty set (all calls to
11400**   xPhraseFirstColumn() set iCol to -1).
11401**
11402**   The information accessed using this API and its companion
11403**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
11404**   (or xInst/xInstCount). The chief advantage of this API is that it is
11405**   significantly more efficient than those alternatives when used with
11406**   "detail=column" tables.
11407**
11408** xPhraseNextColumn()
11409**   See xPhraseFirstColumn above.
11410*/
11411struct Fts5ExtensionApi {
11412  int iVersion;                   /* Currently always set to 3 */
11413
11414  void *(*xUserData)(Fts5Context*);
11415
11416  int (*xColumnCount)(Fts5Context*);
11417  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
11418  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
11419
11420  int (*xTokenize)(Fts5Context*,
11421    const char *pText, int nText, /* Text to tokenize */
11422    void *pCtx,                   /* Context passed to xToken() */
11423    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
11424  );
11425
11426  int (*xPhraseCount)(Fts5Context*);
11427  int (*xPhraseSize)(Fts5Context*, int iPhrase);
11428
11429  int (*xInstCount)(Fts5Context*, int *pnInst);
11430  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
11431
11432  sqlite3_int64 (*xRowid)(Fts5Context*);
11433  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
11434  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
11435
11436  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
11437    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
11438  );
11439  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
11440  void *(*xGetAuxdata)(Fts5Context*, int bClear);
11441
11442  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
11443  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
11444
11445  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
11446  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
11447};
11448
11449/*
11450** CUSTOM AUXILIARY FUNCTIONS
11451*************************************************************************/
11452
11453/*************************************************************************
11454** CUSTOM TOKENIZERS
11455**
11456** Applications may also register custom tokenizer types. A tokenizer
11457** is registered by providing fts5 with a populated instance of the
11458** following structure. All structure methods must be defined, setting
11459** any member of the fts5_tokenizer struct to NULL leads to undefined
11460** behaviour. The structure methods are expected to function as follows:
11461**
11462** xCreate:
11463**   This function is used to allocate and initialize a tokenizer instance.
11464**   A tokenizer instance is required to actually tokenize text.
11465**
11466**   The first argument passed to this function is a copy of the (void*)
11467**   pointer provided by the application when the fts5_tokenizer object
11468**   was registered with FTS5 (the third argument to xCreateTokenizer()).
11469**   The second and third arguments are an array of nul-terminated strings
11470**   containing the tokenizer arguments, if any, specified following the
11471**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
11472**   to create the FTS5 table.
11473**
11474**   The final argument is an output variable. If successful, (*ppOut)
11475**   should be set to point to the new tokenizer handle and SQLITE_OK
11476**   returned. If an error occurs, some value other than SQLITE_OK should
11477**   be returned. In this case, fts5 assumes that the final value of *ppOut
11478**   is undefined.
11479**
11480** xDelete:
11481**   This function is invoked to delete a tokenizer handle previously
11482**   allocated using xCreate(). Fts5 guarantees that this function will
11483**   be invoked exactly once for each successful call to xCreate().
11484**
11485** xTokenize:
11486**   This function is expected to tokenize the nText byte string indicated
11487**   by argument pText. pText may or may not be nul-terminated. The first
11488**   argument passed to this function is a pointer to an Fts5Tokenizer object
11489**   returned by an earlier call to xCreate().
11490**
11491**   The second argument indicates the reason that FTS5 is requesting
11492**   tokenization of the supplied text. This is always one of the following
11493**   four values:
11494**
11495**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
11496**            or removed from the FTS table. The tokenizer is being invoked to
11497**            determine the set of tokens to add to (or delete from) the
11498**            FTS index.
11499**
11500**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
11501**            against the FTS index. The tokenizer is being called to tokenize
11502**            a bareword or quoted string specified as part of the query.
11503**
11504**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
11505**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
11506**            followed by a "*" character, indicating that the last token
11507**            returned by the tokenizer will be treated as a token prefix.
11508**
11509**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
11510**            satisfy an fts5_api.xTokenize() request made by an auxiliary
11511**            function. Or an fts5_api.xColumnSize() request made by the same
11512**            on a columnsize=0 database.
11513**   </ul>
11514**
11515**   For each token in the input string, the supplied callback xToken() must
11516**   be invoked. The first argument to it should be a copy of the pointer
11517**   passed as the second argument to xTokenize(). The third and fourth
11518**   arguments are a pointer to a buffer containing the token text, and the
11519**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
11520**   of the first byte of and first byte immediately following the text from
11521**   which the token is derived within the input.
11522**
11523**   The second argument passed to the xToken() callback ("tflags") should
11524**   normally be set to 0. The exception is if the tokenizer supports
11525**   synonyms. In this case see the discussion below for details.
11526**
11527**   FTS5 assumes the xToken() callback is invoked for each token in the
11528**   order that they occur within the input text.
11529**
11530**   If an xToken() callback returns any value other than SQLITE_OK, then
11531**   the tokenization should be abandoned and the xTokenize() method should
11532**   immediately return a copy of the xToken() return value. Or, if the
11533**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
11534**   if an error occurs with the xTokenize() implementation itself, it
11535**   may abandon the tokenization and return any error code other than
11536**   SQLITE_OK or SQLITE_DONE.
11537**
11538** SYNONYM SUPPORT
11539**
11540**   Custom tokenizers may also support synonyms. Consider a case in which a
11541**   user wishes to query for a phrase such as "first place". Using the
11542**   built-in tokenizers, the FTS5 query 'first + place' will match instances
11543**   of "first place" within the document set, but not alternative forms
11544**   such as "1st place". In some applications, it would be better to match
11545**   all instances of "first place" or "1st place" regardless of which form
11546**   the user specified in the MATCH query text.
11547**
11548**   There are several ways to approach this in FTS5:
11549**
11550**   <ol><li> By mapping all synonyms to a single token. In this case, the
11551**            In the above example, this means that the tokenizer returns the
11552**            same token for inputs "first" and "1st". Say that token is in
11553**            fact "first", so that when the user inserts the document "I won
11554**            1st place" entries are added to the index for tokens "i", "won",
11555**            "first" and "place". If the user then queries for '1st + place',
11556**            the tokenizer substitutes "first" for "1st" and the query works
11557**            as expected.
11558**
11559**       <li> By adding multiple synonyms for a single term to the FTS index.
11560**            In this case, when tokenizing query text, the tokenizer may
11561**            provide multiple synonyms for a single term within the document.
11562**            FTS5 then queries the index for each synonym individually. For
11563**            example, faced with the query:
11564**
11565**   <codeblock>
11566**     ... MATCH 'first place'</codeblock>
11567**
11568**            the tokenizer offers both "1st" and "first" as synonyms for the
11569**            first token in the MATCH query and FTS5 effectively runs a query
11570**            similar to:
11571**
11572**   <codeblock>
11573**     ... MATCH '(first OR 1st) place'</codeblock>
11574**
11575**            except that, for the purposes of auxiliary functions, the query
11576**            still appears to contain just two phrases - "(first OR 1st)"
11577**            being treated as a single phrase.
11578**
11579**       <li> By adding multiple synonyms for a single term to the FTS index.
11580**            Using this method, when tokenizing document text, the tokenizer
11581**            provides multiple synonyms for each token. So that when a
11582**            document such as "I won first place" is tokenized, entries are
11583**            added to the FTS index for "i", "won", "first", "1st" and
11584**            "place".
11585**
11586**            This way, even if the tokenizer does not provide synonyms
11587**            when tokenizing query text (it should not - to do would be
11588**            inefficient), it doesn't matter if the user queries for
11589**            'first + place' or '1st + place', as there are entires in the
11590**            FTS index corresponding to both forms of the first token.
11591**   </ol>
11592**
11593**   Whether it is parsing document or query text, any call to xToken that
11594**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
11595**   is considered to supply a synonym for the previous token. For example,
11596**   when parsing the document "I won first place", a tokenizer that supports
11597**   synonyms would call xToken() 5 times, as follows:
11598**
11599**   <codeblock>
11600**       xToken(pCtx, 0, "i",                      1,  0,  1);
11601**       xToken(pCtx, 0, "won",                    3,  2,  5);
11602**       xToken(pCtx, 0, "first",                  5,  6, 11);
11603**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
11604**       xToken(pCtx, 0, "place",                  5, 12, 17);
11605**</codeblock>
11606**
11607**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
11608**   xToken() is called. Multiple synonyms may be specified for a single token
11609**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
11610**   There is no limit to the number of synonyms that may be provided for a
11611**   single token.
11612**
11613**   In many cases, method (1) above is the best approach. It does not add
11614**   extra data to the FTS index or require FTS5 to query for multiple terms,
11615**   so it is efficient in terms of disk space and query speed. However, it
11616**   does not support prefix queries very well. If, as suggested above, the
11617**   token "first" is subsituted for "1st" by the tokenizer, then the query:
11618**
11619**   <codeblock>
11620**     ... MATCH '1s*'</codeblock>
11621**
11622**   will not match documents that contain the token "1st" (as the tokenizer
11623**   will probably not map "1s" to any prefix of "first").
11624**
11625**   For full prefix support, method (3) may be preferred. In this case,
11626**   because the index contains entries for both "first" and "1st", prefix
11627**   queries such as 'fi*' or '1s*' will match correctly. However, because
11628**   extra entries are added to the FTS index, this method uses more space
11629**   within the database.
11630**
11631**   Method (2) offers a midpoint between (1) and (3). Using this method,
11632**   a query such as '1s*' will match documents that contain the literal
11633**   token "1st", but not "first" (assuming the tokenizer is not able to
11634**   provide synonyms for prefixes). However, a non-prefix query like '1st'
11635**   will match against "1st" and "first". This method does not require
11636**   extra disk space, as no extra entries are added to the FTS index.
11637**   On the other hand, it may require more CPU cycles to run MATCH queries,
11638**   as separate queries of the FTS index are required for each synonym.
11639**
11640**   When using methods (2) or (3), it is important that the tokenizer only
11641**   provide synonyms when tokenizing document text (method (2)) or query
11642**   text (method (3)), not both. Doing so will not cause any errors, but is
11643**   inefficient.
11644*/
11645typedef struct Fts5Tokenizer Fts5Tokenizer;
11646typedef struct fts5_tokenizer fts5_tokenizer;
11647struct fts5_tokenizer {
11648  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
11649  void (*xDelete)(Fts5Tokenizer*);
11650  int (*xTokenize)(Fts5Tokenizer*,
11651      void *pCtx,
11652      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
11653      const char *pText, int nText,
11654      int (*xToken)(
11655        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
11656        int tflags,         /* Mask of FTS5_TOKEN_* flags */
11657        const char *pToken, /* Pointer to buffer containing token */
11658        int nToken,         /* Size of token in bytes */
11659        int iStart,         /* Byte offset of token within input text */
11660        int iEnd            /* Byte offset of end of token within input text */
11661      )
11662  );
11663};
11664
11665/* Flags that may be passed as the third argument to xTokenize() */
11666#define FTS5_TOKENIZE_QUERY     0x0001
11667#define FTS5_TOKENIZE_PREFIX    0x0002
11668#define FTS5_TOKENIZE_DOCUMENT  0x0004
11669#define FTS5_TOKENIZE_AUX       0x0008
11670
11671/* Flags that may be passed by the tokenizer implementation back to FTS5
11672** as the third argument to the supplied xToken callback. */
11673#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
11674
11675/*
11676** END OF CUSTOM TOKENIZERS
11677*************************************************************************/
11678
11679/*************************************************************************
11680** FTS5 EXTENSION REGISTRATION API
11681*/
11682typedef struct fts5_api fts5_api;
11683struct fts5_api {
11684  int iVersion;                   /* Currently always set to 2 */
11685
11686  /* Create a new tokenizer */
11687  int (*xCreateTokenizer)(
11688    fts5_api *pApi,
11689    const char *zName,
11690    void *pContext,
11691    fts5_tokenizer *pTokenizer,
11692    void (*xDestroy)(void*)
11693  );
11694
11695  /* Find an existing tokenizer */
11696  int (*xFindTokenizer)(
11697    fts5_api *pApi,
11698    const char *zName,
11699    void **ppContext,
11700    fts5_tokenizer *pTokenizer
11701  );
11702
11703  /* Create a new auxiliary function */
11704  int (*xCreateFunction)(
11705    fts5_api *pApi,
11706    const char *zName,
11707    void *pContext,
11708    fts5_extension_function xFunction,
11709    void (*xDestroy)(void*)
11710  );
11711};
11712
11713/*
11714** END OF REGISTRATION API
11715*************************************************************************/
11716
11717#if 0
11718}  /* end of the 'extern "C"' block */
11719#endif
11720
11721#endif /* _FTS5_H */
11722
11723/******** End of fts5.h *********/
11724
11725/************** End of sqlite3.h *********************************************/
11726/************** Continuing where we left off in sqliteInt.h ******************/
11727
11728/*
11729** Include the configuration header output by 'configure' if we're using the
11730** autoconf-based build
11731*/
11732#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
11733/* #include "config.h" */
11734#define SQLITECONFIG_H 1
11735#endif
11736
11737/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
11738/************** Begin file sqliteLimit.h *************************************/
11739/*
11740** 2007 May 7
11741**
11742** The author disclaims copyright to this source code.  In place of
11743** a legal notice, here is a blessing:
11744**
11745**    May you do good and not evil.
11746**    May you find forgiveness for yourself and forgive others.
11747**    May you share freely, never taking more than you give.
11748**
11749*************************************************************************
11750**
11751** This file defines various limits of what SQLite can process.
11752*/
11753
11754/*
11755** The maximum length of a TEXT or BLOB in bytes.   This also
11756** limits the size of a row in a table or index.
11757**
11758** The hard limit is the ability of a 32-bit signed integer
11759** to count the size: 2^31-1 or 2147483647.
11760*/
11761#ifndef SQLITE_MAX_LENGTH
11762# define SQLITE_MAX_LENGTH 1000000000
11763#endif
11764
11765/*
11766** This is the maximum number of
11767**
11768**    * Columns in a table
11769**    * Columns in an index
11770**    * Columns in a view
11771**    * Terms in the SET clause of an UPDATE statement
11772**    * Terms in the result set of a SELECT statement
11773**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
11774**    * Terms in the VALUES clause of an INSERT statement
11775**
11776** The hard upper limit here is 32676.  Most database people will
11777** tell you that in a well-normalized database, you usually should
11778** not have more than a dozen or so columns in any table.  And if
11779** that is the case, there is no point in having more than a few
11780** dozen values in any of the other situations described above.
11781*/
11782#ifndef SQLITE_MAX_COLUMN
11783# define SQLITE_MAX_COLUMN 2000
11784#endif
11785
11786/*
11787** The maximum length of a single SQL statement in bytes.
11788**
11789** It used to be the case that setting this value to zero would
11790** turn the limit off.  That is no longer true.  It is not possible
11791** to turn this limit off.
11792*/
11793#ifndef SQLITE_MAX_SQL_LENGTH
11794# define SQLITE_MAX_SQL_LENGTH 1000000000
11795#endif
11796
11797/*
11798** The maximum depth of an expression tree. This is limited to
11799** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
11800** want to place more severe limits on the complexity of an
11801** expression.
11802**
11803** A value of 0 used to mean that the limit was not enforced.
11804** But that is no longer true.  The limit is now strictly enforced
11805** at all times.
11806*/
11807#ifndef SQLITE_MAX_EXPR_DEPTH
11808# define SQLITE_MAX_EXPR_DEPTH 1000
11809#endif
11810
11811/*
11812** The maximum number of terms in a compound SELECT statement.
11813** The code generator for compound SELECT statements does one
11814** level of recursion for each term.  A stack overflow can result
11815** if the number of terms is too large.  In practice, most SQL
11816** never has more than 3 or 4 terms.  Use a value of 0 to disable
11817** any limit on the number of terms in a compount SELECT.
11818*/
11819#ifndef SQLITE_MAX_COMPOUND_SELECT
11820# define SQLITE_MAX_COMPOUND_SELECT 500
11821#endif
11822
11823/*
11824** The maximum number of opcodes in a VDBE program.
11825** Not currently enforced.
11826*/
11827#ifndef SQLITE_MAX_VDBE_OP
11828# define SQLITE_MAX_VDBE_OP 250000000
11829#endif
11830
11831/*
11832** The maximum number of arguments to an SQL function.
11833*/
11834#ifndef SQLITE_MAX_FUNCTION_ARG
11835# define SQLITE_MAX_FUNCTION_ARG 127
11836#endif
11837
11838/*
11839** The suggested maximum number of in-memory pages to use for
11840** the main database table and for temporary tables.
11841**
11842** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
11843** which means the cache size is limited to 2048000 bytes of memory.
11844** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
11845** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
11846*/
11847#ifndef SQLITE_DEFAULT_CACHE_SIZE
11848# define SQLITE_DEFAULT_CACHE_SIZE  -2000
11849#endif
11850
11851/*
11852** The default number of frames to accumulate in the log file before
11853** checkpointing the database in WAL mode.
11854*/
11855#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
11856# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
11857#endif
11858
11859/*
11860** The maximum number of attached databases.  This must be between 0
11861** and 125.  The upper bound of 125 is because the attached databases are
11862** counted using a signed 8-bit integer which has a maximum value of 127
11863** and we have to allow 2 extra counts for the "main" and "temp" databases.
11864*/
11865#ifndef SQLITE_MAX_ATTACHED
11866# define SQLITE_MAX_ATTACHED 10
11867#endif
11868
11869
11870/*
11871** The maximum value of a ?nnn wildcard that the parser will accept.
11872*/
11873#ifndef SQLITE_MAX_VARIABLE_NUMBER
11874# define SQLITE_MAX_VARIABLE_NUMBER 999
11875#endif
11876
11877/* Maximum page size.  The upper bound on this value is 65536.  This a limit
11878** imposed by the use of 16-bit offsets within each page.
11879**
11880** Earlier versions of SQLite allowed the user to change this value at
11881** compile time. This is no longer permitted, on the grounds that it creates
11882** a library that is technically incompatible with an SQLite library
11883** compiled with a different limit. If a process operating on a database
11884** with a page-size of 65536 bytes crashes, then an instance of SQLite
11885** compiled with the default page-size limit will not be able to rollback
11886** the aborted transaction. This could lead to database corruption.
11887*/
11888#ifdef SQLITE_MAX_PAGE_SIZE
11889# undef SQLITE_MAX_PAGE_SIZE
11890#endif
11891#define SQLITE_MAX_PAGE_SIZE 65536
11892
11893
11894/*
11895** The default size of a database page.
11896*/
11897#ifndef SQLITE_DEFAULT_PAGE_SIZE
11898# define SQLITE_DEFAULT_PAGE_SIZE 4096
11899#endif
11900#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
11901# undef SQLITE_DEFAULT_PAGE_SIZE
11902# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
11903#endif
11904
11905/*
11906** Ordinarily, if no value is explicitly provided, SQLite creates databases
11907** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
11908** device characteristics (sector-size and atomic write() support),
11909** SQLite may choose a larger value. This constant is the maximum value
11910** SQLite will choose on its own.
11911*/
11912#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
11913# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
11914#endif
11915#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
11916# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
11917# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
11918#endif
11919
11920
11921/*
11922** Maximum number of pages in one database file.
11923**
11924** This is really just the default value for the max_page_count pragma.
11925** This value can be lowered (or raised) at run-time using that the
11926** max_page_count macro.
11927*/
11928#ifndef SQLITE_MAX_PAGE_COUNT
11929# define SQLITE_MAX_PAGE_COUNT 1073741823
11930#endif
11931
11932/*
11933** Maximum length (in bytes) of the pattern in a LIKE or GLOB
11934** operator.
11935*/
11936#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
11937# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
11938#endif
11939
11940/*
11941** Maximum depth of recursion for triggers.
11942**
11943** A value of 1 means that a trigger program will not be able to itself
11944** fire any triggers. A value of 0 means that no trigger programs at all
11945** may be executed.
11946*/
11947#ifndef SQLITE_MAX_TRIGGER_DEPTH
11948# define SQLITE_MAX_TRIGGER_DEPTH 1000
11949#endif
11950
11951/************** End of sqliteLimit.h *****************************************/
11952/************** Continuing where we left off in sqliteInt.h ******************/
11953
11954/* Disable nuisance warnings on Borland compilers */
11955#if defined(__BORLANDC__)
11956#pragma warn -rch /* unreachable code */
11957#pragma warn -ccc /* Condition is always true or false */
11958#pragma warn -aus /* Assigned value is never used */
11959#pragma warn -csu /* Comparing signed and unsigned */
11960#pragma warn -spa /* Suspicious pointer arithmetic */
11961#endif
11962
11963/*
11964** Include standard header files as necessary
11965*/
11966#ifdef HAVE_STDINT_H
11967#include <stdint.h>
11968#endif
11969#ifdef HAVE_INTTYPES_H
11970#include <inttypes.h>
11971#endif
11972
11973/*
11974** The following macros are used to cast pointers to integers and
11975** integers to pointers.  The way you do this varies from one compiler
11976** to the next, so we have developed the following set of #if statements
11977** to generate appropriate macros for a wide range of compilers.
11978**
11979** The correct "ANSI" way to do this is to use the intptr_t type.
11980** Unfortunately, that typedef is not available on all compilers, or
11981** if it is available, it requires an #include of specific headers
11982** that vary from one machine to the next.
11983**
11984** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
11985** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
11986** So we have to define the macros in different ways depending on the
11987** compiler.
11988*/
11989#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
11990# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
11991# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
11992#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
11993# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
11994# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
11995#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
11996# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
11997# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
11998#else                          /* Generates a warning - but it always works */
11999# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
12000# define SQLITE_PTR_TO_INT(X)  ((int)(X))
12001#endif
12002
12003/*
12004** A macro to hint to the compiler that a function should not be
12005** inlined.
12006*/
12007#if defined(__GNUC__)
12008#  define SQLITE_NOINLINE  __attribute__((noinline))
12009#elif defined(_MSC_VER) && _MSC_VER>=1310
12010#  define SQLITE_NOINLINE  __declspec(noinline)
12011#else
12012#  define SQLITE_NOINLINE
12013#endif
12014
12015/*
12016** Make sure that the compiler intrinsics we desire are enabled when
12017** compiling with an appropriate version of MSVC unless prevented by
12018** the SQLITE_DISABLE_INTRINSIC define.
12019*/
12020#if !defined(SQLITE_DISABLE_INTRINSIC)
12021#  if defined(_MSC_VER) && _MSC_VER>=1400
12022#    if !defined(_WIN32_WCE)
12023#      include <intrin.h>
12024#      pragma intrinsic(_byteswap_ushort)
12025#      pragma intrinsic(_byteswap_ulong)
12026#      pragma intrinsic(_byteswap_uint64)
12027#      pragma intrinsic(_ReadWriteBarrier)
12028#    else
12029#      include <cmnintrin.h>
12030#    endif
12031#  endif
12032#endif
12033
12034/*
12035** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
12036** 0 means mutexes are permanently disable and the library is never
12037** threadsafe.  1 means the library is serialized which is the highest
12038** level of threadsafety.  2 means the library is multithreaded - multiple
12039** threads can use SQLite as long as no two threads try to use the same
12040** database connection at the same time.
12041**
12042** Older versions of SQLite used an optional THREADSAFE macro.
12043** We support that for legacy.
12044**
12045** To ensure that the correct value of "THREADSAFE" is reported when querying
12046** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
12047** logic is partially replicated in ctime.c. If it is updated here, it should
12048** also be updated there.
12049*/
12050#if !defined(SQLITE_THREADSAFE)
12051# if defined(THREADSAFE)
12052#   define SQLITE_THREADSAFE THREADSAFE
12053# else
12054#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
12055# endif
12056#endif
12057
12058/*
12059** Powersafe overwrite is on by default.  But can be turned off using
12060** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
12061*/
12062#ifndef SQLITE_POWERSAFE_OVERWRITE
12063# define SQLITE_POWERSAFE_OVERWRITE 1
12064#endif
12065
12066/*
12067** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
12068** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
12069** which case memory allocation statistics are disabled by default.
12070*/
12071#if !defined(SQLITE_DEFAULT_MEMSTATUS)
12072# define SQLITE_DEFAULT_MEMSTATUS 1
12073#endif
12074
12075/*
12076** Exactly one of the following macros must be defined in order to
12077** specify which memory allocation subsystem to use.
12078**
12079**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
12080**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
12081**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
12082**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
12083**
12084** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
12085** assert() macro is enabled, each call into the Win32 native heap subsystem
12086** will cause HeapValidate to be called.  If heap validation should fail, an
12087** assertion will be triggered.
12088**
12089** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
12090** the default.
12091*/
12092#if defined(SQLITE_SYSTEM_MALLOC) \
12093  + defined(SQLITE_WIN32_MALLOC) \
12094  + defined(SQLITE_ZERO_MALLOC) \
12095  + defined(SQLITE_MEMDEBUG)>1
12096# error "Two or more of the following compile-time configuration options\
12097 are defined but at most one is allowed:\
12098 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
12099 SQLITE_ZERO_MALLOC"
12100#endif
12101#if defined(SQLITE_SYSTEM_MALLOC) \
12102  + defined(SQLITE_WIN32_MALLOC) \
12103  + defined(SQLITE_ZERO_MALLOC) \
12104  + defined(SQLITE_MEMDEBUG)==0
12105# define SQLITE_SYSTEM_MALLOC 1
12106#endif
12107
12108/*
12109** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
12110** sizes of memory allocations below this value where possible.
12111*/
12112#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
12113# define SQLITE_MALLOC_SOFT_LIMIT 1024
12114#endif
12115
12116/*
12117** We need to define _XOPEN_SOURCE as follows in order to enable
12118** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
12119** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
12120** it.
12121*/
12122#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
12123#  define _XOPEN_SOURCE 600
12124#endif
12125
12126/*
12127** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
12128** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
12129** make it true by defining or undefining NDEBUG.
12130**
12131** Setting NDEBUG makes the code smaller and faster by disabling the
12132** assert() statements in the code.  So we want the default action
12133** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
12134** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
12135** feature.
12136*/
12137#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
12138# define NDEBUG 1
12139#endif
12140#if defined(NDEBUG) && defined(SQLITE_DEBUG)
12141# undef NDEBUG
12142#endif
12143
12144/*
12145** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
12146*/
12147#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
12148# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
12149#endif
12150
12151/*
12152** The testcase() macro is used to aid in coverage testing.  When
12153** doing coverage testing, the condition inside the argument to
12154** testcase() must be evaluated both true and false in order to
12155** get full branch coverage.  The testcase() macro is inserted
12156** to help ensure adequate test coverage in places where simple
12157** condition/decision coverage is inadequate.  For example, testcase()
12158** can be used to make sure boundary values are tested.  For
12159** bitmask tests, testcase() can be used to make sure each bit
12160** is significant and used at least once.  On switch statements
12161** where multiple cases go to the same block of code, testcase()
12162** can insure that all cases are evaluated.
12163**
12164*/
12165#ifdef SQLITE_COVERAGE_TEST
12166SQLITE_PRIVATE   void sqlite3Coverage(int);
12167# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
12168#else
12169# define testcase(X)
12170#endif
12171
12172/*
12173** The TESTONLY macro is used to enclose variable declarations or
12174** other bits of code that are needed to support the arguments
12175** within testcase() and assert() macros.
12176*/
12177#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
12178# define TESTONLY(X)  X
12179#else
12180# define TESTONLY(X)
12181#endif
12182
12183/*
12184** Sometimes we need a small amount of code such as a variable initialization
12185** to setup for a later assert() statement.  We do not want this code to
12186** appear when assert() is disabled.  The following macro is therefore
12187** used to contain that setup code.  The "VVA" acronym stands for
12188** "Verification, Validation, and Accreditation".  In other words, the
12189** code within VVA_ONLY() will only run during verification processes.
12190*/
12191#ifndef NDEBUG
12192# define VVA_ONLY(X)  X
12193#else
12194# define VVA_ONLY(X)
12195#endif
12196
12197/*
12198** The ALWAYS and NEVER macros surround boolean expressions which
12199** are intended to always be true or false, respectively.  Such
12200** expressions could be omitted from the code completely.  But they
12201** are included in a few cases in order to enhance the resilience
12202** of SQLite to unexpected behavior - to make the code "self-healing"
12203** or "ductile" rather than being "brittle" and crashing at the first
12204** hint of unplanned behavior.
12205**
12206** In other words, ALWAYS and NEVER are added for defensive code.
12207**
12208** When doing coverage testing ALWAYS and NEVER are hard-coded to
12209** be true and false so that the unreachable code they specify will
12210** not be counted as untested code.
12211*/
12212#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
12213# define ALWAYS(X)      (1)
12214# define NEVER(X)       (0)
12215#elif !defined(NDEBUG)
12216# define ALWAYS(X)      ((X)?1:(assert(0),0))
12217# define NEVER(X)       ((X)?(assert(0),1):0)
12218#else
12219# define ALWAYS(X)      (X)
12220# define NEVER(X)       (X)
12221#endif
12222
12223/*
12224** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
12225** defined.  We need to defend against those failures when testing with
12226** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
12227** during a normal build.  The following macro can be used to disable tests
12228** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
12229*/
12230#if defined(SQLITE_TEST_REALLOC_STRESS)
12231# define ONLY_IF_REALLOC_STRESS(X)  (X)
12232#elif !defined(NDEBUG)
12233# define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
12234#else
12235# define ONLY_IF_REALLOC_STRESS(X)  (0)
12236#endif
12237
12238/*
12239** Declarations used for tracing the operating system interfaces.
12240*/
12241#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
12242    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
12243  extern int sqlite3OSTrace;
12244# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
12245# define SQLITE_HAVE_OS_TRACE
12246#else
12247# define OSTRACE(X)
12248# undef  SQLITE_HAVE_OS_TRACE
12249#endif
12250
12251/*
12252** Is the sqlite3ErrName() function needed in the build?  Currently,
12253** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
12254** OSTRACE is enabled), and by several "test*.c" files (which are
12255** compiled using SQLITE_TEST).
12256*/
12257#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
12258    (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
12259# define SQLITE_NEED_ERR_NAME
12260#else
12261# undef  SQLITE_NEED_ERR_NAME
12262#endif
12263
12264/*
12265** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
12266*/
12267#ifdef SQLITE_OMIT_EXPLAIN
12268# undef SQLITE_ENABLE_EXPLAIN_COMMENTS
12269#endif
12270
12271/*
12272** Return true (non-zero) if the input is an integer that is too large
12273** to fit in 32-bits.  This macro is used inside of various testcase()
12274** macros to verify that we have tested SQLite for large-file support.
12275*/
12276#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
12277
12278/*
12279** The macro unlikely() is a hint that surrounds a boolean
12280** expression that is usually false.  Macro likely() surrounds
12281** a boolean expression that is usually true.  These hints could,
12282** in theory, be used by the compiler to generate better code, but
12283** currently they are just comments for human readers.
12284*/
12285#define likely(X)    (X)
12286#define unlikely(X)  (X)
12287
12288/************** Include hash.h in the middle of sqliteInt.h ******************/
12289/************** Begin file hash.h ********************************************/
12290/*
12291** 2001 September 22
12292**
12293** The author disclaims copyright to this source code.  In place of
12294** a legal notice, here is a blessing:
12295**
12296**    May you do good and not evil.
12297**    May you find forgiveness for yourself and forgive others.
12298**    May you share freely, never taking more than you give.
12299**
12300*************************************************************************
12301** This is the header file for the generic hash-table implementation
12302** used in SQLite.
12303*/
12304#ifndef SQLITE_HASH_H
12305#define SQLITE_HASH_H
12306
12307/* Forward declarations of structures. */
12308typedef struct Hash Hash;
12309typedef struct HashElem HashElem;
12310
12311/* A complete hash table is an instance of the following structure.
12312** The internals of this structure are intended to be opaque -- client
12313** code should not attempt to access or modify the fields of this structure
12314** directly.  Change this structure only by using the routines below.
12315** However, some of the "procedures" and "functions" for modifying and
12316** accessing this structure are really macros, so we can't really make
12317** this structure opaque.
12318**
12319** All elements of the hash table are on a single doubly-linked list.
12320** Hash.first points to the head of this list.
12321**
12322** There are Hash.htsize buckets.  Each bucket points to a spot in
12323** the global doubly-linked list.  The contents of the bucket are the
12324** element pointed to plus the next _ht.count-1 elements in the list.
12325**
12326** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
12327** by a linear search of the global list.  For small tables, the
12328** Hash.ht table is never allocated because if there are few elements
12329** in the table, it is faster to do a linear search than to manage
12330** the hash table.
12331*/
12332struct Hash {
12333  unsigned int htsize;      /* Number of buckets in the hash table */
12334  unsigned int count;       /* Number of entries in this table */
12335  HashElem *first;          /* The first element of the array */
12336  struct _ht {              /* the hash table */
12337    int count;                 /* Number of entries with this hash */
12338    HashElem *chain;           /* Pointer to first entry with this hash */
12339  } *ht;
12340};
12341
12342/* Each element in the hash table is an instance of the following
12343** structure.  All elements are stored on a single doubly-linked list.
12344**
12345** Again, this structure is intended to be opaque, but it can't really
12346** be opaque because it is used by macros.
12347*/
12348struct HashElem {
12349  HashElem *next, *prev;       /* Next and previous elements in the table */
12350  void *data;                  /* Data associated with this element */
12351  const char *pKey;            /* Key associated with this element */
12352};
12353
12354/*
12355** Access routines.  To delete, insert a NULL pointer.
12356*/
12357SQLITE_PRIVATE void sqlite3HashInit(Hash*);
12358SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
12359SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
12360SQLITE_PRIVATE void sqlite3HashClear(Hash*);
12361
12362/*
12363** Macros for looping over all elements of a hash table.  The idiom is
12364** like this:
12365**
12366**   Hash h;
12367**   HashElem *p;
12368**   ...
12369**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
12370**     SomeStructure *pData = sqliteHashData(p);
12371**     // do something with pData
12372**   }
12373*/
12374#define sqliteHashFirst(H)  ((H)->first)
12375#define sqliteHashNext(E)   ((E)->next)
12376#define sqliteHashData(E)   ((E)->data)
12377/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
12378/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
12379
12380/*
12381** Number of entries in a hash table
12382*/
12383/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
12384
12385#endif /* SQLITE_HASH_H */
12386
12387/************** End of hash.h ************************************************/
12388/************** Continuing where we left off in sqliteInt.h ******************/
12389/************** Include parse.h in the middle of sqliteInt.h *****************/
12390/************** Begin file parse.h *******************************************/
12391#define TK_SEMI                             1
12392#define TK_EXPLAIN                          2
12393#define TK_QUERY                            3
12394#define TK_PLAN                             4
12395#define TK_BEGIN                            5
12396#define TK_TRANSACTION                      6
12397#define TK_DEFERRED                         7
12398#define TK_IMMEDIATE                        8
12399#define TK_EXCLUSIVE                        9
12400#define TK_COMMIT                          10
12401#define TK_END                             11
12402#define TK_ROLLBACK                        12
12403#define TK_SAVEPOINT                       13
12404#define TK_RELEASE                         14
12405#define TK_TO                              15
12406#define TK_TABLE                           16
12407#define TK_CREATE                          17
12408#define TK_IF                              18
12409#define TK_NOT                             19
12410#define TK_EXISTS                          20
12411#define TK_TEMP                            21
12412#define TK_LP                              22
12413#define TK_RP                              23
12414#define TK_AS                              24
12415#define TK_WITHOUT                         25
12416#define TK_COMMA                           26
12417#define TK_ID                              27
12418#define TK_ABORT                           28
12419#define TK_ACTION                          29
12420#define TK_AFTER                           30
12421#define TK_ANALYZE                         31
12422#define TK_ASC                             32
12423#define TK_ATTACH                          33
12424#define TK_BEFORE                          34
12425#define TK_BY                              35
12426#define TK_CASCADE                         36
12427#define TK_CAST                            37
12428#define TK_COLUMNKW                        38
12429#define TK_CONFLICT                        39
12430#define TK_DATABASE                        40
12431#define TK_DESC                            41
12432#define TK_DETACH                          42
12433#define TK_EACH                            43
12434#define TK_FAIL                            44
12435#define TK_FOR                             45
12436#define TK_IGNORE                          46
12437#define TK_INITIALLY                       47
12438#define TK_INSTEAD                         48
12439#define TK_LIKE_KW                         49
12440#define TK_MATCH                           50
12441#define TK_NO                              51
12442#define TK_KEY                             52
12443#define TK_OF                              53
12444#define TK_OFFSET                          54
12445#define TK_PRAGMA                          55
12446#define TK_RAISE                           56
12447#define TK_RECURSIVE                       57
12448#define TK_REPLACE                         58
12449#define TK_RESTRICT                        59
12450#define TK_ROW                             60
12451#define TK_TRIGGER                         61
12452#define TK_VACUUM                          62
12453#define TK_VIEW                            63
12454#define TK_VIRTUAL                         64
12455#define TK_WITH                            65
12456#define TK_REINDEX                         66
12457#define TK_RENAME                          67
12458#define TK_CTIME_KW                        68
12459#define TK_ANY                             69
12460#define TK_OR                              70
12461#define TK_AND                             71
12462#define TK_IS                              72
12463#define TK_BETWEEN                         73
12464#define TK_IN                              74
12465#define TK_ISNULL                          75
12466#define TK_NOTNULL                         76
12467#define TK_NE                              77
12468#define TK_EQ                              78
12469#define TK_GT                              79
12470#define TK_LE                              80
12471#define TK_LT                              81
12472#define TK_GE                              82
12473#define TK_ESCAPE                          83
12474#define TK_BITAND                          84
12475#define TK_BITOR                           85
12476#define TK_LSHIFT                          86
12477#define TK_RSHIFT                          87
12478#define TK_PLUS                            88
12479#define TK_MINUS                           89
12480#define TK_STAR                            90
12481#define TK_SLASH                           91
12482#define TK_REM                             92
12483#define TK_CONCAT                          93
12484#define TK_COLLATE                         94
12485#define TK_BITNOT                          95
12486#define TK_INDEXED                         96
12487#define TK_STRING                          97
12488#define TK_JOIN_KW                         98
12489#define TK_CONSTRAINT                      99
12490#define TK_DEFAULT                        100
12491#define TK_NULL                           101
12492#define TK_PRIMARY                        102
12493#define TK_UNIQUE                         103
12494#define TK_CHECK                          104
12495#define TK_REFERENCES                     105
12496#define TK_AUTOINCR                       106
12497#define TK_ON                             107
12498#define TK_INSERT                         108
12499#define TK_DELETE                         109
12500#define TK_UPDATE                         110
12501#define TK_SET                            111
12502#define TK_DEFERRABLE                     112
12503#define TK_FOREIGN                        113
12504#define TK_DROP                           114
12505#define TK_UNION                          115
12506#define TK_ALL                            116
12507#define TK_EXCEPT                         117
12508#define TK_INTERSECT                      118
12509#define TK_SELECT                         119
12510#define TK_VALUES                         120
12511#define TK_DISTINCT                       121
12512#define TK_DOT                            122
12513#define TK_FROM                           123
12514#define TK_JOIN                           124
12515#define TK_USING                          125
12516#define TK_ORDER                          126
12517#define TK_GROUP                          127
12518#define TK_HAVING                         128
12519#define TK_LIMIT                          129
12520#define TK_WHERE                          130
12521#define TK_INTO                           131
12522#define TK_FLOAT                          132
12523#define TK_BLOB                           133
12524#define TK_INTEGER                        134
12525#define TK_VARIABLE                       135
12526#define TK_CASE                           136
12527#define TK_WHEN                           137
12528#define TK_THEN                           138
12529#define TK_ELSE                           139
12530#define TK_INDEX                          140
12531#define TK_ALTER                          141
12532#define TK_ADD                            142
12533#define TK_TO_TEXT                        143
12534#define TK_TO_BLOB                        144
12535#define TK_TO_NUMERIC                     145
12536#define TK_TO_INT                         146
12537#define TK_TO_REAL                        147
12538#define TK_ISNOT                          148
12539#define TK_END_OF_FILE                    149
12540#define TK_UNCLOSED_STRING                150
12541#define TK_FUNCTION                       151
12542#define TK_COLUMN                         152
12543#define TK_AGG_FUNCTION                   153
12544#define TK_AGG_COLUMN                     154
12545#define TK_UMINUS                         155
12546#define TK_UPLUS                          156
12547#define TK_REGISTER                       157
12548#define TK_VECTOR                         158
12549#define TK_SELECT_COLUMN                  159
12550#define TK_IF_NULL_ROW                    160
12551#define TK_ASTERISK                       161
12552#define TK_SPAN                           162
12553#define TK_SPACE                          163
12554#define TK_ILLEGAL                        164
12555
12556/* The token codes above must all fit in 8 bits */
12557#define TKFLG_MASK           0xff
12558
12559/* Flags that can be added to a token code when it is not
12560** being stored in a u8: */
12561#define TKFLG_DONTFOLD       0x100  /* Omit constant folding optimizations */
12562
12563/************** End of parse.h ***********************************************/
12564/************** Continuing where we left off in sqliteInt.h ******************/
12565#include <stdio.h>
12566#include <stdlib.h>
12567#include <string.h>
12568#include <assert.h>
12569#include <stddef.h>
12570
12571/*
12572** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
12573** This allows better measurements of where memcpy() is used when running
12574** cachegrind.  But this macro version of memcpy() is very slow so it
12575** should not be used in production.  This is a performance measurement
12576** hack only.
12577*/
12578#ifdef SQLITE_INLINE_MEMCPY
12579# define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
12580                        int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
12581#endif
12582
12583/*
12584** If compiling for a processor that lacks floating point support,
12585** substitute integer for floating-point
12586*/
12587#ifdef SQLITE_OMIT_FLOATING_POINT
12588# define double sqlite_int64
12589# define float sqlite_int64
12590# define LONGDOUBLE_TYPE sqlite_int64
12591# ifndef SQLITE_BIG_DBL
12592#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
12593# endif
12594# define SQLITE_OMIT_DATETIME_FUNCS 1
12595# define SQLITE_OMIT_TRACE 1
12596# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12597# undef SQLITE_HAVE_ISNAN
12598#endif
12599#ifndef SQLITE_BIG_DBL
12600# define SQLITE_BIG_DBL (1e99)
12601#endif
12602
12603/*
12604** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
12605** afterward. Having this macro allows us to cause the C compiler
12606** to omit code used by TEMP tables without messy #ifndef statements.
12607*/
12608#ifdef SQLITE_OMIT_TEMPDB
12609#define OMIT_TEMPDB 1
12610#else
12611#define OMIT_TEMPDB 0
12612#endif
12613
12614/*
12615** The "file format" number is an integer that is incremented whenever
12616** the VDBE-level file format changes.  The following macros define the
12617** the default file format for new databases and the maximum file format
12618** that the library can read.
12619*/
12620#define SQLITE_MAX_FILE_FORMAT 4
12621#ifndef SQLITE_DEFAULT_FILE_FORMAT
12622# define SQLITE_DEFAULT_FILE_FORMAT 4
12623#endif
12624
12625/*
12626** Determine whether triggers are recursive by default.  This can be
12627** changed at run-time using a pragma.
12628*/
12629#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
12630# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
12631#endif
12632
12633/*
12634** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
12635** on the command-line
12636*/
12637#ifndef SQLITE_TEMP_STORE
12638# define SQLITE_TEMP_STORE 1
12639#endif
12640
12641/*
12642** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
12643** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
12644** to zero.
12645*/
12646#if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
12647# undef SQLITE_MAX_WORKER_THREADS
12648# define SQLITE_MAX_WORKER_THREADS 0
12649#endif
12650#ifndef SQLITE_MAX_WORKER_THREADS
12651# define SQLITE_MAX_WORKER_THREADS 8
12652#endif
12653#ifndef SQLITE_DEFAULT_WORKER_THREADS
12654# define SQLITE_DEFAULT_WORKER_THREADS 0
12655#endif
12656#if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
12657# undef SQLITE_MAX_WORKER_THREADS
12658# define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
12659#endif
12660
12661/*
12662** The default initial allocation for the pagecache when using separate
12663** pagecaches for each database connection.  A positive number is the
12664** number of pages.  A negative number N translations means that a buffer
12665** of -1024*N bytes is allocated and used for as many pages as it will hold.
12666**
12667** The default value of "20" was choosen to minimize the run-time of the
12668** speedtest1 test program with options: --shrink-memory --reprepare
12669*/
12670#ifndef SQLITE_DEFAULT_PCACHE_INITSZ
12671# define SQLITE_DEFAULT_PCACHE_INITSZ 20
12672#endif
12673
12674/*
12675** GCC does not define the offsetof() macro so we'll have to do it
12676** ourselves.
12677*/
12678#ifndef offsetof
12679#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
12680#endif
12681
12682/*
12683** Macros to compute minimum and maximum of two numbers.
12684*/
12685#ifndef MIN
12686# define MIN(A,B) ((A)<(B)?(A):(B))
12687#endif
12688#ifndef MAX
12689# define MAX(A,B) ((A)>(B)?(A):(B))
12690#endif
12691
12692/*
12693** Swap two objects of type TYPE.
12694*/
12695#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
12696
12697/*
12698** Check to see if this machine uses EBCDIC.  (Yes, believe it or
12699** not, there are still machines out there that use EBCDIC.)
12700*/
12701#if 'A' == '\301'
12702# define SQLITE_EBCDIC 1
12703#else
12704# define SQLITE_ASCII 1
12705#endif
12706
12707/*
12708** Integers of known sizes.  These typedefs might change for architectures
12709** where the sizes very.  Preprocessor macros are available so that the
12710** types can be conveniently redefined at compile-type.  Like this:
12711**
12712**         cc '-DUINTPTR_TYPE=long long int' ...
12713*/
12714#ifndef UINT32_TYPE
12715# ifdef HAVE_UINT32_T
12716#  define UINT32_TYPE uint32_t
12717# else
12718#  define UINT32_TYPE unsigned int
12719# endif
12720#endif
12721#ifndef UINT16_TYPE
12722# ifdef HAVE_UINT16_T
12723#  define UINT16_TYPE uint16_t
12724# else
12725#  define UINT16_TYPE unsigned short int
12726# endif
12727#endif
12728#ifndef INT16_TYPE
12729# ifdef HAVE_INT16_T
12730#  define INT16_TYPE int16_t
12731# else
12732#  define INT16_TYPE short int
12733# endif
12734#endif
12735#ifndef UINT8_TYPE
12736# ifdef HAVE_UINT8_T
12737#  define UINT8_TYPE uint8_t
12738# else
12739#  define UINT8_TYPE unsigned char
12740# endif
12741#endif
12742#ifndef INT8_TYPE
12743# ifdef HAVE_INT8_T
12744#  define INT8_TYPE int8_t
12745# else
12746#  define INT8_TYPE signed char
12747# endif
12748#endif
12749#ifndef LONGDOUBLE_TYPE
12750# define LONGDOUBLE_TYPE long double
12751#endif
12752typedef sqlite_int64 i64;          /* 8-byte signed integer */
12753typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
12754typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
12755typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
12756typedef INT16_TYPE i16;            /* 2-byte signed integer */
12757typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
12758typedef INT8_TYPE i8;              /* 1-byte signed integer */
12759
12760/*
12761** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
12762** that can be stored in a u32 without loss of data.  The value
12763** is 0x00000000ffffffff.  But because of quirks of some compilers, we
12764** have to specify the value in the less intuitive manner shown:
12765*/
12766#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
12767
12768/*
12769** The datatype used to store estimates of the number of rows in a
12770** table or index.  This is an unsigned integer type.  For 99.9% of
12771** the world, a 32-bit integer is sufficient.  But a 64-bit integer
12772** can be used at compile-time if desired.
12773*/
12774#ifdef SQLITE_64BIT_STATS
12775 typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
12776#else
12777 typedef u32 tRowcnt;    /* 32-bit is the default */
12778#endif
12779
12780/*
12781** Estimated quantities used for query planning are stored as 16-bit
12782** logarithms.  For quantity X, the value stored is 10*log2(X).  This
12783** gives a possible range of values of approximately 1.0e986 to 1e-986.
12784** But the allowed values are "grainy".  Not every value is representable.
12785** For example, quantities 16 and 17 are both represented by a LogEst
12786** of 40.  However, since LogEst quantities are suppose to be estimates,
12787** not exact values, this imprecision is not a problem.
12788**
12789** "LogEst" is short for "Logarithmic Estimate".
12790**
12791** Examples:
12792**      1 -> 0              20 -> 43          10000 -> 132
12793**      2 -> 10             25 -> 46          25000 -> 146
12794**      3 -> 16            100 -> 66        1000000 -> 199
12795**      4 -> 20           1000 -> 99        1048576 -> 200
12796**     10 -> 33           1024 -> 100    4294967296 -> 320
12797**
12798** The LogEst can be negative to indicate fractional values.
12799** Examples:
12800**
12801**    0.5 -> -10           0.1 -> -33        0.0625 -> -40
12802*/
12803typedef INT16_TYPE LogEst;
12804
12805/*
12806** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
12807*/
12808#ifndef SQLITE_PTRSIZE
12809# if defined(__SIZEOF_POINTER__)
12810#   define SQLITE_PTRSIZE __SIZEOF_POINTER__
12811# elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
12812       defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
12813#   define SQLITE_PTRSIZE 4
12814# else
12815#   define SQLITE_PTRSIZE 8
12816# endif
12817#endif
12818
12819/* The uptr type is an unsigned integer large enough to hold a pointer
12820*/
12821#if defined(HAVE_STDINT_H)
12822  typedef uintptr_t uptr;
12823#elif SQLITE_PTRSIZE==4
12824  typedef u32 uptr;
12825#else
12826  typedef u64 uptr;
12827#endif
12828
12829/*
12830** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
12831** something between S (inclusive) and E (exclusive).
12832**
12833** In other words, S is a buffer and E is a pointer to the first byte after
12834** the end of buffer S.  This macro returns true if P points to something
12835** contained within the buffer S.
12836*/
12837#define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
12838
12839
12840/*
12841** Macros to determine whether the machine is big or little endian,
12842** and whether or not that determination is run-time or compile-time.
12843**
12844** For best performance, an attempt is made to guess at the byte-order
12845** using C-preprocessor macros.  If that is unsuccessful, or if
12846** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
12847** at run-time.
12848*/
12849#ifndef SQLITE_BYTEORDER
12850# if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
12851     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
12852     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
12853     defined(__arm__)
12854#   define SQLITE_BYTEORDER    1234
12855# elif defined(sparc)    || defined(__ppc__)
12856#   define SQLITE_BYTEORDER    4321
12857# else
12858#   define SQLITE_BYTEORDER 0
12859# endif
12860#endif
12861#if SQLITE_BYTEORDER==4321
12862# define SQLITE_BIGENDIAN    1
12863# define SQLITE_LITTLEENDIAN 0
12864# define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
12865#elif SQLITE_BYTEORDER==1234
12866# define SQLITE_BIGENDIAN    0
12867# define SQLITE_LITTLEENDIAN 1
12868# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
12869#else
12870# ifdef SQLITE_AMALGAMATION
12871  const int sqlite3one = 1;
12872# else
12873  extern const int sqlite3one;
12874# endif
12875# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
12876# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
12877# define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
12878#endif
12879
12880/*
12881** Constants for the largest and smallest possible 64-bit signed integers.
12882** These macros are designed to work correctly on both 32-bit and 64-bit
12883** compilers.
12884*/
12885#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
12886#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
12887
12888/*
12889** Round up a number to the next larger multiple of 8.  This is used
12890** to force 8-byte alignment on 64-bit architectures.
12891*/
12892#define ROUND8(x)     (((x)+7)&~7)
12893
12894/*
12895** Round down to the nearest multiple of 8
12896*/
12897#define ROUNDDOWN8(x) ((x)&~7)
12898
12899/*
12900** Assert that the pointer X is aligned to an 8-byte boundary.  This
12901** macro is used only within assert() to verify that the code gets
12902** all alignment restrictions correct.
12903**
12904** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
12905** underlying malloc() implementation might return us 4-byte aligned
12906** pointers.  In that case, only verify 4-byte alignment.
12907*/
12908#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12909# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
12910#else
12911# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
12912#endif
12913
12914/*
12915** Disable MMAP on platforms where it is known to not work
12916*/
12917#if defined(__OpenBSD__) || defined(__QNXNTO__)
12918# undef SQLITE_MAX_MMAP_SIZE
12919# define SQLITE_MAX_MMAP_SIZE 0
12920#endif
12921
12922/*
12923** Default maximum size of memory used by memory-mapped I/O in the VFS
12924*/
12925#ifdef __APPLE__
12926# include <TargetConditionals.h>
12927#endif
12928#ifndef SQLITE_MAX_MMAP_SIZE
12929# if defined(__linux__) \
12930  || defined(_WIN32) \
12931  || (defined(__APPLE__) && defined(__MACH__)) \
12932  || defined(__sun) \
12933  || defined(__FreeBSD__) \
12934  || defined(__DragonFly__)
12935#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
12936# else
12937#   define SQLITE_MAX_MMAP_SIZE 0
12938# endif
12939#endif
12940
12941/*
12942** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
12943** default MMAP_SIZE is specified at compile-time, make sure that it does
12944** not exceed the maximum mmap size.
12945*/
12946#ifndef SQLITE_DEFAULT_MMAP_SIZE
12947# define SQLITE_DEFAULT_MMAP_SIZE 0
12948#endif
12949#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
12950# undef SQLITE_DEFAULT_MMAP_SIZE
12951# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
12952#endif
12953
12954/*
12955** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
12956** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
12957** define SQLITE_ENABLE_STAT3_OR_STAT4
12958*/
12959#ifdef SQLITE_ENABLE_STAT4
12960# undef SQLITE_ENABLE_STAT3
12961# define SQLITE_ENABLE_STAT3_OR_STAT4 1
12962#elif SQLITE_ENABLE_STAT3
12963# define SQLITE_ENABLE_STAT3_OR_STAT4 1
12964#elif SQLITE_ENABLE_STAT3_OR_STAT4
12965# undef SQLITE_ENABLE_STAT3_OR_STAT4
12966#endif
12967
12968/*
12969** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
12970** the Select query generator tracing logic is turned on.
12971*/
12972#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
12973# define SELECTTRACE_ENABLED 1
12974#else
12975# define SELECTTRACE_ENABLED 0
12976#endif
12977
12978/*
12979** An instance of the following structure is used to store the busy-handler
12980** callback for a given sqlite handle.
12981**
12982** The sqlite.busyHandler member of the sqlite struct contains the busy
12983** callback for the database handle. Each pager opened via the sqlite
12984** handle is passed a pointer to sqlite.busyHandler. The busy-handler
12985** callback is currently invoked only from within pager.c.
12986*/
12987typedef struct BusyHandler BusyHandler;
12988struct BusyHandler {
12989  int (*xFunc)(void *,int);  /* The busy callback */
12990  void *pArg;                /* First arg to busy callback */
12991  int nBusy;                 /* Incremented with each busy call */
12992};
12993
12994/*
12995** Name of the master database table.  The master database table
12996** is a special table that holds the names and attributes of all
12997** user tables and indices.
12998*/
12999#define MASTER_NAME       "sqlite_master"
13000#define TEMP_MASTER_NAME  "sqlite_temp_master"
13001
13002/*
13003** The root-page of the master database table.
13004*/
13005#define MASTER_ROOT       1
13006
13007/*
13008** The name of the schema table.
13009*/
13010#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
13011
13012/*
13013** A convenience macro that returns the number of elements in
13014** an array.
13015*/
13016#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
13017
13018/*
13019** Determine if the argument is a power of two
13020*/
13021#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
13022
13023/*
13024** The following value as a destructor means to use sqlite3DbFree().
13025** The sqlite3DbFree() routine requires two parameters instead of the
13026** one parameter that destructors normally want.  So we have to introduce
13027** this magic value that the code knows to handle differently.  Any
13028** pointer will work here as long as it is distinct from SQLITE_STATIC
13029** and SQLITE_TRANSIENT.
13030*/
13031#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
13032
13033/*
13034** When SQLITE_OMIT_WSD is defined, it means that the target platform does
13035** not support Writable Static Data (WSD) such as global and static variables.
13036** All variables must either be on the stack or dynamically allocated from
13037** the heap.  When WSD is unsupported, the variable declarations scattered
13038** throughout the SQLite code must become constants instead.  The SQLITE_WSD
13039** macro is used for this purpose.  And instead of referencing the variable
13040** directly, we use its constant as a key to lookup the run-time allocated
13041** buffer that holds real variable.  The constant is also the initializer
13042** for the run-time allocated buffer.
13043**
13044** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
13045** macros become no-ops and have zero performance impact.
13046*/
13047#ifdef SQLITE_OMIT_WSD
13048  #define SQLITE_WSD const
13049  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
13050  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
13051SQLITE_API int sqlite3_wsd_init(int N, int J);
13052SQLITE_API void *sqlite3_wsd_find(void *K, int L);
13053#else
13054  #define SQLITE_WSD
13055  #define GLOBAL(t,v) v
13056  #define sqlite3GlobalConfig sqlite3Config
13057#endif
13058
13059/*
13060** The following macros are used to suppress compiler warnings and to
13061** make it clear to human readers when a function parameter is deliberately
13062** left unused within the body of a function. This usually happens when
13063** a function is called via a function pointer. For example the
13064** implementation of an SQL aggregate step callback may not use the
13065** parameter indicating the number of arguments passed to the aggregate,
13066** if it knows that this is enforced elsewhere.
13067**
13068** When a function parameter is not used at all within the body of a function,
13069** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
13070** However, these macros may also be used to suppress warnings related to
13071** parameters that may or may not be used depending on compilation options.
13072** For example those parameters only used in assert() statements. In these
13073** cases the parameters are named as per the usual conventions.
13074*/
13075#define UNUSED_PARAMETER(x) (void)(x)
13076#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
13077
13078/*
13079** Forward references to structures
13080*/
13081typedef struct AggInfo AggInfo;
13082typedef struct AuthContext AuthContext;
13083typedef struct AutoincInfo AutoincInfo;
13084typedef struct Bitvec Bitvec;
13085typedef struct CollSeq CollSeq;
13086typedef struct Column Column;
13087typedef struct Db Db;
13088typedef struct Schema Schema;
13089typedef struct Expr Expr;
13090typedef struct ExprList ExprList;
13091typedef struct ExprSpan ExprSpan;
13092typedef struct FKey FKey;
13093typedef struct FuncDestructor FuncDestructor;
13094typedef struct FuncDef FuncDef;
13095typedef struct FuncDefHash FuncDefHash;
13096typedef struct IdList IdList;
13097typedef struct Index Index;
13098typedef struct IndexSample IndexSample;
13099typedef struct KeyClass KeyClass;
13100typedef struct KeyInfo KeyInfo;
13101typedef struct Lookaside Lookaside;
13102typedef struct LookasideSlot LookasideSlot;
13103typedef struct Module Module;
13104typedef struct NameContext NameContext;
13105typedef struct Parse Parse;
13106typedef struct PreUpdate PreUpdate;
13107typedef struct PrintfArguments PrintfArguments;
13108typedef struct RowSet RowSet;
13109typedef struct Savepoint Savepoint;
13110typedef struct Select Select;
13111typedef struct SQLiteThread SQLiteThread;
13112typedef struct SelectDest SelectDest;
13113typedef struct SrcList SrcList;
13114typedef struct StrAccum StrAccum;
13115typedef struct Table Table;
13116typedef struct TableLock TableLock;
13117typedef struct Token Token;
13118typedef struct TreeView TreeView;
13119typedef struct Trigger Trigger;
13120typedef struct TriggerPrg TriggerPrg;
13121typedef struct TriggerStep TriggerStep;
13122typedef struct UnpackedRecord UnpackedRecord;
13123typedef struct VTable VTable;
13124typedef struct VtabCtx VtabCtx;
13125typedef struct Walker Walker;
13126typedef struct WhereInfo WhereInfo;
13127typedef struct With With;
13128
13129/* A VList object records a mapping between parameters/variables/wildcards
13130** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
13131** variable number associated with that parameter.  See the format description
13132** on the sqlite3VListAdd() routine for more information.  A VList is really
13133** just an array of integers.
13134*/
13135typedef int VList;
13136
13137/*
13138** Defer sourcing vdbe.h and btree.h until after the "u8" and
13139** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
13140** pointer types (i.e. FuncDef) defined above.
13141*/
13142/************** Include btree.h in the middle of sqliteInt.h *****************/
13143/************** Begin file btree.h *******************************************/
13144/*
13145** 2001 September 15
13146**
13147** The author disclaims copyright to this source code.  In place of
13148** a legal notice, here is a blessing:
13149**
13150**    May you do good and not evil.
13151**    May you find forgiveness for yourself and forgive others.
13152**    May you share freely, never taking more than you give.
13153**
13154*************************************************************************
13155** This header file defines the interface that the sqlite B-Tree file
13156** subsystem.  See comments in the source code for a detailed description
13157** of what each interface routine does.
13158*/
13159#ifndef SQLITE_BTREE_H
13160#define SQLITE_BTREE_H
13161
13162/* TODO: This definition is just included so other modules compile. It
13163** needs to be revisited.
13164*/
13165#define SQLITE_N_BTREE_META 16
13166
13167/*
13168** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
13169** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
13170*/
13171#ifndef SQLITE_DEFAULT_AUTOVACUUM
13172  #define SQLITE_DEFAULT_AUTOVACUUM 0
13173#endif
13174
13175#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
13176#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
13177#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
13178
13179/*
13180** Forward declarations of structure
13181*/
13182typedef struct Btree Btree;
13183typedef struct BtCursor BtCursor;
13184typedef struct BtShared BtShared;
13185typedef struct BtreePayload BtreePayload;
13186
13187
13188SQLITE_PRIVATE int sqlite3BtreeOpen(
13189  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
13190  const char *zFilename,   /* Name of database file to open */
13191  sqlite3 *db,             /* Associated database connection */
13192  Btree **ppBtree,         /* Return open Btree* here */
13193  int flags,               /* Flags */
13194  int vfsFlags             /* Flags passed through to VFS open */
13195);
13196
13197/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
13198** following values.
13199**
13200** NOTE:  These values must match the corresponding PAGER_ values in
13201** pager.h.
13202*/
13203#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
13204#define BTREE_MEMORY        2  /* This is an in-memory DB */
13205#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
13206#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
13207
13208SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
13209SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
13210SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
13211#if SQLITE_MAX_MMAP_SIZE>0
13212SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
13213#endif
13214SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
13215SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
13216SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
13217SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
13218SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
13219SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
13220SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
13221SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
13222SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
13223SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
13224SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
13225SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
13226SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
13227SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
13228SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
13229SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
13230SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
13231SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
13232SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
13233SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
13234SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
13235SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
13236#ifndef SQLITE_OMIT_SHARED_CACHE
13237SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
13238#endif
13239SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
13240
13241SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
13242SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
13243SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
13244
13245SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
13246
13247/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
13248** of the flags shown below.
13249**
13250** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
13251** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
13252** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
13253** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
13254** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
13255** indices.)
13256*/
13257#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
13258#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
13259
13260SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
13261SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
13262SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
13263SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
13264
13265SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
13266SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
13267
13268SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
13269
13270/*
13271** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
13272** should be one of the following values. The integer values are assigned
13273** to constants so that the offset of the corresponding field in an
13274** SQLite database header may be found using the following formula:
13275**
13276**   offset = 36 + (idx * 4)
13277**
13278** For example, the free-page-count field is located at byte offset 36 of
13279** the database file header. The incr-vacuum-flag field is located at
13280** byte offset 64 (== 36+4*7).
13281**
13282** The BTREE_DATA_VERSION value is not really a value stored in the header.
13283** It is a read-only number computed by the pager.  But we merge it with
13284** the header value access routines since its access pattern is the same.
13285** Call it a "virtual meta value".
13286*/
13287#define BTREE_FREE_PAGE_COUNT     0
13288#define BTREE_SCHEMA_VERSION      1
13289#define BTREE_FILE_FORMAT         2
13290#define BTREE_DEFAULT_CACHE_SIZE  3
13291#define BTREE_LARGEST_ROOT_PAGE   4
13292#define BTREE_TEXT_ENCODING       5
13293#define BTREE_USER_VERSION        6
13294#define BTREE_INCR_VACUUM         7
13295#define BTREE_APPLICATION_ID      8
13296#define BTREE_DATA_VERSION        15  /* A virtual meta-value */
13297
13298/*
13299** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
13300** interface.
13301**
13302** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)
13303**
13304**     The first argument is an Expr* (which is guaranteed to be constant for
13305**     the lifetime of the cursor) that defines constraints on which rows
13306**     might be fetched with this cursor.  The Expr* tree may contain
13307**     TK_REGISTER nodes that refer to values stored in the array of registers
13308**     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER
13309**     then the value of the node is the value in Mem[pExpr.iTable].  Any
13310**     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
13311**     column of the b-tree of the cursor.  The Expr tree will not contain
13312**     any function calls nor subqueries nor references to b-trees other than
13313**     the cursor being hinted.
13314**
13315**     The design of the _RANGE hint is aid b-tree implementations that try
13316**     to prefetch content from remote machines - to provide those
13317**     implementations with limits on what needs to be prefetched and thereby
13318**     reduce network bandwidth.
13319**
13320** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
13321** standard SQLite.  The other hints are provided for extentions that use
13322** the SQLite parser and code generator but substitute their own storage
13323** engine.
13324*/
13325#define BTREE_HINT_RANGE 0       /* Range constraints on queries */
13326
13327/*
13328** Values that may be OR'd together to form the argument to the
13329** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
13330**
13331** The BTREE_BULKLOAD flag is set on index cursors when the index is going
13332** to be filled with content that is already in sorted order.
13333**
13334** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
13335** OP_SeekLE opcodes for a range search, but where the range of entries
13336** selected will all have the same key.  In other words, the cursor will
13337** be used only for equality key searches.
13338**
13339*/
13340#define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
13341#define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
13342
13343/*
13344** Flags passed as the third argument to sqlite3BtreeCursor().
13345**
13346** For read-only cursors the wrFlag argument is always zero. For read-write
13347** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
13348** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
13349** only be used by SQLite for the following:
13350**
13351**   * to seek to and then delete specific entries, and/or
13352**
13353**   * to read values that will be used to create keys that other
13354**     BTREE_FORDELETE cursors will seek to and delete.
13355**
13356** The BTREE_FORDELETE flag is an optimization hint.  It is not used by
13357** by this, the native b-tree engine of SQLite, but it is available to
13358** alternative storage engines that might be substituted in place of this
13359** b-tree system.  For alternative storage engines in which a delete of
13360** the main table row automatically deletes corresponding index rows,
13361** the FORDELETE flag hint allows those alternative storage engines to
13362** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK
13363** and DELETE operations as no-ops, and any READ operation against a
13364** FORDELETE cursor may return a null row: 0x01 0x00.
13365*/
13366#define BTREE_WRCSR     0x00000004     /* read-write cursor */
13367#define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */
13368
13369SQLITE_PRIVATE int sqlite3BtreeCursor(
13370  Btree*,                              /* BTree containing table to open */
13371  int iTable,                          /* Index of root page */
13372  int wrFlag,                          /* 1 for writing.  0 for read-only */
13373  struct KeyInfo*,                     /* First argument to compare function */
13374  BtCursor *pCursor                    /* Space to write cursor structure */
13375);
13376SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
13377SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
13378SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
13379#ifdef SQLITE_ENABLE_CURSOR_HINTS
13380SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
13381#endif
13382
13383SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
13384SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
13385  BtCursor*,
13386  UnpackedRecord *pUnKey,
13387  i64 intKey,
13388  int bias,
13389  int *pRes
13390);
13391SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
13392SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
13393SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
13394
13395/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
13396#define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
13397#define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
13398#define BTREE_APPEND       0x08  /* Insert is likely an append */
13399
13400/* An instance of the BtreePayload object describes the content of a single
13401** entry in either an index or table btree.
13402**
13403** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
13404** an arbitrary key and no data.  These btrees have pKey,nKey set to their
13405** key and pData,nData,nZero set to zero.
13406**
13407** Table btrees (used for rowid tables) contain an integer rowid used as
13408** the key and passed in the nKey field.  The pKey field is zero.
13409** pData,nData hold the content of the new entry.  nZero extra zero bytes
13410** are appended to the end of the content when constructing the entry.
13411**
13412** This object is used to pass information into sqlite3BtreeInsert().  The
13413** same information used to be passed as five separate parameters.  But placing
13414** the information into this object helps to keep the interface more
13415** organized and understandable, and it also helps the resulting code to
13416** run a little faster by using fewer registers for parameter passing.
13417*/
13418struct BtreePayload {
13419  const void *pKey;       /* Key content for indexes.  NULL for tables */
13420  sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
13421  const void *pData;      /* Data for tables.  NULL for indexes */
13422  sqlite3_value *aMem;    /* First of nMem value in the unpacked pKey */
13423  u16 nMem;               /* Number of aMem[] value.  Might be zero */
13424  int nData;              /* Size of pData.  0 if none. */
13425  int nZero;              /* Extra zero data appended after pData,nData */
13426};
13427
13428SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
13429                       int flags, int seekResult);
13430SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
13431SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
13432SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
13433SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
13434SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
13435SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
13436SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
13437SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
13438SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
13439
13440SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
13441SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
13442SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
13443
13444#ifndef SQLITE_OMIT_INCRBLOB
13445SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
13446SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
13447SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
13448#endif
13449SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
13450SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
13451SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
13452SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
13453SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
13454
13455#ifndef NDEBUG
13456SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
13457#endif
13458SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
13459
13460#ifndef SQLITE_OMIT_BTREECOUNT
13461SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
13462#endif
13463
13464#ifdef SQLITE_TEST
13465SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
13466SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
13467#endif
13468
13469#ifndef SQLITE_OMIT_WAL
13470SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
13471#endif
13472
13473/*
13474** If we are not using shared cache, then there is no need to
13475** use mutexes to access the BtShared structures.  So make the
13476** Enter and Leave procedures no-ops.
13477*/
13478#ifndef SQLITE_OMIT_SHARED_CACHE
13479SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
13480SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
13481SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
13482SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
13483SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
13484#else
13485# define sqlite3BtreeEnter(X)
13486# define sqlite3BtreeEnterAll(X)
13487# define sqlite3BtreeSharable(X) 0
13488# define sqlite3BtreeEnterCursor(X)
13489# define sqlite3BtreeConnectionCount(X) 1
13490#endif
13491
13492#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
13493SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
13494SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
13495SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
13496#ifndef NDEBUG
13497  /* These routines are used inside assert() statements only. */
13498SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
13499SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
13500SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
13501#endif
13502#else
13503
13504# define sqlite3BtreeLeave(X)
13505# define sqlite3BtreeLeaveCursor(X)
13506# define sqlite3BtreeLeaveAll(X)
13507
13508# define sqlite3BtreeHoldsMutex(X) 1
13509# define sqlite3BtreeHoldsAllMutexes(X) 1
13510# define sqlite3SchemaMutexHeld(X,Y,Z) 1
13511#endif
13512
13513
13514#endif /* SQLITE_BTREE_H */
13515
13516/************** End of btree.h ***********************************************/
13517/************** Continuing where we left off in sqliteInt.h ******************/
13518/************** Include vdbe.h in the middle of sqliteInt.h ******************/
13519/************** Begin file vdbe.h ********************************************/
13520/*
13521** 2001 September 15
13522**
13523** The author disclaims copyright to this source code.  In place of
13524** a legal notice, here is a blessing:
13525**
13526**    May you do good and not evil.
13527**    May you find forgiveness for yourself and forgive others.
13528**    May you share freely, never taking more than you give.
13529**
13530*************************************************************************
13531** Header file for the Virtual DataBase Engine (VDBE)
13532**
13533** This header defines the interface to the virtual database engine
13534** or VDBE.  The VDBE implements an abstract machine that runs a
13535** simple program to access and modify the underlying database.
13536*/
13537#ifndef SQLITE_VDBE_H
13538#define SQLITE_VDBE_H
13539/* #include <stdio.h> */
13540
13541/*
13542** A single VDBE is an opaque structure named "Vdbe".  Only routines
13543** in the source file sqliteVdbe.c are allowed to see the insides
13544** of this structure.
13545*/
13546typedef struct Vdbe Vdbe;
13547
13548/*
13549** The names of the following types declared in vdbeInt.h are required
13550** for the VdbeOp definition.
13551*/
13552typedef struct sqlite3_value Mem;
13553typedef struct SubProgram SubProgram;
13554
13555/*
13556** A single instruction of the virtual machine has an opcode
13557** and as many as three operands.  The instruction is recorded
13558** as an instance of the following structure:
13559*/
13560struct VdbeOp {
13561  u8 opcode;          /* What operation to perform */
13562  signed char p4type; /* One of the P4_xxx constants for p4 */
13563  u16 p5;             /* Fifth parameter is an unsigned 16-bit integer */
13564  int p1;             /* First operand */
13565  int p2;             /* Second parameter (often the jump destination) */
13566  int p3;             /* The third parameter */
13567  union p4union {     /* fourth parameter */
13568    int i;                 /* Integer value if p4type==P4_INT32 */
13569    void *p;               /* Generic pointer */
13570    char *z;               /* Pointer to data for string (char array) types */
13571    i64 *pI64;             /* Used when p4type is P4_INT64 */
13572    double *pReal;         /* Used when p4type is P4_REAL */
13573    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
13574    sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
13575    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
13576    Mem *pMem;             /* Used when p4type is P4_MEM */
13577    VTable *pVtab;         /* Used when p4type is P4_VTAB */
13578    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
13579    int *ai;               /* Used when p4type is P4_INTARRAY */
13580    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
13581    Table *pTab;           /* Used when p4type is P4_TABLE */
13582#ifdef SQLITE_ENABLE_CURSOR_HINTS
13583    Expr *pExpr;           /* Used when p4type is P4_EXPR */
13584#endif
13585    int (*xAdvance)(BtCursor *, int);
13586  } p4;
13587#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
13588  char *zComment;          /* Comment to improve readability */
13589#endif
13590#ifdef VDBE_PROFILE
13591  u32 cnt;                 /* Number of times this instruction was executed */
13592  u64 cycles;              /* Total time spent executing this instruction */
13593#endif
13594#ifdef SQLITE_VDBE_COVERAGE
13595  int iSrcLine;            /* Source-code line that generated this opcode */
13596#endif
13597};
13598typedef struct VdbeOp VdbeOp;
13599
13600
13601/*
13602** A sub-routine used to implement a trigger program.
13603*/
13604struct SubProgram {
13605  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
13606  int nOp;                      /* Elements in aOp[] */
13607  int nMem;                     /* Number of memory cells required */
13608  int nCsr;                     /* Number of cursors required */
13609  u8 *aOnce;                    /* Array of OP_Once flags */
13610  void *token;                  /* id that may be used to recursive triggers */
13611  SubProgram *pNext;            /* Next sub-program already visited */
13612};
13613
13614/*
13615** A smaller version of VdbeOp used for the VdbeAddOpList() function because
13616** it takes up less space.
13617*/
13618struct VdbeOpList {
13619  u8 opcode;          /* What operation to perform */
13620  signed char p1;     /* First operand */
13621  signed char p2;     /* Second parameter (often the jump destination) */
13622  signed char p3;     /* Third parameter */
13623};
13624typedef struct VdbeOpList VdbeOpList;
13625
13626/*
13627** Allowed values of VdbeOp.p4type
13628*/
13629#define P4_NOTUSED      0   /* The P4 parameter is not used */
13630#define P4_TRANSIENT    0   /* P4 is a pointer to a transient string */
13631#define P4_STATIC     (-1)  /* Pointer to a static string */
13632#define P4_COLLSEQ    (-2)  /* P4 is a pointer to a CollSeq structure */
13633#define P4_INT32      (-3)  /* P4 is a 32-bit signed integer */
13634#define P4_SUBPROGRAM (-4)  /* P4 is a pointer to a SubProgram structure */
13635#define P4_ADVANCE    (-5)  /* P4 is a pointer to BtreeNext() or BtreePrev() */
13636#define P4_TABLE      (-6)  /* P4 is a pointer to a Table structure */
13637/* Above do not own any resources.  Must free those below */
13638#define P4_FREE_IF_LE (-7)
13639#define P4_DYNAMIC    (-7)  /* Pointer to memory from sqliteMalloc() */
13640#define P4_FUNCDEF    (-8)  /* P4 is a pointer to a FuncDef structure */
13641#define P4_KEYINFO    (-9)  /* P4 is a pointer to a KeyInfo structure */
13642#define P4_EXPR       (-10) /* P4 is a pointer to an Expr tree */
13643#define P4_MEM        (-11) /* P4 is a pointer to a Mem*    structure */
13644#define P4_VTAB       (-12) /* P4 is a pointer to an sqlite3_vtab structure */
13645#define P4_REAL       (-13) /* P4 is a 64-bit floating point value */
13646#define P4_INT64      (-14) /* P4 is a 64-bit signed integer */
13647#define P4_INTARRAY   (-15) /* P4 is a vector of 32-bit integers */
13648#define P4_FUNCCTX    (-16) /* P4 is a pointer to an sqlite3_context object */
13649
13650/* Error message codes for OP_Halt */
13651#define P5_ConstraintNotNull 1
13652#define P5_ConstraintUnique  2
13653#define P5_ConstraintCheck   3
13654#define P5_ConstraintFK      4
13655
13656/*
13657** The Vdbe.aColName array contains 5n Mem structures, where n is the
13658** number of columns of data returned by the statement.
13659*/
13660#define COLNAME_NAME     0
13661#define COLNAME_DECLTYPE 1
13662#define COLNAME_DATABASE 2
13663#define COLNAME_TABLE    3
13664#define COLNAME_COLUMN   4
13665#ifdef SQLITE_ENABLE_COLUMN_METADATA
13666# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
13667#else
13668# ifdef SQLITE_OMIT_DECLTYPE
13669#   define COLNAME_N      1      /* Store only the name */
13670# else
13671#   define COLNAME_N      2      /* Store the name and decltype */
13672# endif
13673#endif
13674
13675/*
13676** The following macro converts a relative address in the p2 field
13677** of a VdbeOp structure into a negative number so that
13678** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
13679** the macro again restores the address.
13680*/
13681#define ADDR(X)  (-1-(X))
13682
13683/*
13684** The makefile scans the vdbe.c source file and creates the "opcodes.h"
13685** header file that defines a number for each opcode used by the VDBE.
13686*/
13687/************** Include opcodes.h in the middle of vdbe.h ********************/
13688/************** Begin file opcodes.h *****************************************/
13689/* Automatically generated.  Do not edit */
13690/* See the tool/mkopcodeh.tcl script for details */
13691#define OP_Savepoint       0
13692#define OP_AutoCommit      1
13693#define OP_Transaction     2
13694#define OP_SorterNext      3
13695#define OP_PrevIfOpen      4
13696#define OP_NextIfOpen      5
13697#define OP_Prev            6
13698#define OP_Next            7
13699#define OP_Checkpoint      8
13700#define OP_JournalMode     9
13701#define OP_Vacuum         10
13702#define OP_VFilter        11 /* synopsis: iplan=r[P3] zplan='P4'           */
13703#define OP_VUpdate        12 /* synopsis: data=r[P3@P2]                    */
13704#define OP_Goto           13
13705#define OP_Gosub          14
13706#define OP_InitCoroutine  15
13707#define OP_Yield          16
13708#define OP_MustBeInt      17
13709#define OP_Jump           18
13710#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
13711#define OP_Once           20
13712#define OP_If             21
13713#define OP_IfNot          22
13714#define OP_IfNullRow      23 /* synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
13715#define OP_SeekLT         24 /* synopsis: key=r[P3@P4]                     */
13716#define OP_SeekLE         25 /* synopsis: key=r[P3@P4]                     */
13717#define OP_SeekGE         26 /* synopsis: key=r[P3@P4]                     */
13718#define OP_SeekGT         27 /* synopsis: key=r[P3@P4]                     */
13719#define OP_NoConflict     28 /* synopsis: key=r[P3@P4]                     */
13720#define OP_NotFound       29 /* synopsis: key=r[P3@P4]                     */
13721#define OP_Found          30 /* synopsis: key=r[P3@P4]                     */
13722#define OP_SeekRowid      31 /* synopsis: intkey=r[P3]                     */
13723#define OP_NotExists      32 /* synopsis: intkey=r[P3]                     */
13724#define OP_Last           33
13725#define OP_IfSmaller      34
13726#define OP_SorterSort     35
13727#define OP_Sort           36
13728#define OP_Rewind         37
13729#define OP_IdxLE          38 /* synopsis: key=r[P3@P4]                     */
13730#define OP_IdxGT          39 /* synopsis: key=r[P3@P4]                     */
13731#define OP_IdxLT          40 /* synopsis: key=r[P3@P4]                     */
13732#define OP_IdxGE          41 /* synopsis: key=r[P3@P4]                     */
13733#define OP_RowSetRead     42 /* synopsis: r[P3]=rowset(P1)                 */
13734#define OP_RowSetTest     43 /* synopsis: if r[P3] in rowset(P1) goto P2   */
13735#define OP_Program        44
13736#define OP_FkIfZero       45 /* synopsis: if fkctr[P1]==0 goto P2          */
13737#define OP_IfPos          46 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
13738#define OP_IfNotZero      47 /* synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
13739#define OP_DecrJumpZero   48 /* synopsis: if (--r[P1])==0 goto P2          */
13740#define OP_IncrVacuum     49
13741#define OP_VNext          50
13742#define OP_Init           51 /* synopsis: Start at P2                      */
13743#define OP_Return         52
13744#define OP_EndCoroutine   53
13745#define OP_HaltIfNull     54 /* synopsis: if r[P3]=null halt               */
13746#define OP_Halt           55
13747#define OP_Integer        56 /* synopsis: r[P2]=P1                         */
13748#define OP_Int64          57 /* synopsis: r[P2]=P4                         */
13749#define OP_String         58 /* synopsis: r[P2]='P4' (len=P1)              */
13750#define OP_Null           59 /* synopsis: r[P2..P3]=NULL                   */
13751#define OP_SoftNull       60 /* synopsis: r[P1]=NULL                       */
13752#define OP_Blob           61 /* synopsis: r[P2]=P4 (len=P1)                */
13753#define OP_Variable       62 /* synopsis: r[P2]=parameter(P1,P4)           */
13754#define OP_Move           63 /* synopsis: r[P2@P3]=r[P1@P3]                */
13755#define OP_Copy           64 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
13756#define OP_SCopy          65 /* synopsis: r[P2]=r[P1]                      */
13757#define OP_IntCopy        66 /* synopsis: r[P2]=r[P1]                      */
13758#define OP_ResultRow      67 /* synopsis: output=r[P1@P2]                  */
13759#define OP_CollSeq        68
13760#define OP_AddImm         69 /* synopsis: r[P1]=r[P1]+P2                   */
13761#define OP_Or             70 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
13762#define OP_And            71 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
13763#define OP_RealAffinity   72
13764#define OP_Cast           73 /* synopsis: affinity(r[P1])                  */
13765#define OP_Permutation    74
13766#define OP_IsNull         75 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
13767#define OP_NotNull        76 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
13768#define OP_Ne             77 /* same as TK_NE, synopsis: IF r[P3]!=r[P1]   */
13769#define OP_Eq             78 /* same as TK_EQ, synopsis: IF r[P3]==r[P1]   */
13770#define OP_Gt             79 /* same as TK_GT, synopsis: IF r[P3]>r[P1]    */
13771#define OP_Le             80 /* same as TK_LE, synopsis: IF r[P3]<=r[P1]   */
13772#define OP_Lt             81 /* same as TK_LT, synopsis: IF r[P3]<r[P1]    */
13773#define OP_Ge             82 /* same as TK_GE, synopsis: IF r[P3]>=r[P1]   */
13774#define OP_ElseNotEq      83 /* same as TK_ESCAPE                          */
13775#define OP_BitAnd         84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
13776#define OP_BitOr          85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
13777#define OP_ShiftLeft      86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
13778#define OP_ShiftRight     87 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
13779#define OP_Add            88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
13780#define OP_Subtract       89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
13781#define OP_Multiply       90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
13782#define OP_Divide         91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
13783#define OP_Remainder      92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
13784#define OP_Concat         93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
13785#define OP_Compare        94 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
13786#define OP_BitNot         95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
13787#define OP_Column         96 /* synopsis: r[P3]=PX                         */
13788#define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
13789#define OP_Affinity       98 /* synopsis: affinity(r[P1@P2])               */
13790#define OP_MakeRecord     99 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
13791#define OP_Count         100 /* synopsis: r[P2]=count()                    */
13792#define OP_ReadCookie    101
13793#define OP_SetCookie     102
13794#define OP_ReopenIdx     103 /* synopsis: root=P2 iDb=P3                   */
13795#define OP_OpenRead      104 /* synopsis: root=P2 iDb=P3                   */
13796#define OP_OpenWrite     105 /* synopsis: root=P2 iDb=P3                   */
13797#define OP_OpenDup       106
13798#define OP_OpenAutoindex 107 /* synopsis: nColumn=P2                       */
13799#define OP_OpenEphemeral 108 /* synopsis: nColumn=P2                       */
13800#define OP_SorterOpen    109
13801#define OP_SequenceTest  110 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
13802#define OP_OpenPseudo    111 /* synopsis: P3 columns in r[P2]              */
13803#define OP_Close         112
13804#define OP_ColumnsUsed   113
13805#define OP_Sequence      114 /* synopsis: r[P2]=cursor[P1].ctr++           */
13806#define OP_NewRowid      115 /* synopsis: r[P2]=rowid                      */
13807#define OP_Insert        116 /* synopsis: intkey=r[P3] data=r[P2]          */
13808#define OP_InsertInt     117 /* synopsis: intkey=P3 data=r[P2]             */
13809#define OP_Delete        118
13810#define OP_ResetCount    119
13811#define OP_SorterCompare 120 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
13812#define OP_SorterData    121 /* synopsis: r[P2]=data                       */
13813#define OP_RowData       122 /* synopsis: r[P2]=data                       */
13814#define OP_Rowid         123 /* synopsis: r[P2]=rowid                      */
13815#define OP_NullRow       124
13816#define OP_SorterInsert  125 /* synopsis: key=r[P2]                        */
13817#define OP_IdxInsert     126 /* synopsis: key=r[P2]                        */
13818#define OP_IdxDelete     127 /* synopsis: key=r[P2@P3]                     */
13819#define OP_DeferredSeek  128 /* synopsis: Move P3 to P1.rowid if needed    */
13820#define OP_IdxRowid      129 /* synopsis: r[P2]=rowid                      */
13821#define OP_Destroy       130
13822#define OP_Clear         131
13823#define OP_Real          132 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
13824#define OP_ResetSorter   133
13825#define OP_CreateIndex   134 /* synopsis: r[P2]=root iDb=P1                */
13826#define OP_CreateTable   135 /* synopsis: r[P2]=root iDb=P1                */
13827#define OP_SqlExec       136
13828#define OP_ParseSchema   137
13829#define OP_LoadAnalysis  138
13830#define OP_DropTable     139
13831#define OP_DropIndex     140
13832#define OP_DropTrigger   141
13833#define OP_IntegrityCk   142
13834#define OP_RowSetAdd     143 /* synopsis: rowset(P1)=r[P2]                 */
13835#define OP_Param         144
13836#define OP_FkCounter     145 /* synopsis: fkctr[P1]+=P2                    */
13837#define OP_MemMax        146 /* synopsis: r[P1]=max(r[P1],r[P2])           */
13838#define OP_OffsetLimit   147 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
13839#define OP_AggStep0      148 /* synopsis: accum=r[P3] step(r[P2@P5])       */
13840#define OP_AggStep       149 /* synopsis: accum=r[P3] step(r[P2@P5])       */
13841#define OP_AggFinal      150 /* synopsis: accum=r[P1] N=P2                 */
13842#define OP_Expire        151
13843#define OP_TableLock     152 /* synopsis: iDb=P1 root=P2 write=P3          */
13844#define OP_VBegin        153
13845#define OP_VCreate       154
13846#define OP_VDestroy      155
13847#define OP_VOpen         156
13848#define OP_VColumn       157 /* synopsis: r[P3]=vcolumn(P2)                */
13849#define OP_VRename       158
13850#define OP_Pagecount     159
13851#define OP_MaxPgcnt      160
13852#define OP_PureFunc0     161
13853#define OP_Function0     162 /* synopsis: r[P3]=func(r[P2@P5])             */
13854#define OP_PureFunc      163
13855#define OP_Function      164 /* synopsis: r[P3]=func(r[P2@P5])             */
13856#define OP_CursorHint    165
13857#define OP_Noop          166
13858#define OP_Explain       167
13859
13860/* Properties such as "out2" or "jump" that are specified in
13861** comments following the "case" for each opcode in the vdbe.c
13862** are encoded into bitvectors as follows:
13863*/
13864#define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
13865#define OPFLG_IN1         0x02  /* in1:   P1 is an input */
13866#define OPFLG_IN2         0x04  /* in2:   P2 is an input */
13867#define OPFLG_IN3         0x08  /* in3:   P3 is an input */
13868#define OPFLG_OUT2        0x10  /* out2:  P2 is an output */
13869#define OPFLG_OUT3        0x20  /* out3:  P3 is an output */
13870#define OPFLG_INITIALIZER {\
13871/*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
13872/*   8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
13873/*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
13874/*  24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
13875/*  32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
13876/*  40 */ 0x01, 0x01, 0x23, 0x0b, 0x01, 0x01, 0x03, 0x03,\
13877/*  48 */ 0x03, 0x01, 0x01, 0x01, 0x02, 0x02, 0x08, 0x00,\
13878/*  56 */ 0x10, 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00,\
13879/*  64 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x02, 0x26, 0x26,\
13880/*  72 */ 0x02, 0x02, 0x00, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\
13881/*  80 */ 0x0b, 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26,\
13882/*  88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\
13883/*  96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
13884/* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
13885/* 112 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
13886/* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00,\
13887/* 128 */ 0x00, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10,\
13888/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,\
13889/* 144 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\
13890/* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
13891/* 160 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
13892}
13893
13894/* The sqlite3P2Values() routine is able to run faster if it knows
13895** the value of the largest JUMP opcode.  The smaller the maximum
13896** JUMP opcode the better, so the mkopcodeh.tcl script that
13897** generated this include file strives to group all JUMP opcodes
13898** together near the beginning of the list.
13899*/
13900#define SQLITE_MX_JUMP_OPCODE  83  /* Maximum JUMP opcode */
13901
13902/************** End of opcodes.h *********************************************/
13903/************** Continuing where we left off in vdbe.h ***********************/
13904
13905/*
13906** Additional non-public SQLITE_PREPARE_* flags
13907*/
13908#define SQLITE_PREPARE_SAVESQL  0x80  /* Preserve SQL text */
13909#define SQLITE_PREPARE_MASK     0x0f  /* Mask of public flags */
13910
13911/*
13912** Prototypes for the VDBE interface.  See comments on the implementation
13913** for a description of what each of these routines does.
13914*/
13915SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
13916SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
13917SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
13918SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
13919SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
13920SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
13921SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
13922SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
13923SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
13924SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
13925SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
13926SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
13927#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
13928SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
13929SQLITE_PRIVATE   void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
13930#else
13931# define sqlite3VdbeVerifyNoMallocRequired(A,B)
13932# define sqlite3VdbeVerifyNoResultRow(A)
13933#endif
13934SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
13935SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
13936SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
13937SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
13938SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
13939SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
13940SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
13941SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
13942SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
13943SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
13944SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
13945SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
13946SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
13947SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
13948SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
13949SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
13950SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
13951SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
13952SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
13953SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
13954SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
13955SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
13956SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
13957SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
13958#ifdef SQLITE_DEBUG
13959SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
13960#endif
13961SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
13962SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
13963SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
13964SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
13965SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
13966SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
13967SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
13968SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
13969SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
13970SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
13971SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
13972SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
13973SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
13974#ifndef SQLITE_OMIT_TRACE
13975SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
13976#endif
13977SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13978
13979SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
13980SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
13981SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
13982SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
13983
13984typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
13985SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
13986
13987#ifndef SQLITE_OMIT_TRIGGER
13988SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
13989#endif
13990
13991SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
13992
13993/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
13994** each VDBE opcode.
13995**
13996** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
13997** comments in VDBE programs that show key decision points in the code
13998** generator.
13999*/
14000#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
14001SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
14002# define VdbeComment(X)  sqlite3VdbeComment X
14003SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
14004# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
14005# ifdef SQLITE_ENABLE_MODULE_COMMENTS
14006#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
14007# else
14008#   define VdbeModuleComment(X)
14009# endif
14010#else
14011# define VdbeComment(X)
14012# define VdbeNoopComment(X)
14013# define VdbeModuleComment(X)
14014#endif
14015
14016/*
14017** The VdbeCoverage macros are used to set a coverage testing point
14018** for VDBE branch instructions.  The coverage testing points are line
14019** numbers in the sqlite3.c source file.  VDBE branch coverage testing
14020** only works with an amalagmation build.  That's ok since a VDBE branch
14021** coverage build designed for testing the test suite only.  No application
14022** should ever ship with VDBE branch coverage measuring turned on.
14023**
14024**    VdbeCoverage(v)                  // Mark the previously coded instruction
14025**                                     // as a branch
14026**
14027**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
14028**
14029**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
14030**
14031**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
14032**
14033** Every VDBE branch operation must be tagged with one of the macros above.
14034** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
14035** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
14036** routine in vdbe.c, alerting the developer to the missed tag.
14037*/
14038#ifdef SQLITE_VDBE_COVERAGE
14039SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
14040# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
14041# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
14042# define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
14043# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
14044# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
14045#else
14046# define VdbeCoverage(v)
14047# define VdbeCoverageIf(v,x)
14048# define VdbeCoverageAlwaysTaken(v)
14049# define VdbeCoverageNeverTaken(v)
14050# define VDBE_OFFSET_LINENO(x) 0
14051#endif
14052
14053#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
14054SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
14055#else
14056# define sqlite3VdbeScanStatus(a,b,c,d,e)
14057#endif
14058
14059#endif /* SQLITE_VDBE_H */
14060
14061/************** End of vdbe.h ************************************************/
14062/************** Continuing where we left off in sqliteInt.h ******************/
14063/************** Include pager.h in the middle of sqliteInt.h *****************/
14064/************** Begin file pager.h *******************************************/
14065/*
14066** 2001 September 15
14067**
14068** The author disclaims copyright to this source code.  In place of
14069** a legal notice, here is a blessing:
14070**
14071**    May you do good and not evil.
14072**    May you find forgiveness for yourself and forgive others.
14073**    May you share freely, never taking more than you give.
14074**
14075*************************************************************************
14076** This header file defines the interface that the sqlite page cache
14077** subsystem.  The page cache subsystem reads and writes a file a page
14078** at a time and provides a journal for rollback.
14079*/
14080
14081#ifndef SQLITE_PAGER_H
14082#define SQLITE_PAGER_H
14083
14084/*
14085** Default maximum size for persistent journal files. A negative
14086** value means no limit. This value may be overridden using the
14087** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
14088*/
14089#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
14090  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
14091#endif
14092
14093/*
14094** The type used to represent a page number.  The first page in a file
14095** is called page 1.  0 is used to represent "not a page".
14096*/
14097typedef u32 Pgno;
14098
14099/*
14100** Each open file is managed by a separate instance of the "Pager" structure.
14101*/
14102typedef struct Pager Pager;
14103
14104/*
14105** Handle type for pages.
14106*/
14107typedef struct PgHdr DbPage;
14108
14109/*
14110** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
14111** reserved for working around a windows/posix incompatibility). It is
14112** used in the journal to signify that the remainder of the journal file
14113** is devoted to storing a master journal name - there are no more pages to
14114** roll back. See comments for function writeMasterJournal() in pager.c
14115** for details.
14116*/
14117#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
14118
14119/*
14120** Allowed values for the flags parameter to sqlite3PagerOpen().
14121**
14122** NOTE: These values must match the corresponding BTREE_ values in btree.h.
14123*/
14124#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
14125#define PAGER_MEMORY        0x0002    /* In-memory database */
14126
14127/*
14128** Valid values for the second argument to sqlite3PagerLockingMode().
14129*/
14130#define PAGER_LOCKINGMODE_QUERY      -1
14131#define PAGER_LOCKINGMODE_NORMAL      0
14132#define PAGER_LOCKINGMODE_EXCLUSIVE   1
14133
14134/*
14135** Numeric constants that encode the journalmode.
14136**
14137** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
14138** are exposed in the API via the "PRAGMA journal_mode" command and
14139** therefore cannot be changed without a compatibility break.
14140*/
14141#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
14142#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
14143#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
14144#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
14145#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
14146#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
14147#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
14148
14149/*
14150** Flags that make up the mask passed to sqlite3PagerGet().
14151*/
14152#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
14153#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
14154
14155/*
14156** Flags for sqlite3PagerSetFlags()
14157**
14158** Value constraints (enforced via assert()):
14159**    PAGER_FULLFSYNC      == SQLITE_FullFSync
14160**    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
14161**    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
14162*/
14163#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
14164#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
14165#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
14166#define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
14167#define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
14168#define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
14169#define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
14170#define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
14171#define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
14172
14173/*
14174** The remainder of this file contains the declarations of the functions
14175** that make up the Pager sub-system API. See source code comments for
14176** a detailed description of each routine.
14177*/
14178
14179/* Open and close a Pager connection. */
14180SQLITE_PRIVATE int sqlite3PagerOpen(
14181  sqlite3_vfs*,
14182  Pager **ppPager,
14183  const char*,
14184  int,
14185  int,
14186  int,
14187  void(*)(DbPage*)
14188);
14189SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
14190SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
14191
14192/* Functions used to configure a Pager object. */
14193SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
14194SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
14195#ifdef SQLITE_HAS_CODEC
14196SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
14197#endif
14198SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
14199SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
14200SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
14201SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
14202SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
14203SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
14204SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
14205SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
14206SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
14207SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
14208SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
14209SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
14210SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
14211
14212/* Functions used to obtain and release page references. */
14213SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
14214SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
14215SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
14216SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
14217SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
14218
14219/* Operations on page references. */
14220SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
14221SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
14222SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
14223SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
14224SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
14225SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
14226
14227/* Functions used to manage pager transactions and savepoints. */
14228SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
14229SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
14230SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
14231SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
14232SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
14233SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
14234SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
14235SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
14236SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
14237SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
14238
14239#ifndef SQLITE_OMIT_WAL
14240SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
14241SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
14242SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
14243SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
14244SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
14245# ifdef SQLITE_DIRECT_OVERFLOW_READ
14246SQLITE_PRIVATE   int sqlite3PagerUseWal(Pager *pPager, Pgno);
14247# endif
14248# ifdef SQLITE_ENABLE_SNAPSHOT
14249SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
14250SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
14251SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
14252# endif
14253#else
14254# define sqlite3PagerUseWal(x,y) 0
14255#endif
14256
14257#ifdef SQLITE_ENABLE_ZIPVFS
14258SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
14259#endif
14260
14261/* Functions used to query pager state and configuration. */
14262SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
14263SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
14264#ifdef SQLITE_DEBUG
14265SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
14266#endif
14267SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
14268SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
14269SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
14270SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
14271SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
14272SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
14273SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
14274SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
14275SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
14276SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
14277SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
14278
14279/* Functions used to truncate the database file. */
14280SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
14281
14282SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
14283
14284#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
14285SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
14286#endif
14287
14288/* Functions to support testing and debugging. */
14289#if !defined(NDEBUG) || defined(SQLITE_TEST)
14290SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
14291SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
14292#endif
14293#ifdef SQLITE_TEST
14294SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
14295SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
14296  void disable_simulated_io_errors(void);
14297  void enable_simulated_io_errors(void);
14298#else
14299# define disable_simulated_io_errors()
14300# define enable_simulated_io_errors()
14301#endif
14302
14303#endif /* SQLITE_PAGER_H */
14304
14305/************** End of pager.h ***********************************************/
14306/************** Continuing where we left off in sqliteInt.h ******************/
14307/************** Include pcache.h in the middle of sqliteInt.h ****************/
14308/************** Begin file pcache.h ******************************************/
14309/*
14310** 2008 August 05
14311**
14312** The author disclaims copyright to this source code.  In place of
14313** a legal notice, here is a blessing:
14314**
14315**    May you do good and not evil.
14316**    May you find forgiveness for yourself and forgive others.
14317**    May you share freely, never taking more than you give.
14318**
14319*************************************************************************
14320** This header file defines the interface that the sqlite page cache
14321** subsystem.
14322*/
14323
14324#ifndef _PCACHE_H_
14325
14326typedef struct PgHdr PgHdr;
14327typedef struct PCache PCache;
14328
14329/*
14330** Every page in the cache is controlled by an instance of the following
14331** structure.
14332*/
14333struct PgHdr {
14334  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
14335  void *pData;                   /* Page data */
14336  void *pExtra;                  /* Extra content */
14337  PCache *pCache;                /* PRIVATE: Cache that owns this page */
14338  PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
14339  Pager *pPager;                 /* The pager this page is part of */
14340  Pgno pgno;                     /* Page number for this page */
14341#ifdef SQLITE_CHECK_PAGES
14342  u32 pageHash;                  /* Hash of page content */
14343#endif
14344  u16 flags;                     /* PGHDR flags defined below */
14345
14346  /**********************************************************************
14347  ** Elements above, except pCache, are public.  All that follow are
14348  ** private to pcache.c and should not be accessed by other modules.
14349  ** pCache is grouped with the public elements for efficiency.
14350  */
14351  i16 nRef;                      /* Number of users of this page */
14352  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
14353  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
14354};
14355
14356/* Bit values for PgHdr.flags */
14357#define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
14358#define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
14359#define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
14360#define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
14361                                     ** writing this page to the database */
14362#define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
14363#define PGHDR_MMAP            0x020  /* This is an mmap page object */
14364
14365#define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */
14366
14367/* Initialize and shutdown the page cache subsystem */
14368SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
14369SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
14370
14371/* Page cache buffer management:
14372** These routines implement SQLITE_CONFIG_PAGECACHE.
14373*/
14374SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
14375
14376/* Create a new pager cache.
14377** Under memory stress, invoke xStress to try to make pages clean.
14378** Only clean and unpinned pages can be reclaimed.
14379*/
14380SQLITE_PRIVATE int sqlite3PcacheOpen(
14381  int szPage,                    /* Size of every page */
14382  int szExtra,                   /* Extra space associated with each page */
14383  int bPurgeable,                /* True if pages are on backing store */
14384  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
14385  void *pStress,                 /* Argument to xStress */
14386  PCache *pToInit                /* Preallocated space for the PCache */
14387);
14388
14389/* Modify the page-size after the cache has been created. */
14390SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
14391
14392/* Return the size in bytes of a PCache object.  Used to preallocate
14393** storage space.
14394*/
14395SQLITE_PRIVATE int sqlite3PcacheSize(void);
14396
14397/* One release per successful fetch.  Page is pinned until released.
14398** Reference counted.
14399*/
14400SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
14401SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
14402SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
14403SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
14404
14405SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
14406SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
14407SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
14408SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
14409SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
14410
14411/* Change a page number.  Used by incr-vacuum. */
14412SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
14413
14414/* Remove all pages with pgno>x.  Reset the cache if x==0 */
14415SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
14416
14417/* Get a list of all dirty pages in the cache, sorted by page number */
14418SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
14419
14420/* Reset and close the cache object */
14421SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
14422
14423/* Clear flags from pages of the page cache */
14424SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
14425
14426/* Discard the contents of the cache */
14427SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
14428
14429/* Return the total number of outstanding page references */
14430SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
14431
14432/* Increment the reference count of an existing page */
14433SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
14434
14435SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
14436
14437/* Return the total number of pages stored in the cache */
14438SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
14439
14440#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
14441/* Iterate through all dirty pages currently stored in the cache. This
14442** interface is only available if SQLITE_CHECK_PAGES is defined when the
14443** library is built.
14444*/
14445SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
14446#endif
14447
14448#if defined(SQLITE_DEBUG)
14449/* Check invariants on a PgHdr object */
14450SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
14451#endif
14452
14453/* Set and get the suggested cache-size for the specified pager-cache.
14454**
14455** If no global maximum is configured, then the system attempts to limit
14456** the total number of pages cached by purgeable pager-caches to the sum
14457** of the suggested cache-sizes.
14458*/
14459SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
14460#ifdef SQLITE_TEST
14461SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
14462#endif
14463
14464/* Set or get the suggested spill-size for the specified pager-cache.
14465**
14466** The spill-size is the minimum number of pages in cache before the cache
14467** will attempt to spill dirty pages by calling xStress.
14468*/
14469SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
14470
14471/* Free up as much memory as possible from the page cache */
14472SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
14473
14474#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
14475/* Try to return memory used by the pcache module to the main memory heap */
14476SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
14477#endif
14478
14479#ifdef SQLITE_TEST
14480SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
14481#endif
14482
14483SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
14484
14485/* Return the header size */
14486SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
14487SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
14488
14489/* Number of dirty pages as a percentage of the configured cache size */
14490SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
14491
14492#endif /* _PCACHE_H_ */
14493
14494/************** End of pcache.h **********************************************/
14495/************** Continuing where we left off in sqliteInt.h ******************/
14496/************** Include os.h in the middle of sqliteInt.h ********************/
14497/************** Begin file os.h **********************************************/
14498/*
14499** 2001 September 16
14500**
14501** The author disclaims copyright to this source code.  In place of
14502** a legal notice, here is a blessing:
14503**
14504**    May you do good and not evil.
14505**    May you find forgiveness for yourself and forgive others.
14506**    May you share freely, never taking more than you give.
14507**
14508******************************************************************************
14509**
14510** This header file (together with is companion C source-code file
14511** "os.c") attempt to abstract the underlying operating system so that
14512** the SQLite library will work on both POSIX and windows systems.
14513**
14514** This header file is #include-ed by sqliteInt.h and thus ends up
14515** being included by every source file.
14516*/
14517#ifndef _SQLITE_OS_H_
14518#define _SQLITE_OS_H_
14519
14520/*
14521** Attempt to automatically detect the operating system and setup the
14522** necessary pre-processor macros for it.
14523*/
14524/************** Include os_setup.h in the middle of os.h *********************/
14525/************** Begin file os_setup.h ****************************************/
14526/*
14527** 2013 November 25
14528**
14529** The author disclaims copyright to this source code.  In place of
14530** a legal notice, here is a blessing:
14531**
14532**    May you do good and not evil.
14533**    May you find forgiveness for yourself and forgive others.
14534**    May you share freely, never taking more than you give.
14535**
14536******************************************************************************
14537**
14538** This file contains pre-processor directives related to operating system
14539** detection and/or setup.
14540*/
14541#ifndef SQLITE_OS_SETUP_H
14542#define SQLITE_OS_SETUP_H
14543
14544/*
14545** Figure out if we are dealing with Unix, Windows, or some other operating
14546** system.
14547**
14548** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
14549** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
14550** the three will be 1.  The other two will be 0.
14551*/
14552#if defined(SQLITE_OS_OTHER)
14553#  if SQLITE_OS_OTHER==1
14554#    undef SQLITE_OS_UNIX
14555#    define SQLITE_OS_UNIX 0
14556#    undef SQLITE_OS_WIN
14557#    define SQLITE_OS_WIN 0
14558#  else
14559#    undef SQLITE_OS_OTHER
14560#  endif
14561#endif
14562#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
14563#  define SQLITE_OS_OTHER 0
14564#  ifndef SQLITE_OS_WIN
14565#    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
14566        defined(__MINGW32__) || defined(__BORLANDC__)
14567#      define SQLITE_OS_WIN 1
14568#      define SQLITE_OS_UNIX 0
14569#    else
14570#      define SQLITE_OS_WIN 0
14571#      define SQLITE_OS_UNIX 1
14572#    endif
14573#  else
14574#    define SQLITE_OS_UNIX 0
14575#  endif
14576#else
14577#  ifndef SQLITE_OS_WIN
14578#    define SQLITE_OS_WIN 0
14579#  endif
14580#endif
14581
14582#endif /* SQLITE_OS_SETUP_H */
14583
14584/************** End of os_setup.h ********************************************/
14585/************** Continuing where we left off in os.h *************************/
14586
14587/* If the SET_FULLSYNC macro is not defined above, then make it
14588** a no-op
14589*/
14590#ifndef SET_FULLSYNC
14591# define SET_FULLSYNC(x,y)
14592#endif
14593
14594/*
14595** The default size of a disk sector
14596*/
14597#ifndef SQLITE_DEFAULT_SECTOR_SIZE
14598# define SQLITE_DEFAULT_SECTOR_SIZE 4096
14599#endif
14600
14601/*
14602** Temporary files are named starting with this prefix followed by 16 random
14603** alphanumeric characters, and no file extension. They are stored in the
14604** OS's standard temporary file directory, and are deleted prior to exit.
14605** If sqlite is being embedded in another program, you may wish to change the
14606** prefix to reflect your program's name, so that if your program exits
14607** prematurely, old temporary files can be easily identified. This can be done
14608** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
14609**
14610** 2006-10-31:  The default prefix used to be "sqlite_".  But then
14611** Mcafee started using SQLite in their anti-virus product and it
14612** started putting files with the "sqlite" name in the c:/temp folder.
14613** This annoyed many windows users.  Those users would then do a
14614** Google search for "sqlite", find the telephone numbers of the
14615** developers and call to wake them up at night and complain.
14616** For this reason, the default name prefix is changed to be "sqlite"
14617** spelled backwards.  So the temp files are still identified, but
14618** anybody smart enough to figure out the code is also likely smart
14619** enough to know that calling the developer will not help get rid
14620** of the file.
14621*/
14622#ifndef SQLITE_TEMP_FILE_PREFIX
14623# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
14624#endif
14625
14626/*
14627** The following values may be passed as the second argument to
14628** sqlite3OsLock(). The various locks exhibit the following semantics:
14629**
14630** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
14631** RESERVED:  A single process may hold a RESERVED lock on a file at
14632**            any time. Other processes may hold and obtain new SHARED locks.
14633** PENDING:   A single process may hold a PENDING lock on a file at
14634**            any one time. Existing SHARED locks may persist, but no new
14635**            SHARED locks may be obtained by other processes.
14636** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
14637**
14638** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
14639** process that requests an EXCLUSIVE lock may actually obtain a PENDING
14640** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
14641** sqlite3OsLock().
14642*/
14643#define NO_LOCK         0
14644#define SHARED_LOCK     1
14645#define RESERVED_LOCK   2
14646#define PENDING_LOCK    3
14647#define EXCLUSIVE_LOCK  4
14648
14649/*
14650** File Locking Notes:  (Mostly about windows but also some info for Unix)
14651**
14652** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
14653** those functions are not available.  So we use only LockFile() and
14654** UnlockFile().
14655**
14656** LockFile() prevents not just writing but also reading by other processes.
14657** A SHARED_LOCK is obtained by locking a single randomly-chosen
14658** byte out of a specific range of bytes. The lock byte is obtained at
14659** random so two separate readers can probably access the file at the
14660** same time, unless they are unlucky and choose the same lock byte.
14661** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
14662** There can only be one writer.  A RESERVED_LOCK is obtained by locking
14663** a single byte of the file that is designated as the reserved lock byte.
14664** A PENDING_LOCK is obtained by locking a designated byte different from
14665** the RESERVED_LOCK byte.
14666**
14667** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
14668** which means we can use reader/writer locks.  When reader/writer locks
14669** are used, the lock is placed on the same range of bytes that is used
14670** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
14671** will support two or more Win95 readers or two or more WinNT readers.
14672** But a single Win95 reader will lock out all WinNT readers and a single
14673** WinNT reader will lock out all other Win95 readers.
14674**
14675** The following #defines specify the range of bytes used for locking.
14676** SHARED_SIZE is the number of bytes available in the pool from which
14677** a random byte is selected for a shared lock.  The pool of bytes for
14678** shared locks begins at SHARED_FIRST.
14679**
14680** The same locking strategy and
14681** byte ranges are used for Unix.  This leaves open the possibility of having
14682** clients on win95, winNT, and unix all talking to the same shared file
14683** and all locking correctly.  To do so would require that samba (or whatever
14684** tool is being used for file sharing) implements locks correctly between
14685** windows and unix.  I'm guessing that isn't likely to happen, but by
14686** using the same locking range we are at least open to the possibility.
14687**
14688** Locking in windows is manditory.  For this reason, we cannot store
14689** actual data in the bytes used for locking.  The pager never allocates
14690** the pages involved in locking therefore.  SHARED_SIZE is selected so
14691** that all locks will fit on a single page even at the minimum page size.
14692** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
14693** is set high so that we don't have to allocate an unused page except
14694** for very large databases.  But one should test the page skipping logic
14695** by setting PENDING_BYTE low and running the entire regression suite.
14696**
14697** Changing the value of PENDING_BYTE results in a subtly incompatible
14698** file format.  Depending on how it is changed, you might not notice
14699** the incompatibility right away, even running a full regression test.
14700** The default location of PENDING_BYTE is the first byte past the
14701** 1GB boundary.
14702**
14703*/
14704#ifdef SQLITE_OMIT_WSD
14705# define PENDING_BYTE     (0x40000000)
14706#else
14707# define PENDING_BYTE      sqlite3PendingByte
14708#endif
14709#define RESERVED_BYTE     (PENDING_BYTE+1)
14710#define SHARED_FIRST      (PENDING_BYTE+2)
14711#define SHARED_SIZE       510
14712
14713/*
14714** Wrapper around OS specific sqlite3_os_init() function.
14715*/
14716SQLITE_PRIVATE int sqlite3OsInit(void);
14717
14718/*
14719** Functions for accessing sqlite3_file methods
14720*/
14721SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
14722SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
14723SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
14724SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
14725SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
14726SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
14727SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
14728SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
14729SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
14730SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
14731SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
14732#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
14733SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
14734SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
14735SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
14736SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
14737SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
14738SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
14739SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
14740SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
14741
14742
14743/*
14744** Functions for accessing sqlite3_vfs methods
14745*/
14746SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
14747SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
14748SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
14749SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
14750#ifndef SQLITE_OMIT_LOAD_EXTENSION
14751SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
14752SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
14753SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
14754SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
14755#endif /* SQLITE_OMIT_LOAD_EXTENSION */
14756SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
14757SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
14758SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
14759SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
14760
14761/*
14762** Convenience functions for opening and closing files using
14763** sqlite3_malloc() to obtain space for the file-handle structure.
14764*/
14765SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
14766SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
14767
14768#endif /* _SQLITE_OS_H_ */
14769
14770/************** End of os.h **************************************************/
14771/************** Continuing where we left off in sqliteInt.h ******************/
14772/************** Include mutex.h in the middle of sqliteInt.h *****************/
14773/************** Begin file mutex.h *******************************************/
14774/*
14775** 2007 August 28
14776**
14777** The author disclaims copyright to this source code.  In place of
14778** a legal notice, here is a blessing:
14779**
14780**    May you do good and not evil.
14781**    May you find forgiveness for yourself and forgive others.
14782**    May you share freely, never taking more than you give.
14783**
14784*************************************************************************
14785**
14786** This file contains the common header for all mutex implementations.
14787** The sqliteInt.h header #includes this file so that it is available
14788** to all source files.  We break it out in an effort to keep the code
14789** better organized.
14790**
14791** NOTE:  source files should *not* #include this header file directly.
14792** Source files should #include the sqliteInt.h file and let that file
14793** include this one indirectly.
14794*/
14795
14796
14797/*
14798** Figure out what version of the code to use.  The choices are
14799**
14800**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
14801**                             mutexes implementation cannot be overridden
14802**                             at start-time.
14803**
14804**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
14805**                             mutual exclusion is provided.  But this
14806**                             implementation can be overridden at
14807**                             start-time.
14808**
14809**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
14810**
14811**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
14812*/
14813#if !SQLITE_THREADSAFE
14814# define SQLITE_MUTEX_OMIT
14815#endif
14816#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
14817#  if SQLITE_OS_UNIX
14818#    define SQLITE_MUTEX_PTHREADS
14819#  elif SQLITE_OS_WIN
14820#    define SQLITE_MUTEX_W32
14821#  else
14822#    define SQLITE_MUTEX_NOOP
14823#  endif
14824#endif
14825
14826#ifdef SQLITE_MUTEX_OMIT
14827/*
14828** If this is a no-op implementation, implement everything as macros.
14829*/
14830#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
14831#define sqlite3_mutex_free(X)
14832#define sqlite3_mutex_enter(X)
14833#define sqlite3_mutex_try(X)      SQLITE_OK
14834#define sqlite3_mutex_leave(X)
14835#define sqlite3_mutex_held(X)     ((void)(X),1)
14836#define sqlite3_mutex_notheld(X)  ((void)(X),1)
14837#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
14838#define sqlite3MutexInit()        SQLITE_OK
14839#define sqlite3MutexEnd()
14840#define MUTEX_LOGIC(X)
14841#else
14842#define MUTEX_LOGIC(X)            X
14843#endif /* defined(SQLITE_MUTEX_OMIT) */
14844
14845/************** End of mutex.h ***********************************************/
14846/************** Continuing where we left off in sqliteInt.h ******************/
14847
14848/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
14849** synchronous setting to EXTRA.  It is no longer supported.
14850*/
14851#ifdef SQLITE_EXTRA_DURABLE
14852# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
14853# define SQLITE_DEFAULT_SYNCHRONOUS 3
14854#endif
14855
14856/*
14857** Default synchronous levels.
14858**
14859** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
14860** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
14861**
14862**           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
14863**   OFF           1                         0
14864**   NORMAL        2                         1
14865**   FULL          3                         2
14866**   EXTRA         4                         3
14867**
14868** The "PRAGMA synchronous" statement also uses the zero-based numbers.
14869** In other words, the zero-based numbers are used for all external interfaces
14870** and the one-based values are used internally.
14871*/
14872#ifndef SQLITE_DEFAULT_SYNCHRONOUS
14873# define SQLITE_DEFAULT_SYNCHRONOUS 2
14874#endif
14875#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
14876# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
14877#endif
14878
14879/*
14880** Each database file to be accessed by the system is an instance
14881** of the following structure.  There are normally two of these structures
14882** in the sqlite.aDb[] array.  aDb[0] is the main database file and
14883** aDb[1] is the database file used to hold temporary tables.  Additional
14884** databases may be attached.
14885*/
14886struct Db {
14887  char *zDbSName;      /* Name of this database. (schema name, not filename) */
14888  Btree *pBt;          /* The B*Tree structure for this database file */
14889  u8 safety_level;     /* How aggressive at syncing data to disk */
14890  u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
14891  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
14892};
14893
14894/*
14895** An instance of the following structure stores a database schema.
14896**
14897** Most Schema objects are associated with a Btree.  The exception is
14898** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
14899** In shared cache mode, a single Schema object can be shared by multiple
14900** Btrees that refer to the same underlying BtShared object.
14901**
14902** Schema objects are automatically deallocated when the last Btree that
14903** references them is destroyed.   The TEMP Schema is manually freed by
14904** sqlite3_close().
14905*
14906** A thread must be holding a mutex on the corresponding Btree in order
14907** to access Schema content.  This implies that the thread must also be
14908** holding a mutex on the sqlite3 connection pointer that owns the Btree.
14909** For a TEMP Schema, only the connection mutex is required.
14910*/
14911struct Schema {
14912  int schema_cookie;   /* Database schema version number for this file */
14913  int iGeneration;     /* Generation counter.  Incremented with each change */
14914  Hash tblHash;        /* All tables indexed by name */
14915  Hash idxHash;        /* All (named) indices indexed by name */
14916  Hash trigHash;       /* All triggers indexed by name */
14917  Hash fkeyHash;       /* All foreign keys by referenced table name */
14918  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
14919  u8 file_format;      /* Schema format version for this file */
14920  u8 enc;              /* Text encoding used by this database */
14921  u16 schemaFlags;     /* Flags associated with this schema */
14922  int cache_size;      /* Number of pages to use in the cache */
14923};
14924
14925/*
14926** These macros can be used to test, set, or clear bits in the
14927** Db.pSchema->flags field.
14928*/
14929#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
14930#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
14931#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
14932#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
14933
14934/*
14935** Allowed values for the DB.pSchema->flags field.
14936**
14937** The DB_SchemaLoaded flag is set after the database schema has been
14938** read into internal hash tables.
14939**
14940** DB_UnresetViews means that one or more views have column names that
14941** have been filled out.  If the schema changes, these column names might
14942** changes and so the view will need to be reset.
14943*/
14944#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
14945#define DB_UnresetViews    0x0002  /* Some views have defined column names */
14946#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
14947
14948/*
14949** The number of different kinds of things that can be limited
14950** using the sqlite3_limit() interface.
14951*/
14952#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
14953
14954/*
14955** Lookaside malloc is a set of fixed-size buffers that can be used
14956** to satisfy small transient memory allocation requests for objects
14957** associated with a particular database connection.  The use of
14958** lookaside malloc provides a significant performance enhancement
14959** (approx 10%) by avoiding numerous malloc/free requests while parsing
14960** SQL statements.
14961**
14962** The Lookaside structure holds configuration information about the
14963** lookaside malloc subsystem.  Each available memory allocation in
14964** the lookaside subsystem is stored on a linked list of LookasideSlot
14965** objects.
14966**
14967** Lookaside allocations are only allowed for objects that are associated
14968** with a particular database connection.  Hence, schema information cannot
14969** be stored in lookaside because in shared cache mode the schema information
14970** is shared by multiple database connections.  Therefore, while parsing
14971** schema information, the Lookaside.bEnabled flag is cleared so that
14972** lookaside allocations are not used to construct the schema objects.
14973*/
14974struct Lookaside {
14975  u32 bDisable;           /* Only operate the lookaside when zero */
14976  u16 sz;                 /* Size of each buffer in bytes */
14977  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
14978  int nOut;               /* Number of buffers currently checked out */
14979  int mxOut;              /* Highwater mark for nOut */
14980  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
14981  LookasideSlot *pFree;   /* List of available buffers */
14982  void *pStart;           /* First byte of available memory space */
14983  void *pEnd;             /* First byte past end of available space */
14984};
14985struct LookasideSlot {
14986  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
14987};
14988
14989/*
14990** A hash table for built-in function definitions.  (Application-defined
14991** functions use a regular table table from hash.h.)
14992**
14993** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
14994** Collisions are on the FuncDef.u.pHash chain.
14995*/
14996#define SQLITE_FUNC_HASH_SZ 23
14997struct FuncDefHash {
14998  FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
14999};
15000
15001#ifdef SQLITE_USER_AUTHENTICATION
15002/*
15003** Information held in the "sqlite3" database connection object and used
15004** to manage user authentication.
15005*/
15006typedef struct sqlite3_userauth sqlite3_userauth;
15007struct sqlite3_userauth {
15008  u8 authLevel;                 /* Current authentication level */
15009  int nAuthPW;                  /* Size of the zAuthPW in bytes */
15010  char *zAuthPW;                /* Password used to authenticate */
15011  char *zAuthUser;              /* User name used to authenticate */
15012};
15013
15014/* Allowed values for sqlite3_userauth.authLevel */
15015#define UAUTH_Unknown     0     /* Authentication not yet checked */
15016#define UAUTH_Fail        1     /* User authentication failed */
15017#define UAUTH_User        2     /* Authenticated as a normal user */
15018#define UAUTH_Admin       3     /* Authenticated as an administrator */
15019
15020/* Functions used only by user authorization logic */
15021SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
15022SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
15023SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
15024SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
15025
15026#endif /* SQLITE_USER_AUTHENTICATION */
15027
15028/*
15029** typedef for the authorization callback function.
15030*/
15031#ifdef SQLITE_USER_AUTHENTICATION
15032  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
15033                               const char*, const char*);
15034#else
15035  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
15036                               const char*);
15037#endif
15038
15039#ifndef SQLITE_OMIT_DEPRECATED
15040/* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
15041** in the style of sqlite3_trace()
15042*/
15043#define SQLITE_TRACE_LEGACY  0x80
15044#else
15045#define SQLITE_TRACE_LEGACY  0
15046#endif /* SQLITE_OMIT_DEPRECATED */
15047
15048
15049/*
15050** Each database connection is an instance of the following structure.
15051*/
15052struct sqlite3 {
15053  sqlite3_vfs *pVfs;            /* OS Interface */
15054  struct Vdbe *pVdbe;           /* List of active virtual machines */
15055  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
15056  sqlite3_mutex *mutex;         /* Connection mutex */
15057  Db *aDb;                      /* All backends */
15058  int nDb;                      /* Number of backends currently in use */
15059  int flags;                    /* Miscellaneous flags. See below */
15060  i64 lastRowid;                /* ROWID of most recent insert (see above) */
15061  i64 szMmap;                   /* Default mmap_size setting */
15062  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
15063  int errCode;                  /* Most recent error code (SQLITE_*) */
15064  int errMask;                  /* & result codes with this before returning */
15065  int iSysErrno;                /* Errno value from last system error */
15066  u16 dbOptFlags;               /* Flags to enable/disable optimizations */
15067  u8 enc;                       /* Text encoding */
15068  u8 autoCommit;                /* The auto-commit flag. */
15069  u8 temp_store;                /* 1: file 2: memory 0: default */
15070  u8 mallocFailed;              /* True if we have seen a malloc failure */
15071  u8 bBenignMalloc;             /* Do not require OOMs if true */
15072  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
15073  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
15074  u8 suppressErr;               /* Do not issue error messages if true */
15075  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
15076  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
15077  u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
15078  u8 skipBtreeMutex;            /* True if no shared-cache backends */
15079  u8 nSqlExec;                  /* Number of pending OP_SqlExec opcodes */
15080  int nextPagesize;             /* Pagesize after VACUUM if >0 */
15081  u32 magic;                    /* Magic number for detect library misuse */
15082  int nChange;                  /* Value returned by sqlite3_changes() */
15083  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
15084  int aLimit[SQLITE_N_LIMIT];   /* Limits */
15085  int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
15086  struct sqlite3InitInfo {      /* Information used during initialization */
15087    int newTnum;                /* Rootpage of table being initialized */
15088    u8 iDb;                     /* Which db file is being initialized */
15089    u8 busy;                    /* TRUE if currently initializing */
15090    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
15091    u8 imposterTable;           /* Building an imposter table */
15092  } init;
15093  int nVdbeActive;              /* Number of VDBEs currently running */
15094  int nVdbeRead;                /* Number of active VDBEs that read or write */
15095  int nVdbeWrite;               /* Number of active VDBEs that read and write */
15096  int nVdbeExec;                /* Number of nested calls to VdbeExec() */
15097  int nVDestroy;                /* Number of active OP_VDestroy operations */
15098  int nExtension;               /* Number of loaded extensions */
15099  void **aExtension;            /* Array of shared library handles */
15100  int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
15101  void *pTraceArg;                          /* Argument to the trace function */
15102  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
15103  void *pProfileArg;                        /* Argument to profile function */
15104  void *pCommitArg;                 /* Argument to xCommitCallback() */
15105  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
15106  void *pRollbackArg;               /* Argument to xRollbackCallback() */
15107  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
15108  void *pUpdateArg;
15109  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
15110#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15111  void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
15112  void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
15113    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
15114  );
15115  PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
15116#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
15117#ifndef SQLITE_OMIT_WAL
15118  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
15119  void *pWalArg;
15120#endif
15121  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
15122  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
15123  void *pCollNeededArg;
15124  sqlite3_value *pErr;          /* Most recent error message */
15125  union {
15126    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
15127    double notUsed1;            /* Spacer */
15128  } u1;
15129  Lookaside lookaside;          /* Lookaside malloc configuration */
15130#ifndef SQLITE_OMIT_AUTHORIZATION
15131  sqlite3_xauth xAuth;          /* Access authorization function */
15132  void *pAuthArg;               /* 1st argument to the access auth function */
15133#endif
15134#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
15135  int (*xProgress)(void *);     /* The progress callback */
15136  void *pProgressArg;           /* Argument to the progress callback */
15137  unsigned nProgressOps;        /* Number of opcodes for progress callback */
15138#endif
15139#ifndef SQLITE_OMIT_VIRTUALTABLE
15140  int nVTrans;                  /* Allocated size of aVTrans */
15141  Hash aModule;                 /* populated by sqlite3_create_module() */
15142  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
15143  VTable **aVTrans;             /* Virtual tables with open transactions */
15144  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
15145#endif
15146  Hash aFunc;                   /* Hash table of connection functions */
15147  Hash aCollSeq;                /* All collating sequences */
15148  BusyHandler busyHandler;      /* Busy callback */
15149  Db aDbStatic[2];              /* Static space for the 2 default backends */
15150  Savepoint *pSavepoint;        /* List of active savepoints */
15151  int busyTimeout;              /* Busy handler timeout, in msec */
15152  int nSavepoint;               /* Number of non-transaction savepoints */
15153  int nStatement;               /* Number of nested statement-transactions  */
15154  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
15155  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
15156  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
15157#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
15158  /* The following variables are all protected by the STATIC_MASTER
15159  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
15160  **
15161  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
15162  ** unlock so that it can proceed.
15163  **
15164  ** When X.pBlockingConnection==Y, that means that something that X tried
15165  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
15166  ** held by Y.
15167  */
15168  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
15169  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
15170  void *pUnlockArg;                     /* Argument to xUnlockNotify */
15171  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
15172  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
15173#endif
15174#ifdef SQLITE_USER_AUTHENTICATION
15175  sqlite3_userauth auth;        /* User authentication information */
15176#endif
15177};
15178
15179/*
15180** A macro to discover the encoding of a database.
15181*/
15182#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
15183#define ENC(db)        ((db)->enc)
15184
15185/*
15186** Possible values for the sqlite3.flags.
15187**
15188** Value constraints (enforced via assert()):
15189**      SQLITE_FullFSync     == PAGER_FULLFSYNC
15190**      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
15191**      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
15192*/
15193#define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_MASTER */
15194#define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */
15195#define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
15196#define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
15197#define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
15198#define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
15199#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
15200#define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
15201                                          /*   DELETE, or UPDATE and return */
15202                                          /*   the count using a callback. */
15203#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
15204                                          /*   result set is empty */
15205#define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
15206#define SQLITE_ReadUncommit   0x00000400  /* READ UNCOMMITTED in shared-cache */
15207#define SQLITE_NoCkptOnClose  0x00000800  /* No checkpoint on close()/DETACH */
15208#define SQLITE_ReverseOrder   0x00001000  /* Reverse unordered SELECTs */
15209#define SQLITE_RecTriggers    0x00002000  /* Enable recursive triggers */
15210#define SQLITE_ForeignKeys    0x00004000  /* Enforce foreign key constraints  */
15211#define SQLITE_AutoIndex      0x00008000  /* Enable automatic indexes */
15212#define SQLITE_LoadExtension  0x00010000  /* Enable load_extension */
15213#define SQLITE_EnableTrigger  0x00020000  /* True to enable triggers */
15214#define SQLITE_DeferFKs       0x00040000  /* Defer all FK constraints */
15215#define SQLITE_QueryOnly      0x00080000  /* Disable database changes */
15216#define SQLITE_CellSizeCk     0x00100000  /* Check btree cell sizes on load */
15217#define SQLITE_Fts3Tokenizer  0x00200000  /* Enable fts3_tokenizer(2) */
15218#define SQLITE_EnableQPSG     0x00400000  /* Query Planner Stability Guarantee */
15219/* The next four values are not used by PRAGMAs or by sqlite3_dbconfig() and
15220** could be factored out into a separate bit vector of the sqlite3 object. */
15221#define SQLITE_InternChanges  0x00800000  /* Uncommitted Hash table changes */
15222#define SQLITE_LoadExtFunc    0x01000000  /* Enable load_extension() SQL func */
15223#define SQLITE_PreferBuiltin  0x02000000  /* Preference to built-in funcs */
15224#define SQLITE_Vacuum         0x04000000  /* Currently in a VACUUM */
15225/* Flags used only if debugging */
15226#ifdef SQLITE_DEBUG
15227#define SQLITE_SqlTrace       0x08000000  /* Debug print SQL as it executes */
15228#define SQLITE_VdbeListing    0x10000000  /* Debug listings of VDBE programs */
15229#define SQLITE_VdbeTrace      0x20000000  /* True to trace VDBE execution */
15230#define SQLITE_VdbeAddopTrace 0x40000000  /* Trace sqlite3VdbeAddOp() calls */
15231#define SQLITE_VdbeEQP        0x80000000  /* Debug EXPLAIN QUERY PLAN */
15232#endif
15233
15234
15235/*
15236** Bits of the sqlite3.dbOptFlags field that are used by the
15237** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
15238** selectively disable various optimizations.
15239*/
15240#define SQLITE_QueryFlattener 0x0001   /* Query flattening */
15241#define SQLITE_ColumnCache    0x0002   /* Column cache */
15242#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
15243#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
15244/*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
15245#define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
15246#define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
15247#define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
15248#define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
15249#define SQLITE_Transitive     0x0200   /* Transitive constraints */
15250#define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
15251#define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
15252#define SQLITE_CountOfView    0x1000   /* The count-of-view optimization */
15253#define SQLITE_CursorHints    0x2000   /* Add OP_CursorHint opcodes */
15254#define SQLITE_AllOpts        0xffff   /* All optimizations */
15255
15256/*
15257** Macros for testing whether or not optimizations are enabled or disabled.
15258*/
15259#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
15260#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
15261
15262/*
15263** Return true if it OK to factor constant expressions into the initialization
15264** code. The argument is a Parse object for the code generator.
15265*/
15266#define ConstFactorOk(P) ((P)->okConstFactor)
15267
15268/*
15269** Possible values for the sqlite.magic field.
15270** The numbers are obtained at random and have no special meaning, other
15271** than being distinct from one another.
15272*/
15273#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
15274#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
15275#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
15276#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
15277#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
15278#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
15279
15280/*
15281** Each SQL function is defined by an instance of the following
15282** structure.  For global built-in functions (ex: substr(), max(), count())
15283** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
15284** For per-connection application-defined functions, a pointer to this
15285** structure is held in the db->aHash hash table.
15286**
15287** The u.pHash field is used by the global built-ins.  The u.pDestructor
15288** field is used by per-connection app-def functions.
15289*/
15290struct FuncDef {
15291  i8 nArg;             /* Number of arguments.  -1 means unlimited */
15292  u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
15293  void *pUserData;     /* User data parameter */
15294  FuncDef *pNext;      /* Next function with same name */
15295  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
15296  void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
15297  const char *zName;   /* SQL name of the function. */
15298  union {
15299    FuncDef *pHash;      /* Next with a different name but the same hash */
15300    FuncDestructor *pDestructor;   /* Reference counted destructor function */
15301  } u;
15302};
15303
15304/*
15305** This structure encapsulates a user-function destructor callback (as
15306** configured using create_function_v2()) and a reference counter. When
15307** create_function_v2() is called to create a function with a destructor,
15308** a single object of this type is allocated. FuncDestructor.nRef is set to
15309** the number of FuncDef objects created (either 1 or 3, depending on whether
15310** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
15311** member of each of the new FuncDef objects is set to point to the allocated
15312** FuncDestructor.
15313**
15314** Thereafter, when one of the FuncDef objects is deleted, the reference
15315** count on this object is decremented. When it reaches 0, the destructor
15316** is invoked and the FuncDestructor structure freed.
15317*/
15318struct FuncDestructor {
15319  int nRef;
15320  void (*xDestroy)(void *);
15321  void *pUserData;
15322};
15323
15324/*
15325** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
15326** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
15327** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
15328** are assert() statements in the code to verify this.
15329**
15330** Value constraints (enforced via assert()):
15331**     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
15332**     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
15333**     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
15334**     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
15335**     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
15336*/
15337#define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
15338#define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
15339#define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
15340#define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
15341#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
15342#define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
15343#define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
15344#define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
15345#define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
15346#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
15347#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
15348#define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
15349#define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
15350                                    ** single query - might change over time */
15351#define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
15352
15353/*
15354** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
15355** used to create the initializers for the FuncDef structures.
15356**
15357**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
15358**     Used to create a scalar function definition of a function zName
15359**     implemented by C function xFunc that accepts nArg arguments. The
15360**     value passed as iArg is cast to a (void*) and made available
15361**     as the user-data (sqlite3_user_data()) for the function. If
15362**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
15363**
15364**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
15365**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
15366**
15367**   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
15368**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
15369**     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
15370**     and functions like sqlite_version() that can change, but not during
15371**     a single query.  The iArg is ignored.  The user-data is always set
15372**     to a NULL pointer.  The bNC parameter is not used.
15373**
15374**   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
15375**     Used for "pure" date/time functions, this macro is like DFUNCTION
15376**     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
15377**     ignored and the user-data for these functions is set to an
15378**     arbitrary non-NULL pointer.  The bNC parameter is not used.
15379**
15380**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
15381**     Used to create an aggregate function definition implemented by
15382**     the C functions xStep and xFinal. The first four parameters
15383**     are interpreted in the same way as the first 4 parameters to
15384**     FUNCTION().
15385**
15386**   LIKEFUNC(zName, nArg, pArg, flags)
15387**     Used to create a scalar function definition of a function zName
15388**     that accepts nArg arguments and is implemented by a call to C
15389**     function likeFunc. Argument pArg is cast to a (void *) and made
15390**     available as the function user-data (sqlite3_user_data()). The
15391**     FuncDef.flags variable is set to the value passed as the flags
15392**     parameter.
15393*/
15394#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
15395  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
15396   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
15397#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
15398  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
15399   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
15400#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
15401  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
15402   0, 0, xFunc, 0, #zName, {0} }
15403#define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
15404  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
15405   (void*)&sqlite3Config, 0, xFunc, 0, #zName, {0} }
15406#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
15407  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
15408   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
15409#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
15410  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
15411   pArg, 0, xFunc, 0, #zName, }
15412#define LIKEFUNC(zName, nArg, arg, flags) \
15413  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
15414   (void *)arg, 0, likeFunc, 0, #zName, {0} }
15415#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
15416  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
15417   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
15418#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
15419  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
15420   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
15421
15422/*
15423** All current savepoints are stored in a linked list starting at
15424** sqlite3.pSavepoint. The first element in the list is the most recently
15425** opened savepoint. Savepoints are added to the list by the vdbe
15426** OP_Savepoint instruction.
15427*/
15428struct Savepoint {
15429  char *zName;                        /* Savepoint name (nul-terminated) */
15430  i64 nDeferredCons;                  /* Number of deferred fk violations */
15431  i64 nDeferredImmCons;               /* Number of deferred imm fk. */
15432  Savepoint *pNext;                   /* Parent savepoint (if any) */
15433};
15434
15435/*
15436** The following are used as the second parameter to sqlite3Savepoint(),
15437** and as the P1 argument to the OP_Savepoint instruction.
15438*/
15439#define SAVEPOINT_BEGIN      0
15440#define SAVEPOINT_RELEASE    1
15441#define SAVEPOINT_ROLLBACK   2
15442
15443
15444/*
15445** Each SQLite module (virtual table definition) is defined by an
15446** instance of the following structure, stored in the sqlite3.aModule
15447** hash table.
15448*/
15449struct Module {
15450  const sqlite3_module *pModule;       /* Callback pointers */
15451  const char *zName;                   /* Name passed to create_module() */
15452  void *pAux;                          /* pAux passed to create_module() */
15453  void (*xDestroy)(void *);            /* Module destructor function */
15454  Table *pEpoTab;                      /* Eponymous table for this module */
15455};
15456
15457/*
15458** information about each column of an SQL table is held in an instance
15459** of this structure.
15460*/
15461struct Column {
15462  char *zName;     /* Name of this column, \000, then the type */
15463  Expr *pDflt;     /* Default value of this column */
15464  char *zColl;     /* Collating sequence.  If NULL, use the default */
15465  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
15466  char affinity;   /* One of the SQLITE_AFF_... values */
15467  u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
15468  u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
15469};
15470
15471/* Allowed values for Column.colFlags:
15472*/
15473#define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
15474#define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
15475#define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
15476
15477/*
15478** A "Collating Sequence" is defined by an instance of the following
15479** structure. Conceptually, a collating sequence consists of a name and
15480** a comparison routine that defines the order of that sequence.
15481**
15482** If CollSeq.xCmp is NULL, it means that the
15483** collating sequence is undefined.  Indices built on an undefined
15484** collating sequence may not be read or written.
15485*/
15486struct CollSeq {
15487  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
15488  u8 enc;               /* Text encoding handled by xCmp() */
15489  void *pUser;          /* First argument to xCmp() */
15490  int (*xCmp)(void*,int, const void*, int, const void*);
15491  void (*xDel)(void*);  /* Destructor for pUser */
15492};
15493
15494/*
15495** A sort order can be either ASC or DESC.
15496*/
15497#define SQLITE_SO_ASC       0  /* Sort in ascending order */
15498#define SQLITE_SO_DESC      1  /* Sort in ascending order */
15499#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
15500
15501/*
15502** Column affinity types.
15503**
15504** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
15505** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
15506** the speed a little by numbering the values consecutively.
15507**
15508** But rather than start with 0 or 1, we begin with 'A'.  That way,
15509** when multiple affinity types are concatenated into a string and
15510** used as the P4 operand, they will be more readable.
15511**
15512** Note also that the numeric types are grouped together so that testing
15513** for a numeric type is a single comparison.  And the BLOB type is first.
15514*/
15515#define SQLITE_AFF_BLOB     'A'
15516#define SQLITE_AFF_TEXT     'B'
15517#define SQLITE_AFF_NUMERIC  'C'
15518#define SQLITE_AFF_INTEGER  'D'
15519#define SQLITE_AFF_REAL     'E'
15520
15521#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
15522
15523/*
15524** The SQLITE_AFF_MASK values masks off the significant bits of an
15525** affinity value.
15526*/
15527#define SQLITE_AFF_MASK     0x47
15528
15529/*
15530** Additional bit values that can be ORed with an affinity without
15531** changing the affinity.
15532**
15533** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
15534** It causes an assert() to fire if either operand to a comparison
15535** operator is NULL.  It is added to certain comparison operators to
15536** prove that the operands are always NOT NULL.
15537*/
15538#define SQLITE_KEEPNULL     0x08  /* Used by vector == or <> */
15539#define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
15540#define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
15541#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
15542#define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
15543
15544/*
15545** An object of this type is created for each virtual table present in
15546** the database schema.
15547**
15548** If the database schema is shared, then there is one instance of this
15549** structure for each database connection (sqlite3*) that uses the shared
15550** schema. This is because each database connection requires its own unique
15551** instance of the sqlite3_vtab* handle used to access the virtual table
15552** implementation. sqlite3_vtab* handles can not be shared between
15553** database connections, even when the rest of the in-memory database
15554** schema is shared, as the implementation often stores the database
15555** connection handle passed to it via the xConnect() or xCreate() method
15556** during initialization internally. This database connection handle may
15557** then be used by the virtual table implementation to access real tables
15558** within the database. So that they appear as part of the callers
15559** transaction, these accesses need to be made via the same database
15560** connection as that used to execute SQL operations on the virtual table.
15561**
15562** All VTable objects that correspond to a single table in a shared
15563** database schema are initially stored in a linked-list pointed to by
15564** the Table.pVTable member variable of the corresponding Table object.
15565** When an sqlite3_prepare() operation is required to access the virtual
15566** table, it searches the list for the VTable that corresponds to the
15567** database connection doing the preparing so as to use the correct
15568** sqlite3_vtab* handle in the compiled query.
15569**
15570** When an in-memory Table object is deleted (for example when the
15571** schema is being reloaded for some reason), the VTable objects are not
15572** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
15573** immediately. Instead, they are moved from the Table.pVTable list to
15574** another linked list headed by the sqlite3.pDisconnect member of the
15575** corresponding sqlite3 structure. They are then deleted/xDisconnected
15576** next time a statement is prepared using said sqlite3*. This is done
15577** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
15578** Refer to comments above function sqlite3VtabUnlockList() for an
15579** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
15580** list without holding the corresponding sqlite3.mutex mutex.
15581**
15582** The memory for objects of this type is always allocated by
15583** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
15584** the first argument.
15585*/
15586struct VTable {
15587  sqlite3 *db;              /* Database connection associated with this table */
15588  Module *pMod;             /* Pointer to module implementation */
15589  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
15590  int nRef;                 /* Number of pointers to this structure */
15591  u8 bConstraint;           /* True if constraints are supported */
15592  int iSavepoint;           /* Depth of the SAVEPOINT stack */
15593  VTable *pNext;            /* Next in linked list (see above) */
15594};
15595
15596/*
15597** The schema for each SQL table and view is represented in memory
15598** by an instance of the following structure.
15599*/
15600struct Table {
15601  char *zName;         /* Name of the table or view */
15602  Column *aCol;        /* Information about each column */
15603  Index *pIndex;       /* List of SQL indexes on this table. */
15604  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
15605  FKey *pFKey;         /* Linked list of all foreign keys in this table */
15606  char *zColAff;       /* String defining the affinity of each column */
15607  ExprList *pCheck;    /* All CHECK constraints */
15608                       /*   ... also used as column name list in a VIEW */
15609  int tnum;            /* Root BTree page for this table */
15610  u32 nTabRef;         /* Number of pointers to this Table */
15611  u32 tabFlags;        /* Mask of TF_* values */
15612  i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
15613  i16 nCol;            /* Number of columns in this table */
15614  LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
15615  LogEst szTabRow;     /* Estimated size of each table row in bytes */
15616#ifdef SQLITE_ENABLE_COSTMULT
15617  LogEst costMult;     /* Cost multiplier for using this table */
15618#endif
15619  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
15620#ifndef SQLITE_OMIT_ALTERTABLE
15621  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
15622#endif
15623#ifndef SQLITE_OMIT_VIRTUALTABLE
15624  int nModuleArg;      /* Number of arguments to the module */
15625  char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
15626  VTable *pVTable;     /* List of VTable objects. */
15627#endif
15628  Trigger *pTrigger;   /* List of triggers stored in pSchema */
15629  Schema *pSchema;     /* Schema that contains this table */
15630  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
15631};
15632
15633/*
15634** Allowed values for Table.tabFlags.
15635**
15636** TF_OOOHidden applies to tables or view that have hidden columns that are
15637** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
15638** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
15639** the TF_OOOHidden attribute would apply in this case.  Such tables require
15640** special handling during INSERT processing.
15641*/
15642#define TF_Readonly        0x0001    /* Read-only system table */
15643#define TF_Ephemeral       0x0002    /* An ephemeral table */
15644#define TF_HasPrimaryKey   0x0004    /* Table has a primary key */
15645#define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */
15646#define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
15647#define TF_WithoutRowid    0x0020    /* No rowid.  PRIMARY KEY is the key */
15648#define TF_NoVisibleRowid  0x0040    /* No user-visible "rowid" column */
15649#define TF_OOOHidden       0x0080    /* Out-of-Order hidden columns */
15650#define TF_StatsUsed       0x0100    /* Query planner decisions affected by
15651                                     ** Index.aiRowLogEst[] values */
15652#define TF_HasNotNull      0x0200    /* Contains NOT NULL constraints */
15653
15654/*
15655** Test to see whether or not a table is a virtual table.  This is
15656** done as a macro so that it will be optimized out when virtual
15657** table support is omitted from the build.
15658*/
15659#ifndef SQLITE_OMIT_VIRTUALTABLE
15660#  define IsVirtual(X)      ((X)->nModuleArg)
15661#else
15662#  define IsVirtual(X)      0
15663#endif
15664
15665/*
15666** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
15667** only works for non-virtual tables (ordinary tables and views) and is
15668** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
15669** IsHiddenColumn() macro is general purpose.
15670*/
15671#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
15672#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
15673#  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
15674#elif !defined(SQLITE_OMIT_VIRTUALTABLE)
15675#  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
15676#  define IsOrdinaryHiddenColumn(X) 0
15677#else
15678#  define IsHiddenColumn(X)         0
15679#  define IsOrdinaryHiddenColumn(X) 0
15680#endif
15681
15682
15683/* Does the table have a rowid */
15684#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
15685#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
15686
15687/*
15688** Each foreign key constraint is an instance of the following structure.
15689**
15690** A foreign key is associated with two tables.  The "from" table is
15691** the table that contains the REFERENCES clause that creates the foreign
15692** key.  The "to" table is the table that is named in the REFERENCES clause.
15693** Consider this example:
15694**
15695**     CREATE TABLE ex1(
15696**       a INTEGER PRIMARY KEY,
15697**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
15698**     );
15699**
15700** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
15701** Equivalent names:
15702**
15703**     from-table == child-table
15704**       to-table == parent-table
15705**
15706** Each REFERENCES clause generates an instance of the following structure
15707** which is attached to the from-table.  The to-table need not exist when
15708** the from-table is created.  The existence of the to-table is not checked.
15709**
15710** The list of all parents for child Table X is held at X.pFKey.
15711**
15712** A list of all children for a table named Z (which might not even exist)
15713** is held in Schema.fkeyHash with a hash key of Z.
15714*/
15715struct FKey {
15716  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
15717  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
15718  char *zTo;        /* Name of table that the key points to (aka: Parent) */
15719  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
15720  FKey *pPrevTo;    /* Previous with the same zTo */
15721  int nCol;         /* Number of columns in this key */
15722  /* EV: R-30323-21917 */
15723  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
15724  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
15725  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
15726  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
15727    int iFrom;            /* Index of column in pFrom */
15728    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
15729  } aCol[1];            /* One entry for each of nCol columns */
15730};
15731
15732/*
15733** SQLite supports many different ways to resolve a constraint
15734** error.  ROLLBACK processing means that a constraint violation
15735** causes the operation in process to fail and for the current transaction
15736** to be rolled back.  ABORT processing means the operation in process
15737** fails and any prior changes from that one operation are backed out,
15738** but the transaction is not rolled back.  FAIL processing means that
15739** the operation in progress stops and returns an error code.  But prior
15740** changes due to the same operation are not backed out and no rollback
15741** occurs.  IGNORE means that the particular row that caused the constraint
15742** error is not inserted or updated.  Processing continues and no error
15743** is returned.  REPLACE means that preexisting database rows that caused
15744** a UNIQUE constraint violation are removed so that the new insert or
15745** update can proceed.  Processing continues and no error is reported.
15746**
15747** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
15748** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
15749** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
15750** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
15751** referenced table row is propagated into the row that holds the
15752** foreign key.
15753**
15754** The following symbolic values are used to record which type
15755** of action to take.
15756*/
15757#define OE_None     0   /* There is no constraint to check */
15758#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
15759#define OE_Abort    2   /* Back out changes but do no rollback transaction */
15760#define OE_Fail     3   /* Stop the operation but leave all prior changes */
15761#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
15762#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
15763
15764#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
15765#define OE_SetNull  7   /* Set the foreign key value to NULL */
15766#define OE_SetDflt  8   /* Set the foreign key value to its default */
15767#define OE_Cascade  9   /* Cascade the changes */
15768
15769#define OE_Default  10  /* Do whatever the default action is */
15770
15771
15772/*
15773** An instance of the following structure is passed as the first
15774** argument to sqlite3VdbeKeyCompare and is used to control the
15775** comparison of the two index keys.
15776**
15777** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
15778** are nField slots for the columns of an index then one extra slot
15779** for the rowid at the end.
15780*/
15781struct KeyInfo {
15782  u32 nRef;           /* Number of references to this KeyInfo object */
15783  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
15784  u16 nField;         /* Number of key columns in the index */
15785  u16 nXField;        /* Number of columns beyond the key columns */
15786  sqlite3 *db;        /* The database connection */
15787  u8 *aSortOrder;     /* Sort order for each column. */
15788  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
15789};
15790
15791/*
15792** This object holds a record which has been parsed out into individual
15793** fields, for the purposes of doing a comparison.
15794**
15795** A record is an object that contains one or more fields of data.
15796** Records are used to store the content of a table row and to store
15797** the key of an index.  A blob encoding of a record is created by
15798** the OP_MakeRecord opcode of the VDBE and is disassembled by the
15799** OP_Column opcode.
15800**
15801** An instance of this object serves as a "key" for doing a search on
15802** an index b+tree. The goal of the search is to find the entry that
15803** is closed to the key described by this object.  This object might hold
15804** just a prefix of the key.  The number of fields is given by
15805** pKeyInfo->nField.
15806**
15807** The r1 and r2 fields are the values to return if this key is less than
15808** or greater than a key in the btree, respectively.  These are normally
15809** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
15810** is in DESC order.
15811**
15812** The key comparison functions actually return default_rc when they find
15813** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
15814** multiple entries in the b-tree with the same key (when only looking
15815** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
15816** cause the search to find the last match, or +1 to cause the search to
15817** find the first match.
15818**
15819** The key comparison functions will set eqSeen to true if they ever
15820** get and equal results when comparing this structure to a b-tree record.
15821** When default_rc!=0, the search might end up on the record immediately
15822** before the first match or immediately after the last match.  The
15823** eqSeen field will indicate whether or not an exact match exists in the
15824** b-tree.
15825*/
15826struct UnpackedRecord {
15827  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
15828  Mem *aMem;          /* Values */
15829  u16 nField;         /* Number of entries in apMem[] */
15830  i8 default_rc;      /* Comparison result if keys are equal */
15831  u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
15832  i8 r1;              /* Value to return if (lhs > rhs) */
15833  i8 r2;              /* Value to return if (rhs < lhs) */
15834  u8 eqSeen;          /* True if an equality comparison has been seen */
15835};
15836
15837
15838/*
15839** Each SQL index is represented in memory by an
15840** instance of the following structure.
15841**
15842** The columns of the table that are to be indexed are described
15843** by the aiColumn[] field of this structure.  For example, suppose
15844** we have the following table and index:
15845**
15846**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
15847**     CREATE INDEX Ex2 ON Ex1(c3,c1);
15848**
15849** In the Table structure describing Ex1, nCol==3 because there are
15850** three columns in the table.  In the Index structure describing
15851** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
15852** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
15853** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
15854** The second column to be indexed (c1) has an index of 0 in
15855** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
15856**
15857** The Index.onError field determines whether or not the indexed columns
15858** must be unique and what to do if they are not.  When Index.onError=OE_None,
15859** it means this is not a unique index.  Otherwise it is a unique index
15860** and the value of Index.onError indicate the which conflict resolution
15861** algorithm to employ whenever an attempt is made to insert a non-unique
15862** element.
15863**
15864** While parsing a CREATE TABLE or CREATE INDEX statement in order to
15865** generate VDBE code (as opposed to parsing one read from an sqlite_master
15866** table as part of parsing an existing database schema), transient instances
15867** of this structure may be created. In this case the Index.tnum variable is
15868** used to store the address of a VDBE instruction, not a database page
15869** number (it cannot - the database page is not allocated until the VDBE
15870** program is executed). See convertToWithoutRowidTable() for details.
15871*/
15872struct Index {
15873  char *zName;             /* Name of this index */
15874  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
15875  LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
15876  Table *pTable;           /* The SQL table being indexed */
15877  char *zColAff;           /* String defining the affinity of each column */
15878  Index *pNext;            /* The next index associated with the same table */
15879  Schema *pSchema;         /* Schema containing this index */
15880  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
15881  const char **azColl;     /* Array of collation sequence names for index */
15882  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
15883  ExprList *aColExpr;      /* Column expressions */
15884  int tnum;                /* DB Page containing root of this index */
15885  LogEst szIdxRow;         /* Estimated average row size in bytes */
15886  u16 nKeyCol;             /* Number of columns forming the key */
15887  u16 nColumn;             /* Number of columns stored in the index */
15888  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
15889  unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
15890  unsigned bUnordered:1;   /* Use this index for == or IN queries only */
15891  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
15892  unsigned isResized:1;    /* True if resizeIndexObject() has been called */
15893  unsigned isCovering:1;   /* True if this is a covering index */
15894  unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
15895  unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
15896#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
15897  int nSample;             /* Number of elements in aSample[] */
15898  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
15899  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
15900  IndexSample *aSample;    /* Samples of the left-most key */
15901  tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
15902  tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
15903#endif
15904};
15905
15906/*
15907** Allowed values for Index.idxType
15908*/
15909#define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
15910#define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
15911#define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
15912
15913/* Return true if index X is a PRIMARY KEY index */
15914#define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
15915
15916/* Return true if index X is a UNIQUE index */
15917#define IsUniqueIndex(X)      ((X)->onError!=OE_None)
15918
15919/* The Index.aiColumn[] values are normally positive integer.  But
15920** there are some negative values that have special meaning:
15921*/
15922#define XN_ROWID     (-1)     /* Indexed column is the rowid */
15923#define XN_EXPR      (-2)     /* Indexed column is an expression */
15924
15925/*
15926** Each sample stored in the sqlite_stat3 table is represented in memory
15927** using a structure of this type.  See documentation at the top of the
15928** analyze.c source file for additional information.
15929*/
15930struct IndexSample {
15931  void *p;          /* Pointer to sampled record */
15932  int n;            /* Size of record in bytes */
15933  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
15934  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
15935  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
15936};
15937
15938/*
15939** Each token coming out of the lexer is an instance of
15940** this structure.  Tokens are also used as part of an expression.
15941**
15942** Note if Token.z==0 then Token.dyn and Token.n are undefined and
15943** may contain random values.  Do not make any assumptions about Token.dyn
15944** and Token.n when Token.z==0.
15945*/
15946struct Token {
15947  const char *z;     /* Text of the token.  Not NULL-terminated! */
15948  unsigned int n;    /* Number of characters in this token */
15949};
15950
15951/*
15952** An instance of this structure contains information needed to generate
15953** code for a SELECT that contains aggregate functions.
15954**
15955** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
15956** pointer to this structure.  The Expr.iColumn field is the index in
15957** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
15958** code for that node.
15959**
15960** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
15961** original Select structure that describes the SELECT statement.  These
15962** fields do not need to be freed when deallocating the AggInfo structure.
15963*/
15964struct AggInfo {
15965  u8 directMode;          /* Direct rendering mode means take data directly
15966                          ** from source tables rather than from accumulators */
15967  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
15968                          ** than the source table */
15969  int sortingIdx;         /* Cursor number of the sorting index */
15970  int sortingIdxPTab;     /* Cursor number of pseudo-table */
15971  int nSortingColumn;     /* Number of columns in the sorting index */
15972  int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
15973  ExprList *pGroupBy;     /* The group by clause */
15974  struct AggInfo_col {    /* For each column used in source tables */
15975    Table *pTab;             /* Source table */
15976    int iTable;              /* Cursor number of the source table */
15977    int iColumn;             /* Column number within the source table */
15978    int iSorterColumn;       /* Column number in the sorting index */
15979    int iMem;                /* Memory location that acts as accumulator */
15980    Expr *pExpr;             /* The original expression */
15981  } *aCol;
15982  int nColumn;            /* Number of used entries in aCol[] */
15983  int nAccumulator;       /* Number of columns that show through to the output.
15984                          ** Additional columns are used only as parameters to
15985                          ** aggregate functions */
15986  struct AggInfo_func {   /* For each aggregate function */
15987    Expr *pExpr;             /* Expression encoding the function */
15988    FuncDef *pFunc;          /* The aggregate function implementation */
15989    int iMem;                /* Memory location that acts as accumulator */
15990    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
15991  } *aFunc;
15992  int nFunc;              /* Number of entries in aFunc[] */
15993};
15994
15995/*
15996** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
15997** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
15998** than 32767 we have to make it 32-bit.  16-bit is preferred because
15999** it uses less memory in the Expr object, which is a big memory user
16000** in systems with lots of prepared statements.  And few applications
16001** need more than about 10 or 20 variables.  But some extreme users want
16002** to have prepared statements with over 32767 variables, and for them
16003** the option is available (at compile-time).
16004*/
16005#if SQLITE_MAX_VARIABLE_NUMBER<=32767
16006typedef i16 ynVar;
16007#else
16008typedef int ynVar;
16009#endif
16010
16011/*
16012** Each node of an expression in the parse tree is an instance
16013** of this structure.
16014**
16015** Expr.op is the opcode. The integer parser token codes are reused
16016** as opcodes here. For example, the parser defines TK_GE to be an integer
16017** code representing the ">=" operator. This same integer code is reused
16018** to represent the greater-than-or-equal-to operator in the expression
16019** tree.
16020**
16021** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
16022** or TK_STRING), then Expr.token contains the text of the SQL literal. If
16023** the expression is a variable (TK_VARIABLE), then Expr.token contains the
16024** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
16025** then Expr.token contains the name of the function.
16026**
16027** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
16028** binary operator. Either or both may be NULL.
16029**
16030** Expr.x.pList is a list of arguments if the expression is an SQL function,
16031** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
16032** Expr.x.pSelect is used if the expression is a sub-select or an expression of
16033** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
16034** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
16035** valid.
16036**
16037** An expression of the form ID or ID.ID refers to a column in a table.
16038** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
16039** the integer cursor number of a VDBE cursor pointing to that table and
16040** Expr.iColumn is the column number for the specific column.  If the
16041** expression is used as a result in an aggregate SELECT, then the
16042** value is also stored in the Expr.iAgg column in the aggregate so that
16043** it can be accessed after all aggregates are computed.
16044**
16045** If the expression is an unbound variable marker (a question mark
16046** character '?' in the original SQL) then the Expr.iTable holds the index
16047** number for that variable.
16048**
16049** If the expression is a subquery then Expr.iColumn holds an integer
16050** register number containing the result of the subquery.  If the
16051** subquery gives a constant result, then iTable is -1.  If the subquery
16052** gives a different answer at different times during statement processing
16053** then iTable is the address of a subroutine that computes the subquery.
16054**
16055** If the Expr is of type OP_Column, and the table it is selecting from
16056** is a disk table or the "old.*" pseudo-table, then pTab points to the
16057** corresponding table definition.
16058**
16059** ALLOCATION NOTES:
16060**
16061** Expr objects can use a lot of memory space in database schema.  To
16062** help reduce memory requirements, sometimes an Expr object will be
16063** truncated.  And to reduce the number of memory allocations, sometimes
16064** two or more Expr objects will be stored in a single memory allocation,
16065** together with Expr.zToken strings.
16066**
16067** If the EP_Reduced and EP_TokenOnly flags are set when
16068** an Expr object is truncated.  When EP_Reduced is set, then all
16069** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
16070** are contained within the same memory allocation.  Note, however, that
16071** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
16072** allocated, regardless of whether or not EP_Reduced is set.
16073*/
16074struct Expr {
16075  u8 op;                 /* Operation performed by this node */
16076  char affinity;         /* The affinity of the column or 0 if not a column */
16077  u32 flags;             /* Various flags.  EP_* See below */
16078  union {
16079    char *zToken;          /* Token value. Zero terminated and dequoted */
16080    int iValue;            /* Non-negative integer value if EP_IntValue */
16081  } u;
16082
16083  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
16084  ** space is allocated for the fields below this point. An attempt to
16085  ** access them will result in a segfault or malfunction.
16086  *********************************************************************/
16087
16088  Expr *pLeft;           /* Left subnode */
16089  Expr *pRight;          /* Right subnode */
16090  union {
16091    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
16092    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
16093  } x;
16094
16095  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
16096  ** space is allocated for the fields below this point. An attempt to
16097  ** access them will result in a segfault or malfunction.
16098  *********************************************************************/
16099
16100#if SQLITE_MAX_EXPR_DEPTH>0
16101  int nHeight;           /* Height of the tree headed by this node */
16102#endif
16103  int iTable;            /* TK_COLUMN: cursor number of table holding column
16104                         ** TK_REGISTER: register number
16105                         ** TK_TRIGGER: 1 -> new, 0 -> old
16106                         ** EP_Unlikely:  134217728 times likelihood
16107                         ** TK_SELECT: 1st register of result vector */
16108  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
16109                         ** TK_VARIABLE: variable number (always >= 1).
16110                         ** TK_SELECT_COLUMN: column of the result vector */
16111  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
16112  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
16113  u8 op2;                /* TK_REGISTER: original value of Expr.op
16114                         ** TK_COLUMN: the value of p5 for OP_Column
16115                         ** TK_AGG_FUNCTION: nesting depth */
16116  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
16117  Table *pTab;           /* Table for TK_COLUMN expressions. */
16118};
16119
16120/*
16121** The following are the meanings of bits in the Expr.flags field.
16122*/
16123#define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
16124#define EP_Agg       0x000002 /* Contains one or more aggregate functions */
16125                  /* 0x000004 // available for use */
16126                  /* 0x000008 // available for use */
16127#define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
16128#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
16129#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
16130#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
16131#define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
16132#define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
16133#define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
16134#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
16135#define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
16136#define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
16137#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
16138#define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
16139#define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
16140#define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
16141#define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
16142#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
16143#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
16144#define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
16145#define EP_Alias     0x400000 /* Is an alias for a result set column */
16146#define EP_Leaf      0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
16147
16148/*
16149** Combinations of two or more EP_* flags
16150*/
16151#define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
16152
16153/*
16154** These macros can be used to test, set, or clear bits in the
16155** Expr.flags field.
16156*/
16157#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
16158#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
16159#define ExprSetProperty(E,P)     (E)->flags|=(P)
16160#define ExprClearProperty(E,P)   (E)->flags&=~(P)
16161
16162/* The ExprSetVVAProperty() macro is used for Verification, Validation,
16163** and Accreditation only.  It works like ExprSetProperty() during VVA
16164** processes but is a no-op for delivery.
16165*/
16166#ifdef SQLITE_DEBUG
16167# define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
16168#else
16169# define ExprSetVVAProperty(E,P)
16170#endif
16171
16172/*
16173** Macros to determine the number of bytes required by a normal Expr
16174** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
16175** and an Expr struct with the EP_TokenOnly flag set.
16176*/
16177#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
16178#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
16179#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
16180
16181/*
16182** Flags passed to the sqlite3ExprDup() function. See the header comment
16183** above sqlite3ExprDup() for details.
16184*/
16185#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
16186
16187/*
16188** A list of expressions.  Each expression may optionally have a
16189** name.  An expr/name combination can be used in several ways, such
16190** as the list of "expr AS ID" fields following a "SELECT" or in the
16191** list of "ID = expr" items in an UPDATE.  A list of expressions can
16192** also be used as the argument to a function, in which case the a.zName
16193** field is not used.
16194**
16195** By default the Expr.zSpan field holds a human-readable description of
16196** the expression that is used in the generation of error messages and
16197** column labels.  In this case, Expr.zSpan is typically the text of a
16198** column expression as it exists in a SELECT statement.  However, if
16199** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
16200** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
16201** form is used for name resolution with nested FROM clauses.
16202*/
16203struct ExprList {
16204  int nExpr;             /* Number of expressions on the list */
16205  int nAlloc;            /* Number of a[] slots allocated */
16206  struct ExprList_item { /* For each expression in the list */
16207    Expr *pExpr;            /* The parse tree for this expression */
16208    char *zName;            /* Token associated with this expression */
16209    char *zSpan;            /* Original text of the expression */
16210    u8 sortOrder;           /* 1 for DESC or 0 for ASC */
16211    unsigned done :1;       /* A flag to indicate when processing is finished */
16212    unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
16213    unsigned reusable :1;   /* Constant expression is reusable */
16214    union {
16215      struct {
16216        u16 iOrderByCol;      /* For ORDER BY, column number in result set */
16217        u16 iAlias;           /* Index into Parse.aAlias[] for zName */
16218      } x;
16219      int iConstExprReg;      /* Register in which Expr value is cached */
16220    } u;
16221  } a[1];                  /* One slot for each expression in the list */
16222};
16223
16224/*
16225** An instance of this structure is used by the parser to record both
16226** the parse tree for an expression and the span of input text for an
16227** expression.
16228*/
16229struct ExprSpan {
16230  Expr *pExpr;          /* The expression parse tree */
16231  const char *zStart;   /* First character of input text */
16232  const char *zEnd;     /* One character past the end of input text */
16233};
16234
16235/*
16236** An instance of this structure can hold a simple list of identifiers,
16237** such as the list "a,b,c" in the following statements:
16238**
16239**      INSERT INTO t(a,b,c) VALUES ...;
16240**      CREATE INDEX idx ON t(a,b,c);
16241**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
16242**
16243** The IdList.a.idx field is used when the IdList represents the list of
16244** column names after a table name in an INSERT statement.  In the statement
16245**
16246**     INSERT INTO t(a,b,c) ...
16247**
16248** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
16249*/
16250struct IdList {
16251  struct IdList_item {
16252    char *zName;      /* Name of the identifier */
16253    int idx;          /* Index in some Table.aCol[] of a column named zName */
16254  } *a;
16255  int nId;         /* Number of identifiers on the list */
16256};
16257
16258/*
16259** The bitmask datatype defined below is used for various optimizations.
16260**
16261** Changing this from a 64-bit to a 32-bit type limits the number of
16262** tables in a join to 32 instead of 64.  But it also reduces the size
16263** of the library by 738 bytes on ix86.
16264*/
16265#ifdef SQLITE_BITMASK_TYPE
16266  typedef SQLITE_BITMASK_TYPE Bitmask;
16267#else
16268  typedef u64 Bitmask;
16269#endif
16270
16271/*
16272** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
16273*/
16274#define BMS  ((int)(sizeof(Bitmask)*8))
16275
16276/*
16277** A bit in a Bitmask
16278*/
16279#define MASKBIT(n)   (((Bitmask)1)<<(n))
16280#define MASKBIT32(n) (((unsigned int)1)<<(n))
16281#define ALLBITS      ((Bitmask)-1)
16282
16283/*
16284** The following structure describes the FROM clause of a SELECT statement.
16285** Each table or subquery in the FROM clause is a separate element of
16286** the SrcList.a[] array.
16287**
16288** With the addition of multiple database support, the following structure
16289** can also be used to describe a particular table such as the table that
16290** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
16291** such a table must be a simple name: ID.  But in SQLite, the table can
16292** now be identified by a database name, a dot, then the table name: ID.ID.
16293**
16294** The jointype starts out showing the join type between the current table
16295** and the next table on the list.  The parser builds the list this way.
16296** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
16297** jointype expresses the join between the table and the previous table.
16298**
16299** In the colUsed field, the high-order bit (bit 63) is set if the table
16300** contains more than 63 columns and the 64-th or later column is used.
16301*/
16302struct SrcList {
16303  int nSrc;        /* Number of tables or subqueries in the FROM clause */
16304  u32 nAlloc;      /* Number of entries allocated in a[] below */
16305  struct SrcList_item {
16306    Schema *pSchema;  /* Schema to which this item is fixed */
16307    char *zDatabase;  /* Name of database holding this table */
16308    char *zName;      /* Name of the table */
16309    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
16310    Table *pTab;      /* An SQL table corresponding to zName */
16311    Select *pSelect;  /* A SELECT statement used in place of a table name */
16312    int addrFillSub;  /* Address of subroutine to manifest a subquery */
16313    int regReturn;    /* Register holding return address of addrFillSub */
16314    int regResult;    /* Registers holding results of a co-routine */
16315    struct {
16316      u8 jointype;      /* Type of join between this table and the previous */
16317      unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
16318      unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
16319      unsigned isTabFunc :1;     /* True if table-valued-function syntax */
16320      unsigned isCorrelated :1;  /* True if sub-query is correlated */
16321      unsigned viaCoroutine :1;  /* Implemented as a co-routine */
16322      unsigned isRecursive :1;   /* True for recursive reference in WITH */
16323    } fg;
16324#ifndef SQLITE_OMIT_EXPLAIN
16325    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
16326#endif
16327    int iCursor;      /* The VDBE cursor number used to access this table */
16328    Expr *pOn;        /* The ON clause of a join */
16329    IdList *pUsing;   /* The USING clause of a join */
16330    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
16331    union {
16332      char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
16333      ExprList *pFuncArg;  /* Arguments to table-valued-function */
16334    } u1;
16335    Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
16336  } a[1];             /* One entry for each identifier on the list */
16337};
16338
16339/*
16340** Permitted values of the SrcList.a.jointype field
16341*/
16342#define JT_INNER     0x0001    /* Any kind of inner or cross join */
16343#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
16344#define JT_NATURAL   0x0004    /* True for a "natural" join */
16345#define JT_LEFT      0x0008    /* Left outer join */
16346#define JT_RIGHT     0x0010    /* Right outer join */
16347#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
16348#define JT_ERROR     0x0040    /* unknown or unsupported join type */
16349
16350
16351/*
16352** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
16353** and the WhereInfo.wctrlFlags member.
16354**
16355** Value constraints (enforced via assert()):
16356**     WHERE_USE_LIMIT  == SF_FixedLimit
16357*/
16358#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
16359#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
16360#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
16361#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
16362#define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
16363#define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
16364#define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
16365                                      ** the OR optimization  */
16366#define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
16367#define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
16368#define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
16369#define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
16370#define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
16371#define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
16372#define WHERE_SEEK_UNIQ_TABLE  0x1000 /* Do not defer seeks if unique */
16373                        /*     0x2000    not currently used */
16374#define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
16375                        /*     0x8000    not currently used */
16376
16377/* Allowed return values from sqlite3WhereIsDistinct()
16378*/
16379#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
16380#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
16381#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
16382#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
16383
16384/*
16385** A NameContext defines a context in which to resolve table and column
16386** names.  The context consists of a list of tables (the pSrcList) field and
16387** a list of named expression (pEList).  The named expression list may
16388** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
16389** to the table being operated on by INSERT, UPDATE, or DELETE.  The
16390** pEList corresponds to the result set of a SELECT and is NULL for
16391** other statements.
16392**
16393** NameContexts can be nested.  When resolving names, the inner-most
16394** context is searched first.  If no match is found, the next outer
16395** context is checked.  If there is still no match, the next context
16396** is checked.  This process continues until either a match is found
16397** or all contexts are check.  When a match is found, the nRef member of
16398** the context containing the match is incremented.
16399**
16400** Each subquery gets a new NameContext.  The pNext field points to the
16401** NameContext in the parent query.  Thus the process of scanning the
16402** NameContext list corresponds to searching through successively outer
16403** subqueries looking for a match.
16404*/
16405struct NameContext {
16406  Parse *pParse;       /* The parser */
16407  SrcList *pSrcList;   /* One or more tables used to resolve names */
16408  ExprList *pEList;    /* Optional list of result-set columns */
16409  AggInfo *pAggInfo;   /* Information about aggregates at this level */
16410  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
16411  int nRef;            /* Number of names resolved by this context */
16412  int nErr;            /* Number of errors encountered while resolving names */
16413  u16 ncFlags;         /* Zero or more NC_* flags defined below */
16414};
16415
16416/*
16417** Allowed values for the NameContext, ncFlags field.
16418**
16419** Value constraints (all checked via assert()):
16420**    NC_HasAgg    == SF_HasAgg
16421**    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
16422**
16423*/
16424#define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
16425#define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
16426#define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
16427#define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
16428#define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
16429#define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
16430#define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
16431#define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
16432
16433/*
16434** An instance of the following structure contains all information
16435** needed to generate code for a single SELECT statement.
16436**
16437** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
16438** If there is a LIMIT clause, the parser sets nLimit to the value of the
16439** limit and nOffset to the value of the offset (or 0 if there is not
16440** offset).  But later on, nLimit and nOffset become the memory locations
16441** in the VDBE that record the limit and offset counters.
16442**
16443** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
16444** These addresses must be stored so that we can go back and fill in
16445** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
16446** the number of columns in P2 can be computed at the same time
16447** as the OP_OpenEphm instruction is coded because not
16448** enough information about the compound query is known at that point.
16449** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
16450** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
16451** sequences for the ORDER BY clause.
16452*/
16453struct Select {
16454  ExprList *pEList;      /* The fields of the result */
16455  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
16456  LogEst nSelectRow;     /* Estimated number of result rows */
16457  u32 selFlags;          /* Various SF_* values */
16458  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
16459#if SELECTTRACE_ENABLED
16460  char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
16461#endif
16462  int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
16463  SrcList *pSrc;         /* The FROM clause */
16464  Expr *pWhere;          /* The WHERE clause */
16465  ExprList *pGroupBy;    /* The GROUP BY clause */
16466  Expr *pHaving;         /* The HAVING clause */
16467  ExprList *pOrderBy;    /* The ORDER BY clause */
16468  Select *pPrior;        /* Prior select in a compound select statement */
16469  Select *pNext;         /* Next select to the left in a compound */
16470  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
16471  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
16472  With *pWith;           /* WITH clause attached to this select. Or NULL. */
16473};
16474
16475/*
16476** Allowed values for Select.selFlags.  The "SF" prefix stands for
16477** "Select Flag".
16478**
16479** Value constraints (all checked via assert())
16480**     SF_HasAgg     == NC_HasAgg
16481**     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
16482**     SF_FixedLimit == WHERE_USE_LIMIT
16483*/
16484#define SF_Distinct       0x00001  /* Output should be DISTINCT */
16485#define SF_All            0x00002  /* Includes the ALL keyword */
16486#define SF_Resolved       0x00004  /* Identifiers have been resolved */
16487#define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
16488#define SF_HasAgg         0x00010  /* Contains aggregate functions */
16489#define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
16490#define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
16491#define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
16492#define SF_Compound       0x00100  /* Part of a compound query */
16493#define SF_Values         0x00200  /* Synthesized from VALUES clause */
16494#define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
16495#define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
16496#define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
16497#define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
16498#define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
16499#define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
16500#define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
16501#define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
16502
16503
16504/*
16505** The results of a SELECT can be distributed in several ways, as defined
16506** by one of the following macros.  The "SRT" prefix means "SELECT Result
16507** Type".
16508**
16509**     SRT_Union       Store results as a key in a temporary index
16510**                     identified by pDest->iSDParm.
16511**
16512**     SRT_Except      Remove results from the temporary index pDest->iSDParm.
16513**
16514**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
16515**                     set is not empty.
16516**
16517**     SRT_Discard     Throw the results away.  This is used by SELECT
16518**                     statements within triggers whose only purpose is
16519**                     the side-effects of functions.
16520**
16521** All of the above are free to ignore their ORDER BY clause. Those that
16522** follow must honor the ORDER BY clause.
16523**
16524**     SRT_Output      Generate a row of output (using the OP_ResultRow
16525**                     opcode) for each row in the result set.
16526**
16527**     SRT_Mem         Only valid if the result is a single column.
16528**                     Store the first column of the first result row
16529**                     in register pDest->iSDParm then abandon the rest
16530**                     of the query.  This destination implies "LIMIT 1".
16531**
16532**     SRT_Set         The result must be a single column.  Store each
16533**                     row of result as the key in table pDest->iSDParm.
16534**                     Apply the affinity pDest->affSdst before storing
16535**                     results.  Used to implement "IN (SELECT ...)".
16536**
16537**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
16538**                     the result there. The cursor is left open after
16539**                     returning.  This is like SRT_Table except that
16540**                     this destination uses OP_OpenEphemeral to create
16541**                     the table first.
16542**
16543**     SRT_Coroutine   Generate a co-routine that returns a new row of
16544**                     results each time it is invoked.  The entry point
16545**                     of the co-routine is stored in register pDest->iSDParm
16546**                     and the result row is stored in pDest->nDest registers
16547**                     starting with pDest->iSdst.
16548**
16549**     SRT_Table       Store results in temporary table pDest->iSDParm.
16550**     SRT_Fifo        This is like SRT_EphemTab except that the table
16551**                     is assumed to already be open.  SRT_Fifo has
16552**                     the additional property of being able to ignore
16553**                     the ORDER BY clause.
16554**
16555**     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
16556**                     But also use temporary table pDest->iSDParm+1 as
16557**                     a record of all prior results and ignore any duplicate
16558**                     rows.  Name means:  "Distinct Fifo".
16559**
16560**     SRT_Queue       Store results in priority queue pDest->iSDParm (really
16561**                     an index).  Append a sequence number so that all entries
16562**                     are distinct.
16563**
16564**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
16565**                     the same record has never been stored before.  The
16566**                     index at pDest->iSDParm+1 hold all prior stores.
16567*/
16568#define SRT_Union        1  /* Store result as keys in an index */
16569#define SRT_Except       2  /* Remove result from a UNION index */
16570#define SRT_Exists       3  /* Store 1 if the result is not empty */
16571#define SRT_Discard      4  /* Do not save the results anywhere */
16572#define SRT_Fifo         5  /* Store result as data with an automatic rowid */
16573#define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
16574#define SRT_Queue        7  /* Store result in an queue */
16575#define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
16576
16577/* The ORDER BY clause is ignored for all of the above */
16578#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
16579
16580#define SRT_Output       9  /* Output each row of result */
16581#define SRT_Mem         10  /* Store result in a memory cell */
16582#define SRT_Set         11  /* Store results as keys in an index */
16583#define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
16584#define SRT_Coroutine   13  /* Generate a single row of result */
16585#define SRT_Table       14  /* Store result as data with an automatic rowid */
16586
16587/*
16588** An instance of this object describes where to put of the results of
16589** a SELECT statement.
16590*/
16591struct SelectDest {
16592  u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
16593  int iSDParm;         /* A parameter used by the eDest disposal method */
16594  int iSdst;           /* Base register where results are written */
16595  int nSdst;           /* Number of registers allocated */
16596  char *zAffSdst;      /* Affinity used when eDest==SRT_Set */
16597  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
16598};
16599
16600/*
16601** During code generation of statements that do inserts into AUTOINCREMENT
16602** tables, the following information is attached to the Table.u.autoInc.p
16603** pointer of each autoincrement table to record some side information that
16604** the code generator needs.  We have to keep per-table autoincrement
16605** information in case inserts are done within triggers.  Triggers do not
16606** normally coordinate their activities, but we do need to coordinate the
16607** loading and saving of autoincrement information.
16608*/
16609struct AutoincInfo {
16610  AutoincInfo *pNext;   /* Next info block in a list of them all */
16611  Table *pTab;          /* Table this info block refers to */
16612  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
16613  int regCtr;           /* Memory register holding the rowid counter */
16614};
16615
16616/*
16617** Size of the column cache
16618*/
16619#ifndef SQLITE_N_COLCACHE
16620# define SQLITE_N_COLCACHE 10
16621#endif
16622
16623/*
16624** At least one instance of the following structure is created for each
16625** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
16626** statement. All such objects are stored in the linked list headed at
16627** Parse.pTriggerPrg and deleted once statement compilation has been
16628** completed.
16629**
16630** A Vdbe sub-program that implements the body and WHEN clause of trigger
16631** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
16632** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
16633** The Parse.pTriggerPrg list never contains two entries with the same
16634** values for both pTrigger and orconf.
16635**
16636** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
16637** accessed (or set to 0 for triggers fired as a result of INSERT
16638** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
16639** a mask of new.* columns used by the program.
16640*/
16641struct TriggerPrg {
16642  Trigger *pTrigger;      /* Trigger this program was coded from */
16643  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
16644  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
16645  int orconf;             /* Default ON CONFLICT policy */
16646  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
16647};
16648
16649/*
16650** The yDbMask datatype for the bitmask of all attached databases.
16651*/
16652#if SQLITE_MAX_ATTACHED>30
16653  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
16654# define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
16655# define DbMaskZero(M)      memset((M),0,sizeof(M))
16656# define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
16657# define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
16658# define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
16659#else
16660  typedef unsigned int yDbMask;
16661# define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
16662# define DbMaskZero(M)      (M)=0
16663# define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
16664# define DbMaskAllZero(M)   (M)==0
16665# define DbMaskNonZero(M)   (M)!=0
16666#endif
16667
16668/*
16669** An SQL parser context.  A copy of this structure is passed through
16670** the parser and down into all the parser action routine in order to
16671** carry around information that is global to the entire parse.
16672**
16673** The structure is divided into two parts.  When the parser and code
16674** generate call themselves recursively, the first part of the structure
16675** is constant but the second part is reset at the beginning and end of
16676** each recursion.
16677**
16678** The nTableLock and aTableLock variables are only used if the shared-cache
16679** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
16680** used to store the set of table-locks required by the statement being
16681** compiled. Function sqlite3TableLock() is used to add entries to the
16682** list.
16683*/
16684struct Parse {
16685  sqlite3 *db;         /* The main database structure */
16686  char *zErrMsg;       /* An error message */
16687  Vdbe *pVdbe;         /* An engine for executing database bytecode */
16688  int rc;              /* Return code from execution */
16689  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
16690  u8 checkSchema;      /* Causes schema cookie check after an error */
16691  u8 nested;           /* Number of nested calls to the parser/code generator */
16692  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
16693  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
16694  u8 mayAbort;         /* True if statement may throw an ABORT exception */
16695  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
16696  u8 okConstFactor;    /* OK to factor out constants */
16697  u8 disableLookaside; /* Number of times lookaside has been disabled */
16698  u8 nColCache;        /* Number of entries in aColCache[] */
16699  int nRangeReg;       /* Size of the temporary register block */
16700  int iRangeReg;       /* First register in temporary register block */
16701  int nErr;            /* Number of errors seen */
16702  int nTab;            /* Number of previously allocated VDBE cursors */
16703  int nMem;            /* Number of memory cells used so far */
16704  int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
16705  int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
16706  int iSelfTab;        /* Table for associated with an index on expr, or negative
16707                       ** of the base register during check-constraint eval */
16708  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
16709  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
16710  int nLabel;          /* Number of labels used */
16711  int *aLabel;         /* Space to hold the labels */
16712  ExprList *pConstExpr;/* Constant expressions */
16713  Token constraintName;/* Name of the constraint currently being parsed */
16714  yDbMask writeMask;   /* Start a write transaction on these databases */
16715  yDbMask cookieMask;  /* Bitmask of schema verified databases */
16716  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
16717  int regRoot;         /* Register holding root page number for new objects */
16718  int nMaxArg;         /* Max args passed to user function by sub-program */
16719#if SELECTTRACE_ENABLED
16720  int nSelect;         /* Number of SELECT statements seen */
16721  int nSelectIndent;   /* How far to indent SELECTTRACE() output */
16722#endif
16723#ifndef SQLITE_OMIT_SHARED_CACHE
16724  int nTableLock;        /* Number of locks in aTableLock */
16725  TableLock *aTableLock; /* Required table locks for shared-cache mode */
16726#endif
16727  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
16728  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
16729  Table *pTriggerTab;  /* Table triggers are being coded for */
16730  int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
16731  u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
16732  u32 oldmask;         /* Mask of old.* columns referenced */
16733  u32 newmask;         /* Mask of new.* columns referenced */
16734  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
16735  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
16736  u8 disableTriggers;  /* True to disable triggers */
16737
16738  /**************************************************************************
16739  ** Fields above must be initialized to zero.  The fields that follow,
16740  ** down to the beginning of the recursive section, do not need to be
16741  ** initialized as they will be set before being used.  The boundary is
16742  ** determined by offsetof(Parse,aColCache).
16743  **************************************************************************/
16744
16745  struct yColCache {
16746    int iTable;           /* Table cursor number */
16747    i16 iColumn;          /* Table column number */
16748    u8 tempReg;           /* iReg is a temp register that needs to be freed */
16749    int iLevel;           /* Nesting level */
16750    int iReg;             /* Reg with value of this column. 0 means none. */
16751    int lru;              /* Least recently used entry has the smallest value */
16752  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
16753  int aTempReg[8];        /* Holding area for temporary registers */
16754  Token sNameToken;       /* Token with unqualified schema object name */
16755
16756  /************************************************************************
16757  ** Above is constant between recursions.  Below is reset before and after
16758  ** each recursion.  The boundary between these two regions is determined
16759  ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
16760  ** first field in the recursive region.
16761  ************************************************************************/
16762
16763  Token sLastToken;       /* The last token parsed */
16764  ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
16765  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
16766  u8 explain;               /* True if the EXPLAIN flag is found on the query */
16767#ifndef SQLITE_OMIT_VIRTUALTABLE
16768  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
16769  int nVtabLock;            /* Number of virtual tables to lock */
16770#endif
16771  int nHeight;              /* Expression tree height of current sub-select */
16772#ifndef SQLITE_OMIT_EXPLAIN
16773  int iSelectId;            /* ID of current select for EXPLAIN output */
16774  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
16775#endif
16776  VList *pVList;            /* Mapping between variable names and numbers */
16777  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
16778  const char *zTail;        /* All SQL text past the last semicolon parsed */
16779  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
16780  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
16781  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
16782#ifndef SQLITE_OMIT_VIRTUALTABLE
16783  Token sArg;               /* Complete text of a module argument */
16784  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
16785#endif
16786  Table *pZombieTab;        /* List of Table objects to delete after code gen */
16787  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
16788  With *pWith;              /* Current WITH clause, or NULL */
16789  With *pWithToFree;        /* Free this WITH object at the end of the parse */
16790};
16791
16792/*
16793** Sizes and pointers of various parts of the Parse object.
16794*/
16795#define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
16796#define PARSE_RECURSE_SZ offsetof(Parse,sLastToken)    /* Recursive part */
16797#define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
16798#define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ)  /* Pointer to tail */
16799
16800/*
16801** Return true if currently inside an sqlite3_declare_vtab() call.
16802*/
16803#ifdef SQLITE_OMIT_VIRTUALTABLE
16804  #define IN_DECLARE_VTAB 0
16805#else
16806  #define IN_DECLARE_VTAB (pParse->declareVtab)
16807#endif
16808
16809/*
16810** An instance of the following structure can be declared on a stack and used
16811** to save the Parse.zAuthContext value so that it can be restored later.
16812*/
16813struct AuthContext {
16814  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
16815  Parse *pParse;              /* The Parse structure */
16816};
16817
16818/*
16819** Bitfield flags for P5 value in various opcodes.
16820**
16821** Value constraints (enforced via assert()):
16822**    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
16823**    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
16824**    OPFLAG_BULKCSR      == BTREE_BULKLOAD
16825**    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
16826**    OPFLAG_FORDELETE    == BTREE_FORDELETE
16827**    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
16828**    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
16829*/
16830#define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
16831                                     /* Also used in P2 (not P5) of OP_Delete */
16832#define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
16833#define OPFLAG_LASTROWID     0x20    /* Set to update db->lastRowid */
16834#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
16835#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
16836#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
16837#define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
16838#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
16839#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
16840#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
16841#define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
16842#define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
16843#define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
16844#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
16845#define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete/Insert: save cursor pos */
16846#define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
16847
16848/*
16849 * Each trigger present in the database schema is stored as an instance of
16850 * struct Trigger.
16851 *
16852 * Pointers to instances of struct Trigger are stored in two ways.
16853 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
16854 *    database). This allows Trigger structures to be retrieved by name.
16855 * 2. All triggers associated with a single table form a linked list, using the
16856 *    pNext member of struct Trigger. A pointer to the first element of the
16857 *    linked list is stored as the "pTrigger" member of the associated
16858 *    struct Table.
16859 *
16860 * The "step_list" member points to the first element of a linked list
16861 * containing the SQL statements specified as the trigger program.
16862 */
16863struct Trigger {
16864  char *zName;            /* The name of the trigger                        */
16865  char *table;            /* The table or view to which the trigger applies */
16866  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
16867  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
16868  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
16869  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
16870                             the <column-list> is stored here */
16871  Schema *pSchema;        /* Schema containing the trigger */
16872  Schema *pTabSchema;     /* Schema containing the table */
16873  TriggerStep *step_list; /* Link list of trigger program steps             */
16874  Trigger *pNext;         /* Next trigger associated with the table */
16875};
16876
16877/*
16878** A trigger is either a BEFORE or an AFTER trigger.  The following constants
16879** determine which.
16880**
16881** If there are multiple triggers, you might of some BEFORE and some AFTER.
16882** In that cases, the constants below can be ORed together.
16883*/
16884#define TRIGGER_BEFORE  1
16885#define TRIGGER_AFTER   2
16886
16887/*
16888 * An instance of struct TriggerStep is used to store a single SQL statement
16889 * that is a part of a trigger-program.
16890 *
16891 * Instances of struct TriggerStep are stored in a singly linked list (linked
16892 * using the "pNext" member) referenced by the "step_list" member of the
16893 * associated struct Trigger instance. The first element of the linked list is
16894 * the first step of the trigger-program.
16895 *
16896 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
16897 * "SELECT" statement. The meanings of the other members is determined by the
16898 * value of "op" as follows:
16899 *
16900 * (op == TK_INSERT)
16901 * orconf    -> stores the ON CONFLICT algorithm
16902 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
16903 *              this stores a pointer to the SELECT statement. Otherwise NULL.
16904 * zTarget   -> Dequoted name of the table to insert into.
16905 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
16906 *              this stores values to be inserted. Otherwise NULL.
16907 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
16908 *              statement, then this stores the column-names to be
16909 *              inserted into.
16910 *
16911 * (op == TK_DELETE)
16912 * zTarget   -> Dequoted name of the table to delete from.
16913 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
16914 *              Otherwise NULL.
16915 *
16916 * (op == TK_UPDATE)
16917 * zTarget   -> Dequoted name of the table to update.
16918 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
16919 *              Otherwise NULL.
16920 * pExprList -> A list of the columns to update and the expressions to update
16921 *              them to. See sqlite3Update() documentation of "pChanges"
16922 *              argument.
16923 *
16924 */
16925struct TriggerStep {
16926  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
16927  u8 orconf;           /* OE_Rollback etc. */
16928  Trigger *pTrig;      /* The trigger that this step is a part of */
16929  Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
16930  char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
16931  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
16932  ExprList *pExprList; /* SET clause for UPDATE. */
16933  IdList *pIdList;     /* Column names for INSERT */
16934  TriggerStep *pNext;  /* Next in the link-list */
16935  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
16936};
16937
16938/*
16939** The following structure contains information used by the sqliteFix...
16940** routines as they walk the parse tree to make database references
16941** explicit.
16942*/
16943typedef struct DbFixer DbFixer;
16944struct DbFixer {
16945  Parse *pParse;      /* The parsing context.  Error messages written here */
16946  Schema *pSchema;    /* Fix items to this schema */
16947  int bVarOnly;       /* Check for variable references only */
16948  const char *zDb;    /* Make sure all objects are contained in this database */
16949  const char *zType;  /* Type of the container - used for error messages */
16950  const Token *pName; /* Name of the container - used for error messages */
16951};
16952
16953/*
16954** An objected used to accumulate the text of a string where we
16955** do not necessarily know how big the string will be in the end.
16956*/
16957struct StrAccum {
16958  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
16959  char *zBase;         /* A base allocation.  Not from malloc. */
16960  char *zText;         /* The string collected so far */
16961  u32  nChar;          /* Length of the string so far */
16962  u32  nAlloc;         /* Amount of space allocated in zText */
16963  u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
16964  u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
16965  u8   printfFlags;    /* SQLITE_PRINTF flags below */
16966};
16967#define STRACCUM_NOMEM   1
16968#define STRACCUM_TOOBIG  2
16969#define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
16970#define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
16971#define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
16972
16973#define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
16974
16975
16976/*
16977** A pointer to this structure is used to communicate information
16978** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
16979*/
16980typedef struct {
16981  sqlite3 *db;        /* The database being initialized */
16982  char **pzErrMsg;    /* Error message stored here */
16983  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
16984  int rc;             /* Result code stored here */
16985} InitData;
16986
16987/*
16988** Structure containing global configuration data for the SQLite library.
16989**
16990** This structure also contains some state information.
16991*/
16992struct Sqlite3Config {
16993  int bMemstat;                     /* True to enable memory status */
16994  int bCoreMutex;                   /* True to enable core mutexing */
16995  int bFullMutex;                   /* True to enable full mutexing */
16996  int bOpenUri;                     /* True to interpret filenames as URIs */
16997  int bUseCis;                      /* Use covering indices for full-scans */
16998  int mxStrlen;                     /* Maximum string length */
16999  int neverCorrupt;                 /* Database is always well-formed */
17000  int szLookaside;                  /* Default lookaside buffer size */
17001  int nLookaside;                   /* Default lookaside buffer count */
17002  int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
17003  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
17004  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
17005  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
17006  void *pHeap;                      /* Heap storage space */
17007  int nHeap;                        /* Size of pHeap[] */
17008  int mnReq, mxReq;                 /* Min and max heap requests sizes */
17009  sqlite3_int64 szMmap;             /* mmap() space per open file */
17010  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
17011  void *pScratch;                   /* Scratch memory */
17012  int szScratch;                    /* Size of each scratch buffer */
17013  int nScratch;                     /* Number of scratch buffers */
17014  void *pPage;                      /* Page cache memory */
17015  int szPage;                       /* Size of each page in pPage[] */
17016  int nPage;                        /* Number of pages in pPage[] */
17017  int mxParserStack;                /* maximum depth of the parser stack */
17018  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
17019  u32 szPma;                        /* Maximum Sorter PMA size */
17020  /* The above might be initialized to non-zero.  The following need to always
17021  ** initially be zero, however. */
17022  int isInit;                       /* True after initialization has finished */
17023  int inProgress;                   /* True while initialization in progress */
17024  int isMutexInit;                  /* True after mutexes are initialized */
17025  int isMallocInit;                 /* True after malloc is initialized */
17026  int isPCacheInit;                 /* True after malloc is initialized */
17027  int nRefInitMutex;                /* Number of users of pInitMutex */
17028  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
17029  void (*xLog)(void*,int,const char*); /* Function for logging */
17030  void *pLogArg;                       /* First argument to xLog() */
17031#ifdef SQLITE_ENABLE_SQLLOG
17032  void(*xSqllog)(void*,sqlite3*,const char*, int);
17033  void *pSqllogArg;
17034#endif
17035#ifdef SQLITE_VDBE_COVERAGE
17036  /* The following callback (if not NULL) is invoked on every VDBE branch
17037  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
17038  */
17039  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
17040  void *pVdbeBranchArg;                                     /* 1st argument */
17041#endif
17042#ifndef SQLITE_UNTESTABLE
17043  int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
17044#endif
17045  int bLocaltimeFault;              /* True to fail localtime() calls */
17046  int iOnceResetThreshold;          /* When to reset OP_Once counters */
17047};
17048
17049/*
17050** This macro is used inside of assert() statements to indicate that
17051** the assert is only valid on a well-formed database.  Instead of:
17052**
17053**     assert( X );
17054**
17055** One writes:
17056**
17057**     assert( X || CORRUPT_DB );
17058**
17059** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
17060** that the database is definitely corrupt, only that it might be corrupt.
17061** For most test cases, CORRUPT_DB is set to false using a special
17062** sqlite3_test_control().  This enables assert() statements to prove
17063** things that are always true for well-formed databases.
17064*/
17065#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
17066
17067/*
17068** Context pointer passed down through the tree-walk.
17069*/
17070struct Walker {
17071  Parse *pParse;                            /* Parser context.  */
17072  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
17073  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
17074  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
17075  int walkerDepth;                          /* Number of subqueries */
17076  u8 eCode;                                 /* A small processing code */
17077  union {                                   /* Extra data for callback */
17078    NameContext *pNC;                         /* Naming context */
17079    int n;                                    /* A counter */
17080    int iCur;                                 /* A cursor number */
17081    SrcList *pSrcList;                        /* FROM clause */
17082    struct SrcCount *pSrcCount;               /* Counting column references */
17083    struct CCurHint *pCCurHint;               /* Used by codeCursorHint() */
17084    int *aiCol;                               /* array of column indexes */
17085    struct IdxCover *pIdxCover;               /* Check for index coverage */
17086    struct IdxExprTrans *pIdxTrans;           /* Convert indexed expr to column */
17087    ExprList *pGroupBy;                       /* GROUP BY clause */
17088    struct HavingToWhereCtx *pHavingCtx;      /* HAVING to WHERE clause ctx */
17089  } u;
17090};
17091
17092/* Forward declarations */
17093SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
17094SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
17095SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
17096SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
17097SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
17098SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
17099SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
17100#ifdef SQLITE_DEBUG
17101SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
17102#endif
17103
17104/*
17105** Return code from the parse-tree walking primitives and their
17106** callbacks.
17107*/
17108#define WRC_Continue    0   /* Continue down into children */
17109#define WRC_Prune       1   /* Omit children but continue walking siblings */
17110#define WRC_Abort       2   /* Abandon the tree walk */
17111
17112/*
17113** An instance of this structure represents a set of one or more CTEs
17114** (common table expressions) created by a single WITH clause.
17115*/
17116struct With {
17117  int nCte;                       /* Number of CTEs in the WITH clause */
17118  With *pOuter;                   /* Containing WITH clause, or NULL */
17119  struct Cte {                    /* For each CTE in the WITH clause.... */
17120    char *zName;                    /* Name of this CTE */
17121    ExprList *pCols;                /* List of explicit column names, or NULL */
17122    Select *pSelect;                /* The definition of this CTE */
17123    const char *zCteErr;            /* Error message for circular references */
17124  } a[1];
17125};
17126
17127#ifdef SQLITE_DEBUG
17128/*
17129** An instance of the TreeView object is used for printing the content of
17130** data structures on sqlite3DebugPrintf() using a tree-like view.
17131*/
17132struct TreeView {
17133  int iLevel;             /* Which level of the tree we are on */
17134  u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
17135};
17136#endif /* SQLITE_DEBUG */
17137
17138/*
17139** Assuming zIn points to the first byte of a UTF-8 character,
17140** advance zIn to point to the first byte of the next UTF-8 character.
17141*/
17142#define SQLITE_SKIP_UTF8(zIn) {                        \
17143  if( (*(zIn++))>=0xc0 ){                              \
17144    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
17145  }                                                    \
17146}
17147
17148/*
17149** The SQLITE_*_BKPT macros are substitutes for the error codes with
17150** the same name but without the _BKPT suffix.  These macros invoke
17151** routines that report the line-number on which the error originated
17152** using sqlite3_log().  The routines also provide a convenient place
17153** to set a debugger breakpoint.
17154*/
17155SQLITE_PRIVATE int sqlite3CorruptError(int);
17156SQLITE_PRIVATE int sqlite3MisuseError(int);
17157SQLITE_PRIVATE int sqlite3CantopenError(int);
17158#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
17159#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
17160#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
17161#ifdef SQLITE_DEBUG
17162SQLITE_PRIVATE   int sqlite3NomemError(int);
17163SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
17164SQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);
17165# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
17166# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
17167# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
17168#else
17169# define SQLITE_NOMEM_BKPT SQLITE_NOMEM
17170# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
17171# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
17172#endif
17173
17174/*
17175** FTS3 and FTS4 both require virtual table support
17176*/
17177#if defined(SQLITE_OMIT_VIRTUALTABLE)
17178# undef SQLITE_ENABLE_FTS3
17179# undef SQLITE_ENABLE_FTS4
17180#endif
17181
17182/*
17183** FTS4 is really an extension for FTS3.  It is enabled using the
17184** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
17185** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
17186*/
17187#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
17188# define SQLITE_ENABLE_FTS3 1
17189#endif
17190
17191/*
17192** The ctype.h header is needed for non-ASCII systems.  It is also
17193** needed by FTS3 when FTS3 is included in the amalgamation.
17194*/
17195#if !defined(SQLITE_ASCII) || \
17196    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
17197# include <ctype.h>
17198#endif
17199
17200/*
17201** The following macros mimic the standard library functions toupper(),
17202** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
17203** sqlite versions only work for ASCII characters, regardless of locale.
17204*/
17205#ifdef SQLITE_ASCII
17206# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
17207# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
17208# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
17209# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
17210# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
17211# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
17212# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
17213# define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
17214#else
17215# define sqlite3Toupper(x)   toupper((unsigned char)(x))
17216# define sqlite3Isspace(x)   isspace((unsigned char)(x))
17217# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
17218# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
17219# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
17220# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
17221# define sqlite3Tolower(x)   tolower((unsigned char)(x))
17222# define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
17223#endif
17224#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17225SQLITE_PRIVATE int sqlite3IsIdChar(u8);
17226#endif
17227
17228/*
17229** Internal function prototypes
17230*/
17231SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
17232SQLITE_PRIVATE int sqlite3Strlen30(const char*);
17233SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
17234#define sqlite3StrNICmp sqlite3_strnicmp
17235
17236SQLITE_PRIVATE int sqlite3MallocInit(void);
17237SQLITE_PRIVATE void sqlite3MallocEnd(void);
17238SQLITE_PRIVATE void *sqlite3Malloc(u64);
17239SQLITE_PRIVATE void *sqlite3MallocZero(u64);
17240SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
17241SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
17242SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
17243SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
17244SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
17245SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
17246SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
17247SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
17248SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
17249SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
17250SQLITE_PRIVATE int sqlite3MallocSize(void*);
17251SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
17252SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
17253SQLITE_PRIVATE void sqlite3ScratchFree(void*);
17254SQLITE_PRIVATE void *sqlite3PageMalloc(int);
17255SQLITE_PRIVATE void sqlite3PageFree(void*);
17256SQLITE_PRIVATE void sqlite3MemSetDefault(void);
17257#ifndef SQLITE_UNTESTABLE
17258SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
17259#endif
17260SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
17261
17262/*
17263** On systems with ample stack space and that support alloca(), make
17264** use of alloca() to obtain space for large automatic objects.  By default,
17265** obtain space from malloc().
17266**
17267** The alloca() routine never returns NULL.  This will cause code paths
17268** that deal with sqlite3StackAlloc() failures to be unreachable.
17269*/
17270#ifdef SQLITE_USE_ALLOCA
17271# define sqlite3StackAllocRaw(D,N)   alloca(N)
17272# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
17273# define sqlite3StackFree(D,P)
17274#else
17275# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
17276# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
17277# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
17278#endif
17279
17280/* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
17281** are, disable MEMSYS3
17282*/
17283#ifdef SQLITE_ENABLE_MEMSYS5
17284SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
17285#undef SQLITE_ENABLE_MEMSYS3
17286#endif
17287#ifdef SQLITE_ENABLE_MEMSYS3
17288SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
17289#endif
17290
17291
17292#ifndef SQLITE_MUTEX_OMIT
17293SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
17294SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
17295SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
17296SQLITE_PRIVATE   int sqlite3MutexInit(void);
17297SQLITE_PRIVATE   int sqlite3MutexEnd(void);
17298#endif
17299#if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
17300SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
17301#else
17302# define sqlite3MemoryBarrier()
17303#endif
17304
17305SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
17306SQLITE_PRIVATE void sqlite3StatusUp(int, int);
17307SQLITE_PRIVATE void sqlite3StatusDown(int, int);
17308SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
17309
17310/* Access to mutexes used by sqlite3_status() */
17311SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
17312SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
17313
17314#ifndef SQLITE_OMIT_FLOATING_POINT
17315SQLITE_PRIVATE   int sqlite3IsNaN(double);
17316#else
17317# define sqlite3IsNaN(X)  0
17318#endif
17319
17320/*
17321** An instance of the following structure holds information about SQL
17322** functions arguments that are the parameters to the printf() function.
17323*/
17324struct PrintfArguments {
17325  int nArg;                /* Total number of arguments */
17326  int nUsed;               /* Number of arguments used so far */
17327  sqlite3_value **apArg;   /* The argument values */
17328};
17329
17330SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
17331SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
17332SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
17333SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
17334#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
17335SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
17336#endif
17337#if defined(SQLITE_TEST)
17338SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
17339#endif
17340
17341#if defined(SQLITE_DEBUG)
17342SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
17343SQLITE_PRIVATE   void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
17344SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
17345SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
17346SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
17347#endif
17348
17349
17350SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
17351SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
17352SQLITE_PRIVATE void sqlite3Dequote(char*);
17353SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
17354SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
17355SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
17356SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
17357SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
17358SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
17359SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
17360SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
17361SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
17362#ifdef SQLITE_DEBUG
17363SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
17364#endif
17365SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
17366SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
17367SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
17368SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
17369SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
17370SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
17371SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
17372SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
17373SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
17374SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
17375SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
17376SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
17377SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
17378SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
17379SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
17380SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
17381SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
17382SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
17383SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
17384#ifndef SQLITE_OMIT_VIRTUALTABLE
17385SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
17386#endif
17387SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
17388SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
17389SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
17390SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
17391SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
17392SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
17393SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
17394SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
17395SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
17396SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
17397SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
17398SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
17399#if SQLITE_ENABLE_HIDDEN_COLUMNS
17400SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
17401#else
17402# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
17403#endif
17404SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
17405SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
17406SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
17407SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
17408SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
17409SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
17410SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
17411SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
17412                    sqlite3_vfs**,char**,char **);
17413SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
17414
17415#ifdef SQLITE_UNTESTABLE
17416# define sqlite3FaultSim(X) SQLITE_OK
17417#else
17418SQLITE_PRIVATE   int sqlite3FaultSim(int);
17419#endif
17420
17421SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
17422SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
17423SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
17424SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
17425SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
17426SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
17427SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
17428#ifndef SQLITE_UNTESTABLE
17429SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
17430#endif
17431
17432SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
17433SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
17434SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
17435SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
17436SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
17437
17438SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
17439
17440#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
17441SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
17442#else
17443# define sqlite3ViewGetColumnNames(A,B) 0
17444#endif
17445
17446#if SQLITE_MAX_ATTACHED>30
17447SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
17448#endif
17449SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
17450SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
17451SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
17452#ifndef SQLITE_OMIT_AUTOINCREMENT
17453SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
17454SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
17455#else
17456# define sqlite3AutoincrementBegin(X)
17457# define sqlite3AutoincrementEnd(X)
17458#endif
17459SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
17460SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
17461SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
17462SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
17463SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
17464SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
17465SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
17466                                      Token*, Select*, Expr*, IdList*);
17467SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
17468SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
17469SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
17470SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
17471SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
17472SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
17473SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
17474SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
17475SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
17476                          Expr*, int, int, u8);
17477SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
17478SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
17479SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
17480                         Expr*,ExprList*,u32,Expr*,Expr*);
17481SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
17482SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
17483SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
17484SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
17485#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
17486SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
17487#endif
17488SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
17489SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
17490SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
17491SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
17492SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
17493SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
17494SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
17495SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
17496SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
17497SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
17498SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
17499SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
17500#define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
17501#define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
17502#define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
17503SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
17504SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
17505SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
17506SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
17507SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
17508SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
17509SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
17510SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
17511SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
17512SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
17513SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
17514SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
17515SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
17516SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
17517SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
17518SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
17519SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
17520SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
17521SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
17522#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
17523#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
17524#define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
17525#define SQLITE_ECEL_OMITREF  0x08  /* Omit if ExprList.u.x.iOrderByCol */
17526SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
17527SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
17528SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
17529SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
17530#define LOCATE_VIEW    0x01
17531#define LOCATE_NOERR   0x02
17532SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
17533SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
17534SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
17535SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
17536SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
17537SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
17538SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
17539SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
17540SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
17541SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
17542SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
17543SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
17544SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
17545SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
17546SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
17547SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
17548SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
17549#ifndef SQLITE_UNTESTABLE
17550SQLITE_PRIVATE void sqlite3PrngSaveState(void);
17551SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
17552#endif
17553SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
17554SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
17555SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
17556SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
17557SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
17558SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
17559SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
17560SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
17561SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
17562SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
17563SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
17564SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
17565SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
17566#ifdef SQLITE_ENABLE_CURSOR_HINTS
17567SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
17568#endif
17569SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
17570SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
17571SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
17572SQLITE_PRIVATE int sqlite3IsRowid(const char*);
17573SQLITE_PRIVATE void sqlite3GenerateRowDelete(
17574    Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
17575SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
17576SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
17577SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
17578SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
17579                                     u8,u8,int,int*,int*);
17580#ifdef SQLITE_ENABLE_NULL_TRIM
17581SQLITE_PRIVATE   void sqlite3SetMakeRecordP5(Vdbe*,Table*);
17582#else
17583# define sqlite3SetMakeRecordP5(A,B)
17584#endif
17585SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
17586SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
17587SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
17588SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
17589SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
17590SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
17591SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
17592SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
17593SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
17594SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
17595SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
17596SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
17597SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
17598#if SELECTTRACE_ENABLED
17599SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
17600#else
17601# define sqlite3SelectSetName(A,B)
17602#endif
17603SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
17604SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
17605SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
17606SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
17607SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
17608SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
17609SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
17610SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
17611
17612#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
17613SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
17614#endif
17615
17616#ifndef SQLITE_OMIT_TRIGGER
17617SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
17618                           Expr*,int, int);
17619SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
17620SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
17621SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
17622SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
17623SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
17624SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
17625                            int, int, int);
17626SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
17627  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
17628SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
17629SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
17630SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
17631                                        Select*,u8);
17632SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
17633SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
17634SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
17635SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
17636SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
17637# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
17638# define sqlite3IsToplevel(p) ((p)->pToplevel==0)
17639#else
17640# define sqlite3TriggersExist(B,C,D,E,F) 0
17641# define sqlite3DeleteTrigger(A,B)
17642# define sqlite3DropTriggerPtr(A,B)
17643# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
17644# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
17645# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
17646# define sqlite3TriggerList(X, Y) 0
17647# define sqlite3ParseToplevel(p) p
17648# define sqlite3IsToplevel(p) 1
17649# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
17650#endif
17651
17652SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
17653SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
17654SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
17655#ifndef SQLITE_OMIT_AUTHORIZATION
17656SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
17657SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
17658SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
17659SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
17660SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
17661#else
17662# define sqlite3AuthRead(a,b,c,d)
17663# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
17664# define sqlite3AuthContextPush(a,b,c)
17665# define sqlite3AuthContextPop(a)  ((void)(a))
17666#endif
17667SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
17668SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
17669SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
17670SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
17671SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
17672SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
17673SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
17674SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
17675SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
17676SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
17677SQLITE_PRIVATE int sqlite3Atoi(const char*);
17678#ifndef SQLITE_OMIT_UTF16
17679SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
17680#endif
17681SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
17682SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
17683SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
17684SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
17685#ifndef SQLITE_OMIT_VIRTUALTABLE
17686SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
17687#endif
17688#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
17689    defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
17690    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
17691SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
17692#endif
17693SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
17694SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
17695SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
17696
17697/*
17698** Routines to read and write variable-length integers.  These used to
17699** be defined locally, but now we use the varint routines in the util.c
17700** file.
17701*/
17702SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
17703SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
17704SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
17705SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
17706
17707/*
17708** The common case is for a varint to be a single byte.  They following
17709** macros handle the common case without a procedure call, but then call
17710** the procedure for larger varints.
17711*/
17712#define getVarint32(A,B)  \
17713  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
17714#define putVarint32(A,B)  \
17715  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
17716  sqlite3PutVarint((A),(B)))
17717#define getVarint    sqlite3GetVarint
17718#define putVarint    sqlite3PutVarint
17719
17720
17721SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
17722SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
17723SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
17724SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
17725SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
17726SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
17727SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
17728SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
17729SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
17730SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
17731SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
17732SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
17733SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
17734SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
17735
17736#if defined(SQLITE_NEED_ERR_NAME)
17737SQLITE_PRIVATE const char *sqlite3ErrName(int);
17738#endif
17739
17740SQLITE_PRIVATE const char *sqlite3ErrStr(int);
17741SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
17742SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
17743SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
17744SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
17745SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
17746SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
17747SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
17748SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
17749SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
17750SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
17751SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
17752SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
17753SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
17754SQLITE_PRIVATE int sqlite3AbsInt32(int);
17755#ifdef SQLITE_ENABLE_8_3_NAMES
17756SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
17757#else
17758# define sqlite3FileSuffix3(X,Y)
17759#endif
17760SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
17761
17762SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
17763SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
17764SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
17765                        void(*)(void*));
17766SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
17767SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
17768SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
17769#ifndef SQLITE_OMIT_UTF16
17770SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
17771#endif
17772SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
17773SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
17774#ifndef SQLITE_AMALGAMATION
17775SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
17776SQLITE_PRIVATE const char sqlite3StrBINARY[];
17777SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
17778SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
17779SQLITE_PRIVATE const Token sqlite3IntTokens[];
17780SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
17781SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
17782#ifndef SQLITE_OMIT_WSD
17783SQLITE_PRIVATE int sqlite3PendingByte;
17784#endif
17785#endif
17786SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
17787SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
17788SQLITE_PRIVATE void sqlite3AlterFunctions(void);
17789SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
17790SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
17791SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
17792SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
17793SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
17794SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
17795SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
17796SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
17797SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
17798SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
17799SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
17800SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
17801SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
17802SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
17803SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
17804SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
17805SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
17806SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
17807SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
17808SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
17809SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
17810SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
17811SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
17812SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
17813SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
17814SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
17815SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
17816SQLITE_PRIVATE void sqlite3SchemaClear(void *);
17817SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
17818SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
17819SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
17820SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
17821SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
17822SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
17823#ifdef SQLITE_DEBUG
17824SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
17825#endif
17826SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
17827  void (*)(sqlite3_context*,int,sqlite3_value **),
17828  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
17829  FuncDestructor *pDestructor
17830);
17831SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
17832SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
17833SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
17834SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
17835
17836SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
17837SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
17838SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
17839SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
17840SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
17841SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
17842SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
17843SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
17844
17845SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
17846SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
17847
17848#ifndef SQLITE_OMIT_SUBQUERY
17849SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
17850#else
17851# define sqlite3ExprCheckIN(x,y) SQLITE_OK
17852#endif
17853
17854#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
17855SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
17856SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
17857    Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
17858SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
17859SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
17860SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
17861SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
17862#endif
17863
17864/*
17865** The interface to the LEMON-generated parser
17866*/
17867#ifndef SQLITE_AMALGAMATION
17868SQLITE_PRIVATE   void *sqlite3ParserAlloc(void*(*)(u64));
17869SQLITE_PRIVATE   void sqlite3ParserFree(void*, void(*)(void*));
17870#endif
17871SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
17872#ifdef YYTRACKMAXSTACKDEPTH
17873SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
17874#endif
17875
17876SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
17877#ifndef SQLITE_OMIT_LOAD_EXTENSION
17878SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
17879#else
17880# define sqlite3CloseExtensions(X)
17881#endif
17882
17883#ifndef SQLITE_OMIT_SHARED_CACHE
17884SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
17885#else
17886  #define sqlite3TableLock(v,w,x,y,z)
17887#endif
17888
17889#ifdef SQLITE_TEST
17890SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
17891#endif
17892
17893#ifdef SQLITE_OMIT_VIRTUALTABLE
17894#  define sqlite3VtabClear(Y)
17895#  define sqlite3VtabSync(X,Y) SQLITE_OK
17896#  define sqlite3VtabRollback(X)
17897#  define sqlite3VtabCommit(X)
17898#  define sqlite3VtabInSync(db) 0
17899#  define sqlite3VtabLock(X)
17900#  define sqlite3VtabUnlock(X)
17901#  define sqlite3VtabUnlockList(X)
17902#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
17903#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
17904#else
17905SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
17906SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
17907SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
17908SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
17909SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
17910SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
17911SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
17912SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
17913SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
17914SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
17915SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
17916SQLITE_PRIVATE    Module *sqlite3VtabCreateModule(
17917     sqlite3*,
17918     const char*,
17919     const sqlite3_module*,
17920     void*,
17921     void(*)(void*)
17922   );
17923#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
17924#endif
17925SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
17926SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
17927SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
17928SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
17929SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
17930SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
17931SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
17932SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
17933SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
17934SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
17935SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
17936SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
17937SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
17938SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
17939SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
17940SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
17941SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
17942SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
17943SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
17944SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
17945SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
17946SQLITE_PRIVATE const char *sqlite3JournalModename(int);
17947#ifndef SQLITE_OMIT_WAL
17948SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
17949SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
17950#endif
17951#ifndef SQLITE_OMIT_CTE
17952SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
17953SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
17954SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
17955#else
17956#define sqlite3WithPush(x,y,z)
17957#define sqlite3WithDelete(x,y)
17958#endif
17959
17960/* Declarations for functions in fkey.c. All of these are replaced by
17961** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
17962** key functionality is available. If OMIT_TRIGGER is defined but
17963** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
17964** this case foreign keys are parsed, but no other functionality is
17965** provided (enforcement of FK constraints requires the triggers sub-system).
17966*/
17967#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
17968SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
17969SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
17970SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
17971SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
17972SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
17973SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
17974#else
17975  #define sqlite3FkActions(a,b,c,d,e,f)
17976  #define sqlite3FkCheck(a,b,c,d,e,f)
17977  #define sqlite3FkDropTable(a,b,c)
17978  #define sqlite3FkOldmask(a,b)         0
17979  #define sqlite3FkRequired(a,b,c,d)    0
17980  #define sqlite3FkReferences(a)        0
17981#endif
17982#ifndef SQLITE_OMIT_FOREIGN_KEY
17983SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
17984SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
17985#else
17986  #define sqlite3FkDelete(a,b)
17987  #define sqlite3FkLocateIndex(a,b,c,d,e)
17988#endif
17989
17990
17991/*
17992** Available fault injectors.  Should be numbered beginning with 0.
17993*/
17994#define SQLITE_FAULTINJECTOR_MALLOC     0
17995#define SQLITE_FAULTINJECTOR_COUNT      1
17996
17997/*
17998** The interface to the code in fault.c used for identifying "benign"
17999** malloc failures. This is only present if SQLITE_UNTESTABLE
18000** is not defined.
18001*/
18002#ifndef SQLITE_UNTESTABLE
18003SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
18004SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
18005#else
18006  #define sqlite3BeginBenignMalloc()
18007  #define sqlite3EndBenignMalloc()
18008#endif
18009
18010/*
18011** Allowed return values from sqlite3FindInIndex()
18012*/
18013#define IN_INDEX_ROWID        1   /* Search the rowid of the table */
18014#define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
18015#define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
18016#define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
18017#define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
18018/*
18019** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
18020*/
18021#define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
18022#define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
18023#define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
18024SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
18025
18026SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
18027SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
18028#ifdef SQLITE_ENABLE_ATOMIC_WRITE
18029SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
18030#endif
18031
18032SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
18033SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
18034
18035SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
18036#if SQLITE_MAX_EXPR_DEPTH>0
18037SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
18038SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
18039#else
18040  #define sqlite3SelectExprHeight(x) 0
18041  #define sqlite3ExprCheckHeight(x,y)
18042#endif
18043
18044SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
18045SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
18046
18047#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
18048SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
18049SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
18050SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
18051#else
18052  #define sqlite3ConnectionBlocked(x,y)
18053  #define sqlite3ConnectionUnlocked(x)
18054  #define sqlite3ConnectionClosed(x)
18055#endif
18056
18057#ifdef SQLITE_DEBUG
18058SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
18059#endif
18060
18061/*
18062** If the SQLITE_ENABLE IOTRACE exists then the global variable
18063** sqlite3IoTrace is a pointer to a printf-like routine used to
18064** print I/O tracing messages.
18065*/
18066#ifdef SQLITE_ENABLE_IOTRACE
18067# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
18068SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
18069SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
18070#else
18071# define IOTRACE(A)
18072# define sqlite3VdbeIOTraceSql(X)
18073#endif
18074
18075/*
18076** These routines are available for the mem2.c debugging memory allocator
18077** only.  They are used to verify that different "types" of memory
18078** allocations are properly tracked by the system.
18079**
18080** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
18081** the MEMTYPE_* macros defined below.  The type must be a bitmask with
18082** a single bit set.
18083**
18084** sqlite3MemdebugHasType() returns true if any of the bits in its second
18085** argument match the type set by the previous sqlite3MemdebugSetType().
18086** sqlite3MemdebugHasType() is intended for use inside assert() statements.
18087**
18088** sqlite3MemdebugNoType() returns true if none of the bits in its second
18089** argument match the type set by the previous sqlite3MemdebugSetType().
18090**
18091** Perhaps the most important point is the difference between MEMTYPE_HEAP
18092** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
18093** it might have been allocated by lookaside, except the allocation was
18094** too large or lookaside was already full.  It is important to verify
18095** that allocations that might have been satisfied by lookaside are not
18096** passed back to non-lookaside free() routines.  Asserts such as the
18097** example above are placed on the non-lookaside free() routines to verify
18098** this constraint.
18099**
18100** All of this is no-op for a production build.  It only comes into
18101** play when the SQLITE_MEMDEBUG compile-time option is used.
18102*/
18103#ifdef SQLITE_MEMDEBUG
18104SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
18105SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
18106SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
18107#else
18108# define sqlite3MemdebugSetType(X,Y)  /* no-op */
18109# define sqlite3MemdebugHasType(X,Y)  1
18110# define sqlite3MemdebugNoType(X,Y)   1
18111#endif
18112#define MEMTYPE_HEAP       0x01  /* General heap allocations */
18113#define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
18114#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
18115#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
18116
18117/*
18118** Threading interface
18119*/
18120#if SQLITE_MAX_WORKER_THREADS>0
18121SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
18122SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
18123#endif
18124
18125#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
18126SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
18127#endif
18128
18129SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
18130SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
18131SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
18132SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
18133SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
18134
18135#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
18136SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
18137#endif
18138
18139#endif /* SQLITEINT_H */
18140
18141/************** End of sqliteInt.h *******************************************/
18142/************** Begin file global.c ******************************************/
18143/*
18144** 2008 June 13
18145**
18146** The author disclaims copyright to this source code.  In place of
18147** a legal notice, here is a blessing:
18148**
18149**    May you do good and not evil.
18150**    May you find forgiveness for yourself and forgive others.
18151**    May you share freely, never taking more than you give.
18152**
18153*************************************************************************
18154**
18155** This file contains definitions of global variables and constants.
18156*/
18157/* #include "sqliteInt.h" */
18158
18159/* An array to map all upper-case characters into their corresponding
18160** lower-case character.
18161**
18162** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
18163** handle case conversions for the UTF character set since the tables
18164** involved are nearly as big or bigger than SQLite itself.
18165*/
18166SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
18167#ifdef SQLITE_ASCII
18168      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
18169     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
18170     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
18171     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
18172    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
18173    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
18174    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
18175    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
18176    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
18177    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
18178    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
18179    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
18180    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
18181    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
18182    252,253,254,255
18183#endif
18184#ifdef SQLITE_EBCDIC
18185      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
18186     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
18187     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
18188     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
18189     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
18190     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
18191     96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
18192    112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
18193    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
18194    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
18195    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
18196    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
18197    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
18198    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
18199    224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
18200    240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
18201#endif
18202};
18203
18204/*
18205** The following 256 byte lookup table is used to support SQLites built-in
18206** equivalents to the following standard library functions:
18207**
18208**   isspace()                        0x01
18209**   isalpha()                        0x02
18210**   isdigit()                        0x04
18211**   isalnum()                        0x06
18212**   isxdigit()                       0x08
18213**   toupper()                        0x20
18214**   SQLite identifier character      0x40
18215**   Quote character                  0x80
18216**
18217** Bit 0x20 is set if the mapped character requires translation to upper
18218** case. i.e. if the character is a lower-case ASCII character.
18219** If x is a lower-case ASCII character, then its upper-case equivalent
18220** is (x - 0x20). Therefore toupper() can be implemented as:
18221**
18222**   (x & ~(map[x]&0x20))
18223**
18224** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
18225** array. tolower() is used more often than toupper() by SQLite.
18226**
18227** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
18228** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
18229** non-ASCII UTF character. Hence the test for whether or not a character is
18230** part of an identifier is 0x46.
18231*/
18232#ifdef SQLITE_ASCII
18233SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
18234  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
18235  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
18236  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
18237  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
18238  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !"#$%&' */
18239  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
18240  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
18241  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
18242
18243  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
18244  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
18245  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
18246  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
18247  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
18248  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
18249  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
18250  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
18251
18252  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
18253  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
18254  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
18255  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
18256  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
18257  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
18258  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
18259  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
18260
18261  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
18262  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
18263  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
18264  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
18265  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
18266  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
18267  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
18268  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
18269};
18270#endif
18271
18272/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
18273** compatibility for legacy applications, the URI filename capability is
18274** disabled by default.
18275**
18276** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
18277** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
18278**
18279** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
18280** disabled. The default value may be changed by compiling with the
18281** SQLITE_USE_URI symbol defined.
18282**
18283** URI filenames are enabled by default if SQLITE_HAS_CODEC is
18284** enabled.
18285*/
18286#ifndef SQLITE_USE_URI
18287# ifdef SQLITE_HAS_CODEC
18288#  define SQLITE_USE_URI 1
18289# else
18290#  define SQLITE_USE_URI 0
18291# endif
18292#endif
18293
18294/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
18295** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
18296** that compile-time option is omitted.
18297*/
18298#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
18299# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
18300#endif
18301
18302/* The minimum PMA size is set to this value multiplied by the database
18303** page size in bytes.
18304*/
18305#ifndef SQLITE_SORTER_PMASZ
18306# define SQLITE_SORTER_PMASZ 250
18307#endif
18308
18309/* Statement journals spill to disk when their size exceeds the following
18310** threshold (in bytes). 0 means that statement journals are created and
18311** written to disk immediately (the default behavior for SQLite versions
18312** before 3.12.0).  -1 means always keep the entire statement journal in
18313** memory.  (The statement journal is also always held entirely in memory
18314** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
18315** setting.)
18316*/
18317#ifndef SQLITE_STMTJRNL_SPILL
18318# define SQLITE_STMTJRNL_SPILL (64*1024)
18319#endif
18320
18321/*
18322** The default lookaside-configuration, the format "SZ,N".  SZ is the
18323** number of bytes in each lookaside slot (should be a multiple of 8)
18324** and N is the number of slots.  The lookaside-configuration can be
18325** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
18326** or at run-time for an individual database connection using
18327** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
18328*/
18329#ifndef SQLITE_DEFAULT_LOOKASIDE
18330# define SQLITE_DEFAULT_LOOKASIDE 1200,100
18331#endif
18332
18333
18334/*
18335** The following singleton contains the global configuration for
18336** the SQLite library.
18337*/
18338SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
18339   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
18340   1,                         /* bCoreMutex */
18341   SQLITE_THREADSAFE==1,      /* bFullMutex */
18342   SQLITE_USE_URI,            /* bOpenUri */
18343   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
18344   0x7ffffffe,                /* mxStrlen */
18345   0,                         /* neverCorrupt */
18346   SQLITE_DEFAULT_LOOKASIDE,  /* szLookaside, nLookaside */
18347   SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
18348   {0,0,0,0,0,0,0,0},         /* m */
18349   {0,0,0,0,0,0,0,0,0},       /* mutex */
18350   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
18351   (void*)0,                  /* pHeap */
18352   0,                         /* nHeap */
18353   0, 0,                      /* mnHeap, mxHeap */
18354   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
18355   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
18356   (void*)0,                  /* pScratch */
18357   0,                         /* szScratch */
18358   0,                         /* nScratch */
18359   (void*)0,                  /* pPage */
18360   0,                         /* szPage */
18361   SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
18362   0,                         /* mxParserStack */
18363   0,                         /* sharedCacheEnabled */
18364   SQLITE_SORTER_PMASZ,       /* szPma */
18365   /* All the rest should always be initialized to zero */
18366   0,                         /* isInit */
18367   0,                         /* inProgress */
18368   0,                         /* isMutexInit */
18369   0,                         /* isMallocInit */
18370   0,                         /* isPCacheInit */
18371   0,                         /* nRefInitMutex */
18372   0,                         /* pInitMutex */
18373   0,                         /* xLog */
18374   0,                         /* pLogArg */
18375#ifdef SQLITE_ENABLE_SQLLOG
18376   0,                         /* xSqllog */
18377   0,                         /* pSqllogArg */
18378#endif
18379#ifdef SQLITE_VDBE_COVERAGE
18380   0,                         /* xVdbeBranch */
18381   0,                         /* pVbeBranchArg */
18382#endif
18383#ifndef SQLITE_UNTESTABLE
18384   0,                         /* xTestCallback */
18385#endif
18386   0,                         /* bLocaltimeFault */
18387   0x7ffffffe                 /* iOnceResetThreshold */
18388};
18389
18390/*
18391** Hash table for global functions - functions common to all
18392** database connections.  After initialization, this table is
18393** read-only.
18394*/
18395SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
18396
18397/*
18398** Constant tokens for values 0 and 1.
18399*/
18400SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
18401   { "0", 1 },
18402   { "1", 1 }
18403};
18404
18405
18406/*
18407** The value of the "pending" byte must be 0x40000000 (1 byte past the
18408** 1-gibabyte boundary) in a compatible database.  SQLite never uses
18409** the database page that contains the pending byte.  It never attempts
18410** to read or write that page.  The pending byte page is set aside
18411** for use by the VFS layers as space for managing file locks.
18412**
18413** During testing, it is often desirable to move the pending byte to
18414** a different position in the file.  This allows code that has to
18415** deal with the pending byte to run on files that are much smaller
18416** than 1 GiB.  The sqlite3_test_control() interface can be used to
18417** move the pending byte.
18418**
18419** IMPORTANT:  Changing the pending byte to any value other than
18420** 0x40000000 results in an incompatible database file format!
18421** Changing the pending byte during operation will result in undefined
18422** and incorrect behavior.
18423*/
18424#ifndef SQLITE_OMIT_WSD
18425SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
18426#endif
18427
18428/* #include "opcodes.h" */
18429/*
18430** Properties of opcodes.  The OPFLG_INITIALIZER macro is
18431** created by mkopcodeh.awk during compilation.  Data is obtained
18432** from the comments following the "case OP_xxxx:" statements in
18433** the vdbe.c file.
18434*/
18435SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
18436
18437/*
18438** Name of the default collating sequence
18439*/
18440SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
18441
18442/************** End of global.c **********************************************/
18443/************** Begin file status.c ******************************************/
18444/*
18445** 2008 June 18
18446**
18447** The author disclaims copyright to this source code.  In place of
18448** a legal notice, here is a blessing:
18449**
18450**    May you do good and not evil.
18451**    May you find forgiveness for yourself and forgive others.
18452**    May you share freely, never taking more than you give.
18453**
18454*************************************************************************
18455**
18456** This module implements the sqlite3_status() interface and related
18457** functionality.
18458*/
18459/* #include "sqliteInt.h" */
18460/************** Include vdbeInt.h in the middle of status.c ******************/
18461/************** Begin file vdbeInt.h *****************************************/
18462/*
18463** 2003 September 6
18464**
18465** The author disclaims copyright to this source code.  In place of
18466** a legal notice, here is a blessing:
18467**
18468**    May you do good and not evil.
18469**    May you find forgiveness for yourself and forgive others.
18470**    May you share freely, never taking more than you give.
18471**
18472*************************************************************************
18473** This is the header file for information that is private to the
18474** VDBE.  This information used to all be at the top of the single
18475** source code file "vdbe.c".  When that file became too big (over
18476** 6000 lines long) it was split up into several smaller files and
18477** this header information was factored out.
18478*/
18479#ifndef SQLITE_VDBEINT_H
18480#define SQLITE_VDBEINT_H
18481
18482/*
18483** The maximum number of times that a statement will try to reparse
18484** itself before giving up and returning SQLITE_SCHEMA.
18485*/
18486#ifndef SQLITE_MAX_SCHEMA_RETRY
18487# define SQLITE_MAX_SCHEMA_RETRY 50
18488#endif
18489
18490/*
18491** VDBE_DISPLAY_P4 is true or false depending on whether or not the
18492** "explain" P4 display logic is enabled.
18493*/
18494#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
18495     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
18496# define VDBE_DISPLAY_P4 1
18497#else
18498# define VDBE_DISPLAY_P4 0
18499#endif
18500
18501/*
18502** SQL is translated into a sequence of instructions to be
18503** executed by a virtual machine.  Each instruction is an instance
18504** of the following structure.
18505*/
18506typedef struct VdbeOp Op;
18507
18508/*
18509** Boolean values
18510*/
18511typedef unsigned Bool;
18512
18513/* Opaque type used by code in vdbesort.c */
18514typedef struct VdbeSorter VdbeSorter;
18515
18516/* Elements of the linked list at Vdbe.pAuxData */
18517typedef struct AuxData AuxData;
18518
18519/* Types of VDBE cursors */
18520#define CURTYPE_BTREE       0
18521#define CURTYPE_SORTER      1
18522#define CURTYPE_VTAB        2
18523#define CURTYPE_PSEUDO      3
18524
18525/*
18526** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
18527**
18528**      * A b-tree cursor
18529**          -  In the main database or in an ephemeral database
18530**          -  On either an index or a table
18531**      * A sorter
18532**      * A virtual table
18533**      * A one-row "pseudotable" stored in a single register
18534*/
18535typedef struct VdbeCursor VdbeCursor;
18536struct VdbeCursor {
18537  u8 eCurType;            /* One of the CURTYPE_* values above */
18538  i8 iDb;                 /* Index of cursor database in db->aDb[] (or -1) */
18539  u8 nullRow;             /* True if pointing to a row with no data */
18540  u8 deferredMoveto;      /* A call to sqlite3BtreeMoveto() is needed */
18541  u8 isTable;             /* True for rowid tables.  False for indexes */
18542#ifdef SQLITE_DEBUG
18543  u8 seekOp;              /* Most recent seek operation on this cursor */
18544  u8 wrFlag;              /* The wrFlag argument to sqlite3BtreeCursor() */
18545#endif
18546  Bool isEphemeral:1;     /* True for an ephemeral table */
18547  Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */
18548  Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */
18549  Btree *pBtx;            /* Separate file holding temporary table */
18550  i64 seqCount;           /* Sequence counter */
18551  int *aAltMap;           /* Mapping from table to index column numbers */
18552
18553  /* Cached OP_Column parse information is only valid if cacheStatus matches
18554  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
18555  ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
18556  ** the cache is out of date. */
18557  u32 cacheStatus;        /* Cache is valid if this matches Vdbe.cacheCtr */
18558  int seekResult;         /* Result of previous sqlite3BtreeMoveto() or 0
18559                          ** if there have been no prior seeks on the cursor. */
18560  /* NB: seekResult does not distinguish between "no seeks have ever occurred
18561  ** on this cursor" and "the most recent seek was an exact match". */
18562
18563  /* When a new VdbeCursor is allocated, only the fields above are zeroed.
18564  ** The fields that follow are uninitialized, and must be individually
18565  ** initialized prior to first use. */
18566  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
18567  union {
18568    BtCursor *pCursor;          /* CURTYPE_BTREE.  Btree cursor */
18569    sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.   Vtab cursor */
18570    int pseudoTableReg;         /* CURTYPE_PSEUDO. Reg holding content. */
18571    VdbeSorter *pSorter;        /* CURTYPE_SORTER. Sorter object */
18572  } uc;
18573  KeyInfo *pKeyInfo;      /* Info about index keys needed by index cursors */
18574  u32 iHdrOffset;         /* Offset to next unparsed byte of the header */
18575  Pgno pgnoRoot;          /* Root page of the open btree cursor */
18576  i16 nField;             /* Number of fields in the header */
18577  u16 nHdrParsed;         /* Number of header fields parsed so far */
18578  i64 movetoTarget;       /* Argument to the deferred sqlite3BtreeMoveto() */
18579  u32 *aOffset;           /* Pointer to aType[nField] */
18580  const u8 *aRow;         /* Data for the current row, if all on one page */
18581  u32 payloadSize;        /* Total number of bytes in the record */
18582  u32 szRow;              /* Byte available in aRow */
18583#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
18584  u64 maskUsed;           /* Mask of columns used by this cursor */
18585#endif
18586
18587  /* 2*nField extra array elements allocated for aType[], beyond the one
18588  ** static element declared in the structure.  nField total array slots for
18589  ** aType[] and nField+1 array slots for aOffset[] */
18590  u32 aType[1];           /* Type values record decode.  MUST BE LAST */
18591};
18592
18593
18594/*
18595** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
18596*/
18597#define CACHE_STALE 0
18598
18599/*
18600** When a sub-program is executed (OP_Program), a structure of this type
18601** is allocated to store the current value of the program counter, as
18602** well as the current memory cell array and various other frame specific
18603** values stored in the Vdbe struct. When the sub-program is finished,
18604** these values are copied back to the Vdbe from the VdbeFrame structure,
18605** restoring the state of the VM to as it was before the sub-program
18606** began executing.
18607**
18608** The memory for a VdbeFrame object is allocated and managed by a memory
18609** cell in the parent (calling) frame. When the memory cell is deleted or
18610** overwritten, the VdbeFrame object is not freed immediately. Instead, it
18611** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
18612** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
18613** this instead of deleting the VdbeFrame immediately is to avoid recursive
18614** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
18615** child frame are released.
18616**
18617** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
18618** set to NULL if the currently executing frame is the main program.
18619*/
18620typedef struct VdbeFrame VdbeFrame;
18621struct VdbeFrame {
18622  Vdbe *v;                /* VM this frame belongs to */
18623  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
18624  Op *aOp;                /* Program instructions for parent frame */
18625  i64 *anExec;            /* Event counters from parent frame */
18626  Mem *aMem;              /* Array of memory cells for parent frame */
18627  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
18628  u8 *aOnce;              /* Bitmask used by OP_Once */
18629  void *token;            /* Copy of SubProgram.token */
18630  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
18631  AuxData *pAuxData;      /* Linked list of auxdata allocations */
18632  int nCursor;            /* Number of entries in apCsr */
18633  int pc;                 /* Program Counter in parent (calling) frame */
18634  int nOp;                /* Size of aOp array */
18635  int nMem;               /* Number of entries in aMem */
18636  int nChildMem;          /* Number of memory cells for child frame */
18637  int nChildCsr;          /* Number of cursors for child frame */
18638  int nChange;            /* Statement changes (Vdbe.nChange)     */
18639  int nDbChange;          /* Value of db->nChange */
18640};
18641
18642#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
18643
18644/*
18645** Internally, the vdbe manipulates nearly all SQL values as Mem
18646** structures. Each Mem struct may cache multiple representations (string,
18647** integer etc.) of the same value.
18648*/
18649struct sqlite3_value {
18650  union MemValue {
18651    double r;           /* Real value used when MEM_Real is set in flags */
18652    i64 i;              /* Integer value used when MEM_Int is set in flags */
18653    int nZero;          /* Extra zero bytes when MEM_Zero and MEM_Blob set */
18654    const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
18655    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
18656    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
18657    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
18658  } u;
18659  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18660  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18661  u8  eSubtype;       /* Subtype for this value */
18662  int n;              /* Number of characters in string value, excluding '\0' */
18663  char *z;            /* String or BLOB value */
18664  /* ShallowCopy only needs to copy the information above */
18665  char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
18666  int szMalloc;       /* Size of the zMalloc allocation */
18667  u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
18668  sqlite3 *db;        /* The associated database connection */
18669  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
18670#ifdef SQLITE_DEBUG
18671  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
18672  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
18673#endif
18674};
18675
18676/*
18677** Size of struct Mem not including the Mem.zMalloc member or anything that
18678** follows.
18679*/
18680#define MEMCELLSIZE offsetof(Mem,zMalloc)
18681
18682/* One or more of the following flags are set to indicate the validOK
18683** representations of the value stored in the Mem struct.
18684**
18685** If the MEM_Null flag is set, then the value is an SQL NULL value.
18686** For a pointer type created using sqlite3_bind_pointer() or
18687** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
18688**
18689** If the MEM_Str flag is set then Mem.z points at a string representation.
18690** Usually this is encoded in the same unicode encoding as the main
18691** database (see below for exceptions). If the MEM_Term flag is also
18692** set, then the string is nul terminated. The MEM_Int and MEM_Real
18693** flags may coexist with the MEM_Str flag.
18694*/
18695#define MEM_Null      0x0001   /* Value is NULL (or a pointer) */
18696#define MEM_Str       0x0002   /* Value is a string */
18697#define MEM_Int       0x0004   /* Value is an integer */
18698#define MEM_Real      0x0008   /* Value is a real number */
18699#define MEM_Blob      0x0010   /* Value is a BLOB */
18700#define MEM_AffMask   0x001f   /* Mask of affinity bits */
18701#define MEM_RowSet    0x0020   /* Value is a RowSet object */
18702#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
18703#define MEM_Undefined 0x0080   /* Value is undefined */
18704#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
18705#define MEM_TypeMask  0xc1ff   /* Mask of type bits */
18706
18707
18708/* Whenever Mem contains a valid string or blob representation, one of
18709** the following flags must be set to determine the memory management
18710** policy for Mem.z.  The MEM_Term flag tells us whether or not the
18711** string is \000 or \u0000 terminated
18712*/
18713#define MEM_Term      0x0200   /* String in Mem.z is zero terminated */
18714#define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
18715#define MEM_Static    0x0800   /* Mem.z points to a static string */
18716#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
18717#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
18718#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
18719#define MEM_Subtype   0x8000   /* Mem.eSubtype is valid */
18720#ifdef SQLITE_OMIT_INCRBLOB
18721  #undef MEM_Zero
18722  #define MEM_Zero 0x0000
18723#endif
18724
18725/* Return TRUE if Mem X contains dynamically allocated content - anything
18726** that needs to be deallocated to avoid a leak.
18727*/
18728#define VdbeMemDynamic(X)  \
18729  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
18730
18731/*
18732** Clear any existing type flags from a Mem and replace them with f
18733*/
18734#define MemSetTypeFlag(p, f) \
18735   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
18736
18737/*
18738** Return true if a memory cell is not marked as invalid.  This macro
18739** is for use inside assert() statements only.
18740*/
18741#ifdef SQLITE_DEBUG
18742#define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
18743#endif
18744
18745/*
18746** Each auxiliary data pointer stored by a user defined function
18747** implementation calling sqlite3_set_auxdata() is stored in an instance
18748** of this structure. All such structures associated with a single VM
18749** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
18750** when the VM is halted (if not before).
18751*/
18752struct AuxData {
18753  int iAuxOp;                     /* Instruction number of OP_Function opcode */
18754  int iAuxArg;                    /* Index of function argument. */
18755  void *pAux;                     /* Aux data pointer */
18756  void (*xDeleteAux)(void*);      /* Destructor for the aux data */
18757  AuxData *pNextAux;              /* Next element in list */
18758};
18759
18760/*
18761** The "context" argument for an installable function.  A pointer to an
18762** instance of this structure is the first argument to the routines used
18763** implement the SQL functions.
18764**
18765** There is a typedef for this structure in sqlite.h.  So all routines,
18766** even the public interface to SQLite, can use a pointer to this structure.
18767** But this file is the only place where the internal details of this
18768** structure are known.
18769**
18770** This structure is defined inside of vdbeInt.h because it uses substructures
18771** (Mem) which are only defined there.
18772*/
18773struct sqlite3_context {
18774  Mem *pOut;              /* The return value is stored here */
18775  FuncDef *pFunc;         /* Pointer to function information */
18776  Mem *pMem;              /* Memory cell used to store aggregate context */
18777  Vdbe *pVdbe;            /* The VM that owns this context */
18778  int iOp;                /* Instruction number of OP_Function */
18779  int isError;            /* Error code returned by the function. */
18780  u8 skipFlag;            /* Skip accumulator loading if true */
18781  u8 fErrorOrAux;         /* isError!=0 or pVdbe->pAuxData modified */
18782  u8 argc;                /* Number of arguments */
18783  sqlite3_value *argv[1]; /* Argument set */
18784};
18785
18786/* A bitfield type for use inside of structures.  Always follow with :N where
18787** N is the number of bits.
18788*/
18789typedef unsigned bft;  /* Bit Field Type */
18790
18791typedef struct ScanStatus ScanStatus;
18792struct ScanStatus {
18793  int addrExplain;                /* OP_Explain for loop */
18794  int addrLoop;                   /* Address of "loops" counter */
18795  int addrVisit;                  /* Address of "rows visited" counter */
18796  int iSelectID;                  /* The "Select-ID" for this loop */
18797  LogEst nEst;                    /* Estimated output rows per loop */
18798  char *zName;                    /* Name of table or index */
18799};
18800
18801/*
18802** An instance of the virtual machine.  This structure contains the complete
18803** state of the virtual machine.
18804**
18805** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
18806** is really a pointer to an instance of this structure.
18807*/
18808struct Vdbe {
18809  sqlite3 *db;            /* The database connection that owns this statement */
18810  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
18811  Parse *pParse;          /* Parsing context used to create this Vdbe */
18812  ynVar nVar;             /* Number of entries in aVar[] */
18813  u32 magic;              /* Magic number for sanity checking */
18814  int nMem;               /* Number of memory locations currently allocated */
18815  int nCursor;            /* Number of slots in apCsr[] */
18816  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
18817  int pc;                 /* The program counter */
18818  int rc;                 /* Value to return */
18819  int nChange;            /* Number of db changes made since last reset */
18820  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
18821  i64 iCurrentTime;       /* Value of julianday('now') for this statement */
18822  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
18823  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
18824  i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
18825
18826  /* When allocating a new Vdbe object, all of the fields below should be
18827  ** initialized to zero or NULL */
18828
18829  Op *aOp;                /* Space to hold the virtual machine's program */
18830  Mem *aMem;              /* The memory locations */
18831  Mem **apArg;            /* Arguments to currently executing user function */
18832  Mem *aColName;          /* Column names to return */
18833  Mem *pResultSet;        /* Pointer to an array of results */
18834  char *zErrMsg;          /* Error message written here */
18835  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
18836  Mem *aVar;              /* Values for the OP_Variable opcode. */
18837  VList *pVList;          /* Name of variables */
18838#ifndef SQLITE_OMIT_TRACE
18839  i64 startTime;          /* Time when query started - used for profiling */
18840#endif
18841  int nOp;                /* Number of instructions in the program */
18842#ifdef SQLITE_DEBUG
18843  int rcApp;              /* errcode set by sqlite3_result_error_code() */
18844#endif
18845  u16 nResColumn;         /* Number of columns in one row of the result set */
18846  u8 errorAction;         /* Recovery action to do in case of an error */
18847  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18848  u8 prepFlags;           /* SQLITE_PREPARE_* flags */
18849  bft expired:1;          /* True if the VM needs to be recompiled */
18850  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
18851  bft explain:2;          /* True if EXPLAIN present on SQL command */
18852  bft changeCntOn:1;      /* True to update the change-counter */
18853  bft runOnlyOnce:1;      /* Automatically expire on reset */
18854  bft usesStmtJournal:1;  /* True if uses a statement journal */
18855  bft readOnly:1;         /* True for statements that do not write */
18856  bft bIsReader:1;        /* True for statements that read */
18857  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
18858  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
18859  u32 aCounter[7];        /* Counters used by sqlite3_stmt_status() */
18860  char *zSql;             /* Text of the SQL statement that generated this */
18861  void *pFree;            /* Free this when deleting the vdbe */
18862  VdbeFrame *pFrame;      /* Parent frame */
18863  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
18864  int nFrame;             /* Number of frames in pFrame list */
18865  u32 expmask;            /* Binding to these vars invalidates VM */
18866  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
18867  AuxData *pAuxData;      /* Linked list of auxdata allocations */
18868#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18869  i64 *anExec;            /* Number of times each op has been executed */
18870  int nScan;              /* Entries in aScan[] */
18871  ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
18872#endif
18873};
18874
18875/*
18876** The following are allowed values for Vdbe.magic
18877*/
18878#define VDBE_MAGIC_INIT     0x16bceaa5    /* Building a VDBE program */
18879#define VDBE_MAGIC_RUN      0x2df20da3    /* VDBE is ready to execute */
18880#define VDBE_MAGIC_HALT     0x319c2973    /* VDBE has completed execution */
18881#define VDBE_MAGIC_RESET    0x48fa9f76    /* Reset and ready to run again */
18882#define VDBE_MAGIC_DEAD     0x5606c3c8    /* The VDBE has been deallocated */
18883
18884/*
18885** Structure used to store the context required by the
18886** sqlite3_preupdate_*() API functions.
18887*/
18888struct PreUpdate {
18889  Vdbe *v;
18890  VdbeCursor *pCsr;               /* Cursor to read old values from */
18891  int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */
18892  u8 *aRecord;                    /* old.* database record */
18893  KeyInfo keyinfo;
18894  UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
18895  UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
18896  int iNewReg;                    /* Register for new.* values */
18897  i64 iKey1;                      /* First key value passed to hook */
18898  i64 iKey2;                      /* Second key value passed to hook */
18899  Mem *aNew;                      /* Array of new.* values */
18900  Table *pTab;                    /* Schema object being upated */
18901  Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */
18902};
18903
18904/*
18905** Function prototypes
18906*/
18907SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
18908SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18909void sqliteVdbePopStack(Vdbe*,int);
18910SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
18911SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
18912#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18913SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18914#endif
18915SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18916SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
18917SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
18918SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
18919SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18920SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
18921
18922int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18923SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
18924SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
18925SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18926SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18927SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18928SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18929SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18930SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18931SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18932SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18933SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18934SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18935SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18936#ifdef SQLITE_OMIT_FLOATING_POINT
18937# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18938#else
18939SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
18940#endif
18941SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
18942SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
18943SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18944SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18945SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18946SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18947SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
18948SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18949SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18950SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18951SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18952SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18953SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18954SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
18955SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
18956SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18957SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18958SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18959SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18960SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
18961SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18962SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18963SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18964#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
18965SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
18966#endif
18967SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
18968
18969SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
18970SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
18971SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
18972SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
18973SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
18974SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
18975SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
18976SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
18977
18978#if !defined(SQLITE_OMIT_SHARED_CACHE)
18979SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
18980#else
18981# define sqlite3VdbeEnter(X)
18982#endif
18983
18984#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
18985SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
18986#else
18987# define sqlite3VdbeLeave(X)
18988#endif
18989
18990#ifdef SQLITE_DEBUG
18991SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
18992SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
18993#endif
18994
18995#ifndef SQLITE_OMIT_FOREIGN_KEY
18996SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18997#else
18998# define sqlite3VdbeCheckFk(p,i) 0
18999#endif
19000
19001#ifdef SQLITE_DEBUG
19002SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
19003SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
19004#endif
19005#ifndef SQLITE_OMIT_UTF16
19006SQLITE_PRIVATE   int sqlite3VdbeMemTranslate(Mem*, u8);
19007SQLITE_PRIVATE   int sqlite3VdbeMemHandleBom(Mem *pMem);
19008#endif
19009
19010#ifndef SQLITE_OMIT_INCRBLOB
19011SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
19012  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
19013#else
19014  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
19015  #define ExpandBlob(P) SQLITE_OK
19016#endif
19017
19018#endif /* !defined(SQLITE_VDBEINT_H) */
19019
19020/************** End of vdbeInt.h *********************************************/
19021/************** Continuing where we left off in status.c *********************/
19022
19023/*
19024** Variables in which to record status information.
19025*/
19026#if SQLITE_PTRSIZE>4
19027typedef sqlite3_int64 sqlite3StatValueType;
19028#else
19029typedef u32 sqlite3StatValueType;
19030#endif
19031typedef struct sqlite3StatType sqlite3StatType;
19032static SQLITE_WSD struct sqlite3StatType {
19033  sqlite3StatValueType nowValue[10];  /* Current value */
19034  sqlite3StatValueType mxValue[10];   /* Maximum value */
19035} sqlite3Stat = { {0,}, {0,} };
19036
19037/*
19038** Elements of sqlite3Stat[] are protected by either the memory allocator
19039** mutex, or by the pcache1 mutex.  The following array determines which.
19040*/
19041static const char statMutex[] = {
19042  0,  /* SQLITE_STATUS_MEMORY_USED */
19043  1,  /* SQLITE_STATUS_PAGECACHE_USED */
19044  1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
19045  0,  /* SQLITE_STATUS_SCRATCH_USED */
19046  0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
19047  0,  /* SQLITE_STATUS_MALLOC_SIZE */
19048  0,  /* SQLITE_STATUS_PARSER_STACK */
19049  1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
19050  0,  /* SQLITE_STATUS_SCRATCH_SIZE */
19051  0,  /* SQLITE_STATUS_MALLOC_COUNT */
19052};
19053
19054
19055/* The "wsdStat" macro will resolve to the status information
19056** state vector.  If writable static data is unsupported on the target,
19057** we have to locate the state vector at run-time.  In the more common
19058** case where writable static data is supported, wsdStat can refer directly
19059** to the "sqlite3Stat" state vector declared above.
19060*/
19061#ifdef SQLITE_OMIT_WSD
19062# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
19063# define wsdStat x[0]
19064#else
19065# define wsdStatInit
19066# define wsdStat sqlite3Stat
19067#endif
19068
19069/*
19070** Return the current value of a status parameter.  The caller must
19071** be holding the appropriate mutex.
19072*/
19073SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
19074  wsdStatInit;
19075  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
19076  assert( op>=0 && op<ArraySize(statMutex) );
19077  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
19078                                           : sqlite3MallocMutex()) );
19079  return wsdStat.nowValue[op];
19080}
19081
19082/*
19083** Add N to the value of a status record.  The caller must hold the
19084** appropriate mutex.  (Locking is checked by assert()).
19085**
19086** The StatusUp() routine can accept positive or negative values for N.
19087** The value of N is added to the current status value and the high-water
19088** mark is adjusted if necessary.
19089**
19090** The StatusDown() routine lowers the current value by N.  The highwater
19091** mark is unchanged.  N must be non-negative for StatusDown().
19092*/
19093SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
19094  wsdStatInit;
19095  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
19096  assert( op>=0 && op<ArraySize(statMutex) );
19097  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
19098                                           : sqlite3MallocMutex()) );
19099  wsdStat.nowValue[op] += N;
19100  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
19101    wsdStat.mxValue[op] = wsdStat.nowValue[op];
19102  }
19103}
19104SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
19105  wsdStatInit;
19106  assert( N>=0 );
19107  assert( op>=0 && op<ArraySize(statMutex) );
19108  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
19109                                           : sqlite3MallocMutex()) );
19110  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
19111  wsdStat.nowValue[op] -= N;
19112}
19113
19114/*
19115** Adjust the highwater mark if necessary.
19116** The caller must hold the appropriate mutex.
19117*/
19118SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
19119  sqlite3StatValueType newValue;
19120  wsdStatInit;
19121  assert( X>=0 );
19122  newValue = (sqlite3StatValueType)X;
19123  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
19124  assert( op>=0 && op<ArraySize(statMutex) );
19125  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
19126                                           : sqlite3MallocMutex()) );
19127  assert( op==SQLITE_STATUS_MALLOC_SIZE
19128          || op==SQLITE_STATUS_PAGECACHE_SIZE
19129          || op==SQLITE_STATUS_SCRATCH_SIZE
19130          || op==SQLITE_STATUS_PARSER_STACK );
19131  if( newValue>wsdStat.mxValue[op] ){
19132    wsdStat.mxValue[op] = newValue;
19133  }
19134}
19135
19136/*
19137** Query status information.
19138*/
19139SQLITE_API int sqlite3_status64(
19140  int op,
19141  sqlite3_int64 *pCurrent,
19142  sqlite3_int64 *pHighwater,
19143  int resetFlag
19144){
19145  sqlite3_mutex *pMutex;
19146  wsdStatInit;
19147  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
19148    return SQLITE_MISUSE_BKPT;
19149  }
19150#ifdef SQLITE_ENABLE_API_ARMOR
19151  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
19152#endif
19153  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
19154  sqlite3_mutex_enter(pMutex);
19155  *pCurrent = wsdStat.nowValue[op];
19156  *pHighwater = wsdStat.mxValue[op];
19157  if( resetFlag ){
19158    wsdStat.mxValue[op] = wsdStat.nowValue[op];
19159  }
19160  sqlite3_mutex_leave(pMutex);
19161  (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
19162  return SQLITE_OK;
19163}
19164SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
19165  sqlite3_int64 iCur = 0, iHwtr = 0;
19166  int rc;
19167#ifdef SQLITE_ENABLE_API_ARMOR
19168  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
19169#endif
19170  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
19171  if( rc==0 ){
19172    *pCurrent = (int)iCur;
19173    *pHighwater = (int)iHwtr;
19174  }
19175  return rc;
19176}
19177
19178/*
19179** Query status information for a single database connection
19180*/
19181SQLITE_API int sqlite3_db_status(
19182  sqlite3 *db,          /* The database connection whose status is desired */
19183  int op,               /* Status verb */
19184  int *pCurrent,        /* Write current value here */
19185  int *pHighwater,      /* Write high-water mark here */
19186  int resetFlag         /* Reset high-water mark if true */
19187){
19188  int rc = SQLITE_OK;   /* Return code */
19189#ifdef SQLITE_ENABLE_API_ARMOR
19190  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
19191    return SQLITE_MISUSE_BKPT;
19192  }
19193#endif
19194  sqlite3_mutex_enter(db->mutex);
19195  switch( op ){
19196    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
19197      *pCurrent = db->lookaside.nOut;
19198      *pHighwater = db->lookaside.mxOut;
19199      if( resetFlag ){
19200        db->lookaside.mxOut = db->lookaside.nOut;
19201      }
19202      break;
19203    }
19204
19205    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
19206    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
19207    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
19208      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
19209      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
19210      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
19211      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
19212      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
19213      *pCurrent = 0;
19214      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
19215      if( resetFlag ){
19216        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
19217      }
19218      break;
19219    }
19220
19221    /*
19222    ** Return an approximation for the amount of memory currently used
19223    ** by all pagers associated with the given database connection.  The
19224    ** highwater mark is meaningless and is returned as zero.
19225    */
19226    case SQLITE_DBSTATUS_CACHE_USED_SHARED:
19227    case SQLITE_DBSTATUS_CACHE_USED: {
19228      int totalUsed = 0;
19229      int i;
19230      sqlite3BtreeEnterAll(db);
19231      for(i=0; i<db->nDb; i++){
19232        Btree *pBt = db->aDb[i].pBt;
19233        if( pBt ){
19234          Pager *pPager = sqlite3BtreePager(pBt);
19235          int nByte = sqlite3PagerMemUsed(pPager);
19236          if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
19237            nByte = nByte / sqlite3BtreeConnectionCount(pBt);
19238          }
19239          totalUsed += nByte;
19240        }
19241      }
19242      sqlite3BtreeLeaveAll(db);
19243      *pCurrent = totalUsed;
19244      *pHighwater = 0;
19245      break;
19246    }
19247
19248    /*
19249    ** *pCurrent gets an accurate estimate of the amount of memory used
19250    ** to store the schema for all databases (main, temp, and any ATTACHed
19251    ** databases.  *pHighwater is set to zero.
19252    */
19253    case SQLITE_DBSTATUS_SCHEMA_USED: {
19254      int i;                      /* Used to iterate through schemas */
19255      int nByte = 0;              /* Used to accumulate return value */
19256
19257      sqlite3BtreeEnterAll(db);
19258      db->pnBytesFreed = &nByte;
19259      for(i=0; i<db->nDb; i++){
19260        Schema *pSchema = db->aDb[i].pSchema;
19261        if( ALWAYS(pSchema!=0) ){
19262          HashElem *p;
19263
19264          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
19265              pSchema->tblHash.count
19266            + pSchema->trigHash.count
19267            + pSchema->idxHash.count
19268            + pSchema->fkeyHash.count
19269          );
19270          nByte += sqlite3_msize(pSchema->tblHash.ht);
19271          nByte += sqlite3_msize(pSchema->trigHash.ht);
19272          nByte += sqlite3_msize(pSchema->idxHash.ht);
19273          nByte += sqlite3_msize(pSchema->fkeyHash.ht);
19274
19275          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
19276            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
19277          }
19278          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
19279            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
19280          }
19281        }
19282      }
19283      db->pnBytesFreed = 0;
19284      sqlite3BtreeLeaveAll(db);
19285
19286      *pHighwater = 0;
19287      *pCurrent = nByte;
19288      break;
19289    }
19290
19291    /*
19292    ** *pCurrent gets an accurate estimate of the amount of memory used
19293    ** to store all prepared statements.
19294    ** *pHighwater is set to zero.
19295    */
19296    case SQLITE_DBSTATUS_STMT_USED: {
19297      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
19298      int nByte = 0;              /* Used to accumulate return value */
19299
19300      db->pnBytesFreed = &nByte;
19301      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
19302        sqlite3VdbeClearObject(db, pVdbe);
19303        sqlite3DbFree(db, pVdbe);
19304      }
19305      db->pnBytesFreed = 0;
19306
19307      *pHighwater = 0;  /* IMP: R-64479-57858 */
19308      *pCurrent = nByte;
19309
19310      break;
19311    }
19312
19313    /*
19314    ** Set *pCurrent to the total cache hits or misses encountered by all
19315    ** pagers the database handle is connected to. *pHighwater is always set
19316    ** to zero.
19317    */
19318    case SQLITE_DBSTATUS_CACHE_HIT:
19319    case SQLITE_DBSTATUS_CACHE_MISS:
19320    case SQLITE_DBSTATUS_CACHE_WRITE:{
19321      int i;
19322      int nRet = 0;
19323      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
19324      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
19325
19326      for(i=0; i<db->nDb; i++){
19327        if( db->aDb[i].pBt ){
19328          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
19329          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
19330        }
19331      }
19332      *pHighwater = 0; /* IMP: R-42420-56072 */
19333                       /* IMP: R-54100-20147 */
19334                       /* IMP: R-29431-39229 */
19335      *pCurrent = nRet;
19336      break;
19337    }
19338
19339    /* Set *pCurrent to non-zero if there are unresolved deferred foreign
19340    ** key constraints.  Set *pCurrent to zero if all foreign key constraints
19341    ** have been satisfied.  The *pHighwater is always set to zero.
19342    */
19343    case SQLITE_DBSTATUS_DEFERRED_FKS: {
19344      *pHighwater = 0;  /* IMP: R-11967-56545 */
19345      *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
19346      break;
19347    }
19348
19349    default: {
19350      rc = SQLITE_ERROR;
19351    }
19352  }
19353  sqlite3_mutex_leave(db->mutex);
19354  return rc;
19355}
19356
19357/************** End of status.c **********************************************/
19358/************** Begin file date.c ********************************************/
19359/*
19360** 2003 October 31
19361**
19362** The author disclaims copyright to this source code.  In place of
19363** a legal notice, here is a blessing:
19364**
19365**    May you do good and not evil.
19366**    May you find forgiveness for yourself and forgive others.
19367**    May you share freely, never taking more than you give.
19368**
19369*************************************************************************
19370** This file contains the C functions that implement date and time
19371** functions for SQLite.
19372**
19373** There is only one exported symbol in this file - the function
19374** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
19375** All other code has file scope.
19376**
19377** SQLite processes all times and dates as julian day numbers.  The
19378** dates and times are stored as the number of days since noon
19379** in Greenwich on November 24, 4714 B.C. according to the Gregorian
19380** calendar system.
19381**
19382** 1970-01-01 00:00:00 is JD 2440587.5
19383** 2000-01-01 00:00:00 is JD 2451544.5
19384**
19385** This implementation requires years to be expressed as a 4-digit number
19386** which means that only dates between 0000-01-01 and 9999-12-31 can
19387** be represented, even though julian day numbers allow a much wider
19388** range of dates.
19389**
19390** The Gregorian calendar system is used for all dates and times,
19391** even those that predate the Gregorian calendar.  Historians usually
19392** use the julian calendar for dates prior to 1582-10-15 and for some
19393** dates afterwards, depending on locale.  Beware of this difference.
19394**
19395** The conversion algorithms are implemented based on descriptions
19396** in the following text:
19397**
19398**      Jean Meeus
19399**      Astronomical Algorithms, 2nd Edition, 1998
19400**      ISBM 0-943396-61-1
19401**      Willmann-Bell, Inc
19402**      Richmond, Virginia (USA)
19403*/
19404/* #include "sqliteInt.h" */
19405/* #include <stdlib.h> */
19406/* #include <assert.h> */
19407#include <time.h>
19408
19409#ifndef SQLITE_OMIT_DATETIME_FUNCS
19410
19411/*
19412** The MSVC CRT on Windows CE may not have a localtime() function.
19413** So declare a substitute.  The substitute function itself is
19414** defined in "os_win.c".
19415*/
19416#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
19417    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
19418struct tm *__cdecl localtime(const time_t *);
19419#endif
19420
19421/*
19422** A structure for holding a single date and time.
19423*/
19424typedef struct DateTime DateTime;
19425struct DateTime {
19426  sqlite3_int64 iJD;  /* The julian day number times 86400000 */
19427  int Y, M, D;        /* Year, month, and day */
19428  int h, m;           /* Hour and minutes */
19429  int tz;             /* Timezone offset in minutes */
19430  double s;           /* Seconds */
19431  char validJD;       /* True (1) if iJD is valid */
19432  char rawS;          /* Raw numeric value stored in s */
19433  char validYMD;      /* True (1) if Y,M,D are valid */
19434  char validHMS;      /* True (1) if h,m,s are valid */
19435  char validTZ;       /* True (1) if tz is valid */
19436  char tzSet;         /* Timezone was set explicitly */
19437  char isError;       /* An overflow has occurred */
19438};
19439
19440
19441/*
19442** Convert zDate into one or more integers according to the conversion
19443** specifier zFormat.
19444**
19445** zFormat[] contains 4 characters for each integer converted, except for
19446** the last integer which is specified by three characters.  The meaning
19447** of a four-character format specifiers ABCD is:
19448**
19449**    A:   number of digits to convert.  Always "2" or "4".
19450**    B:   minimum value.  Always "0" or "1".
19451**    C:   maximum value, decoded as:
19452**           a:  12
19453**           b:  14
19454**           c:  24
19455**           d:  31
19456**           e:  59
19457**           f:  9999
19458**    D:   the separator character, or \000 to indicate this is the
19459**         last number to convert.
19460**
19461** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
19462** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
19463** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
19464** the 2-digit day which is the last integer in the set.
19465**
19466** The function returns the number of successful conversions.
19467*/
19468static int getDigits(const char *zDate, const char *zFormat, ...){
19469  /* The aMx[] array translates the 3rd character of each format
19470  ** spec into a max size:    a   b   c   d   e     f */
19471  static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
19472  va_list ap;
19473  int cnt = 0;
19474  char nextC;
19475  va_start(ap, zFormat);
19476  do{
19477    char N = zFormat[0] - '0';
19478    char min = zFormat[1] - '0';
19479    int val = 0;
19480    u16 max;
19481
19482    assert( zFormat[2]>='a' && zFormat[2]<='f' );
19483    max = aMx[zFormat[2] - 'a'];
19484    nextC = zFormat[3];
19485    val = 0;
19486    while( N-- ){
19487      if( !sqlite3Isdigit(*zDate) ){
19488        goto end_getDigits;
19489      }
19490      val = val*10 + *zDate - '0';
19491      zDate++;
19492    }
19493    if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
19494      goto end_getDigits;
19495    }
19496    *va_arg(ap,int*) = val;
19497    zDate++;
19498    cnt++;
19499    zFormat += 4;
19500  }while( nextC );
19501end_getDigits:
19502  va_end(ap);
19503  return cnt;
19504}
19505
19506/*
19507** Parse a timezone extension on the end of a date-time.
19508** The extension is of the form:
19509**
19510**        (+/-)HH:MM
19511**
19512** Or the "zulu" notation:
19513**
19514**        Z
19515**
19516** If the parse is successful, write the number of minutes
19517** of change in p->tz and return 0.  If a parser error occurs,
19518** return non-zero.
19519**
19520** A missing specifier is not considered an error.
19521*/
19522static int parseTimezone(const char *zDate, DateTime *p){
19523  int sgn = 0;
19524  int nHr, nMn;
19525  int c;
19526  while( sqlite3Isspace(*zDate) ){ zDate++; }
19527  p->tz = 0;
19528  c = *zDate;
19529  if( c=='-' ){
19530    sgn = -1;
19531  }else if( c=='+' ){
19532    sgn = +1;
19533  }else if( c=='Z' || c=='z' ){
19534    zDate++;
19535    goto zulu_time;
19536  }else{
19537    return c!=0;
19538  }
19539  zDate++;
19540  if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
19541    return 1;
19542  }
19543  zDate += 5;
19544  p->tz = sgn*(nMn + nHr*60);
19545zulu_time:
19546  while( sqlite3Isspace(*zDate) ){ zDate++; }
19547  p->tzSet = 1;
19548  return *zDate!=0;
19549}
19550
19551/*
19552** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
19553** The HH, MM, and SS must each be exactly 2 digits.  The
19554** fractional seconds FFFF can be one or more digits.
19555**
19556** Return 1 if there is a parsing error and 0 on success.
19557*/
19558static int parseHhMmSs(const char *zDate, DateTime *p){
19559  int h, m, s;
19560  double ms = 0.0;
19561  if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
19562    return 1;
19563  }
19564  zDate += 5;
19565  if( *zDate==':' ){
19566    zDate++;
19567    if( getDigits(zDate, "20e", &s)!=1 ){
19568      return 1;
19569    }
19570    zDate += 2;
19571    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
19572      double rScale = 1.0;
19573      zDate++;
19574      while( sqlite3Isdigit(*zDate) ){
19575        ms = ms*10.0 + *zDate - '0';
19576        rScale *= 10.0;
19577        zDate++;
19578      }
19579      ms /= rScale;
19580    }
19581  }else{
19582    s = 0;
19583  }
19584  p->validJD = 0;
19585  p->rawS = 0;
19586  p->validHMS = 1;
19587  p->h = h;
19588  p->m = m;
19589  p->s = s + ms;
19590  if( parseTimezone(zDate, p) ) return 1;
19591  p->validTZ = (p->tz!=0)?1:0;
19592  return 0;
19593}
19594
19595/*
19596** Put the DateTime object into its error state.
19597*/
19598static void datetimeError(DateTime *p){
19599  memset(p, 0, sizeof(*p));
19600  p->isError = 1;
19601}
19602
19603/*
19604** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
19605** that the YYYY-MM-DD is according to the Gregorian calendar.
19606**
19607** Reference:  Meeus page 61
19608*/
19609static void computeJD(DateTime *p){
19610  int Y, M, D, A, B, X1, X2;
19611
19612  if( p->validJD ) return;
19613  if( p->validYMD ){
19614    Y = p->Y;
19615    M = p->M;
19616    D = p->D;
19617  }else{
19618    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
19619    M = 1;
19620    D = 1;
19621  }
19622  if( Y<-4713 || Y>9999 || p->rawS ){
19623    datetimeError(p);
19624    return;
19625  }
19626  if( M<=2 ){
19627    Y--;
19628    M += 12;
19629  }
19630  A = Y/100;
19631  B = 2 - A + (A/4);
19632  X1 = 36525*(Y+4716)/100;
19633  X2 = 306001*(M+1)/10000;
19634  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
19635  p->validJD = 1;
19636  if( p->validHMS ){
19637    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
19638    if( p->validTZ ){
19639      p->iJD -= p->tz*60000;
19640      p->validYMD = 0;
19641      p->validHMS = 0;
19642      p->validTZ = 0;
19643    }
19644  }
19645}
19646
19647/*
19648** Parse dates of the form
19649**
19650**     YYYY-MM-DD HH:MM:SS.FFF
19651**     YYYY-MM-DD HH:MM:SS
19652**     YYYY-MM-DD HH:MM
19653**     YYYY-MM-DD
19654**
19655** Write the result into the DateTime structure and return 0
19656** on success and 1 if the input string is not a well-formed
19657** date.
19658*/
19659static int parseYyyyMmDd(const char *zDate, DateTime *p){
19660  int Y, M, D, neg;
19661
19662  if( zDate[0]=='-' ){
19663    zDate++;
19664    neg = 1;
19665  }else{
19666    neg = 0;
19667  }
19668  if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
19669    return 1;
19670  }
19671  zDate += 10;
19672  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
19673  if( parseHhMmSs(zDate, p)==0 ){
19674    /* We got the time */
19675  }else if( *zDate==0 ){
19676    p->validHMS = 0;
19677  }else{
19678    return 1;
19679  }
19680  p->validJD = 0;
19681  p->validYMD = 1;
19682  p->Y = neg ? -Y : Y;
19683  p->M = M;
19684  p->D = D;
19685  if( p->validTZ ){
19686    computeJD(p);
19687  }
19688  return 0;
19689}
19690
19691/*
19692** Set the time to the current time reported by the VFS.
19693**
19694** Return the number of errors.
19695*/
19696static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
19697  p->iJD = sqlite3StmtCurrentTime(context);
19698  if( p->iJD>0 ){
19699    p->validJD = 1;
19700    return 0;
19701  }else{
19702    return 1;
19703  }
19704}
19705
19706/*
19707** Input "r" is a numeric quantity which might be a julian day number,
19708** or the number of seconds since 1970.  If the value if r is within
19709** range of a julian day number, install it as such and set validJD.
19710** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
19711*/
19712static void setRawDateNumber(DateTime *p, double r){
19713  p->s = r;
19714  p->rawS = 1;
19715  if( r>=0.0 && r<5373484.5 ){
19716    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
19717    p->validJD = 1;
19718  }
19719}
19720
19721/*
19722** Attempt to parse the given string into a julian day number.  Return
19723** the number of errors.
19724**
19725** The following are acceptable forms for the input string:
19726**
19727**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
19728**      DDDD.DD
19729**      now
19730**
19731** In the first form, the +/-HH:MM is always optional.  The fractional
19732** seconds extension (the ".FFF") is optional.  The seconds portion
19733** (":SS.FFF") is option.  The year and date can be omitted as long
19734** as there is a time string.  The time string can be omitted as long
19735** as there is a year and date.
19736*/
19737static int parseDateOrTime(
19738  sqlite3_context *context,
19739  const char *zDate,
19740  DateTime *p
19741){
19742  double r;
19743  if( parseYyyyMmDd(zDate,p)==0 ){
19744    return 0;
19745  }else if( parseHhMmSs(zDate, p)==0 ){
19746    return 0;
19747  }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
19748    return setDateTimeToCurrent(context, p);
19749  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
19750    setRawDateNumber(p, r);
19751    return 0;
19752  }
19753  return 1;
19754}
19755
19756/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
19757** Multiplying this by 86400000 gives 464269060799999 as the maximum value
19758** for DateTime.iJD.
19759**
19760** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
19761** such a large integer literal, so we have to encode it.
19762*/
19763#define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)
19764
19765/*
19766** Return TRUE if the given julian day number is within range.
19767**
19768** The input is the JulianDay times 86400000.
19769*/
19770static int validJulianDay(sqlite3_int64 iJD){
19771  return iJD>=0 && iJD<=INT_464269060799999;
19772}
19773
19774/*
19775** Compute the Year, Month, and Day from the julian day number.
19776*/
19777static void computeYMD(DateTime *p){
19778  int Z, A, B, C, D, E, X1;
19779  if( p->validYMD ) return;
19780  if( !p->validJD ){
19781    p->Y = 2000;
19782    p->M = 1;
19783    p->D = 1;
19784  }else if( !validJulianDay(p->iJD) ){
19785    datetimeError(p);
19786    return;
19787  }else{
19788    Z = (int)((p->iJD + 43200000)/86400000);
19789    A = (int)((Z - 1867216.25)/36524.25);
19790    A = Z + 1 + A - (A/4);
19791    B = A + 1524;
19792    C = (int)((B - 122.1)/365.25);
19793    D = (36525*(C&32767))/100;
19794    E = (int)((B-D)/30.6001);
19795    X1 = (int)(30.6001*E);
19796    p->D = B - D - X1;
19797    p->M = E<14 ? E-1 : E-13;
19798    p->Y = p->M>2 ? C - 4716 : C - 4715;
19799  }
19800  p->validYMD = 1;
19801}
19802
19803/*
19804** Compute the Hour, Minute, and Seconds from the julian day number.
19805*/
19806static void computeHMS(DateTime *p){
19807  int s;
19808  if( p->validHMS ) return;
19809  computeJD(p);
19810  s = (int)((p->iJD + 43200000) % 86400000);
19811  p->s = s/1000.0;
19812  s = (int)p->s;
19813  p->s -= s;
19814  p->h = s/3600;
19815  s -= p->h*3600;
19816  p->m = s/60;
19817  p->s += s - p->m*60;
19818  p->rawS = 0;
19819  p->validHMS = 1;
19820}
19821
19822/*
19823** Compute both YMD and HMS
19824*/
19825static void computeYMD_HMS(DateTime *p){
19826  computeYMD(p);
19827  computeHMS(p);
19828}
19829
19830/*
19831** Clear the YMD and HMS and the TZ
19832*/
19833static void clearYMD_HMS_TZ(DateTime *p){
19834  p->validYMD = 0;
19835  p->validHMS = 0;
19836  p->validTZ = 0;
19837}
19838
19839#ifndef SQLITE_OMIT_LOCALTIME
19840/*
19841** On recent Windows platforms, the localtime_s() function is available
19842** as part of the "Secure CRT". It is essentially equivalent to
19843** localtime_r() available under most POSIX platforms, except that the
19844** order of the parameters is reversed.
19845**
19846** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
19847**
19848** If the user has not indicated to use localtime_r() or localtime_s()
19849** already, check for an MSVC build environment that provides
19850** localtime_s().
19851*/
19852#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
19853    && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
19854#undef  HAVE_LOCALTIME_S
19855#define HAVE_LOCALTIME_S 1
19856#endif
19857
19858/*
19859** The following routine implements the rough equivalent of localtime_r()
19860** using whatever operating-system specific localtime facility that
19861** is available.  This routine returns 0 on success and
19862** non-zero on any kind of error.
19863**
19864** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
19865** routine will always fail.
19866**
19867** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
19868** library function localtime_r() is used to assist in the calculation of
19869** local time.
19870*/
19871static int osLocaltime(time_t *t, struct tm *pTm){
19872  int rc;
19873#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
19874  struct tm *pX;
19875#if SQLITE_THREADSAFE>0
19876  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
19877#endif
19878  sqlite3_mutex_enter(mutex);
19879  pX = localtime(t);
19880#ifndef SQLITE_UNTESTABLE
19881  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
19882#endif
19883  if( pX ) *pTm = *pX;
19884  sqlite3_mutex_leave(mutex);
19885  rc = pX==0;
19886#else
19887#ifndef SQLITE_UNTESTABLE
19888  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
19889#endif
19890#if HAVE_LOCALTIME_R
19891  rc = localtime_r(t, pTm)==0;
19892#else
19893  rc = localtime_s(pTm, t);
19894#endif /* HAVE_LOCALTIME_R */
19895#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
19896  return rc;
19897}
19898#endif /* SQLITE_OMIT_LOCALTIME */
19899
19900
19901#ifndef SQLITE_OMIT_LOCALTIME
19902/*
19903** Compute the difference (in milliseconds) between localtime and UTC
19904** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
19905** return this value and set *pRc to SQLITE_OK.
19906**
19907** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
19908** is undefined in this case.
19909*/
19910static sqlite3_int64 localtimeOffset(
19911  DateTime *p,                    /* Date at which to calculate offset */
19912  sqlite3_context *pCtx,          /* Write error here if one occurs */
19913  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
19914){
19915  DateTime x, y;
19916  time_t t;
19917  struct tm sLocal;
19918
19919  /* Initialize the contents of sLocal to avoid a compiler warning. */
19920  memset(&sLocal, 0, sizeof(sLocal));
19921
19922  x = *p;
19923  computeYMD_HMS(&x);
19924  if( x.Y<1971 || x.Y>=2038 ){
19925    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
19926    ** works for years between 1970 and 2037. For dates outside this range,
19927    ** SQLite attempts to map the year into an equivalent year within this
19928    ** range, do the calculation, then map the year back.
19929    */
19930    x.Y = 2000;
19931    x.M = 1;
19932    x.D = 1;
19933    x.h = 0;
19934    x.m = 0;
19935    x.s = 0.0;
19936  } else {
19937    int s = (int)(x.s + 0.5);
19938    x.s = s;
19939  }
19940  x.tz = 0;
19941  x.validJD = 0;
19942  computeJD(&x);
19943  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
19944  if( osLocaltime(&t, &sLocal) ){
19945    sqlite3_result_error(pCtx, "local time unavailable", -1);
19946    *pRc = SQLITE_ERROR;
19947    return 0;
19948  }
19949  y.Y = sLocal.tm_year + 1900;
19950  y.M = sLocal.tm_mon + 1;
19951  y.D = sLocal.tm_mday;
19952  y.h = sLocal.tm_hour;
19953  y.m = sLocal.tm_min;
19954  y.s = sLocal.tm_sec;
19955  y.validYMD = 1;
19956  y.validHMS = 1;
19957  y.validJD = 0;
19958  y.rawS = 0;
19959  y.validTZ = 0;
19960  y.isError = 0;
19961  computeJD(&y);
19962  *pRc = SQLITE_OK;
19963  return y.iJD - x.iJD;
19964}
19965#endif /* SQLITE_OMIT_LOCALTIME */
19966
19967/*
19968** The following table defines various date transformations of the form
19969**
19970**            'NNN days'
19971**
19972** Where NNN is an arbitrary floating-point number and "days" can be one
19973** of several units of time.
19974*/
19975static const struct {
19976  u8 eType;           /* Transformation type code */
19977  u8 nName;           /* Length of th name */
19978  char *zName;        /* Name of the transformation */
19979  double rLimit;      /* Maximum NNN value for this transform */
19980  double rXform;      /* Constant used for this transform */
19981} aXformType[] = {
19982  { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
19983  { 0, 6, "minute", 7737817680.0,   86400000.0/(24.0*60.0)      },
19984  { 0, 4, "hour",   128963628.0,    86400000.0/24.0             },
19985  { 0, 3, "day",    5373485.0,      86400000.0                  },
19986  { 1, 5, "month",  176546.0,       30.0*86400000.0             },
19987  { 2, 4, "year",   14713.0,        365.0*86400000.0            },
19988};
19989
19990/*
19991** Process a modifier to a date-time stamp.  The modifiers are
19992** as follows:
19993**
19994**     NNN days
19995**     NNN hours
19996**     NNN minutes
19997**     NNN.NNNN seconds
19998**     NNN months
19999**     NNN years
20000**     start of month
20001**     start of year
20002**     start of week
20003**     start of day
20004**     weekday N
20005**     unixepoch
20006**     localtime
20007**     utc
20008**
20009** Return 0 on success and 1 if there is any kind of error. If the error
20010** is in a system call (i.e. localtime()), then an error message is written
20011** to context pCtx. If the error is an unrecognized modifier, no error is
20012** written to pCtx.
20013*/
20014static int parseModifier(
20015  sqlite3_context *pCtx,      /* Function context */
20016  const char *z,              /* The text of the modifier */
20017  int n,                      /* Length of zMod in bytes */
20018  DateTime *p                 /* The date/time value to be modified */
20019){
20020  int rc = 1;
20021  double r;
20022  switch(sqlite3UpperToLower[(u8)z[0]] ){
20023#ifndef SQLITE_OMIT_LOCALTIME
20024    case 'l': {
20025      /*    localtime
20026      **
20027      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
20028      ** show local time.
20029      */
20030      if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
20031        computeJD(p);
20032        p->iJD += localtimeOffset(p, pCtx, &rc);
20033        clearYMD_HMS_TZ(p);
20034      }
20035      break;
20036    }
20037#endif
20038    case 'u': {
20039      /*
20040      **    unixepoch
20041      **
20042      ** Treat the current value of p->s as the number of
20043      ** seconds since 1970.  Convert to a real julian day number.
20044      */
20045      if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
20046        r = p->s*1000.0 + 210866760000000.0;
20047        if( r>=0.0 && r<464269060800000.0 ){
20048          clearYMD_HMS_TZ(p);
20049          p->iJD = (sqlite3_int64)r;
20050          p->validJD = 1;
20051          p->rawS = 0;
20052          rc = 0;
20053        }
20054      }
20055#ifndef SQLITE_OMIT_LOCALTIME
20056      else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
20057        if( p->tzSet==0 ){
20058          sqlite3_int64 c1;
20059          computeJD(p);
20060          c1 = localtimeOffset(p, pCtx, &rc);
20061          if( rc==SQLITE_OK ){
20062            p->iJD -= c1;
20063            clearYMD_HMS_TZ(p);
20064            p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
20065          }
20066          p->tzSet = 1;
20067        }else{
20068          rc = SQLITE_OK;
20069        }
20070      }
20071#endif
20072      break;
20073    }
20074    case 'w': {
20075      /*
20076      **    weekday N
20077      **
20078      ** Move the date to the same time on the next occurrence of
20079      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
20080      ** date is already on the appropriate weekday, this is a no-op.
20081      */
20082      if( sqlite3_strnicmp(z, "weekday ", 8)==0
20083               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
20084               && (n=(int)r)==r && n>=0 && r<7 ){
20085        sqlite3_int64 Z;
20086        computeYMD_HMS(p);
20087        p->validTZ = 0;
20088        p->validJD = 0;
20089        computeJD(p);
20090        Z = ((p->iJD + 129600000)/86400000) % 7;
20091        if( Z>n ) Z -= 7;
20092        p->iJD += (n - Z)*86400000;
20093        clearYMD_HMS_TZ(p);
20094        rc = 0;
20095      }
20096      break;
20097    }
20098    case 's': {
20099      /*
20100      **    start of TTTTT
20101      **
20102      ** Move the date backwards to the beginning of the current day,
20103      ** or month or year.
20104      */
20105      if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
20106      if( !p->validJD && !p->validYMD && !p->validHMS ) break;
20107      z += 9;
20108      computeYMD(p);
20109      p->validHMS = 1;
20110      p->h = p->m = 0;
20111      p->s = 0.0;
20112      p->rawS = 0;
20113      p->validTZ = 0;
20114      p->validJD = 0;
20115      if( sqlite3_stricmp(z,"month")==0 ){
20116        p->D = 1;
20117        rc = 0;
20118      }else if( sqlite3_stricmp(z,"year")==0 ){
20119        p->M = 1;
20120        p->D = 1;
20121        rc = 0;
20122      }else if( sqlite3_stricmp(z,"day")==0 ){
20123        rc = 0;
20124      }
20125      break;
20126    }
20127    case '+':
20128    case '-':
20129    case '0':
20130    case '1':
20131    case '2':
20132    case '3':
20133    case '4':
20134    case '5':
20135    case '6':
20136    case '7':
20137    case '8':
20138    case '9': {
20139      double rRounder;
20140      int i;
20141      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
20142      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
20143        rc = 1;
20144        break;
20145      }
20146      if( z[n]==':' ){
20147        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
20148        ** specified number of hours, minutes, seconds, and fractional seconds
20149        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
20150        ** omitted.
20151        */
20152        const char *z2 = z;
20153        DateTime tx;
20154        sqlite3_int64 day;
20155        if( !sqlite3Isdigit(*z2) ) z2++;
20156        memset(&tx, 0, sizeof(tx));
20157        if( parseHhMmSs(z2, &tx) ) break;
20158        computeJD(&tx);
20159        tx.iJD -= 43200000;
20160        day = tx.iJD/86400000;
20161        tx.iJD -= day*86400000;
20162        if( z[0]=='-' ) tx.iJD = -tx.iJD;
20163        computeJD(p);
20164        clearYMD_HMS_TZ(p);
20165        p->iJD += tx.iJD;
20166        rc = 0;
20167        break;
20168      }
20169
20170      /* If control reaches this point, it means the transformation is
20171      ** one of the forms like "+NNN days".  */
20172      z += n;
20173      while( sqlite3Isspace(*z) ) z++;
20174      n = sqlite3Strlen30(z);
20175      if( n>10 || n<3 ) break;
20176      if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
20177      computeJD(p);
20178      rc = 1;
20179      rRounder = r<0 ? -0.5 : +0.5;
20180      for(i=0; i<ArraySize(aXformType); i++){
20181        if( aXformType[i].nName==n
20182         && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
20183         && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
20184        ){
20185          switch( aXformType[i].eType ){
20186            case 1: { /* Special processing to add months */
20187              int x;
20188              computeYMD_HMS(p);
20189              p->M += (int)r;
20190              x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
20191              p->Y += x;
20192              p->M -= x*12;
20193              p->validJD = 0;
20194              r -= (int)r;
20195              break;
20196            }
20197            case 2: { /* Special processing to add years */
20198              int y = (int)r;
20199              computeYMD_HMS(p);
20200              p->Y += y;
20201              p->validJD = 0;
20202              r -= (int)r;
20203              break;
20204            }
20205          }
20206          computeJD(p);
20207          p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
20208          rc = 0;
20209          break;
20210        }
20211      }
20212      clearYMD_HMS_TZ(p);
20213      break;
20214    }
20215    default: {
20216      break;
20217    }
20218  }
20219  return rc;
20220}
20221
20222/*
20223** Process time function arguments.  argv[0] is a date-time stamp.
20224** argv[1] and following are modifiers.  Parse them all and write
20225** the resulting time into the DateTime structure p.  Return 0
20226** on success and 1 if there are any errors.
20227**
20228** If there are zero parameters (if even argv[0] is undefined)
20229** then assume a default value of "now" for argv[0].
20230*/
20231static int isDate(
20232  sqlite3_context *context,
20233  int argc,
20234  sqlite3_value **argv,
20235  DateTime *p
20236){
20237  int i, n;
20238  const unsigned char *z;
20239  int eType;
20240  memset(p, 0, sizeof(*p));
20241  if( argc==0 ){
20242    return setDateTimeToCurrent(context, p);
20243  }
20244  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
20245                   || eType==SQLITE_INTEGER ){
20246    setRawDateNumber(p, sqlite3_value_double(argv[0]));
20247  }else{
20248    z = sqlite3_value_text(argv[0]);
20249    if( !z || parseDateOrTime(context, (char*)z, p) ){
20250      return 1;
20251    }
20252  }
20253  for(i=1; i<argc; i++){
20254    z = sqlite3_value_text(argv[i]);
20255    n = sqlite3_value_bytes(argv[i]);
20256    if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
20257  }
20258  computeJD(p);
20259  if( p->isError || !validJulianDay(p->iJD) ) return 1;
20260  return 0;
20261}
20262
20263
20264/*
20265** The following routines implement the various date and time functions
20266** of SQLite.
20267*/
20268
20269/*
20270**    julianday( TIMESTRING, MOD, MOD, ...)
20271**
20272** Return the julian day number of the date specified in the arguments
20273*/
20274static void juliandayFunc(
20275  sqlite3_context *context,
20276  int argc,
20277  sqlite3_value **argv
20278){
20279  DateTime x;
20280  if( isDate(context, argc, argv, &x)==0 ){
20281    computeJD(&x);
20282    sqlite3_result_double(context, x.iJD/86400000.0);
20283  }
20284}
20285
20286/*
20287**    datetime( TIMESTRING, MOD, MOD, ...)
20288**
20289** Return YYYY-MM-DD HH:MM:SS
20290*/
20291static void datetimeFunc(
20292  sqlite3_context *context,
20293  int argc,
20294  sqlite3_value **argv
20295){
20296  DateTime x;
20297  if( isDate(context, argc, argv, &x)==0 ){
20298    char zBuf[100];
20299    computeYMD_HMS(&x);
20300    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
20301                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
20302    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20303  }
20304}
20305
20306/*
20307**    time( TIMESTRING, MOD, MOD, ...)
20308**
20309** Return HH:MM:SS
20310*/
20311static void timeFunc(
20312  sqlite3_context *context,
20313  int argc,
20314  sqlite3_value **argv
20315){
20316  DateTime x;
20317  if( isDate(context, argc, argv, &x)==0 ){
20318    char zBuf[100];
20319    computeHMS(&x);
20320    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
20321    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20322  }
20323}
20324
20325/*
20326**    date( TIMESTRING, MOD, MOD, ...)
20327**
20328** Return YYYY-MM-DD
20329*/
20330static void dateFunc(
20331  sqlite3_context *context,
20332  int argc,
20333  sqlite3_value **argv
20334){
20335  DateTime x;
20336  if( isDate(context, argc, argv, &x)==0 ){
20337    char zBuf[100];
20338    computeYMD(&x);
20339    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
20340    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20341  }
20342}
20343
20344/*
20345**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
20346**
20347** Return a string described by FORMAT.  Conversions as follows:
20348**
20349**   %d  day of month
20350**   %f  ** fractional seconds  SS.SSS
20351**   %H  hour 00-24
20352**   %j  day of year 000-366
20353**   %J  ** julian day number
20354**   %m  month 01-12
20355**   %M  minute 00-59
20356**   %s  seconds since 1970-01-01
20357**   %S  seconds 00-59
20358**   %w  day of week 0-6  sunday==0
20359**   %W  week of year 00-53
20360**   %Y  year 0000-9999
20361**   %%  %
20362*/
20363static void strftimeFunc(
20364  sqlite3_context *context,
20365  int argc,
20366  sqlite3_value **argv
20367){
20368  DateTime x;
20369  u64 n;
20370  size_t i,j;
20371  char *z;
20372  sqlite3 *db;
20373  const char *zFmt;
20374  char zBuf[100];
20375  if( argc==0 ) return;
20376  zFmt = (const char*)sqlite3_value_text(argv[0]);
20377  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
20378  db = sqlite3_context_db_handle(context);
20379  for(i=0, n=1; zFmt[i]; i++, n++){
20380    if( zFmt[i]=='%' ){
20381      switch( zFmt[i+1] ){
20382        case 'd':
20383        case 'H':
20384        case 'm':
20385        case 'M':
20386        case 'S':
20387        case 'W':
20388          n++;
20389          /* fall thru */
20390        case 'w':
20391        case '%':
20392          break;
20393        case 'f':
20394          n += 8;
20395          break;
20396        case 'j':
20397          n += 3;
20398          break;
20399        case 'Y':
20400          n += 8;
20401          break;
20402        case 's':
20403        case 'J':
20404          n += 50;
20405          break;
20406        default:
20407          return;  /* ERROR.  return a NULL */
20408      }
20409      i++;
20410    }
20411  }
20412  testcase( n==sizeof(zBuf)-1 );
20413  testcase( n==sizeof(zBuf) );
20414  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
20415  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
20416  if( n<sizeof(zBuf) ){
20417    z = zBuf;
20418  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
20419    sqlite3_result_error_toobig(context);
20420    return;
20421  }else{
20422    z = sqlite3DbMallocRawNN(db, (int)n);
20423    if( z==0 ){
20424      sqlite3_result_error_nomem(context);
20425      return;
20426    }
20427  }
20428  computeJD(&x);
20429  computeYMD_HMS(&x);
20430  for(i=j=0; zFmt[i]; i++){
20431    if( zFmt[i]!='%' ){
20432      z[j++] = zFmt[i];
20433    }else{
20434      i++;
20435      switch( zFmt[i] ){
20436        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
20437        case 'f': {
20438          double s = x.s;
20439          if( s>59.999 ) s = 59.999;
20440          sqlite3_snprintf(7, &z[j],"%06.3f", s);
20441          j += sqlite3Strlen30(&z[j]);
20442          break;
20443        }
20444        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
20445        case 'W': /* Fall thru */
20446        case 'j': {
20447          int nDay;             /* Number of days since 1st day of year */
20448          DateTime y = x;
20449          y.validJD = 0;
20450          y.M = 1;
20451          y.D = 1;
20452          computeJD(&y);
20453          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
20454          if( zFmt[i]=='W' ){
20455            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
20456            wd = (int)(((x.iJD+43200000)/86400000)%7);
20457            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
20458            j += 2;
20459          }else{
20460            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
20461            j += 3;
20462          }
20463          break;
20464        }
20465        case 'J': {
20466          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
20467          j+=sqlite3Strlen30(&z[j]);
20468          break;
20469        }
20470        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
20471        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
20472        case 's': {
20473          sqlite3_snprintf(30,&z[j],"%lld",
20474                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
20475          j += sqlite3Strlen30(&z[j]);
20476          break;
20477        }
20478        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
20479        case 'w': {
20480          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
20481          break;
20482        }
20483        case 'Y': {
20484          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
20485          break;
20486        }
20487        default:   z[j++] = '%'; break;
20488      }
20489    }
20490  }
20491  z[j] = 0;
20492  sqlite3_result_text(context, z, -1,
20493                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
20494}
20495
20496/*
20497** current_time()
20498**
20499** This function returns the same value as time('now').
20500*/
20501static void ctimeFunc(
20502  sqlite3_context *context,
20503  int NotUsed,
20504  sqlite3_value **NotUsed2
20505){
20506  UNUSED_PARAMETER2(NotUsed, NotUsed2);
20507  timeFunc(context, 0, 0);
20508}
20509
20510/*
20511** current_date()
20512**
20513** This function returns the same value as date('now').
20514*/
20515static void cdateFunc(
20516  sqlite3_context *context,
20517  int NotUsed,
20518  sqlite3_value **NotUsed2
20519){
20520  UNUSED_PARAMETER2(NotUsed, NotUsed2);
20521  dateFunc(context, 0, 0);
20522}
20523
20524/*
20525** current_timestamp()
20526**
20527** This function returns the same value as datetime('now').
20528*/
20529static void ctimestampFunc(
20530  sqlite3_context *context,
20531  int NotUsed,
20532  sqlite3_value **NotUsed2
20533){
20534  UNUSED_PARAMETER2(NotUsed, NotUsed2);
20535  datetimeFunc(context, 0, 0);
20536}
20537#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
20538
20539#ifdef SQLITE_OMIT_DATETIME_FUNCS
20540/*
20541** If the library is compiled to omit the full-scale date and time
20542** handling (to get a smaller binary), the following minimal version
20543** of the functions current_time(), current_date() and current_timestamp()
20544** are included instead. This is to support column declarations that
20545** include "DEFAULT CURRENT_TIME" etc.
20546**
20547** This function uses the C-library functions time(), gmtime()
20548** and strftime(). The format string to pass to strftime() is supplied
20549** as the user-data for the function.
20550*/
20551static void currentTimeFunc(
20552  sqlite3_context *context,
20553  int argc,
20554  sqlite3_value **argv
20555){
20556  time_t t;
20557  char *zFormat = (char *)sqlite3_user_data(context);
20558  sqlite3_int64 iT;
20559  struct tm *pTm;
20560  struct tm sNow;
20561  char zBuf[20];
20562
20563  UNUSED_PARAMETER(argc);
20564  UNUSED_PARAMETER(argv);
20565
20566  iT = sqlite3StmtCurrentTime(context);
20567  if( iT<=0 ) return;
20568  t = iT/1000 - 10000*(sqlite3_int64)21086676;
20569#if HAVE_GMTIME_R
20570  pTm = gmtime_r(&t, &sNow);
20571#else
20572  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
20573  pTm = gmtime(&t);
20574  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
20575  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
20576#endif
20577  if( pTm ){
20578    strftime(zBuf, 20, zFormat, &sNow);
20579    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
20580  }
20581}
20582#endif
20583
20584/*
20585** This function registered all of the above C functions as SQL
20586** functions.  This should be the only routine in this file with
20587** external linkage.
20588*/
20589SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
20590  static FuncDef aDateTimeFuncs[] = {
20591#ifndef SQLITE_OMIT_DATETIME_FUNCS
20592    PURE_DATE(julianday,        -1, 0, 0, juliandayFunc ),
20593    PURE_DATE(date,             -1, 0, 0, dateFunc      ),
20594    PURE_DATE(time,             -1, 0, 0, timeFunc      ),
20595    PURE_DATE(datetime,         -1, 0, 0, datetimeFunc  ),
20596    PURE_DATE(strftime,         -1, 0, 0, strftimeFunc  ),
20597    DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
20598    DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
20599    DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
20600#else
20601    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
20602    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
20603    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
20604#endif
20605  };
20606  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
20607}
20608
20609/************** End of date.c ************************************************/
20610/************** Begin file os.c **********************************************/
20611/*
20612** 2005 November 29
20613**
20614** The author disclaims copyright to this source code.  In place of
20615** a legal notice, here is a blessing:
20616**
20617**    May you do good and not evil.
20618**    May you find forgiveness for yourself and forgive others.
20619**    May you share freely, never taking more than you give.
20620**
20621******************************************************************************
20622**
20623** This file contains OS interface code that is common to all
20624** architectures.
20625*/
20626/* #include "sqliteInt.h" */
20627
20628/*
20629** If we compile with the SQLITE_TEST macro set, then the following block
20630** of code will give us the ability to simulate a disk I/O error.  This
20631** is used for testing the I/O recovery logic.
20632*/
20633#if defined(SQLITE_TEST)
20634SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20635SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20636SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20637SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20638SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20639SQLITE_API int sqlite3_diskfull_pending = 0;
20640SQLITE_API int sqlite3_diskfull = 0;
20641#endif /* defined(SQLITE_TEST) */
20642
20643/*
20644** When testing, also keep a count of the number of open files.
20645*/
20646#if defined(SQLITE_TEST)
20647SQLITE_API int sqlite3_open_file_count = 0;
20648#endif /* defined(SQLITE_TEST) */
20649
20650/*
20651** The default SQLite sqlite3_vfs implementations do not allocate
20652** memory (actually, os_unix.c allocates a small amount of memory
20653** from within OsOpen()), but some third-party implementations may.
20654** So we test the effects of a malloc() failing and the sqlite3OsXXX()
20655** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
20656**
20657** The following functions are instrumented for malloc() failure
20658** testing:
20659**
20660**     sqlite3OsRead()
20661**     sqlite3OsWrite()
20662**     sqlite3OsSync()
20663**     sqlite3OsFileSize()
20664**     sqlite3OsLock()
20665**     sqlite3OsCheckReservedLock()
20666**     sqlite3OsFileControl()
20667**     sqlite3OsShmMap()
20668**     sqlite3OsOpen()
20669**     sqlite3OsDelete()
20670**     sqlite3OsAccess()
20671**     sqlite3OsFullPathname()
20672**
20673*/
20674#if defined(SQLITE_TEST)
20675SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
20676  #define DO_OS_MALLOC_TEST(x)                                       \
20677  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
20678    void *pTstAlloc = sqlite3Malloc(10);                             \
20679    if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
20680    sqlite3_free(pTstAlloc);                                         \
20681  }
20682#else
20683  #define DO_OS_MALLOC_TEST(x)
20684#endif
20685
20686/*
20687** The following routines are convenience wrappers around methods
20688** of the sqlite3_file object.  This is mostly just syntactic sugar. All
20689** of this would be completely automatic if SQLite were coded using
20690** C++ instead of plain old C.
20691*/
20692SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
20693  if( pId->pMethods ){
20694    pId->pMethods->xClose(pId);
20695    pId->pMethods = 0;
20696  }
20697}
20698SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
20699  DO_OS_MALLOC_TEST(id);
20700  return id->pMethods->xRead(id, pBuf, amt, offset);
20701}
20702SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
20703  DO_OS_MALLOC_TEST(id);
20704  return id->pMethods->xWrite(id, pBuf, amt, offset);
20705}
20706SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
20707  return id->pMethods->xTruncate(id, size);
20708}
20709SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
20710  DO_OS_MALLOC_TEST(id);
20711  return id->pMethods->xSync(id, flags);
20712}
20713SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
20714  DO_OS_MALLOC_TEST(id);
20715  return id->pMethods->xFileSize(id, pSize);
20716}
20717SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
20718  DO_OS_MALLOC_TEST(id);
20719  return id->pMethods->xLock(id, lockType);
20720}
20721SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
20722  return id->pMethods->xUnlock(id, lockType);
20723}
20724SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
20725  DO_OS_MALLOC_TEST(id);
20726  return id->pMethods->xCheckReservedLock(id, pResOut);
20727}
20728
20729/*
20730** Use sqlite3OsFileControl() when we are doing something that might fail
20731** and we need to know about the failures.  Use sqlite3OsFileControlHint()
20732** when simply tossing information over the wall to the VFS and we do not
20733** really care if the VFS receives and understands the information since it
20734** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
20735** routine has no return value since the return value would be meaningless.
20736*/
20737SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
20738#ifdef SQLITE_TEST
20739  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
20740    /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
20741    ** is using a regular VFS, it is called after the corresponding
20742    ** transaction has been committed. Injecting a fault at this point
20743    ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
20744    ** but the transaction is committed anyway.
20745    **
20746    ** The core must call OsFileControl() though, not OsFileControlHint(),
20747    ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
20748    ** means the commit really has failed and an error should be returned
20749    ** to the user.  */
20750    DO_OS_MALLOC_TEST(id);
20751  }
20752#endif
20753  return id->pMethods->xFileControl(id, op, pArg);
20754}
20755SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
20756  (void)id->pMethods->xFileControl(id, op, pArg);
20757}
20758
20759SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
20760  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
20761  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
20762}
20763SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
20764  return id->pMethods->xDeviceCharacteristics(id);
20765}
20766SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
20767  return id->pMethods->xShmLock(id, offset, n, flags);
20768}
20769SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
20770  id->pMethods->xShmBarrier(id);
20771}
20772SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
20773  return id->pMethods->xShmUnmap(id, deleteFlag);
20774}
20775SQLITE_PRIVATE int sqlite3OsShmMap(
20776  sqlite3_file *id,               /* Database file handle */
20777  int iPage,
20778  int pgsz,
20779  int bExtend,                    /* True to extend file if necessary */
20780  void volatile **pp              /* OUT: Pointer to mapping */
20781){
20782  DO_OS_MALLOC_TEST(id);
20783  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
20784}
20785
20786#if SQLITE_MAX_MMAP_SIZE>0
20787/* The real implementation of xFetch and xUnfetch */
20788SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
20789  DO_OS_MALLOC_TEST(id);
20790  return id->pMethods->xFetch(id, iOff, iAmt, pp);
20791}
20792SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
20793  return id->pMethods->xUnfetch(id, iOff, p);
20794}
20795#else
20796/* No-op stubs to use when memory-mapped I/O is disabled */
20797SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
20798  *pp = 0;
20799  return SQLITE_OK;
20800}
20801SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
20802  return SQLITE_OK;
20803}
20804#endif
20805
20806/*
20807** The next group of routines are convenience wrappers around the
20808** VFS methods.
20809*/
20810SQLITE_PRIVATE int sqlite3OsOpen(
20811  sqlite3_vfs *pVfs,
20812  const char *zPath,
20813  sqlite3_file *pFile,
20814  int flags,
20815  int *pFlagsOut
20816){
20817  int rc;
20818  DO_OS_MALLOC_TEST(0);
20819  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
20820  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
20821  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
20822  ** reaching the VFS. */
20823  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
20824  assert( rc==SQLITE_OK || pFile->pMethods==0 );
20825  return rc;
20826}
20827SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
20828  DO_OS_MALLOC_TEST(0);
20829  assert( dirSync==0 || dirSync==1 );
20830  return pVfs->xDelete(pVfs, zPath, dirSync);
20831}
20832SQLITE_PRIVATE int sqlite3OsAccess(
20833  sqlite3_vfs *pVfs,
20834  const char *zPath,
20835  int flags,
20836  int *pResOut
20837){
20838  DO_OS_MALLOC_TEST(0);
20839  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
20840}
20841SQLITE_PRIVATE int sqlite3OsFullPathname(
20842  sqlite3_vfs *pVfs,
20843  const char *zPath,
20844  int nPathOut,
20845  char *zPathOut
20846){
20847  DO_OS_MALLOC_TEST(0);
20848  zPathOut[0] = 0;
20849  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
20850}
20851#ifndef SQLITE_OMIT_LOAD_EXTENSION
20852SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
20853  return pVfs->xDlOpen(pVfs, zPath);
20854}
20855SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
20856  pVfs->xDlError(pVfs, nByte, zBufOut);
20857}
20858SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
20859  return pVfs->xDlSym(pVfs, pHdle, zSym);
20860}
20861SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
20862  pVfs->xDlClose(pVfs, pHandle);
20863}
20864#endif /* SQLITE_OMIT_LOAD_EXTENSION */
20865SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
20866  return pVfs->xRandomness(pVfs, nByte, zBufOut);
20867}
20868SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
20869  return pVfs->xSleep(pVfs, nMicro);
20870}
20871SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
20872  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
20873}
20874SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
20875  int rc;
20876  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
20877  ** method to get the current date and time if that method is available
20878  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
20879  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
20880  ** unavailable.
20881  */
20882  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
20883    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
20884  }else{
20885    double r;
20886    rc = pVfs->xCurrentTime(pVfs, &r);
20887    *pTimeOut = (sqlite3_int64)(r*86400000.0);
20888  }
20889  return rc;
20890}
20891
20892SQLITE_PRIVATE int sqlite3OsOpenMalloc(
20893  sqlite3_vfs *pVfs,
20894  const char *zFile,
20895  sqlite3_file **ppFile,
20896  int flags,
20897  int *pOutFlags
20898){
20899  int rc;
20900  sqlite3_file *pFile;
20901  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
20902  if( pFile ){
20903    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
20904    if( rc!=SQLITE_OK ){
20905      sqlite3_free(pFile);
20906    }else{
20907      *ppFile = pFile;
20908    }
20909  }else{
20910    rc = SQLITE_NOMEM_BKPT;
20911  }
20912  return rc;
20913}
20914SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
20915  assert( pFile );
20916  sqlite3OsClose(pFile);
20917  sqlite3_free(pFile);
20918}
20919
20920/*
20921** This function is a wrapper around the OS specific implementation of
20922** sqlite3_os_init(). The purpose of the wrapper is to provide the
20923** ability to simulate a malloc failure, so that the handling of an
20924** error in sqlite3_os_init() by the upper layers can be tested.
20925*/
20926SQLITE_PRIVATE int sqlite3OsInit(void){
20927  void *p = sqlite3_malloc(10);
20928  if( p==0 ) return SQLITE_NOMEM_BKPT;
20929  sqlite3_free(p);
20930  return sqlite3_os_init();
20931}
20932
20933/*
20934** The list of all registered VFS implementations.
20935*/
20936static sqlite3_vfs * SQLITE_WSD vfsList = 0;
20937#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
20938
20939/*
20940** Locate a VFS by name.  If no name is given, simply return the
20941** first VFS on the list.
20942*/
20943SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
20944  sqlite3_vfs *pVfs = 0;
20945#if SQLITE_THREADSAFE
20946  sqlite3_mutex *mutex;
20947#endif
20948#ifndef SQLITE_OMIT_AUTOINIT
20949  int rc = sqlite3_initialize();
20950  if( rc ) return 0;
20951#endif
20952#if SQLITE_THREADSAFE
20953  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20954#endif
20955  sqlite3_mutex_enter(mutex);
20956  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
20957    if( zVfs==0 ) break;
20958    if( strcmp(zVfs, pVfs->zName)==0 ) break;
20959  }
20960  sqlite3_mutex_leave(mutex);
20961  return pVfs;
20962}
20963
20964/*
20965** Unlink a VFS from the linked list
20966*/
20967static void vfsUnlink(sqlite3_vfs *pVfs){
20968  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
20969  if( pVfs==0 ){
20970    /* No-op */
20971  }else if( vfsList==pVfs ){
20972    vfsList = pVfs->pNext;
20973  }else if( vfsList ){
20974    sqlite3_vfs *p = vfsList;
20975    while( p->pNext && p->pNext!=pVfs ){
20976      p = p->pNext;
20977    }
20978    if( p->pNext==pVfs ){
20979      p->pNext = pVfs->pNext;
20980    }
20981  }
20982}
20983
20984/*
20985** Register a VFS with the system.  It is harmless to register the same
20986** VFS multiple times.  The new VFS becomes the default if makeDflt is
20987** true.
20988*/
20989SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
20990  MUTEX_LOGIC(sqlite3_mutex *mutex;)
20991#ifndef SQLITE_OMIT_AUTOINIT
20992  int rc = sqlite3_initialize();
20993  if( rc ) return rc;
20994#endif
20995#ifdef SQLITE_ENABLE_API_ARMOR
20996  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
20997#endif
20998
20999  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
21000  sqlite3_mutex_enter(mutex);
21001  vfsUnlink(pVfs);
21002  if( makeDflt || vfsList==0 ){
21003    pVfs->pNext = vfsList;
21004    vfsList = pVfs;
21005  }else{
21006    pVfs->pNext = vfsList->pNext;
21007    vfsList->pNext = pVfs;
21008  }
21009  assert(vfsList);
21010  sqlite3_mutex_leave(mutex);
21011  return SQLITE_OK;
21012}
21013
21014/*
21015** Unregister a VFS so that it is no longer accessible.
21016*/
21017SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
21018#if SQLITE_THREADSAFE
21019  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
21020#endif
21021  sqlite3_mutex_enter(mutex);
21022  vfsUnlink(pVfs);
21023  sqlite3_mutex_leave(mutex);
21024  return SQLITE_OK;
21025}
21026
21027/************** End of os.c **************************************************/
21028/************** Begin file fault.c *******************************************/
21029/*
21030** 2008 Jan 22
21031**
21032** The author disclaims copyright to this source code.  In place of
21033** a legal notice, here is a blessing:
21034**
21035**    May you do good and not evil.
21036**    May you find forgiveness for yourself and forgive others.
21037**    May you share freely, never taking more than you give.
21038**
21039*************************************************************************
21040**
21041** This file contains code to support the concept of "benign"
21042** malloc failures (when the xMalloc() or xRealloc() method of the
21043** sqlite3_mem_methods structure fails to allocate a block of memory
21044** and returns 0).
21045**
21046** Most malloc failures are non-benign. After they occur, SQLite
21047** abandons the current operation and returns an error code (usually
21048** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
21049** fatal. For example, if a malloc fails while resizing a hash table, this
21050** is completely recoverable simply by not carrying out the resize. The
21051** hash table will continue to function normally.  So a malloc failure
21052** during a hash table resize is a benign fault.
21053*/
21054
21055/* #include "sqliteInt.h" */
21056
21057#ifndef SQLITE_UNTESTABLE
21058
21059/*
21060** Global variables.
21061*/
21062typedef struct BenignMallocHooks BenignMallocHooks;
21063static SQLITE_WSD struct BenignMallocHooks {
21064  void (*xBenignBegin)(void);
21065  void (*xBenignEnd)(void);
21066} sqlite3Hooks = { 0, 0 };
21067
21068/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
21069** structure.  If writable static data is unsupported on the target,
21070** we have to locate the state vector at run-time.  In the more common
21071** case where writable static data is supported, wsdHooks can refer directly
21072** to the "sqlite3Hooks" state vector declared above.
21073*/
21074#ifdef SQLITE_OMIT_WSD
21075# define wsdHooksInit \
21076  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
21077# define wsdHooks x[0]
21078#else
21079# define wsdHooksInit
21080# define wsdHooks sqlite3Hooks
21081#endif
21082
21083
21084/*
21085** Register hooks to call when sqlite3BeginBenignMalloc() and
21086** sqlite3EndBenignMalloc() are called, respectively.
21087*/
21088SQLITE_PRIVATE void sqlite3BenignMallocHooks(
21089  void (*xBenignBegin)(void),
21090  void (*xBenignEnd)(void)
21091){
21092  wsdHooksInit;
21093  wsdHooks.xBenignBegin = xBenignBegin;
21094  wsdHooks.xBenignEnd = xBenignEnd;
21095}
21096
21097/*
21098** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
21099** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
21100** indicates that subsequent malloc failures are non-benign.
21101*/
21102SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
21103  wsdHooksInit;
21104  if( wsdHooks.xBenignBegin ){
21105    wsdHooks.xBenignBegin();
21106  }
21107}
21108SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
21109  wsdHooksInit;
21110  if( wsdHooks.xBenignEnd ){
21111    wsdHooks.xBenignEnd();
21112  }
21113}
21114
21115#endif   /* #ifndef SQLITE_UNTESTABLE */
21116
21117/************** End of fault.c ***********************************************/
21118/************** Begin file mem0.c ********************************************/
21119/*
21120** 2008 October 28
21121**
21122** The author disclaims copyright to this source code.  In place of
21123** a legal notice, here is a blessing:
21124**
21125**    May you do good and not evil.
21126**    May you find forgiveness for yourself and forgive others.
21127**    May you share freely, never taking more than you give.
21128**
21129*************************************************************************
21130**
21131** This file contains a no-op memory allocation drivers for use when
21132** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
21133** here always fail.  SQLite will not operate with these drivers.  These
21134** are merely placeholders.  Real drivers must be substituted using
21135** sqlite3_config() before SQLite will operate.
21136*/
21137/* #include "sqliteInt.h" */
21138
21139/*
21140** This version of the memory allocator is the default.  It is
21141** used when no other memory allocator is specified using compile-time
21142** macros.
21143*/
21144#ifdef SQLITE_ZERO_MALLOC
21145
21146/*
21147** No-op versions of all memory allocation routines
21148*/
21149static void *sqlite3MemMalloc(int nByte){ return 0; }
21150static void sqlite3MemFree(void *pPrior){ return; }
21151static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
21152static int sqlite3MemSize(void *pPrior){ return 0; }
21153static int sqlite3MemRoundup(int n){ return n; }
21154static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
21155static void sqlite3MemShutdown(void *NotUsed){ return; }
21156
21157/*
21158** This routine is the only routine in this file with external linkage.
21159**
21160** Populate the low-level memory allocation function pointers in
21161** sqlite3GlobalConfig.m with pointers to the routines in this file.
21162*/
21163SQLITE_PRIVATE void sqlite3MemSetDefault(void){
21164  static const sqlite3_mem_methods defaultMethods = {
21165     sqlite3MemMalloc,
21166     sqlite3MemFree,
21167     sqlite3MemRealloc,
21168     sqlite3MemSize,
21169     sqlite3MemRoundup,
21170     sqlite3MemInit,
21171     sqlite3MemShutdown,
21172     0
21173  };
21174  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
21175}
21176
21177#endif /* SQLITE_ZERO_MALLOC */
21178
21179/************** End of mem0.c ************************************************/
21180/************** Begin file mem1.c ********************************************/
21181/*
21182** 2007 August 14
21183**
21184** The author disclaims copyright to this source code.  In place of
21185** a legal notice, here is a blessing:
21186**
21187**    May you do good and not evil.
21188**    May you find forgiveness for yourself and forgive others.
21189**    May you share freely, never taking more than you give.
21190**
21191*************************************************************************
21192**
21193** This file contains low-level memory allocation drivers for when
21194** SQLite will use the standard C-library malloc/realloc/free interface
21195** to obtain the memory it needs.
21196**
21197** This file contains implementations of the low-level memory allocation
21198** routines specified in the sqlite3_mem_methods object.  The content of
21199** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
21200** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
21201** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
21202** default configuration is to use memory allocation routines in this
21203** file.
21204**
21205** C-preprocessor macro summary:
21206**
21207**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
21208**                                the malloc_usable_size() interface exists
21209**                                on the target platform.  Or, this symbol
21210**                                can be set manually, if desired.
21211**                                If an equivalent interface exists by
21212**                                a different name, using a separate -D
21213**                                option to rename it.
21214**
21215**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
21216**                                memory allocator.  Set this symbol to enable
21217**                                building on older macs.
21218**
21219**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
21220**                                _msize() on windows systems.  This might
21221**                                be necessary when compiling for Delphi,
21222**                                for example.
21223*/
21224/* #include "sqliteInt.h" */
21225
21226/*
21227** This version of the memory allocator is the default.  It is
21228** used when no other memory allocator is specified using compile-time
21229** macros.
21230*/
21231#ifdef SQLITE_SYSTEM_MALLOC
21232#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
21233
21234/*
21235** Use the zone allocator available on apple products unless the
21236** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
21237*/
21238#include <sys/sysctl.h>
21239#include <malloc/malloc.h>
21240#ifdef SQLITE_MIGHT_BE_SINGLE_CORE
21241#include <libkern/OSAtomic.h>
21242#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
21243static malloc_zone_t* _sqliteZone_;
21244#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
21245#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
21246#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
21247#define SQLITE_MALLOCSIZE(x) \
21248        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
21249
21250#else /* if not __APPLE__ */
21251
21252/*
21253** Use standard C library malloc and free on non-Apple systems.
21254** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
21255*/
21256#define SQLITE_MALLOC(x)             malloc(x)
21257#define SQLITE_FREE(x)               free(x)
21258#define SQLITE_REALLOC(x,y)          realloc((x),(y))
21259
21260/*
21261** The malloc.h header file is needed for malloc_usable_size() function
21262** on some systems (e.g. Linux).
21263*/
21264#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
21265#  define SQLITE_USE_MALLOC_H 1
21266#  define SQLITE_USE_MALLOC_USABLE_SIZE 1
21267/*
21268** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
21269** use of _msize() is automatic, but can be disabled by compiling with
21270** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
21271** the malloc.h header file.
21272*/
21273#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
21274#  define SQLITE_USE_MALLOC_H
21275#  define SQLITE_USE_MSIZE
21276#endif
21277
21278/*
21279** Include the malloc.h header file, if necessary.  Also set define macro
21280** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
21281** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
21282** The memory size function can always be overridden manually by defining
21283** the macro SQLITE_MALLOCSIZE to the desired function name.
21284*/
21285#if defined(SQLITE_USE_MALLOC_H)
21286#  include <malloc.h>
21287#  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
21288#    if !defined(SQLITE_MALLOCSIZE)
21289#      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
21290#    endif
21291#  elif defined(SQLITE_USE_MSIZE)
21292#    if !defined(SQLITE_MALLOCSIZE)
21293#      define SQLITE_MALLOCSIZE      _msize
21294#    endif
21295#  endif
21296#endif /* defined(SQLITE_USE_MALLOC_H) */
21297
21298#endif /* __APPLE__ or not __APPLE__ */
21299
21300/*
21301** Like malloc(), but remember the size of the allocation
21302** so that we can find it later using sqlite3MemSize().
21303**
21304** For this low-level routine, we are guaranteed that nByte>0 because
21305** cases of nByte<=0 will be intercepted and dealt with by higher level
21306** routines.
21307*/
21308static void *sqlite3MemMalloc(int nByte){
21309#ifdef SQLITE_MALLOCSIZE
21310  void *p;
21311  testcase( ROUND8(nByte)==nByte );
21312  p = SQLITE_MALLOC( nByte );
21313  if( p==0 ){
21314    testcase( sqlite3GlobalConfig.xLog!=0 );
21315    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
21316  }
21317  return p;
21318#else
21319  sqlite3_int64 *p;
21320  assert( nByte>0 );
21321  testcase( ROUND8(nByte)!=nByte );
21322  p = SQLITE_MALLOC( nByte+8 );
21323  if( p ){
21324    p[0] = nByte;
21325    p++;
21326  }else{
21327    testcase( sqlite3GlobalConfig.xLog!=0 );
21328    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
21329  }
21330  return (void *)p;
21331#endif
21332}
21333
21334/*
21335** Like free() but works for allocations obtained from sqlite3MemMalloc()
21336** or sqlite3MemRealloc().
21337**
21338** For this low-level routine, we already know that pPrior!=0 since
21339** cases where pPrior==0 will have been intecepted and dealt with
21340** by higher-level routines.
21341*/
21342static void sqlite3MemFree(void *pPrior){
21343#ifdef SQLITE_MALLOCSIZE
21344  SQLITE_FREE(pPrior);
21345#else
21346  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
21347  assert( pPrior!=0 );
21348  p--;
21349  SQLITE_FREE(p);
21350#endif
21351}
21352
21353/*
21354** Report the allocated size of a prior return from xMalloc()
21355** or xRealloc().
21356*/
21357static int sqlite3MemSize(void *pPrior){
21358#ifdef SQLITE_MALLOCSIZE
21359  assert( pPrior!=0 );
21360  return (int)SQLITE_MALLOCSIZE(pPrior);
21361#else
21362  sqlite3_int64 *p;
21363  assert( pPrior!=0 );
21364  p = (sqlite3_int64*)pPrior;
21365  p--;
21366  return (int)p[0];
21367#endif
21368}
21369
21370/*
21371** Like realloc().  Resize an allocation previously obtained from
21372** sqlite3MemMalloc().
21373**
21374** For this low-level interface, we know that pPrior!=0.  Cases where
21375** pPrior==0 while have been intercepted by higher-level routine and
21376** redirected to xMalloc.  Similarly, we know that nByte>0 because
21377** cases where nByte<=0 will have been intercepted by higher-level
21378** routines and redirected to xFree.
21379*/
21380static void *sqlite3MemRealloc(void *pPrior, int nByte){
21381#ifdef SQLITE_MALLOCSIZE
21382  void *p = SQLITE_REALLOC(pPrior, nByte);
21383  if( p==0 ){
21384    testcase( sqlite3GlobalConfig.xLog!=0 );
21385    sqlite3_log(SQLITE_NOMEM,
21386      "failed memory resize %u to %u bytes",
21387      SQLITE_MALLOCSIZE(pPrior), nByte);
21388  }
21389  return p;
21390#else
21391  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
21392  assert( pPrior!=0 && nByte>0 );
21393  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
21394  p--;
21395  p = SQLITE_REALLOC(p, nByte+8 );
21396  if( p ){
21397    p[0] = nByte;
21398    p++;
21399  }else{
21400    testcase( sqlite3GlobalConfig.xLog!=0 );
21401    sqlite3_log(SQLITE_NOMEM,
21402      "failed memory resize %u to %u bytes",
21403      sqlite3MemSize(pPrior), nByte);
21404  }
21405  return (void*)p;
21406#endif
21407}
21408
21409/*
21410** Round up a request size to the next valid allocation size.
21411*/
21412static int sqlite3MemRoundup(int n){
21413  return ROUND8(n);
21414}
21415
21416/*
21417** Initialize this module.
21418*/
21419static int sqlite3MemInit(void *NotUsed){
21420#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
21421  int cpuCount;
21422  size_t len;
21423  if( _sqliteZone_ ){
21424    return SQLITE_OK;
21425  }
21426  len = sizeof(cpuCount);
21427  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
21428  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
21429  if( cpuCount>1 ){
21430    /* defer MT decisions to system malloc */
21431    _sqliteZone_ = malloc_default_zone();
21432  }else{
21433    /* only 1 core, use our own zone to contention over global locks,
21434    ** e.g. we have our own dedicated locks */
21435    _sqliteZone_ = malloc_create_zone(4096, 0);
21436    malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
21437  }
21438#endif /*  defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
21439  UNUSED_PARAMETER(NotUsed);
21440  return SQLITE_OK;
21441}
21442
21443/*
21444** Deinitialize this module.
21445*/
21446static void sqlite3MemShutdown(void *NotUsed){
21447  UNUSED_PARAMETER(NotUsed);
21448  return;
21449}
21450
21451/*
21452** This routine is the only routine in this file with external linkage.
21453**
21454** Populate the low-level memory allocation function pointers in
21455** sqlite3GlobalConfig.m with pointers to the routines in this file.
21456*/
21457SQLITE_PRIVATE void sqlite3MemSetDefault(void){
21458  static const sqlite3_mem_methods defaultMethods = {
21459     sqlite3MemMalloc,
21460     sqlite3MemFree,
21461     sqlite3MemRealloc,
21462     sqlite3MemSize,
21463     sqlite3MemRoundup,
21464     sqlite3MemInit,
21465     sqlite3MemShutdown,
21466     0
21467  };
21468  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
21469}
21470
21471#endif /* SQLITE_SYSTEM_MALLOC */
21472
21473/************** End of mem1.c ************************************************/
21474/************** Begin file mem2.c ********************************************/
21475/*
21476** 2007 August 15
21477**
21478** The author disclaims copyright to this source code.  In place of
21479** a legal notice, here is a blessing:
21480**
21481**    May you do good and not evil.
21482**    May you find forgiveness for yourself and forgive others.
21483**    May you share freely, never taking more than you give.
21484**
21485*************************************************************************
21486**
21487** This file contains low-level memory allocation drivers for when
21488** SQLite will use the standard C-library malloc/realloc/free interface
21489** to obtain the memory it needs while adding lots of additional debugging
21490** information to each allocation in order to help detect and fix memory
21491** leaks and memory usage errors.
21492**
21493** This file contains implementations of the low-level memory allocation
21494** routines specified in the sqlite3_mem_methods object.
21495*/
21496/* #include "sqliteInt.h" */
21497
21498/*
21499** This version of the memory allocator is used only if the
21500** SQLITE_MEMDEBUG macro is defined
21501*/
21502#ifdef SQLITE_MEMDEBUG
21503
21504/*
21505** The backtrace functionality is only available with GLIBC
21506*/
21507#ifdef __GLIBC__
21508  extern int backtrace(void**,int);
21509  extern void backtrace_symbols_fd(void*const*,int,int);
21510#else
21511# define backtrace(A,B) 1
21512# define backtrace_symbols_fd(A,B,C)
21513#endif
21514/* #include <stdio.h> */
21515
21516/*
21517** Each memory allocation looks like this:
21518**
21519**  ------------------------------------------------------------------------
21520**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
21521**  ------------------------------------------------------------------------
21522**
21523** The application code sees only a pointer to the allocation.  We have
21524** to back up from the allocation pointer to find the MemBlockHdr.  The
21525** MemBlockHdr tells us the size of the allocation and the number of
21526** backtrace pointers.  There is also a guard word at the end of the
21527** MemBlockHdr.
21528*/
21529struct MemBlockHdr {
21530  i64 iSize;                          /* Size of this allocation */
21531  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
21532  char nBacktrace;                    /* Number of backtraces on this alloc */
21533  char nBacktraceSlots;               /* Available backtrace slots */
21534  u8 nTitle;                          /* Bytes of title; includes '\0' */
21535  u8 eType;                           /* Allocation type code */
21536  int iForeGuard;                     /* Guard word for sanity */
21537};
21538
21539/*
21540** Guard words
21541*/
21542#define FOREGUARD 0x80F5E153
21543#define REARGUARD 0xE4676B53
21544
21545/*
21546** Number of malloc size increments to track.
21547*/
21548#define NCSIZE  1000
21549
21550/*
21551** All of the static variables used by this module are collected
21552** into a single structure named "mem".  This is to keep the
21553** static variables organized and to reduce namespace pollution
21554** when this module is combined with other in the amalgamation.
21555*/
21556static struct {
21557
21558  /*
21559  ** Mutex to control access to the memory allocation subsystem.
21560  */
21561  sqlite3_mutex *mutex;
21562
21563  /*
21564  ** Head and tail of a linked list of all outstanding allocations
21565  */
21566  struct MemBlockHdr *pFirst;
21567  struct MemBlockHdr *pLast;
21568
21569  /*
21570  ** The number of levels of backtrace to save in new allocations.
21571  */
21572  int nBacktrace;
21573  void (*xBacktrace)(int, int, void **);
21574
21575  /*
21576  ** Title text to insert in front of each block
21577  */
21578  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
21579  char zTitle[100];  /* The title text */
21580
21581  /*
21582  ** sqlite3MallocDisallow() increments the following counter.
21583  ** sqlite3MallocAllow() decrements it.
21584  */
21585  int disallow; /* Do not allow memory allocation */
21586
21587  /*
21588  ** Gather statistics on the sizes of memory allocations.
21589  ** nAlloc[i] is the number of allocation attempts of i*8
21590  ** bytes.  i==NCSIZE is the number of allocation attempts for
21591  ** sizes more than NCSIZE*8 bytes.
21592  */
21593  int nAlloc[NCSIZE];      /* Total number of allocations */
21594  int nCurrent[NCSIZE];    /* Current number of allocations */
21595  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
21596
21597} mem;
21598
21599
21600/*
21601** Adjust memory usage statistics
21602*/
21603static void adjustStats(int iSize, int increment){
21604  int i = ROUND8(iSize)/8;
21605  if( i>NCSIZE-1 ){
21606    i = NCSIZE - 1;
21607  }
21608  if( increment>0 ){
21609    mem.nAlloc[i]++;
21610    mem.nCurrent[i]++;
21611    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
21612      mem.mxCurrent[i] = mem.nCurrent[i];
21613    }
21614  }else{
21615    mem.nCurrent[i]--;
21616    assert( mem.nCurrent[i]>=0 );
21617  }
21618}
21619
21620/*
21621** Given an allocation, find the MemBlockHdr for that allocation.
21622**
21623** This routine checks the guards at either end of the allocation and
21624** if they are incorrect it asserts.
21625*/
21626static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
21627  struct MemBlockHdr *p;
21628  int *pInt;
21629  u8 *pU8;
21630  int nReserve;
21631
21632  p = (struct MemBlockHdr*)pAllocation;
21633  p--;
21634  assert( p->iForeGuard==(int)FOREGUARD );
21635  nReserve = ROUND8(p->iSize);
21636  pInt = (int*)pAllocation;
21637  pU8 = (u8*)pAllocation;
21638  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
21639  /* This checks any of the "extra" bytes allocated due
21640  ** to rounding up to an 8 byte boundary to ensure
21641  ** they haven't been overwritten.
21642  */
21643  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
21644  return p;
21645}
21646
21647/*
21648** Return the number of bytes currently allocated at address p.
21649*/
21650static int sqlite3MemSize(void *p){
21651  struct MemBlockHdr *pHdr;
21652  if( !p ){
21653    return 0;
21654  }
21655  pHdr = sqlite3MemsysGetHeader(p);
21656  return (int)pHdr->iSize;
21657}
21658
21659/*
21660** Initialize the memory allocation subsystem.
21661*/
21662static int sqlite3MemInit(void *NotUsed){
21663  UNUSED_PARAMETER(NotUsed);
21664  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
21665  if( !sqlite3GlobalConfig.bMemstat ){
21666    /* If memory status is enabled, then the malloc.c wrapper will already
21667    ** hold the STATIC_MEM mutex when the routines here are invoked. */
21668    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21669  }
21670  return SQLITE_OK;
21671}
21672
21673/*
21674** Deinitialize the memory allocation subsystem.
21675*/
21676static void sqlite3MemShutdown(void *NotUsed){
21677  UNUSED_PARAMETER(NotUsed);
21678  mem.mutex = 0;
21679}
21680
21681/*
21682** Round up a request size to the next valid allocation size.
21683*/
21684static int sqlite3MemRoundup(int n){
21685  return ROUND8(n);
21686}
21687
21688/*
21689** Fill a buffer with pseudo-random bytes.  This is used to preset
21690** the content of a new memory allocation to unpredictable values and
21691** to clear the content of a freed allocation to unpredictable values.
21692*/
21693static void randomFill(char *pBuf, int nByte){
21694  unsigned int x, y, r;
21695  x = SQLITE_PTR_TO_INT(pBuf);
21696  y = nByte | 1;
21697  while( nByte >= 4 ){
21698    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
21699    y = y*1103515245 + 12345;
21700    r = x ^ y;
21701    *(int*)pBuf = r;
21702    pBuf += 4;
21703    nByte -= 4;
21704  }
21705  while( nByte-- > 0 ){
21706    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
21707    y = y*1103515245 + 12345;
21708    r = x ^ y;
21709    *(pBuf++) = r & 0xff;
21710  }
21711}
21712
21713/*
21714** Allocate nByte bytes of memory.
21715*/
21716static void *sqlite3MemMalloc(int nByte){
21717  struct MemBlockHdr *pHdr;
21718  void **pBt;
21719  char *z;
21720  int *pInt;
21721  void *p = 0;
21722  int totalSize;
21723  int nReserve;
21724  sqlite3_mutex_enter(mem.mutex);
21725  assert( mem.disallow==0 );
21726  nReserve = ROUND8(nByte);
21727  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
21728               mem.nBacktrace*sizeof(void*) + mem.nTitle;
21729  p = malloc(totalSize);
21730  if( p ){
21731    z = p;
21732    pBt = (void**)&z[mem.nTitle];
21733    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
21734    pHdr->pNext = 0;
21735    pHdr->pPrev = mem.pLast;
21736    if( mem.pLast ){
21737      mem.pLast->pNext = pHdr;
21738    }else{
21739      mem.pFirst = pHdr;
21740    }
21741    mem.pLast = pHdr;
21742    pHdr->iForeGuard = FOREGUARD;
21743    pHdr->eType = MEMTYPE_HEAP;
21744    pHdr->nBacktraceSlots = mem.nBacktrace;
21745    pHdr->nTitle = mem.nTitle;
21746    if( mem.nBacktrace ){
21747      void *aAddr[40];
21748      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
21749      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
21750      assert(pBt[0]);
21751      if( mem.xBacktrace ){
21752        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
21753      }
21754    }else{
21755      pHdr->nBacktrace = 0;
21756    }
21757    if( mem.nTitle ){
21758      memcpy(z, mem.zTitle, mem.nTitle);
21759    }
21760    pHdr->iSize = nByte;
21761    adjustStats(nByte, +1);
21762    pInt = (int*)&pHdr[1];
21763    pInt[nReserve/sizeof(int)] = REARGUARD;
21764    randomFill((char*)pInt, nByte);
21765    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
21766    p = (void*)pInt;
21767  }
21768  sqlite3_mutex_leave(mem.mutex);
21769  return p;
21770}
21771
21772/*
21773** Free memory.
21774*/
21775static void sqlite3MemFree(void *pPrior){
21776  struct MemBlockHdr *pHdr;
21777  void **pBt;
21778  char *z;
21779  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
21780       || mem.mutex!=0 );
21781  pHdr = sqlite3MemsysGetHeader(pPrior);
21782  pBt = (void**)pHdr;
21783  pBt -= pHdr->nBacktraceSlots;
21784  sqlite3_mutex_enter(mem.mutex);
21785  if( pHdr->pPrev ){
21786    assert( pHdr->pPrev->pNext==pHdr );
21787    pHdr->pPrev->pNext = pHdr->pNext;
21788  }else{
21789    assert( mem.pFirst==pHdr );
21790    mem.pFirst = pHdr->pNext;
21791  }
21792  if( pHdr->pNext ){
21793    assert( pHdr->pNext->pPrev==pHdr );
21794    pHdr->pNext->pPrev = pHdr->pPrev;
21795  }else{
21796    assert( mem.pLast==pHdr );
21797    mem.pLast = pHdr->pPrev;
21798  }
21799  z = (char*)pBt;
21800  z -= pHdr->nTitle;
21801  adjustStats((int)pHdr->iSize, -1);
21802  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
21803                (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
21804  free(z);
21805  sqlite3_mutex_leave(mem.mutex);
21806}
21807
21808/*
21809** Change the size of an existing memory allocation.
21810**
21811** For this debugging implementation, we *always* make a copy of the
21812** allocation into a new place in memory.  In this way, if the
21813** higher level code is using pointer to the old allocation, it is
21814** much more likely to break and we are much more liking to find
21815** the error.
21816*/
21817static void *sqlite3MemRealloc(void *pPrior, int nByte){
21818  struct MemBlockHdr *pOldHdr;
21819  void *pNew;
21820  assert( mem.disallow==0 );
21821  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
21822  pOldHdr = sqlite3MemsysGetHeader(pPrior);
21823  pNew = sqlite3MemMalloc(nByte);
21824  if( pNew ){
21825    memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
21826    if( nByte>pOldHdr->iSize ){
21827      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
21828    }
21829    sqlite3MemFree(pPrior);
21830  }
21831  return pNew;
21832}
21833
21834/*
21835** Populate the low-level memory allocation function pointers in
21836** sqlite3GlobalConfig.m with pointers to the routines in this file.
21837*/
21838SQLITE_PRIVATE void sqlite3MemSetDefault(void){
21839  static const sqlite3_mem_methods defaultMethods = {
21840     sqlite3MemMalloc,
21841     sqlite3MemFree,
21842     sqlite3MemRealloc,
21843     sqlite3MemSize,
21844     sqlite3MemRoundup,
21845     sqlite3MemInit,
21846     sqlite3MemShutdown,
21847     0
21848  };
21849  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
21850}
21851
21852/*
21853** Set the "type" of an allocation.
21854*/
21855SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
21856  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21857    struct MemBlockHdr *pHdr;
21858    pHdr = sqlite3MemsysGetHeader(p);
21859    assert( pHdr->iForeGuard==FOREGUARD );
21860    pHdr->eType = eType;
21861  }
21862}
21863
21864/*
21865** Return TRUE if the mask of type in eType matches the type of the
21866** allocation p.  Also return true if p==NULL.
21867**
21868** This routine is designed for use within an assert() statement, to
21869** verify the type of an allocation.  For example:
21870**
21871**     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21872*/
21873SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
21874  int rc = 1;
21875  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21876    struct MemBlockHdr *pHdr;
21877    pHdr = sqlite3MemsysGetHeader(p);
21878    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
21879    if( (pHdr->eType&eType)==0 ){
21880      rc = 0;
21881    }
21882  }
21883  return rc;
21884}
21885
21886/*
21887** Return TRUE if the mask of type in eType matches no bits of the type of the
21888** allocation p.  Also return true if p==NULL.
21889**
21890** This routine is designed for use within an assert() statement, to
21891** verify the type of an allocation.  For example:
21892**
21893**     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21894*/
21895SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
21896  int rc = 1;
21897  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21898    struct MemBlockHdr *pHdr;
21899    pHdr = sqlite3MemsysGetHeader(p);
21900    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
21901    if( (pHdr->eType&eType)!=0 ){
21902      rc = 0;
21903    }
21904  }
21905  return rc;
21906}
21907
21908/*
21909** Set the number of backtrace levels kept for each allocation.
21910** A value of zero turns off backtracing.  The number is always rounded
21911** up to a multiple of 2.
21912*/
21913SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
21914  if( depth<0 ){ depth = 0; }
21915  if( depth>20 ){ depth = 20; }
21916  depth = (depth+1)&0xfe;
21917  mem.nBacktrace = depth;
21918}
21919
21920SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
21921  mem.xBacktrace = xBacktrace;
21922}
21923
21924/*
21925** Set the title string for subsequent allocations.
21926*/
21927SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
21928  unsigned int n = sqlite3Strlen30(zTitle) + 1;
21929  sqlite3_mutex_enter(mem.mutex);
21930  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
21931  memcpy(mem.zTitle, zTitle, n);
21932  mem.zTitle[n] = 0;
21933  mem.nTitle = ROUND8(n);
21934  sqlite3_mutex_leave(mem.mutex);
21935}
21936
21937SQLITE_PRIVATE void sqlite3MemdebugSync(){
21938  struct MemBlockHdr *pHdr;
21939  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21940    void **pBt = (void**)pHdr;
21941    pBt -= pHdr->nBacktraceSlots;
21942    mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
21943  }
21944}
21945
21946/*
21947** Open the file indicated and write a log of all unfreed memory
21948** allocations into that log.
21949*/
21950SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
21951  FILE *out;
21952  struct MemBlockHdr *pHdr;
21953  void **pBt;
21954  int i;
21955  out = fopen(zFilename, "w");
21956  if( out==0 ){
21957    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21958                    zFilename);
21959    return;
21960  }
21961  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21962    char *z = (char*)pHdr;
21963    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
21964    fprintf(out, "**** %lld bytes at %p from %s ****\n",
21965            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
21966    if( pHdr->nBacktrace ){
21967      fflush(out);
21968      pBt = (void**)pHdr;
21969      pBt -= pHdr->nBacktraceSlots;
21970      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
21971      fprintf(out, "\n");
21972    }
21973  }
21974  fprintf(out, "COUNTS:\n");
21975  for(i=0; i<NCSIZE-1; i++){
21976    if( mem.nAlloc[i] ){
21977      fprintf(out, "   %5d: %10d %10d %10d\n",
21978            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
21979    }
21980  }
21981  if( mem.nAlloc[NCSIZE-1] ){
21982    fprintf(out, "   %5d: %10d %10d %10d\n",
21983             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
21984             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
21985  }
21986  fclose(out);
21987}
21988
21989/*
21990** Return the number of times sqlite3MemMalloc() has been called.
21991*/
21992SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
21993  int i;
21994  int nTotal = 0;
21995  for(i=0; i<NCSIZE; i++){
21996    nTotal += mem.nAlloc[i];
21997  }
21998  return nTotal;
21999}
22000
22001
22002#endif /* SQLITE_MEMDEBUG */
22003
22004/************** End of mem2.c ************************************************/
22005/************** Begin file mem3.c ********************************************/
22006/*
22007** 2007 October 14
22008**
22009** The author disclaims copyright to this source code.  In place of
22010** a legal notice, here is a blessing:
22011**
22012**    May you do good and not evil.
22013**    May you find forgiveness for yourself and forgive others.
22014**    May you share freely, never taking more than you give.
22015**
22016*************************************************************************
22017** This file contains the C functions that implement a memory
22018** allocation subsystem for use by SQLite.
22019**
22020** This version of the memory allocation subsystem omits all
22021** use of malloc(). The SQLite user supplies a block of memory
22022** before calling sqlite3_initialize() from which allocations
22023** are made and returned by the xMalloc() and xRealloc()
22024** implementations. Once sqlite3_initialize() has been called,
22025** the amount of memory available to SQLite is fixed and cannot
22026** be changed.
22027**
22028** This version of the memory allocation subsystem is included
22029** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
22030*/
22031/* #include "sqliteInt.h" */
22032
22033/*
22034** This version of the memory allocator is only built into the library
22035** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
22036** mean that the library will use a memory-pool by default, just that
22037** it is available. The mempool allocator is activated by calling
22038** sqlite3_config().
22039*/
22040#ifdef SQLITE_ENABLE_MEMSYS3
22041
22042/*
22043** Maximum size (in Mem3Blocks) of a "small" chunk.
22044*/
22045#define MX_SMALL 10
22046
22047
22048/*
22049** Number of freelist hash slots
22050*/
22051#define N_HASH  61
22052
22053/*
22054** A memory allocation (also called a "chunk") consists of two or
22055** more blocks where each block is 8 bytes.  The first 8 bytes are
22056** a header that is not returned to the user.
22057**
22058** A chunk is two or more blocks that is either checked out or
22059** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
22060** size of the allocation in blocks if the allocation is free.
22061** The u.hdr.size4x&1 bit is true if the chunk is checked out and
22062** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
22063** is true if the previous chunk is checked out and false if the
22064** previous chunk is free.  The u.hdr.prevSize field is the size of
22065** the previous chunk in blocks if the previous chunk is on the
22066** freelist. If the previous chunk is checked out, then
22067** u.hdr.prevSize can be part of the data for that chunk and should
22068** not be read or written.
22069**
22070** We often identify a chunk by its index in mem3.aPool[].  When
22071** this is done, the chunk index refers to the second block of
22072** the chunk.  In this way, the first chunk has an index of 1.
22073** A chunk index of 0 means "no such chunk" and is the equivalent
22074** of a NULL pointer.
22075**
22076** The second block of free chunks is of the form u.list.  The
22077** two fields form a double-linked list of chunks of related sizes.
22078** Pointers to the head of the list are stored in mem3.aiSmall[]
22079** for smaller chunks and mem3.aiHash[] for larger chunks.
22080**
22081** The second block of a chunk is user data if the chunk is checked
22082** out.  If a chunk is checked out, the user data may extend into
22083** the u.hdr.prevSize value of the following chunk.
22084*/
22085typedef struct Mem3Block Mem3Block;
22086struct Mem3Block {
22087  union {
22088    struct {
22089      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
22090      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
22091    } hdr;
22092    struct {
22093      u32 next;       /* Index in mem3.aPool[] of next free chunk */
22094      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
22095    } list;
22096  } u;
22097};
22098
22099/*
22100** All of the static variables used by this module are collected
22101** into a single structure named "mem3".  This is to keep the
22102** static variables organized and to reduce namespace pollution
22103** when this module is combined with other in the amalgamation.
22104*/
22105static SQLITE_WSD struct Mem3Global {
22106  /*
22107  ** Memory available for allocation. nPool is the size of the array
22108  ** (in Mem3Blocks) pointed to by aPool less 2.
22109  */
22110  u32 nPool;
22111  Mem3Block *aPool;
22112
22113  /*
22114  ** True if we are evaluating an out-of-memory callback.
22115  */
22116  int alarmBusy;
22117
22118  /*
22119  ** Mutex to control access to the memory allocation subsystem.
22120  */
22121  sqlite3_mutex *mutex;
22122
22123  /*
22124  ** The minimum amount of free space that we have seen.
22125  */
22126  u32 mnMaster;
22127
22128  /*
22129  ** iMaster is the index of the master chunk.  Most new allocations
22130  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
22131  ** of the current master.  iMaster is 0 if there is not master chunk.
22132  ** The master chunk is not in either the aiHash[] or aiSmall[].
22133  */
22134  u32 iMaster;
22135  u32 szMaster;
22136
22137  /*
22138  ** Array of lists of free blocks according to the block size
22139  ** for smaller chunks, or a hash on the block size for larger
22140  ** chunks.
22141  */
22142  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
22143  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
22144} mem3 = { 97535575 };
22145
22146#define mem3 GLOBAL(struct Mem3Global, mem3)
22147
22148/*
22149** Unlink the chunk at mem3.aPool[i] from list it is currently
22150** on.  *pRoot is the list that i is a member of.
22151*/
22152static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
22153  u32 next = mem3.aPool[i].u.list.next;
22154  u32 prev = mem3.aPool[i].u.list.prev;
22155  assert( sqlite3_mutex_held(mem3.mutex) );
22156  if( prev==0 ){
22157    *pRoot = next;
22158  }else{
22159    mem3.aPool[prev].u.list.next = next;
22160  }
22161  if( next ){
22162    mem3.aPool[next].u.list.prev = prev;
22163  }
22164  mem3.aPool[i].u.list.next = 0;
22165  mem3.aPool[i].u.list.prev = 0;
22166}
22167
22168/*
22169** Unlink the chunk at index i from
22170** whatever list is currently a member of.
22171*/
22172static void memsys3Unlink(u32 i){
22173  u32 size, hash;
22174  assert( sqlite3_mutex_held(mem3.mutex) );
22175  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
22176  assert( i>=1 );
22177  size = mem3.aPool[i-1].u.hdr.size4x/4;
22178  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
22179  assert( size>=2 );
22180  if( size <= MX_SMALL ){
22181    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
22182  }else{
22183    hash = size % N_HASH;
22184    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
22185  }
22186}
22187
22188/*
22189** Link the chunk at mem3.aPool[i] so that is on the list rooted
22190** at *pRoot.
22191*/
22192static void memsys3LinkIntoList(u32 i, u32 *pRoot){
22193  assert( sqlite3_mutex_held(mem3.mutex) );
22194  mem3.aPool[i].u.list.next = *pRoot;
22195  mem3.aPool[i].u.list.prev = 0;
22196  if( *pRoot ){
22197    mem3.aPool[*pRoot].u.list.prev = i;
22198  }
22199  *pRoot = i;
22200}
22201
22202/*
22203** Link the chunk at index i into either the appropriate
22204** small chunk list, or into the large chunk hash table.
22205*/
22206static void memsys3Link(u32 i){
22207  u32 size, hash;
22208  assert( sqlite3_mutex_held(mem3.mutex) );
22209  assert( i>=1 );
22210  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
22211  size = mem3.aPool[i-1].u.hdr.size4x/4;
22212  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
22213  assert( size>=2 );
22214  if( size <= MX_SMALL ){
22215    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
22216  }else{
22217    hash = size % N_HASH;
22218    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
22219  }
22220}
22221
22222/*
22223** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
22224** will already be held (obtained by code in malloc.c) if
22225** sqlite3GlobalConfig.bMemStat is true.
22226*/
22227static void memsys3Enter(void){
22228  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
22229    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
22230  }
22231  sqlite3_mutex_enter(mem3.mutex);
22232}
22233static void memsys3Leave(void){
22234  sqlite3_mutex_leave(mem3.mutex);
22235}
22236
22237/*
22238** Called when we are unable to satisfy an allocation of nBytes.
22239*/
22240static void memsys3OutOfMemory(int nByte){
22241  if( !mem3.alarmBusy ){
22242    mem3.alarmBusy = 1;
22243    assert( sqlite3_mutex_held(mem3.mutex) );
22244    sqlite3_mutex_leave(mem3.mutex);
22245    sqlite3_release_memory(nByte);
22246    sqlite3_mutex_enter(mem3.mutex);
22247    mem3.alarmBusy = 0;
22248  }
22249}
22250
22251
22252/*
22253** Chunk i is a free chunk that has been unlinked.  Adjust its
22254** size parameters for check-out and return a pointer to the
22255** user portion of the chunk.
22256*/
22257static void *memsys3Checkout(u32 i, u32 nBlock){
22258  u32 x;
22259  assert( sqlite3_mutex_held(mem3.mutex) );
22260  assert( i>=1 );
22261  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
22262  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
22263  x = mem3.aPool[i-1].u.hdr.size4x;
22264  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
22265  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
22266  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
22267  return &mem3.aPool[i];
22268}
22269
22270/*
22271** Carve a piece off of the end of the mem3.iMaster free chunk.
22272** Return a pointer to the new allocation.  Or, if the master chunk
22273** is not large enough, return 0.
22274*/
22275static void *memsys3FromMaster(u32 nBlock){
22276  assert( sqlite3_mutex_held(mem3.mutex) );
22277  assert( mem3.szMaster>=nBlock );
22278  if( nBlock>=mem3.szMaster-1 ){
22279    /* Use the entire master */
22280    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
22281    mem3.iMaster = 0;
22282    mem3.szMaster = 0;
22283    mem3.mnMaster = 0;
22284    return p;
22285  }else{
22286    /* Split the master block.  Return the tail. */
22287    u32 newi, x;
22288    newi = mem3.iMaster + mem3.szMaster - nBlock;
22289    assert( newi > mem3.iMaster+1 );
22290    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
22291    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
22292    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
22293    mem3.szMaster -= nBlock;
22294    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
22295    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
22296    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
22297    if( mem3.szMaster < mem3.mnMaster ){
22298      mem3.mnMaster = mem3.szMaster;
22299    }
22300    return (void*)&mem3.aPool[newi];
22301  }
22302}
22303
22304/*
22305** *pRoot is the head of a list of free chunks of the same size
22306** or same size hash.  In other words, *pRoot is an entry in either
22307** mem3.aiSmall[] or mem3.aiHash[].
22308**
22309** This routine examines all entries on the given list and tries
22310** to coalesce each entries with adjacent free chunks.
22311**
22312** If it sees a chunk that is larger than mem3.iMaster, it replaces
22313** the current mem3.iMaster with the new larger chunk.  In order for
22314** this mem3.iMaster replacement to work, the master chunk must be
22315** linked into the hash tables.  That is not the normal state of
22316** affairs, of course.  The calling routine must link the master
22317** chunk before invoking this routine, then must unlink the (possibly
22318** changed) master chunk once this routine has finished.
22319*/
22320static void memsys3Merge(u32 *pRoot){
22321  u32 iNext, prev, size, i, x;
22322
22323  assert( sqlite3_mutex_held(mem3.mutex) );
22324  for(i=*pRoot; i>0; i=iNext){
22325    iNext = mem3.aPool[i].u.list.next;
22326    size = mem3.aPool[i-1].u.hdr.size4x;
22327    assert( (size&1)==0 );
22328    if( (size&2)==0 ){
22329      memsys3UnlinkFromList(i, pRoot);
22330      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
22331      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
22332      if( prev==iNext ){
22333        iNext = mem3.aPool[prev].u.list.next;
22334      }
22335      memsys3Unlink(prev);
22336      size = i + size/4 - prev;
22337      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
22338      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
22339      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
22340      memsys3Link(prev);
22341      i = prev;
22342    }else{
22343      size /= 4;
22344    }
22345    if( size>mem3.szMaster ){
22346      mem3.iMaster = i;
22347      mem3.szMaster = size;
22348    }
22349  }
22350}
22351
22352/*
22353** Return a block of memory of at least nBytes in size.
22354** Return NULL if unable.
22355**
22356** This function assumes that the necessary mutexes, if any, are
22357** already held by the caller. Hence "Unsafe".
22358*/
22359static void *memsys3MallocUnsafe(int nByte){
22360  u32 i;
22361  u32 nBlock;
22362  u32 toFree;
22363
22364  assert( sqlite3_mutex_held(mem3.mutex) );
22365  assert( sizeof(Mem3Block)==8 );
22366  if( nByte<=12 ){
22367    nBlock = 2;
22368  }else{
22369    nBlock = (nByte + 11)/8;
22370  }
22371  assert( nBlock>=2 );
22372
22373  /* STEP 1:
22374  ** Look for an entry of the correct size in either the small
22375  ** chunk table or in the large chunk hash table.  This is
22376  ** successful most of the time (about 9 times out of 10).
22377  */
22378  if( nBlock <= MX_SMALL ){
22379    i = mem3.aiSmall[nBlock-2];
22380    if( i>0 ){
22381      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
22382      return memsys3Checkout(i, nBlock);
22383    }
22384  }else{
22385    int hash = nBlock % N_HASH;
22386    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
22387      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
22388        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
22389        return memsys3Checkout(i, nBlock);
22390      }
22391    }
22392  }
22393
22394  /* STEP 2:
22395  ** Try to satisfy the allocation by carving a piece off of the end
22396  ** of the master chunk.  This step usually works if step 1 fails.
22397  */
22398  if( mem3.szMaster>=nBlock ){
22399    return memsys3FromMaster(nBlock);
22400  }
22401
22402
22403  /* STEP 3:
22404  ** Loop through the entire memory pool.  Coalesce adjacent free
22405  ** chunks.  Recompute the master chunk as the largest free chunk.
22406  ** Then try again to satisfy the allocation by carving a piece off
22407  ** of the end of the master chunk.  This step happens very
22408  ** rarely (we hope!)
22409  */
22410  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
22411    memsys3OutOfMemory(toFree);
22412    if( mem3.iMaster ){
22413      memsys3Link(mem3.iMaster);
22414      mem3.iMaster = 0;
22415      mem3.szMaster = 0;
22416    }
22417    for(i=0; i<N_HASH; i++){
22418      memsys3Merge(&mem3.aiHash[i]);
22419    }
22420    for(i=0; i<MX_SMALL-1; i++){
22421      memsys3Merge(&mem3.aiSmall[i]);
22422    }
22423    if( mem3.szMaster ){
22424      memsys3Unlink(mem3.iMaster);
22425      if( mem3.szMaster>=nBlock ){
22426        return memsys3FromMaster(nBlock);
22427      }
22428    }
22429  }
22430
22431  /* If none of the above worked, then we fail. */
22432  return 0;
22433}
22434
22435/*
22436** Free an outstanding memory allocation.
22437**
22438** This function assumes that the necessary mutexes, if any, are
22439** already held by the caller. Hence "Unsafe".
22440*/
22441static void memsys3FreeUnsafe(void *pOld){
22442  Mem3Block *p = (Mem3Block*)pOld;
22443  int i;
22444  u32 size, x;
22445  assert( sqlite3_mutex_held(mem3.mutex) );
22446  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
22447  i = p - mem3.aPool;
22448  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
22449  size = mem3.aPool[i-1].u.hdr.size4x/4;
22450  assert( i+size<=mem3.nPool+1 );
22451  mem3.aPool[i-1].u.hdr.size4x &= ~1;
22452  mem3.aPool[i+size-1].u.hdr.prevSize = size;
22453  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
22454  memsys3Link(i);
22455
22456  /* Try to expand the master using the newly freed chunk */
22457  if( mem3.iMaster ){
22458    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
22459      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
22460      mem3.iMaster -= size;
22461      mem3.szMaster += size;
22462      memsys3Unlink(mem3.iMaster);
22463      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
22464      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
22465      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
22466    }
22467    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
22468    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
22469      memsys3Unlink(mem3.iMaster+mem3.szMaster);
22470      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
22471      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
22472      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
22473    }
22474  }
22475}
22476
22477/*
22478** Return the size of an outstanding allocation, in bytes.  The
22479** size returned omits the 8-byte header overhead.  This only
22480** works for chunks that are currently checked out.
22481*/
22482static int memsys3Size(void *p){
22483  Mem3Block *pBlock;
22484  assert( p!=0 );
22485  pBlock = (Mem3Block*)p;
22486  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
22487  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
22488}
22489
22490/*
22491** Round up a request size to the next valid allocation size.
22492*/
22493static int memsys3Roundup(int n){
22494  if( n<=12 ){
22495    return 12;
22496  }else{
22497    return ((n+11)&~7) - 4;
22498  }
22499}
22500
22501/*
22502** Allocate nBytes of memory.
22503*/
22504static void *memsys3Malloc(int nBytes){
22505  sqlite3_int64 *p;
22506  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
22507  memsys3Enter();
22508  p = memsys3MallocUnsafe(nBytes);
22509  memsys3Leave();
22510  return (void*)p;
22511}
22512
22513/*
22514** Free memory.
22515*/
22516static void memsys3Free(void *pPrior){
22517  assert( pPrior );
22518  memsys3Enter();
22519  memsys3FreeUnsafe(pPrior);
22520  memsys3Leave();
22521}
22522
22523/*
22524** Change the size of an existing memory allocation
22525*/
22526static void *memsys3Realloc(void *pPrior, int nBytes){
22527  int nOld;
22528  void *p;
22529  if( pPrior==0 ){
22530    return sqlite3_malloc(nBytes);
22531  }
22532  if( nBytes<=0 ){
22533    sqlite3_free(pPrior);
22534    return 0;
22535  }
22536  nOld = memsys3Size(pPrior);
22537  if( nBytes<=nOld && nBytes>=nOld-128 ){
22538    return pPrior;
22539  }
22540  memsys3Enter();
22541  p = memsys3MallocUnsafe(nBytes);
22542  if( p ){
22543    if( nOld<nBytes ){
22544      memcpy(p, pPrior, nOld);
22545    }else{
22546      memcpy(p, pPrior, nBytes);
22547    }
22548    memsys3FreeUnsafe(pPrior);
22549  }
22550  memsys3Leave();
22551  return p;
22552}
22553
22554/*
22555** Initialize this module.
22556*/
22557static int memsys3Init(void *NotUsed){
22558  UNUSED_PARAMETER(NotUsed);
22559  if( !sqlite3GlobalConfig.pHeap ){
22560    return SQLITE_ERROR;
22561  }
22562
22563  /* Store a pointer to the memory block in global structure mem3. */
22564  assert( sizeof(Mem3Block)==8 );
22565  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
22566  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
22567
22568  /* Initialize the master block. */
22569  mem3.szMaster = mem3.nPool;
22570  mem3.mnMaster = mem3.szMaster;
22571  mem3.iMaster = 1;
22572  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
22573  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
22574  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
22575
22576  return SQLITE_OK;
22577}
22578
22579/*
22580** Deinitialize this module.
22581*/
22582static void memsys3Shutdown(void *NotUsed){
22583  UNUSED_PARAMETER(NotUsed);
22584  mem3.mutex = 0;
22585  return;
22586}
22587
22588
22589
22590/*
22591** Open the file indicated and write a log of all unfreed memory
22592** allocations into that log.
22593*/
22594SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
22595#ifdef SQLITE_DEBUG
22596  FILE *out;
22597  u32 i, j;
22598  u32 size;
22599  if( zFilename==0 || zFilename[0]==0 ){
22600    out = stdout;
22601  }else{
22602    out = fopen(zFilename, "w");
22603    if( out==0 ){
22604      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22605                      zFilename);
22606      return;
22607    }
22608  }
22609  memsys3Enter();
22610  fprintf(out, "CHUNKS:\n");
22611  for(i=1; i<=mem3.nPool; i+=size/4){
22612    size = mem3.aPool[i-1].u.hdr.size4x;
22613    if( size/4<=1 ){
22614      fprintf(out, "%p size error\n", &mem3.aPool[i]);
22615      assert( 0 );
22616      break;
22617    }
22618    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
22619      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
22620      assert( 0 );
22621      break;
22622    }
22623    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
22624      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
22625      assert( 0 );
22626      break;
22627    }
22628    if( size&1 ){
22629      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
22630    }else{
22631      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
22632                  i==mem3.iMaster ? " **master**" : "");
22633    }
22634  }
22635  for(i=0; i<MX_SMALL-1; i++){
22636    if( mem3.aiSmall[i]==0 ) continue;
22637    fprintf(out, "small(%2d):", i);
22638    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
22639      fprintf(out, " %p(%d)", &mem3.aPool[j],
22640              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
22641    }
22642    fprintf(out, "\n");
22643  }
22644  for(i=0; i<N_HASH; i++){
22645    if( mem3.aiHash[i]==0 ) continue;
22646    fprintf(out, "hash(%2d):", i);
22647    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
22648      fprintf(out, " %p(%d)", &mem3.aPool[j],
22649              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
22650    }
22651    fprintf(out, "\n");
22652  }
22653  fprintf(out, "master=%d\n", mem3.iMaster);
22654  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
22655  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
22656  sqlite3_mutex_leave(mem3.mutex);
22657  if( out==stdout ){
22658    fflush(stdout);
22659  }else{
22660    fclose(out);
22661  }
22662#else
22663  UNUSED_PARAMETER(zFilename);
22664#endif
22665}
22666
22667/*
22668** This routine is the only routine in this file with external
22669** linkage.
22670**
22671** Populate the low-level memory allocation function pointers in
22672** sqlite3GlobalConfig.m with pointers to the routines in this file. The
22673** arguments specify the block of memory to manage.
22674**
22675** This routine is only called by sqlite3_config(), and therefore
22676** is not required to be threadsafe (it is not).
22677*/
22678SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
22679  static const sqlite3_mem_methods mempoolMethods = {
22680     memsys3Malloc,
22681     memsys3Free,
22682     memsys3Realloc,
22683     memsys3Size,
22684     memsys3Roundup,
22685     memsys3Init,
22686     memsys3Shutdown,
22687     0
22688  };
22689  return &mempoolMethods;
22690}
22691
22692#endif /* SQLITE_ENABLE_MEMSYS3 */
22693
22694/************** End of mem3.c ************************************************/
22695/************** Begin file mem5.c ********************************************/
22696/*
22697** 2007 October 14
22698**
22699** The author disclaims copyright to this source code.  In place of
22700** a legal notice, here is a blessing:
22701**
22702**    May you do good and not evil.
22703**    May you find forgiveness for yourself and forgive others.
22704**    May you share freely, never taking more than you give.
22705**
22706*************************************************************************
22707** This file contains the C functions that implement a memory
22708** allocation subsystem for use by SQLite.
22709**
22710** This version of the memory allocation subsystem omits all
22711** use of malloc(). The application gives SQLite a block of memory
22712** before calling sqlite3_initialize() from which allocations
22713** are made and returned by the xMalloc() and xRealloc()
22714** implementations. Once sqlite3_initialize() has been called,
22715** the amount of memory available to SQLite is fixed and cannot
22716** be changed.
22717**
22718** This version of the memory allocation subsystem is included
22719** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
22720**
22721** This memory allocator uses the following algorithm:
22722**
22723**   1.  All memory allocation sizes are rounded up to a power of 2.
22724**
22725**   2.  If two adjacent free blocks are the halves of a larger block,
22726**       then the two blocks are coalesced into the single larger block.
22727**
22728**   3.  New memory is allocated from the first available free block.
22729**
22730** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
22731** Concerning Dynamic Storage Allocation". Journal of the Association for
22732** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
22733**
22734** Let n be the size of the largest allocation divided by the minimum
22735** allocation size (after rounding all sizes up to a power of 2.)  Let M
22736** be the maximum amount of memory ever outstanding at one time.  Let
22737** N be the total amount of memory available for allocation.  Robson
22738** proved that this memory allocator will never breakdown due to
22739** fragmentation as long as the following constraint holds:
22740**
22741**      N >=  M*(1 + log2(n)/2) - n + 1
22742**
22743** The sqlite3_status() logic tracks the maximum values of n and M so
22744** that an application can, at any time, verify this constraint.
22745*/
22746/* #include "sqliteInt.h" */
22747
22748/*
22749** This version of the memory allocator is used only when
22750** SQLITE_ENABLE_MEMSYS5 is defined.
22751*/
22752#ifdef SQLITE_ENABLE_MEMSYS5
22753
22754/*
22755** A minimum allocation is an instance of the following structure.
22756** Larger allocations are an array of these structures where the
22757** size of the array is a power of 2.
22758**
22759** The size of this object must be a power of two.  That fact is
22760** verified in memsys5Init().
22761*/
22762typedef struct Mem5Link Mem5Link;
22763struct Mem5Link {
22764  int next;       /* Index of next free chunk */
22765  int prev;       /* Index of previous free chunk */
22766};
22767
22768/*
22769** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
22770** mem5.szAtom is always at least 8 and 32-bit integers are used,
22771** it is not actually possible to reach this limit.
22772*/
22773#define LOGMAX 30
22774
22775/*
22776** Masks used for mem5.aCtrl[] elements.
22777*/
22778#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
22779#define CTRL_FREE     0x20    /* True if not checked out */
22780
22781/*
22782** All of the static variables used by this module are collected
22783** into a single structure named "mem5".  This is to keep the
22784** static variables organized and to reduce namespace pollution
22785** when this module is combined with other in the amalgamation.
22786*/
22787static SQLITE_WSD struct Mem5Global {
22788  /*
22789  ** Memory available for allocation
22790  */
22791  int szAtom;      /* Smallest possible allocation in bytes */
22792  int nBlock;      /* Number of szAtom sized blocks in zPool */
22793  u8 *zPool;       /* Memory available to be allocated */
22794
22795  /*
22796  ** Mutex to control access to the memory allocation subsystem.
22797  */
22798  sqlite3_mutex *mutex;
22799
22800#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22801  /*
22802  ** Performance statistics
22803  */
22804  u64 nAlloc;         /* Total number of calls to malloc */
22805  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
22806  u64 totalExcess;    /* Total internal fragmentation */
22807  u32 currentOut;     /* Current checkout, including internal fragmentation */
22808  u32 currentCount;   /* Current number of distinct checkouts */
22809  u32 maxOut;         /* Maximum instantaneous currentOut */
22810  u32 maxCount;       /* Maximum instantaneous currentCount */
22811  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
22812#endif
22813
22814  /*
22815  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
22816  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
22817  ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.
22818  */
22819  int aiFreelist[LOGMAX+1];
22820
22821  /*
22822  ** Space for tracking which blocks are checked out and the size
22823  ** of each block.  One byte per block.
22824  */
22825  u8 *aCtrl;
22826
22827} mem5;
22828
22829/*
22830** Access the static variable through a macro for SQLITE_OMIT_WSD.
22831*/
22832#define mem5 GLOBAL(struct Mem5Global, mem5)
22833
22834/*
22835** Assuming mem5.zPool is divided up into an array of Mem5Link
22836** structures, return a pointer to the idx-th such link.
22837*/
22838#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
22839
22840/*
22841** Unlink the chunk at mem5.aPool[i] from list it is currently
22842** on.  It should be found on mem5.aiFreelist[iLogsize].
22843*/
22844static void memsys5Unlink(int i, int iLogsize){
22845  int next, prev;
22846  assert( i>=0 && i<mem5.nBlock );
22847  assert( iLogsize>=0 && iLogsize<=LOGMAX );
22848  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22849
22850  next = MEM5LINK(i)->next;
22851  prev = MEM5LINK(i)->prev;
22852  if( prev<0 ){
22853    mem5.aiFreelist[iLogsize] = next;
22854  }else{
22855    MEM5LINK(prev)->next = next;
22856  }
22857  if( next>=0 ){
22858    MEM5LINK(next)->prev = prev;
22859  }
22860}
22861
22862/*
22863** Link the chunk at mem5.aPool[i] so that is on the iLogsize
22864** free list.
22865*/
22866static void memsys5Link(int i, int iLogsize){
22867  int x;
22868  assert( sqlite3_mutex_held(mem5.mutex) );
22869  assert( i>=0 && i<mem5.nBlock );
22870  assert( iLogsize>=0 && iLogsize<=LOGMAX );
22871  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22872
22873  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
22874  MEM5LINK(i)->prev = -1;
22875  if( x>=0 ){
22876    assert( x<mem5.nBlock );
22877    MEM5LINK(x)->prev = i;
22878  }
22879  mem5.aiFreelist[iLogsize] = i;
22880}
22881
22882/*
22883** Obtain or release the mutex needed to access global data structures.
22884*/
22885static void memsys5Enter(void){
22886  sqlite3_mutex_enter(mem5.mutex);
22887}
22888static void memsys5Leave(void){
22889  sqlite3_mutex_leave(mem5.mutex);
22890}
22891
22892/*
22893** Return the size of an outstanding allocation, in bytes.
22894** This only works for chunks that are currently checked out.
22895*/
22896static int memsys5Size(void *p){
22897  int iSize, i;
22898  assert( p!=0 );
22899  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
22900  assert( i>=0 && i<mem5.nBlock );
22901  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
22902  return iSize;
22903}
22904
22905/*
22906** Return a block of memory of at least nBytes in size.
22907** Return NULL if unable.  Return NULL if nBytes==0.
22908**
22909** The caller guarantees that nByte is positive.
22910**
22911** The caller has obtained a mutex prior to invoking this
22912** routine so there is never any chance that two or more
22913** threads can be in this routine at the same time.
22914*/
22915static void *memsys5MallocUnsafe(int nByte){
22916  int i;           /* Index of a mem5.aPool[] slot */
22917  int iBin;        /* Index into mem5.aiFreelist[] */
22918  int iFullSz;     /* Size of allocation rounded up to power of 2 */
22919  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
22920
22921  /* nByte must be a positive */
22922  assert( nByte>0 );
22923
22924  /* No more than 1GiB per allocation */
22925  if( nByte > 0x40000000 ) return 0;
22926
22927#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22928  /* Keep track of the maximum allocation request.  Even unfulfilled
22929  ** requests are counted */
22930  if( (u32)nByte>mem5.maxRequest ){
22931    mem5.maxRequest = nByte;
22932  }
22933#endif
22934
22935
22936  /* Round nByte up to the next valid power of two */
22937  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
22938
22939  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
22940  ** block.  If not, then split a block of the next larger power of
22941  ** two in order to create a new free block of size iLogsize.
22942  */
22943  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
22944  if( iBin>LOGMAX ){
22945    testcase( sqlite3GlobalConfig.xLog!=0 );
22946    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
22947    return 0;
22948  }
22949  i = mem5.aiFreelist[iBin];
22950  memsys5Unlink(i, iBin);
22951  while( iBin>iLogsize ){
22952    int newSize;
22953
22954    iBin--;
22955    newSize = 1 << iBin;
22956    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
22957    memsys5Link(i+newSize, iBin);
22958  }
22959  mem5.aCtrl[i] = iLogsize;
22960
22961#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22962  /* Update allocator performance statistics. */
22963  mem5.nAlloc++;
22964  mem5.totalAlloc += iFullSz;
22965  mem5.totalExcess += iFullSz - nByte;
22966  mem5.currentCount++;
22967  mem5.currentOut += iFullSz;
22968  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
22969  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
22970#endif
22971
22972#ifdef SQLITE_DEBUG
22973  /* Make sure the allocated memory does not assume that it is set to zero
22974  ** or retains a value from a previous allocation */
22975  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
22976#endif
22977
22978  /* Return a pointer to the allocated memory. */
22979  return (void*)&mem5.zPool[i*mem5.szAtom];
22980}
22981
22982/*
22983** Free an outstanding memory allocation.
22984*/
22985static void memsys5FreeUnsafe(void *pOld){
22986  u32 size, iLogsize;
22987  int iBlock;
22988
22989  /* Set iBlock to the index of the block pointed to by pOld in
22990  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
22991  */
22992  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
22993
22994  /* Check that the pointer pOld points to a valid, non-free block. */
22995  assert( iBlock>=0 && iBlock<mem5.nBlock );
22996  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
22997  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
22998
22999  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
23000  size = 1<<iLogsize;
23001  assert( iBlock+size-1<(u32)mem5.nBlock );
23002
23003  mem5.aCtrl[iBlock] |= CTRL_FREE;
23004  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
23005
23006#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23007  assert( mem5.currentCount>0 );
23008  assert( mem5.currentOut>=(size*mem5.szAtom) );
23009  mem5.currentCount--;
23010  mem5.currentOut -= size*mem5.szAtom;
23011  assert( mem5.currentOut>0 || mem5.currentCount==0 );
23012  assert( mem5.currentCount>0 || mem5.currentOut==0 );
23013#endif
23014
23015  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
23016  while( ALWAYS(iLogsize<LOGMAX) ){
23017    int iBuddy;
23018    if( (iBlock>>iLogsize) & 1 ){
23019      iBuddy = iBlock - size;
23020      assert( iBuddy>=0 );
23021    }else{
23022      iBuddy = iBlock + size;
23023      if( iBuddy>=mem5.nBlock ) break;
23024    }
23025    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
23026    memsys5Unlink(iBuddy, iLogsize);
23027    iLogsize++;
23028    if( iBuddy<iBlock ){
23029      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
23030      mem5.aCtrl[iBlock] = 0;
23031      iBlock = iBuddy;
23032    }else{
23033      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
23034      mem5.aCtrl[iBuddy] = 0;
23035    }
23036    size *= 2;
23037  }
23038
23039#ifdef SQLITE_DEBUG
23040  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
23041  ** not used after being freed */
23042  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
23043#endif
23044
23045  memsys5Link(iBlock, iLogsize);
23046}
23047
23048/*
23049** Allocate nBytes of memory.
23050*/
23051static void *memsys5Malloc(int nBytes){
23052  sqlite3_int64 *p = 0;
23053  if( nBytes>0 ){
23054    memsys5Enter();
23055    p = memsys5MallocUnsafe(nBytes);
23056    memsys5Leave();
23057  }
23058  return (void*)p;
23059}
23060
23061/*
23062** Free memory.
23063**
23064** The outer layer memory allocator prevents this routine from
23065** being called with pPrior==0.
23066*/
23067static void memsys5Free(void *pPrior){
23068  assert( pPrior!=0 );
23069  memsys5Enter();
23070  memsys5FreeUnsafe(pPrior);
23071  memsys5Leave();
23072}
23073
23074/*
23075** Change the size of an existing memory allocation.
23076**
23077** The outer layer memory allocator prevents this routine from
23078** being called with pPrior==0.
23079**
23080** nBytes is always a value obtained from a prior call to
23081** memsys5Round().  Hence nBytes is always a non-negative power
23082** of two.  If nBytes==0 that means that an oversize allocation
23083** (an allocation larger than 0x40000000) was requested and this
23084** routine should return 0 without freeing pPrior.
23085*/
23086static void *memsys5Realloc(void *pPrior, int nBytes){
23087  int nOld;
23088  void *p;
23089  assert( pPrior!=0 );
23090  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
23091  assert( nBytes>=0 );
23092  if( nBytes==0 ){
23093    return 0;
23094  }
23095  nOld = memsys5Size(pPrior);
23096  if( nBytes<=nOld ){
23097    return pPrior;
23098  }
23099  p = memsys5Malloc(nBytes);
23100  if( p ){
23101    memcpy(p, pPrior, nOld);
23102    memsys5Free(pPrior);
23103  }
23104  return p;
23105}
23106
23107/*
23108** Round up a request size to the next valid allocation size.  If
23109** the allocation is too large to be handled by this allocation system,
23110** return 0.
23111**
23112** All allocations must be a power of two and must be expressed by a
23113** 32-bit signed integer.  Hence the largest allocation is 0x40000000
23114** or 1073741824 bytes.
23115*/
23116static int memsys5Roundup(int n){
23117  int iFullSz;
23118  if( n > 0x40000000 ) return 0;
23119  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
23120  return iFullSz;
23121}
23122
23123/*
23124** Return the ceiling of the logarithm base 2 of iValue.
23125**
23126** Examples:   memsys5Log(1) -> 0
23127**             memsys5Log(2) -> 1
23128**             memsys5Log(4) -> 2
23129**             memsys5Log(5) -> 3
23130**             memsys5Log(8) -> 3
23131**             memsys5Log(9) -> 4
23132*/
23133static int memsys5Log(int iValue){
23134  int iLog;
23135  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
23136  return iLog;
23137}
23138
23139/*
23140** Initialize the memory allocator.
23141**
23142** This routine is not threadsafe.  The caller must be holding a mutex
23143** to prevent multiple threads from entering at the same time.
23144*/
23145static int memsys5Init(void *NotUsed){
23146  int ii;            /* Loop counter */
23147  int nByte;         /* Number of bytes of memory available to this allocator */
23148  u8 *zByte;         /* Memory usable by this allocator */
23149  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
23150  int iOffset;       /* An offset into mem5.aCtrl[] */
23151
23152  UNUSED_PARAMETER(NotUsed);
23153
23154  /* For the purposes of this routine, disable the mutex */
23155  mem5.mutex = 0;
23156
23157  /* The size of a Mem5Link object must be a power of two.  Verify that
23158  ** this is case.
23159  */
23160  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
23161
23162  nByte = sqlite3GlobalConfig.nHeap;
23163  zByte = (u8*)sqlite3GlobalConfig.pHeap;
23164  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
23165
23166  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
23167  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
23168  mem5.szAtom = (1<<nMinLog);
23169  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
23170    mem5.szAtom = mem5.szAtom << 1;
23171  }
23172
23173  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
23174  mem5.zPool = zByte;
23175  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
23176
23177  for(ii=0; ii<=LOGMAX; ii++){
23178    mem5.aiFreelist[ii] = -1;
23179  }
23180
23181  iOffset = 0;
23182  for(ii=LOGMAX; ii>=0; ii--){
23183    int nAlloc = (1<<ii);
23184    if( (iOffset+nAlloc)<=mem5.nBlock ){
23185      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
23186      memsys5Link(iOffset, ii);
23187      iOffset += nAlloc;
23188    }
23189    assert((iOffset+nAlloc)>mem5.nBlock);
23190  }
23191
23192  /* If a mutex is required for normal operation, allocate one */
23193  if( sqlite3GlobalConfig.bMemstat==0 ){
23194    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
23195  }
23196
23197  return SQLITE_OK;
23198}
23199
23200/*
23201** Deinitialize this module.
23202*/
23203static void memsys5Shutdown(void *NotUsed){
23204  UNUSED_PARAMETER(NotUsed);
23205  mem5.mutex = 0;
23206  return;
23207}
23208
23209#ifdef SQLITE_TEST
23210/*
23211** Open the file indicated and write a log of all unfreed memory
23212** allocations into that log.
23213*/
23214SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
23215  FILE *out;
23216  int i, j, n;
23217  int nMinLog;
23218
23219  if( zFilename==0 || zFilename[0]==0 ){
23220    out = stdout;
23221  }else{
23222    out = fopen(zFilename, "w");
23223    if( out==0 ){
23224      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
23225                      zFilename);
23226      return;
23227    }
23228  }
23229  memsys5Enter();
23230  nMinLog = memsys5Log(mem5.szAtom);
23231  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
23232    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
23233    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
23234  }
23235  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
23236  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
23237  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
23238  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
23239  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
23240  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
23241  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
23242  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
23243  memsys5Leave();
23244  if( out==stdout ){
23245    fflush(stdout);
23246  }else{
23247    fclose(out);
23248  }
23249}
23250#endif
23251
23252/*
23253** This routine is the only routine in this file with external
23254** linkage. It returns a pointer to a static sqlite3_mem_methods
23255** struct populated with the memsys5 methods.
23256*/
23257SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
23258  static const sqlite3_mem_methods memsys5Methods = {
23259     memsys5Malloc,
23260     memsys5Free,
23261     memsys5Realloc,
23262     memsys5Size,
23263     memsys5Roundup,
23264     memsys5Init,
23265     memsys5Shutdown,
23266     0
23267  };
23268  return &memsys5Methods;
23269}
23270
23271#endif /* SQLITE_ENABLE_MEMSYS5 */
23272
23273/************** End of mem5.c ************************************************/
23274/************** Begin file mutex.c *******************************************/
23275/*
23276** 2007 August 14
23277**
23278** The author disclaims copyright to this source code.  In place of
23279** a legal notice, here is a blessing:
23280**
23281**    May you do good and not evil.
23282**    May you find forgiveness for yourself and forgive others.
23283**    May you share freely, never taking more than you give.
23284**
23285*************************************************************************
23286** This file contains the C functions that implement mutexes.
23287**
23288** This file contains code that is common across all mutex implementations.
23289*/
23290/* #include "sqliteInt.h" */
23291
23292#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
23293/*
23294** For debugging purposes, record when the mutex subsystem is initialized
23295** and uninitialized so that we can assert() if there is an attempt to
23296** allocate a mutex while the system is uninitialized.
23297*/
23298static SQLITE_WSD int mutexIsInit = 0;
23299#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
23300
23301
23302#ifndef SQLITE_MUTEX_OMIT
23303/*
23304** Initialize the mutex system.
23305*/
23306SQLITE_PRIVATE int sqlite3MutexInit(void){
23307  int rc = SQLITE_OK;
23308  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
23309    /* If the xMutexAlloc method has not been set, then the user did not
23310    ** install a mutex implementation via sqlite3_config() prior to
23311    ** sqlite3_initialize() being called. This block copies pointers to
23312    ** the default implementation into the sqlite3GlobalConfig structure.
23313    */
23314    sqlite3_mutex_methods const *pFrom;
23315    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
23316
23317    if( sqlite3GlobalConfig.bCoreMutex ){
23318      pFrom = sqlite3DefaultMutex();
23319    }else{
23320      pFrom = sqlite3NoopMutex();
23321    }
23322    pTo->xMutexInit = pFrom->xMutexInit;
23323    pTo->xMutexEnd = pFrom->xMutexEnd;
23324    pTo->xMutexFree = pFrom->xMutexFree;
23325    pTo->xMutexEnter = pFrom->xMutexEnter;
23326    pTo->xMutexTry = pFrom->xMutexTry;
23327    pTo->xMutexLeave = pFrom->xMutexLeave;
23328    pTo->xMutexHeld = pFrom->xMutexHeld;
23329    pTo->xMutexNotheld = pFrom->xMutexNotheld;
23330    sqlite3MemoryBarrier();
23331    pTo->xMutexAlloc = pFrom->xMutexAlloc;
23332  }
23333  assert( sqlite3GlobalConfig.mutex.xMutexInit );
23334  rc = sqlite3GlobalConfig.mutex.xMutexInit();
23335
23336#ifdef SQLITE_DEBUG
23337  GLOBAL(int, mutexIsInit) = 1;
23338#endif
23339
23340  return rc;
23341}
23342
23343/*
23344** Shutdown the mutex system. This call frees resources allocated by
23345** sqlite3MutexInit().
23346*/
23347SQLITE_PRIVATE int sqlite3MutexEnd(void){
23348  int rc = SQLITE_OK;
23349  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
23350    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
23351  }
23352
23353#ifdef SQLITE_DEBUG
23354  GLOBAL(int, mutexIsInit) = 0;
23355#endif
23356
23357  return rc;
23358}
23359
23360/*
23361** Retrieve a pointer to a static mutex or allocate a new dynamic one.
23362*/
23363SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
23364#ifndef SQLITE_OMIT_AUTOINIT
23365  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
23366  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
23367#endif
23368  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
23369  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
23370}
23371
23372SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
23373  if( !sqlite3GlobalConfig.bCoreMutex ){
23374    return 0;
23375  }
23376  assert( GLOBAL(int, mutexIsInit) );
23377  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
23378  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
23379}
23380
23381/*
23382** Free a dynamic mutex.
23383*/
23384SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
23385  if( p ){
23386    assert( sqlite3GlobalConfig.mutex.xMutexFree );
23387    sqlite3GlobalConfig.mutex.xMutexFree(p);
23388  }
23389}
23390
23391/*
23392** Obtain the mutex p. If some other thread already has the mutex, block
23393** until it can be obtained.
23394*/
23395SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
23396  if( p ){
23397    assert( sqlite3GlobalConfig.mutex.xMutexEnter );
23398    sqlite3GlobalConfig.mutex.xMutexEnter(p);
23399  }
23400}
23401
23402/*
23403** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
23404** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
23405*/
23406SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
23407  int rc = SQLITE_OK;
23408  if( p ){
23409    assert( sqlite3GlobalConfig.mutex.xMutexTry );
23410    return sqlite3GlobalConfig.mutex.xMutexTry(p);
23411  }
23412  return rc;
23413}
23414
23415/*
23416** The sqlite3_mutex_leave() routine exits a mutex that was previously
23417** entered by the same thread.  The behavior is undefined if the mutex
23418** is not currently entered. If a NULL pointer is passed as an argument
23419** this function is a no-op.
23420*/
23421SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
23422  if( p ){
23423    assert( sqlite3GlobalConfig.mutex.xMutexLeave );
23424    sqlite3GlobalConfig.mutex.xMutexLeave(p);
23425  }
23426}
23427
23428#ifndef NDEBUG
23429/*
23430** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23431** intended for use inside assert() statements.
23432*/
23433SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
23434  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
23435  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
23436}
23437SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
23438  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
23439  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
23440}
23441#endif
23442
23443#endif /* !defined(SQLITE_MUTEX_OMIT) */
23444
23445/************** End of mutex.c ***********************************************/
23446/************** Begin file mutex_noop.c **************************************/
23447/*
23448** 2008 October 07
23449**
23450** The author disclaims copyright to this source code.  In place of
23451** a legal notice, here is a blessing:
23452**
23453**    May you do good and not evil.
23454**    May you find forgiveness for yourself and forgive others.
23455**    May you share freely, never taking more than you give.
23456**
23457*************************************************************************
23458** This file contains the C functions that implement mutexes.
23459**
23460** This implementation in this file does not provide any mutual
23461** exclusion and is thus suitable for use only in applications
23462** that use SQLite in a single thread.  The routines defined
23463** here are place-holders.  Applications can substitute working
23464** mutex routines at start-time using the
23465**
23466**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
23467**
23468** interface.
23469**
23470** If compiled with SQLITE_DEBUG, then additional logic is inserted
23471** that does error checking on mutexes to make sure they are being
23472** called correctly.
23473*/
23474/* #include "sqliteInt.h" */
23475
23476#ifndef SQLITE_MUTEX_OMIT
23477
23478#ifndef SQLITE_DEBUG
23479/*
23480** Stub routines for all mutex methods.
23481**
23482** This routines provide no mutual exclusion or error checking.
23483*/
23484static int noopMutexInit(void){ return SQLITE_OK; }
23485static int noopMutexEnd(void){ return SQLITE_OK; }
23486static sqlite3_mutex *noopMutexAlloc(int id){
23487  UNUSED_PARAMETER(id);
23488  return (sqlite3_mutex*)8;
23489}
23490static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
23491static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
23492static int noopMutexTry(sqlite3_mutex *p){
23493  UNUSED_PARAMETER(p);
23494  return SQLITE_OK;
23495}
23496static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
23497
23498SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
23499  static const sqlite3_mutex_methods sMutex = {
23500    noopMutexInit,
23501    noopMutexEnd,
23502    noopMutexAlloc,
23503    noopMutexFree,
23504    noopMutexEnter,
23505    noopMutexTry,
23506    noopMutexLeave,
23507
23508    0,
23509    0,
23510  };
23511
23512  return &sMutex;
23513}
23514#endif /* !SQLITE_DEBUG */
23515
23516#ifdef SQLITE_DEBUG
23517/*
23518** In this implementation, error checking is provided for testing
23519** and debugging purposes.  The mutexes still do not provide any
23520** mutual exclusion.
23521*/
23522
23523/*
23524** The mutex object
23525*/
23526typedef struct sqlite3_debug_mutex {
23527  int id;     /* The mutex type */
23528  int cnt;    /* Number of entries without a matching leave */
23529} sqlite3_debug_mutex;
23530
23531/*
23532** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23533** intended for use inside assert() statements.
23534*/
23535static int debugMutexHeld(sqlite3_mutex *pX){
23536  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23537  return p==0 || p->cnt>0;
23538}
23539static int debugMutexNotheld(sqlite3_mutex *pX){
23540  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23541  return p==0 || p->cnt==0;
23542}
23543
23544/*
23545** Initialize and deinitialize the mutex subsystem.
23546*/
23547static int debugMutexInit(void){ return SQLITE_OK; }
23548static int debugMutexEnd(void){ return SQLITE_OK; }
23549
23550/*
23551** The sqlite3_mutex_alloc() routine allocates a new
23552** mutex and returns a pointer to it.  If it returns NULL
23553** that means that a mutex could not be allocated.
23554*/
23555static sqlite3_mutex *debugMutexAlloc(int id){
23556  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
23557  sqlite3_debug_mutex *pNew = 0;
23558  switch( id ){
23559    case SQLITE_MUTEX_FAST:
23560    case SQLITE_MUTEX_RECURSIVE: {
23561      pNew = sqlite3Malloc(sizeof(*pNew));
23562      if( pNew ){
23563        pNew->id = id;
23564        pNew->cnt = 0;
23565      }
23566      break;
23567    }
23568    default: {
23569#ifdef SQLITE_ENABLE_API_ARMOR
23570      if( id-2<0 || id-2>=ArraySize(aStatic) ){
23571        (void)SQLITE_MISUSE_BKPT;
23572        return 0;
23573      }
23574#endif
23575      pNew = &aStatic[id-2];
23576      pNew->id = id;
23577      break;
23578    }
23579  }
23580  return (sqlite3_mutex*)pNew;
23581}
23582
23583/*
23584** This routine deallocates a previously allocated mutex.
23585*/
23586static void debugMutexFree(sqlite3_mutex *pX){
23587  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23588  assert( p->cnt==0 );
23589  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
23590    sqlite3_free(p);
23591  }else{
23592#ifdef SQLITE_ENABLE_API_ARMOR
23593    (void)SQLITE_MISUSE_BKPT;
23594#endif
23595  }
23596}
23597
23598/*
23599** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23600** to enter a mutex.  If another thread is already within the mutex,
23601** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23602** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
23603** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
23604** be entered multiple times by the same thread.  In such cases the,
23605** mutex must be exited an equal number of times before another thread
23606** can enter.  If the same thread tries to enter any other kind of mutex
23607** more than once, the behavior is undefined.
23608*/
23609static void debugMutexEnter(sqlite3_mutex *pX){
23610  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23611  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23612  p->cnt++;
23613}
23614static int debugMutexTry(sqlite3_mutex *pX){
23615  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23616  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23617  p->cnt++;
23618  return SQLITE_OK;
23619}
23620
23621/*
23622** The sqlite3_mutex_leave() routine exits a mutex that was
23623** previously entered by the same thread.  The behavior
23624** is undefined if the mutex is not currently entered or
23625** is not currently allocated.  SQLite will never do either.
23626*/
23627static void debugMutexLeave(sqlite3_mutex *pX){
23628  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
23629  assert( debugMutexHeld(pX) );
23630  p->cnt--;
23631  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
23632}
23633
23634SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
23635  static const sqlite3_mutex_methods sMutex = {
23636    debugMutexInit,
23637    debugMutexEnd,
23638    debugMutexAlloc,
23639    debugMutexFree,
23640    debugMutexEnter,
23641    debugMutexTry,
23642    debugMutexLeave,
23643
23644    debugMutexHeld,
23645    debugMutexNotheld
23646  };
23647
23648  return &sMutex;
23649}
23650#endif /* SQLITE_DEBUG */
23651
23652/*
23653** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
23654** is used regardless of the run-time threadsafety setting.
23655*/
23656#ifdef SQLITE_MUTEX_NOOP
23657SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23658  return sqlite3NoopMutex();
23659}
23660#endif /* defined(SQLITE_MUTEX_NOOP) */
23661#endif /* !defined(SQLITE_MUTEX_OMIT) */
23662
23663/************** End of mutex_noop.c ******************************************/
23664/************** Begin file mutex_unix.c **************************************/
23665/*
23666** 2007 August 28
23667**
23668** The author disclaims copyright to this source code.  In place of
23669** a legal notice, here is a blessing:
23670**
23671**    May you do good and not evil.
23672**    May you find forgiveness for yourself and forgive others.
23673**    May you share freely, never taking more than you give.
23674**
23675*************************************************************************
23676** This file contains the C functions that implement mutexes for pthreads
23677*/
23678/* #include "sqliteInt.h" */
23679
23680/*
23681** The code in this file is only used if we are compiling threadsafe
23682** under unix with pthreads.
23683**
23684** Note that this implementation requires a version of pthreads that
23685** supports recursive mutexes.
23686*/
23687#ifdef SQLITE_MUTEX_PTHREADS
23688
23689#include <pthread.h>
23690
23691/*
23692** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
23693** are necessary under two condidtions:  (1) Debug builds and (2) using
23694** home-grown mutexes.  Encapsulate these conditions into a single #define.
23695*/
23696#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
23697# define SQLITE_MUTEX_NREF 1
23698#else
23699# define SQLITE_MUTEX_NREF 0
23700#endif
23701
23702/*
23703** Each recursive mutex is an instance of the following structure.
23704*/
23705struct sqlite3_mutex {
23706  pthread_mutex_t mutex;     /* Mutex controlling the lock */
23707#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
23708  int id;                    /* Mutex type */
23709#endif
23710#if SQLITE_MUTEX_NREF
23711  volatile int nRef;         /* Number of entrances */
23712  volatile pthread_t owner;  /* Thread that is within this mutex */
23713  int trace;                 /* True to trace changes */
23714#endif
23715};
23716#if SQLITE_MUTEX_NREF
23717#define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
23718#elif defined(SQLITE_ENABLE_API_ARMOR)
23719#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
23720#else
23721#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
23722#endif
23723
23724/*
23725** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23726** intended for use only inside assert() statements.  On some platforms,
23727** there might be race conditions that can cause these routines to
23728** deliver incorrect results.  In particular, if pthread_equal() is
23729** not an atomic operation, then these routines might delivery
23730** incorrect results.  On most platforms, pthread_equal() is a
23731** comparison of two integers and is therefore atomic.  But we are
23732** told that HPUX is not such a platform.  If so, then these routines
23733** will not always work correctly on HPUX.
23734**
23735** On those platforms where pthread_equal() is not atomic, SQLite
23736** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
23737** make sure no assert() statements are evaluated and hence these
23738** routines are never called.
23739*/
23740#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
23741static int pthreadMutexHeld(sqlite3_mutex *p){
23742  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
23743}
23744static int pthreadMutexNotheld(sqlite3_mutex *p){
23745  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
23746}
23747#endif
23748
23749/*
23750** Try to provide a memory barrier operation, needed for initialization
23751** and also for the implementation of xShmBarrier in the VFS in cases
23752** where SQLite is compiled without mutexes.
23753*/
23754SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
23755#if defined(SQLITE_MEMORY_BARRIER)
23756  SQLITE_MEMORY_BARRIER;
23757#elif defined(__GNUC__) && GCC_VERSION>=4001000
23758  __sync_synchronize();
23759#endif
23760}
23761
23762/*
23763** Initialize and deinitialize the mutex subsystem.
23764*/
23765static int pthreadMutexInit(void){ return SQLITE_OK; }
23766static int pthreadMutexEnd(void){ return SQLITE_OK; }
23767
23768/*
23769** The sqlite3_mutex_alloc() routine allocates a new
23770** mutex and returns a pointer to it.  If it returns NULL
23771** that means that a mutex could not be allocated.  SQLite
23772** will unwind its stack and return an error.  The argument
23773** to sqlite3_mutex_alloc() is one of these integer constants:
23774**
23775** <ul>
23776** <li>  SQLITE_MUTEX_FAST
23777** <li>  SQLITE_MUTEX_RECURSIVE
23778** <li>  SQLITE_MUTEX_STATIC_MASTER
23779** <li>  SQLITE_MUTEX_STATIC_MEM
23780** <li>  SQLITE_MUTEX_STATIC_OPEN
23781** <li>  SQLITE_MUTEX_STATIC_PRNG
23782** <li>  SQLITE_MUTEX_STATIC_LRU
23783** <li>  SQLITE_MUTEX_STATIC_PMEM
23784** <li>  SQLITE_MUTEX_STATIC_APP1
23785** <li>  SQLITE_MUTEX_STATIC_APP2
23786** <li>  SQLITE_MUTEX_STATIC_APP3
23787** <li>  SQLITE_MUTEX_STATIC_VFS1
23788** <li>  SQLITE_MUTEX_STATIC_VFS2
23789** <li>  SQLITE_MUTEX_STATIC_VFS3
23790** </ul>
23791**
23792** The first two constants cause sqlite3_mutex_alloc() to create
23793** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23794** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23795** The mutex implementation does not need to make a distinction
23796** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23797** not want to.  But SQLite will only request a recursive mutex in
23798** cases where it really needs one.  If a faster non-recursive mutex
23799** implementation is available on the host platform, the mutex subsystem
23800** might return such a mutex in response to SQLITE_MUTEX_FAST.
23801**
23802** The other allowed parameters to sqlite3_mutex_alloc() each return
23803** a pointer to a static preexisting mutex.  Six static mutexes are
23804** used by the current version of SQLite.  Future versions of SQLite
23805** may add additional static mutexes.  Static mutexes are for internal
23806** use by SQLite only.  Applications that use SQLite mutexes should
23807** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23808** SQLITE_MUTEX_RECURSIVE.
23809**
23810** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23811** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23812** returns a different mutex on every call.  But for the static
23813** mutex types, the same mutex is returned on every call that has
23814** the same type number.
23815*/
23816static sqlite3_mutex *pthreadMutexAlloc(int iType){
23817  static sqlite3_mutex staticMutexes[] = {
23818    SQLITE3_MUTEX_INITIALIZER,
23819    SQLITE3_MUTEX_INITIALIZER,
23820    SQLITE3_MUTEX_INITIALIZER,
23821    SQLITE3_MUTEX_INITIALIZER,
23822    SQLITE3_MUTEX_INITIALIZER,
23823    SQLITE3_MUTEX_INITIALIZER,
23824    SQLITE3_MUTEX_INITIALIZER,
23825    SQLITE3_MUTEX_INITIALIZER,
23826    SQLITE3_MUTEX_INITIALIZER,
23827    SQLITE3_MUTEX_INITIALIZER,
23828    SQLITE3_MUTEX_INITIALIZER,
23829    SQLITE3_MUTEX_INITIALIZER
23830  };
23831  sqlite3_mutex *p;
23832  switch( iType ){
23833    case SQLITE_MUTEX_RECURSIVE: {
23834      p = sqlite3MallocZero( sizeof(*p) );
23835      if( p ){
23836#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23837        /* If recursive mutexes are not available, we will have to
23838        ** build our own.  See below. */
23839        pthread_mutex_init(&p->mutex, 0);
23840#else
23841        /* Use a recursive mutex if it is available */
23842        pthread_mutexattr_t recursiveAttr;
23843        pthread_mutexattr_init(&recursiveAttr);
23844        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
23845        pthread_mutex_init(&p->mutex, &recursiveAttr);
23846        pthread_mutexattr_destroy(&recursiveAttr);
23847#endif
23848      }
23849      break;
23850    }
23851    case SQLITE_MUTEX_FAST: {
23852      p = sqlite3MallocZero( sizeof(*p) );
23853      if( p ){
23854        pthread_mutex_init(&p->mutex, 0);
23855      }
23856      break;
23857    }
23858    default: {
23859#ifdef SQLITE_ENABLE_API_ARMOR
23860      if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
23861        (void)SQLITE_MISUSE_BKPT;
23862        return 0;
23863      }
23864#endif
23865      p = &staticMutexes[iType-2];
23866      break;
23867    }
23868  }
23869#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
23870  if( p ) p->id = iType;
23871#endif
23872  return p;
23873}
23874
23875
23876/*
23877** This routine deallocates a previously
23878** allocated mutex.  SQLite is careful to deallocate every
23879** mutex that it allocates.
23880*/
23881static void pthreadMutexFree(sqlite3_mutex *p){
23882  assert( p->nRef==0 );
23883#if SQLITE_ENABLE_API_ARMOR
23884  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
23885#endif
23886  {
23887    pthread_mutex_destroy(&p->mutex);
23888    sqlite3_free(p);
23889  }
23890#ifdef SQLITE_ENABLE_API_ARMOR
23891  else{
23892    (void)SQLITE_MISUSE_BKPT;
23893  }
23894#endif
23895}
23896
23897/*
23898** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23899** to enter a mutex.  If another thread is already within the mutex,
23900** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23901** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
23902** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
23903** be entered multiple times by the same thread.  In such cases the,
23904** mutex must be exited an equal number of times before another thread
23905** can enter.  If the same thread tries to enter any other kind of mutex
23906** more than once, the behavior is undefined.
23907*/
23908static void pthreadMutexEnter(sqlite3_mutex *p){
23909  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23910
23911#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23912  /* If recursive mutexes are not available, then we have to grow
23913  ** our own.  This implementation assumes that pthread_equal()
23914  ** is atomic - that it cannot be deceived into thinking self
23915  ** and p->owner are equal if p->owner changes between two values
23916  ** that are not equal to self while the comparison is taking place.
23917  ** This implementation also assumes a coherent cache - that
23918  ** separate processes cannot read different values from the same
23919  ** address at the same time.  If either of these two conditions
23920  ** are not met, then the mutexes will fail and problems will result.
23921  */
23922  {
23923    pthread_t self = pthread_self();
23924    if( p->nRef>0 && pthread_equal(p->owner, self) ){
23925      p->nRef++;
23926    }else{
23927      pthread_mutex_lock(&p->mutex);
23928      assert( p->nRef==0 );
23929      p->owner = self;
23930      p->nRef = 1;
23931    }
23932  }
23933#else
23934  /* Use the built-in recursive mutexes if they are available.
23935  */
23936  pthread_mutex_lock(&p->mutex);
23937#if SQLITE_MUTEX_NREF
23938  assert( p->nRef>0 || p->owner==0 );
23939  p->owner = pthread_self();
23940  p->nRef++;
23941#endif
23942#endif
23943
23944#ifdef SQLITE_DEBUG
23945  if( p->trace ){
23946    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23947  }
23948#endif
23949}
23950static int pthreadMutexTry(sqlite3_mutex *p){
23951  int rc;
23952  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23953
23954#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23955  /* If recursive mutexes are not available, then we have to grow
23956  ** our own.  This implementation assumes that pthread_equal()
23957  ** is atomic - that it cannot be deceived into thinking self
23958  ** and p->owner are equal if p->owner changes between two values
23959  ** that are not equal to self while the comparison is taking place.
23960  ** This implementation also assumes a coherent cache - that
23961  ** separate processes cannot read different values from the same
23962  ** address at the same time.  If either of these two conditions
23963  ** are not met, then the mutexes will fail and problems will result.
23964  */
23965  {
23966    pthread_t self = pthread_self();
23967    if( p->nRef>0 && pthread_equal(p->owner, self) ){
23968      p->nRef++;
23969      rc = SQLITE_OK;
23970    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
23971      assert( p->nRef==0 );
23972      p->owner = self;
23973      p->nRef = 1;
23974      rc = SQLITE_OK;
23975    }else{
23976      rc = SQLITE_BUSY;
23977    }
23978  }
23979#else
23980  /* Use the built-in recursive mutexes if they are available.
23981  */
23982  if( pthread_mutex_trylock(&p->mutex)==0 ){
23983#if SQLITE_MUTEX_NREF
23984    p->owner = pthread_self();
23985    p->nRef++;
23986#endif
23987    rc = SQLITE_OK;
23988  }else{
23989    rc = SQLITE_BUSY;
23990  }
23991#endif
23992
23993#ifdef SQLITE_DEBUG
23994  if( rc==SQLITE_OK && p->trace ){
23995    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23996  }
23997#endif
23998  return rc;
23999}
24000
24001/*
24002** The sqlite3_mutex_leave() routine exits a mutex that was
24003** previously entered by the same thread.  The behavior
24004** is undefined if the mutex is not currently entered or
24005** is not currently allocated.  SQLite will never do either.
24006*/
24007static void pthreadMutexLeave(sqlite3_mutex *p){
24008  assert( pthreadMutexHeld(p) );
24009#if SQLITE_MUTEX_NREF
24010  p->nRef--;
24011  if( p->nRef==0 ) p->owner = 0;
24012#endif
24013  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
24014
24015#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
24016  if( p->nRef==0 ){
24017    pthread_mutex_unlock(&p->mutex);
24018  }
24019#else
24020  pthread_mutex_unlock(&p->mutex);
24021#endif
24022
24023#ifdef SQLITE_DEBUG
24024  if( p->trace ){
24025    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
24026  }
24027#endif
24028}
24029
24030SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
24031  static const sqlite3_mutex_methods sMutex = {
24032    pthreadMutexInit,
24033    pthreadMutexEnd,
24034    pthreadMutexAlloc,
24035    pthreadMutexFree,
24036    pthreadMutexEnter,
24037    pthreadMutexTry,
24038    pthreadMutexLeave,
24039#ifdef SQLITE_DEBUG
24040    pthreadMutexHeld,
24041    pthreadMutexNotheld
24042#else
24043    0,
24044    0
24045#endif
24046  };
24047
24048  return &sMutex;
24049}
24050
24051#endif /* SQLITE_MUTEX_PTHREADS */
24052
24053/************** End of mutex_unix.c ******************************************/
24054/************** Begin file mutex_w32.c ***************************************/
24055/*
24056** 2007 August 14
24057**
24058** The author disclaims copyright to this source code.  In place of
24059** a legal notice, here is a blessing:
24060**
24061**    May you do good and not evil.
24062**    May you find forgiveness for yourself and forgive others.
24063**    May you share freely, never taking more than you give.
24064**
24065*************************************************************************
24066** This file contains the C functions that implement mutexes for Win32.
24067*/
24068/* #include "sqliteInt.h" */
24069
24070#if SQLITE_OS_WIN
24071/*
24072** Include code that is common to all os_*.c files
24073*/
24074/************** Include os_common.h in the middle of mutex_w32.c *************/
24075/************** Begin file os_common.h ***************************************/
24076/*
24077** 2004 May 22
24078**
24079** The author disclaims copyright to this source code.  In place of
24080** a legal notice, here is a blessing:
24081**
24082**    May you do good and not evil.
24083**    May you find forgiveness for yourself and forgive others.
24084**    May you share freely, never taking more than you give.
24085**
24086******************************************************************************
24087**
24088** This file contains macros and a little bit of code that is common to
24089** all of the platform-specific files (os_*.c) and is #included into those
24090** files.
24091**
24092** This file should be #included by the os_*.c files only.  It is not a
24093** general purpose header file.
24094*/
24095#ifndef _OS_COMMON_H_
24096#define _OS_COMMON_H_
24097
24098/*
24099** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24100** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24101** switch.  The following code should catch this problem at compile-time.
24102*/
24103#ifdef MEMORY_DEBUG
24104# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24105#endif
24106
24107/*
24108** Macros for performance tracing.  Normally turned off.  Only works
24109** on i486 hardware.
24110*/
24111#ifdef SQLITE_PERFORMANCE_TRACE
24112
24113/*
24114** hwtime.h contains inline assembler code for implementing
24115** high-performance timing routines.
24116*/
24117/************** Include hwtime.h in the middle of os_common.h ****************/
24118/************** Begin file hwtime.h ******************************************/
24119/*
24120** 2008 May 27
24121**
24122** The author disclaims copyright to this source code.  In place of
24123** a legal notice, here is a blessing:
24124**
24125**    May you do good and not evil.
24126**    May you find forgiveness for yourself and forgive others.
24127**    May you share freely, never taking more than you give.
24128**
24129******************************************************************************
24130**
24131** This file contains inline asm code for retrieving "high-performance"
24132** counters for x86 class CPUs.
24133*/
24134#ifndef SQLITE_HWTIME_H
24135#define SQLITE_HWTIME_H
24136
24137/*
24138** The following routine only works on pentium-class (or newer) processors.
24139** It uses the RDTSC opcode to read the cycle count value out of the
24140** processor and returns that value.  This can be used for high-res
24141** profiling.
24142*/
24143#if (defined(__GNUC__) || defined(_MSC_VER)) && \
24144      (defined(i386) || defined(__i386__) || defined(_M_IX86))
24145
24146  #if defined(__GNUC__)
24147
24148  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24149     unsigned int lo, hi;
24150     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24151     return (sqlite_uint64)hi << 32 | lo;
24152  }
24153
24154  #elif defined(_MSC_VER)
24155
24156  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24157     __asm {
24158        rdtsc
24159        ret       ; return value at EDX:EAX
24160     }
24161  }
24162
24163  #endif
24164
24165#elif (defined(__GNUC__) && defined(__x86_64__))
24166
24167  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24168      unsigned long val;
24169      __asm__ __volatile__ ("rdtsc" : "=A" (val));
24170      return val;
24171  }
24172
24173#elif (defined(__GNUC__) && defined(__ppc__))
24174
24175  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24176      unsigned long long retval;
24177      unsigned long junk;
24178      __asm__ __volatile__ ("\n\
24179          1:      mftbu   %1\n\
24180                  mftb    %L0\n\
24181                  mftbu   %0\n\
24182                  cmpw    %0,%1\n\
24183                  bne     1b"
24184                  : "=r" (retval), "=r" (junk));
24185      return retval;
24186  }
24187
24188#else
24189
24190  #error Need implementation of sqlite3Hwtime() for your platform.
24191
24192  /*
24193  ** To compile without implementing sqlite3Hwtime() for your platform,
24194  ** you can remove the above #error and use the following
24195  ** stub function.  You will lose timing support for many
24196  ** of the debugging and testing utilities, but it should at
24197  ** least compile and run.
24198  */
24199SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24200
24201#endif
24202
24203#endif /* !defined(SQLITE_HWTIME_H) */
24204
24205/************** End of hwtime.h **********************************************/
24206/************** Continuing where we left off in os_common.h ******************/
24207
24208static sqlite_uint64 g_start;
24209static sqlite_uint64 g_elapsed;
24210#define TIMER_START       g_start=sqlite3Hwtime()
24211#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24212#define TIMER_ELAPSED     g_elapsed
24213#else
24214#define TIMER_START
24215#define TIMER_END
24216#define TIMER_ELAPSED     ((sqlite_uint64)0)
24217#endif
24218
24219/*
24220** If we compile with the SQLITE_TEST macro set, then the following block
24221** of code will give us the ability to simulate a disk I/O error.  This
24222** is used for testing the I/O recovery logic.
24223*/
24224#if defined(SQLITE_TEST)
24225SQLITE_API extern int sqlite3_io_error_hit;
24226SQLITE_API extern int sqlite3_io_error_hardhit;
24227SQLITE_API extern int sqlite3_io_error_pending;
24228SQLITE_API extern int sqlite3_io_error_persist;
24229SQLITE_API extern int sqlite3_io_error_benign;
24230SQLITE_API extern int sqlite3_diskfull_pending;
24231SQLITE_API extern int sqlite3_diskfull;
24232#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24233#define SimulateIOError(CODE)  \
24234  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24235       || sqlite3_io_error_pending-- == 1 )  \
24236              { local_ioerr(); CODE; }
24237static void local_ioerr(){
24238  IOTRACE(("IOERR\n"));
24239  sqlite3_io_error_hit++;
24240  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24241}
24242#define SimulateDiskfullError(CODE) \
24243   if( sqlite3_diskfull_pending ){ \
24244     if( sqlite3_diskfull_pending == 1 ){ \
24245       local_ioerr(); \
24246       sqlite3_diskfull = 1; \
24247       sqlite3_io_error_hit = 1; \
24248       CODE; \
24249     }else{ \
24250       sqlite3_diskfull_pending--; \
24251     } \
24252   }
24253#else
24254#define SimulateIOErrorBenign(X)
24255#define SimulateIOError(A)
24256#define SimulateDiskfullError(A)
24257#endif /* defined(SQLITE_TEST) */
24258
24259/*
24260** When testing, keep a count of the number of open files.
24261*/
24262#if defined(SQLITE_TEST)
24263SQLITE_API extern int sqlite3_open_file_count;
24264#define OpenCounter(X)  sqlite3_open_file_count+=(X)
24265#else
24266#define OpenCounter(X)
24267#endif /* defined(SQLITE_TEST) */
24268
24269#endif /* !defined(_OS_COMMON_H_) */
24270
24271/************** End of os_common.h *******************************************/
24272/************** Continuing where we left off in mutex_w32.c ******************/
24273
24274/*
24275** Include the header file for the Windows VFS.
24276*/
24277/************** Include os_win.h in the middle of mutex_w32.c ****************/
24278/************** Begin file os_win.h ******************************************/
24279/*
24280** 2013 November 25
24281**
24282** The author disclaims copyright to this source code.  In place of
24283** a legal notice, here is a blessing:
24284**
24285**    May you do good and not evil.
24286**    May you find forgiveness for yourself and forgive others.
24287**    May you share freely, never taking more than you give.
24288**
24289******************************************************************************
24290**
24291** This file contains code that is specific to Windows.
24292*/
24293#ifndef SQLITE_OS_WIN_H
24294#define SQLITE_OS_WIN_H
24295
24296/*
24297** Include the primary Windows SDK header file.
24298*/
24299#include "windows.h"
24300
24301#ifdef __CYGWIN__
24302# include <sys/cygwin.h>
24303# include <errno.h> /* amalgamator: dontcache */
24304#endif
24305
24306/*
24307** Determine if we are dealing with Windows NT.
24308**
24309** We ought to be able to determine if we are compiling for Windows 9x or
24310** Windows NT using the _WIN32_WINNT macro as follows:
24311**
24312** #if defined(_WIN32_WINNT)
24313** # define SQLITE_OS_WINNT 1
24314** #else
24315** # define SQLITE_OS_WINNT 0
24316** #endif
24317**
24318** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
24319** it ought to, so the above test does not work.  We'll just assume that
24320** everything is Windows NT unless the programmer explicitly says otherwise
24321** by setting SQLITE_OS_WINNT to 0.
24322*/
24323#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
24324# define SQLITE_OS_WINNT 1
24325#endif
24326
24327/*
24328** Determine if we are dealing with Windows CE - which has a much reduced
24329** API.
24330*/
24331#if defined(_WIN32_WCE)
24332# define SQLITE_OS_WINCE 1
24333#else
24334# define SQLITE_OS_WINCE 0
24335#endif
24336
24337/*
24338** Determine if we are dealing with WinRT, which provides only a subset of
24339** the full Win32 API.
24340*/
24341#if !defined(SQLITE_OS_WINRT)
24342# define SQLITE_OS_WINRT 0
24343#endif
24344
24345/*
24346** For WinCE, some API function parameters do not appear to be declared as
24347** volatile.
24348*/
24349#if SQLITE_OS_WINCE
24350# define SQLITE_WIN32_VOLATILE
24351#else
24352# define SQLITE_WIN32_VOLATILE volatile
24353#endif
24354
24355/*
24356** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
24357** functions are not available (e.g. those not using MSVC, Cygwin, etc).
24358*/
24359#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
24360    SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
24361# define SQLITE_OS_WIN_THREADS 1
24362#else
24363# define SQLITE_OS_WIN_THREADS 0
24364#endif
24365
24366#endif /* SQLITE_OS_WIN_H */
24367
24368/************** End of os_win.h **********************************************/
24369/************** Continuing where we left off in mutex_w32.c ******************/
24370#endif
24371
24372/*
24373** The code in this file is only used if we are compiling multithreaded
24374** on a Win32 system.
24375*/
24376#ifdef SQLITE_MUTEX_W32
24377
24378/*
24379** Each recursive mutex is an instance of the following structure.
24380*/
24381struct sqlite3_mutex {
24382  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
24383  int id;                    /* Mutex type */
24384#ifdef SQLITE_DEBUG
24385  volatile int nRef;         /* Number of enterances */
24386  volatile DWORD owner;      /* Thread holding this mutex */
24387  volatile int trace;        /* True to trace changes */
24388#endif
24389};
24390
24391/*
24392** These are the initializer values used when declaring a "static" mutex
24393** on Win32.  It should be noted that all mutexes require initialization
24394** on the Win32 platform.
24395*/
24396#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
24397
24398#ifdef SQLITE_DEBUG
24399#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
24400                                    0L, (DWORD)0, 0 }
24401#else
24402#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
24403#endif
24404
24405#ifdef SQLITE_DEBUG
24406/*
24407** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
24408** intended for use only inside assert() statements.
24409*/
24410static int winMutexHeld(sqlite3_mutex *p){
24411  return p->nRef!=0 && p->owner==GetCurrentThreadId();
24412}
24413
24414static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
24415  return p->nRef==0 || p->owner!=tid;
24416}
24417
24418static int winMutexNotheld(sqlite3_mutex *p){
24419  DWORD tid = GetCurrentThreadId();
24420  return winMutexNotheld2(p, tid);
24421}
24422#endif
24423
24424/*
24425** Try to provide a memory barrier operation, needed for initialization
24426** and also for the xShmBarrier method of the VFS in cases when SQLite is
24427** compiled without mutexes (SQLITE_THREADSAFE=0).
24428*/
24429SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
24430#if defined(SQLITE_MEMORY_BARRIER)
24431  SQLITE_MEMORY_BARRIER;
24432#elif defined(__GNUC__)
24433  __sync_synchronize();
24434#elif MSVC_VERSION>=1300
24435  _ReadWriteBarrier();
24436#elif defined(MemoryBarrier)
24437  MemoryBarrier();
24438#endif
24439}
24440
24441/*
24442** Initialize and deinitialize the mutex subsystem.
24443*/
24444static sqlite3_mutex winMutex_staticMutexes[] = {
24445  SQLITE3_MUTEX_INITIALIZER,
24446  SQLITE3_MUTEX_INITIALIZER,
24447  SQLITE3_MUTEX_INITIALIZER,
24448  SQLITE3_MUTEX_INITIALIZER,
24449  SQLITE3_MUTEX_INITIALIZER,
24450  SQLITE3_MUTEX_INITIALIZER,
24451  SQLITE3_MUTEX_INITIALIZER,
24452  SQLITE3_MUTEX_INITIALIZER,
24453  SQLITE3_MUTEX_INITIALIZER,
24454  SQLITE3_MUTEX_INITIALIZER,
24455  SQLITE3_MUTEX_INITIALIZER,
24456  SQLITE3_MUTEX_INITIALIZER
24457};
24458
24459static int winMutex_isInit = 0;
24460static int winMutex_isNt = -1; /* <0 means "need to query" */
24461
24462/* As the winMutexInit() and winMutexEnd() functions are called as part
24463** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
24464** "interlocked" magic used here is probably not strictly necessary.
24465*/
24466static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
24467
24468SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
24469SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
24470
24471static int winMutexInit(void){
24472  /* The first to increment to 1 does actual initialization */
24473  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
24474    int i;
24475    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
24476#if SQLITE_OS_WINRT
24477      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
24478#else
24479      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
24480#endif
24481    }
24482    winMutex_isInit = 1;
24483  }else{
24484    /* Another thread is (in the process of) initializing the static
24485    ** mutexes */
24486    while( !winMutex_isInit ){
24487      sqlite3_win32_sleep(1);
24488    }
24489  }
24490  return SQLITE_OK;
24491}
24492
24493static int winMutexEnd(void){
24494  /* The first to decrement to 0 does actual shutdown
24495  ** (which should be the last to shutdown.) */
24496  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
24497    if( winMutex_isInit==1 ){
24498      int i;
24499      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
24500        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
24501      }
24502      winMutex_isInit = 0;
24503    }
24504  }
24505  return SQLITE_OK;
24506}
24507
24508/*
24509** The sqlite3_mutex_alloc() routine allocates a new
24510** mutex and returns a pointer to it.  If it returns NULL
24511** that means that a mutex could not be allocated.  SQLite
24512** will unwind its stack and return an error.  The argument
24513** to sqlite3_mutex_alloc() is one of these integer constants:
24514**
24515** <ul>
24516** <li>  SQLITE_MUTEX_FAST
24517** <li>  SQLITE_MUTEX_RECURSIVE
24518** <li>  SQLITE_MUTEX_STATIC_MASTER
24519** <li>  SQLITE_MUTEX_STATIC_MEM
24520** <li>  SQLITE_MUTEX_STATIC_OPEN
24521** <li>  SQLITE_MUTEX_STATIC_PRNG
24522** <li>  SQLITE_MUTEX_STATIC_LRU
24523** <li>  SQLITE_MUTEX_STATIC_PMEM
24524** <li>  SQLITE_MUTEX_STATIC_APP1
24525** <li>  SQLITE_MUTEX_STATIC_APP2
24526** <li>  SQLITE_MUTEX_STATIC_APP3
24527** <li>  SQLITE_MUTEX_STATIC_VFS1
24528** <li>  SQLITE_MUTEX_STATIC_VFS2
24529** <li>  SQLITE_MUTEX_STATIC_VFS3
24530** </ul>
24531**
24532** The first two constants cause sqlite3_mutex_alloc() to create
24533** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
24534** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
24535** The mutex implementation does not need to make a distinction
24536** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
24537** not want to.  But SQLite will only request a recursive mutex in
24538** cases where it really needs one.  If a faster non-recursive mutex
24539** implementation is available on the host platform, the mutex subsystem
24540** might return such a mutex in response to SQLITE_MUTEX_FAST.
24541**
24542** The other allowed parameters to sqlite3_mutex_alloc() each return
24543** a pointer to a static preexisting mutex.  Six static mutexes are
24544** used by the current version of SQLite.  Future versions of SQLite
24545** may add additional static mutexes.  Static mutexes are for internal
24546** use by SQLite only.  Applications that use SQLite mutexes should
24547** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
24548** SQLITE_MUTEX_RECURSIVE.
24549**
24550** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
24551** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
24552** returns a different mutex on every call.  But for the static
24553** mutex types, the same mutex is returned on every call that has
24554** the same type number.
24555*/
24556static sqlite3_mutex *winMutexAlloc(int iType){
24557  sqlite3_mutex *p;
24558
24559  switch( iType ){
24560    case SQLITE_MUTEX_FAST:
24561    case SQLITE_MUTEX_RECURSIVE: {
24562      p = sqlite3MallocZero( sizeof(*p) );
24563      if( p ){
24564        p->id = iType;
24565#ifdef SQLITE_DEBUG
24566#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
24567        p->trace = 1;
24568#endif
24569#endif
24570#if SQLITE_OS_WINRT
24571        InitializeCriticalSectionEx(&p->mutex, 0, 0);
24572#else
24573        InitializeCriticalSection(&p->mutex);
24574#endif
24575      }
24576      break;
24577    }
24578    default: {
24579#ifdef SQLITE_ENABLE_API_ARMOR
24580      if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
24581        (void)SQLITE_MISUSE_BKPT;
24582        return 0;
24583      }
24584#endif
24585      p = &winMutex_staticMutexes[iType-2];
24586      p->id = iType;
24587#ifdef SQLITE_DEBUG
24588#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
24589      p->trace = 1;
24590#endif
24591#endif
24592      break;
24593    }
24594  }
24595  return p;
24596}
24597
24598
24599/*
24600** This routine deallocates a previously
24601** allocated mutex.  SQLite is careful to deallocate every
24602** mutex that it allocates.
24603*/
24604static void winMutexFree(sqlite3_mutex *p){
24605  assert( p );
24606  assert( p->nRef==0 && p->owner==0 );
24607  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
24608    DeleteCriticalSection(&p->mutex);
24609    sqlite3_free(p);
24610  }else{
24611#ifdef SQLITE_ENABLE_API_ARMOR
24612    (void)SQLITE_MISUSE_BKPT;
24613#endif
24614  }
24615}
24616
24617/*
24618** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
24619** to enter a mutex.  If another thread is already within the mutex,
24620** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
24621** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
24622** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
24623** be entered multiple times by the same thread.  In such cases the,
24624** mutex must be exited an equal number of times before another thread
24625** can enter.  If the same thread tries to enter any other kind of mutex
24626** more than once, the behavior is undefined.
24627*/
24628static void winMutexEnter(sqlite3_mutex *p){
24629#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24630  DWORD tid = GetCurrentThreadId();
24631#endif
24632#ifdef SQLITE_DEBUG
24633  assert( p );
24634  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
24635#else
24636  assert( p );
24637#endif
24638  assert( winMutex_isInit==1 );
24639  EnterCriticalSection(&p->mutex);
24640#ifdef SQLITE_DEBUG
24641  assert( p->nRef>0 || p->owner==0 );
24642  p->owner = tid;
24643  p->nRef++;
24644  if( p->trace ){
24645    OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
24646             tid, p->id, p, p->trace, p->nRef));
24647  }
24648#endif
24649}
24650
24651static int winMutexTry(sqlite3_mutex *p){
24652#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24653  DWORD tid = GetCurrentThreadId();
24654#endif
24655  int rc = SQLITE_BUSY;
24656  assert( p );
24657  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
24658  /*
24659  ** The sqlite3_mutex_try() routine is very rarely used, and when it
24660  ** is used it is merely an optimization.  So it is OK for it to always
24661  ** fail.
24662  **
24663  ** The TryEnterCriticalSection() interface is only available on WinNT.
24664  ** And some windows compilers complain if you try to use it without
24665  ** first doing some #defines that prevent SQLite from building on Win98.
24666  ** For that reason, we will omit this optimization for now.  See
24667  ** ticket #2685.
24668  */
24669#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
24670  assert( winMutex_isInit==1 );
24671  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
24672  if( winMutex_isNt<0 ){
24673    winMutex_isNt = sqlite3_win32_is_nt();
24674  }
24675  assert( winMutex_isNt==0 || winMutex_isNt==1 );
24676  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
24677#ifdef SQLITE_DEBUG
24678    p->owner = tid;
24679    p->nRef++;
24680#endif
24681    rc = SQLITE_OK;
24682  }
24683#else
24684  UNUSED_PARAMETER(p);
24685#endif
24686#ifdef SQLITE_DEBUG
24687  if( p->trace ){
24688    OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
24689             tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
24690  }
24691#endif
24692  return rc;
24693}
24694
24695/*
24696** The sqlite3_mutex_leave() routine exits a mutex that was
24697** previously entered by the same thread.  The behavior
24698** is undefined if the mutex is not currently entered or
24699** is not currently allocated.  SQLite will never do either.
24700*/
24701static void winMutexLeave(sqlite3_mutex *p){
24702#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
24703  DWORD tid = GetCurrentThreadId();
24704#endif
24705  assert( p );
24706#ifdef SQLITE_DEBUG
24707  assert( p->nRef>0 );
24708  assert( p->owner==tid );
24709  p->nRef--;
24710  if( p->nRef==0 ) p->owner = 0;
24711  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
24712#endif
24713  assert( winMutex_isInit==1 );
24714  LeaveCriticalSection(&p->mutex);
24715#ifdef SQLITE_DEBUG
24716  if( p->trace ){
24717    OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
24718             tid, p->id, p, p->trace, p->nRef));
24719  }
24720#endif
24721}
24722
24723SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
24724  static const sqlite3_mutex_methods sMutex = {
24725    winMutexInit,
24726    winMutexEnd,
24727    winMutexAlloc,
24728    winMutexFree,
24729    winMutexEnter,
24730    winMutexTry,
24731    winMutexLeave,
24732#ifdef SQLITE_DEBUG
24733    winMutexHeld,
24734    winMutexNotheld
24735#else
24736    0,
24737    0
24738#endif
24739  };
24740  return &sMutex;
24741}
24742
24743#endif /* SQLITE_MUTEX_W32 */
24744
24745/************** End of mutex_w32.c *******************************************/
24746/************** Begin file malloc.c ******************************************/
24747/*
24748** 2001 September 15
24749**
24750** The author disclaims copyright to this source code.  In place of
24751** a legal notice, here is a blessing:
24752**
24753**    May you do good and not evil.
24754**    May you find forgiveness for yourself and forgive others.
24755**    May you share freely, never taking more than you give.
24756**
24757*************************************************************************
24758**
24759** Memory allocation functions used throughout sqlite.
24760*/
24761/* #include "sqliteInt.h" */
24762/* #include <stdarg.h> */
24763
24764/*
24765** Attempt to release up to n bytes of non-essential memory currently
24766** held by SQLite. An example of non-essential memory is memory used to
24767** cache database pages that are not currently in use.
24768*/
24769SQLITE_API int sqlite3_release_memory(int n){
24770#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24771  return sqlite3PcacheReleaseMemory(n);
24772#else
24773  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
24774  ** is a no-op returning zero if SQLite is not compiled with
24775  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
24776  UNUSED_PARAMETER(n);
24777  return 0;
24778#endif
24779}
24780
24781/*
24782** An instance of the following object records the location of
24783** each unused scratch buffer.
24784*/
24785typedef struct ScratchFreeslot {
24786  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
24787} ScratchFreeslot;
24788
24789/*
24790** State information local to the memory allocation subsystem.
24791*/
24792static SQLITE_WSD struct Mem0Global {
24793  sqlite3_mutex *mutex;         /* Mutex to serialize access */
24794  sqlite3_int64 alarmThreshold; /* The soft heap limit */
24795
24796  /*
24797  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
24798  ** (so that a range test can be used to determine if an allocation
24799  ** being freed came from pScratch) and a pointer to the list of
24800  ** unused scratch allocations.
24801  */
24802  void *pScratchEnd;
24803  ScratchFreeslot *pScratchFree;
24804  u32 nScratchFree;
24805
24806  /*
24807  ** True if heap is nearly "full" where "full" is defined by the
24808  ** sqlite3_soft_heap_limit() setting.
24809  */
24810  int nearlyFull;
24811} mem0 = { 0, 0, 0, 0, 0, 0 };
24812
24813#define mem0 GLOBAL(struct Mem0Global, mem0)
24814
24815/*
24816** Return the memory allocator mutex. sqlite3_status() needs it.
24817*/
24818SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
24819  return mem0.mutex;
24820}
24821
24822#ifndef SQLITE_OMIT_DEPRECATED
24823/*
24824** Deprecated external interface.  It used to set an alarm callback
24825** that was invoked when memory usage grew too large.  Now it is a
24826** no-op.
24827*/
24828SQLITE_API int sqlite3_memory_alarm(
24829  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
24830  void *pArg,
24831  sqlite3_int64 iThreshold
24832){
24833  (void)xCallback;
24834  (void)pArg;
24835  (void)iThreshold;
24836  return SQLITE_OK;
24837}
24838#endif
24839
24840/*
24841** Set the soft heap-size limit for the library. Passing a zero or
24842** negative value indicates no limit.
24843*/
24844SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
24845  sqlite3_int64 priorLimit;
24846  sqlite3_int64 excess;
24847  sqlite3_int64 nUsed;
24848#ifndef SQLITE_OMIT_AUTOINIT
24849  int rc = sqlite3_initialize();
24850  if( rc ) return -1;
24851#endif
24852  sqlite3_mutex_enter(mem0.mutex);
24853  priorLimit = mem0.alarmThreshold;
24854  if( n<0 ){
24855    sqlite3_mutex_leave(mem0.mutex);
24856    return priorLimit;
24857  }
24858  mem0.alarmThreshold = n;
24859  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24860  mem0.nearlyFull = (n>0 && n<=nUsed);
24861  sqlite3_mutex_leave(mem0.mutex);
24862  excess = sqlite3_memory_used() - n;
24863  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
24864  return priorLimit;
24865}
24866SQLITE_API void sqlite3_soft_heap_limit(int n){
24867  if( n<0 ) n = 0;
24868  sqlite3_soft_heap_limit64(n);
24869}
24870
24871/*
24872** Initialize the memory allocation subsystem.
24873*/
24874SQLITE_PRIVATE int sqlite3MallocInit(void){
24875  int rc;
24876  if( sqlite3GlobalConfig.m.xMalloc==0 ){
24877    sqlite3MemSetDefault();
24878  }
24879  memset(&mem0, 0, sizeof(mem0));
24880  mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
24881  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
24882      && sqlite3GlobalConfig.nScratch>0 ){
24883    int i, n, sz;
24884    ScratchFreeslot *pSlot;
24885    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
24886    sqlite3GlobalConfig.szScratch = sz;
24887    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
24888    n = sqlite3GlobalConfig.nScratch;
24889    mem0.pScratchFree = pSlot;
24890    mem0.nScratchFree = n;
24891    for(i=0; i<n-1; i++){
24892      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
24893      pSlot = pSlot->pNext;
24894    }
24895    pSlot->pNext = 0;
24896    mem0.pScratchEnd = (void*)&pSlot[1];
24897  }else{
24898    mem0.pScratchEnd = 0;
24899    sqlite3GlobalConfig.pScratch = 0;
24900    sqlite3GlobalConfig.szScratch = 0;
24901    sqlite3GlobalConfig.nScratch = 0;
24902  }
24903  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
24904      || sqlite3GlobalConfig.nPage<=0 ){
24905    sqlite3GlobalConfig.pPage = 0;
24906    sqlite3GlobalConfig.szPage = 0;
24907  }
24908  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
24909  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
24910  return rc;
24911}
24912
24913/*
24914** Return true if the heap is currently under memory pressure - in other
24915** words if the amount of heap used is close to the limit set by
24916** sqlite3_soft_heap_limit().
24917*/
24918SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
24919  return mem0.nearlyFull;
24920}
24921
24922/*
24923** Deinitialize the memory allocation subsystem.
24924*/
24925SQLITE_PRIVATE void sqlite3MallocEnd(void){
24926  if( sqlite3GlobalConfig.m.xShutdown ){
24927    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
24928  }
24929  memset(&mem0, 0, sizeof(mem0));
24930}
24931
24932/*
24933** Return the amount of memory currently checked out.
24934*/
24935SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
24936  sqlite3_int64 res, mx;
24937  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
24938  return res;
24939}
24940
24941/*
24942** Return the maximum amount of memory that has ever been
24943** checked out since either the beginning of this process
24944** or since the most recent reset.
24945*/
24946SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
24947  sqlite3_int64 res, mx;
24948  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
24949  return mx;
24950}
24951
24952/*
24953** Trigger the alarm
24954*/
24955static void sqlite3MallocAlarm(int nByte){
24956  if( mem0.alarmThreshold<=0 ) return;
24957  sqlite3_mutex_leave(mem0.mutex);
24958  sqlite3_release_memory(nByte);
24959  sqlite3_mutex_enter(mem0.mutex);
24960}
24961
24962/*
24963** Do a memory allocation with statistics and alarms.  Assume the
24964** lock is already held.
24965*/
24966static void mallocWithAlarm(int n, void **pp){
24967  void *p;
24968  int nFull;
24969  assert( sqlite3_mutex_held(mem0.mutex) );
24970  assert( n>0 );
24971
24972  /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
24973  ** implementation of malloc_good_size(), which must be called in debug
24974  ** mode and specifically when the DMD "Dark Matter Detector" is enabled
24975  ** or else a crash results.  Hence, do not attempt to optimize out the
24976  ** following xRoundup() call. */
24977  nFull = sqlite3GlobalConfig.m.xRoundup(n);
24978
24979#ifdef SQLITE_MAX_MEMORY
24980  if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
24981    *pp = 0;
24982    return;
24983  }
24984#endif
24985
24986  sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
24987  if( mem0.alarmThreshold>0 ){
24988    sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24989    if( nUsed >= mem0.alarmThreshold - nFull ){
24990      mem0.nearlyFull = 1;
24991      sqlite3MallocAlarm(nFull);
24992    }else{
24993      mem0.nearlyFull = 0;
24994    }
24995  }
24996  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24997#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24998  if( p==0 && mem0.alarmThreshold>0 ){
24999    sqlite3MallocAlarm(nFull);
25000    p = sqlite3GlobalConfig.m.xMalloc(nFull);
25001  }
25002#endif
25003  if( p ){
25004    nFull = sqlite3MallocSize(p);
25005    sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
25006    sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
25007  }
25008  *pp = p;
25009}
25010
25011/*
25012** Allocate memory.  This routine is like sqlite3_malloc() except that it
25013** assumes the memory subsystem has already been initialized.
25014*/
25015SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
25016  void *p;
25017  if( n==0 || n>=0x7fffff00 ){
25018    /* A memory allocation of a number of bytes which is near the maximum
25019    ** signed integer value might cause an integer overflow inside of the
25020    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
25021    ** 255 bytes of overhead.  SQLite itself will never use anything near
25022    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
25023    p = 0;
25024  }else if( sqlite3GlobalConfig.bMemstat ){
25025    sqlite3_mutex_enter(mem0.mutex);
25026    mallocWithAlarm((int)n, &p);
25027    sqlite3_mutex_leave(mem0.mutex);
25028  }else{
25029    p = sqlite3GlobalConfig.m.xMalloc((int)n);
25030  }
25031  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
25032  return p;
25033}
25034
25035/*
25036** This version of the memory allocation is for use by the application.
25037** First make sure the memory subsystem is initialized, then do the
25038** allocation.
25039*/
25040SQLITE_API void *sqlite3_malloc(int n){
25041#ifndef SQLITE_OMIT_AUTOINIT
25042  if( sqlite3_initialize() ) return 0;
25043#endif
25044  return n<=0 ? 0 : sqlite3Malloc(n);
25045}
25046SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
25047#ifndef SQLITE_OMIT_AUTOINIT
25048  if( sqlite3_initialize() ) return 0;
25049#endif
25050  return sqlite3Malloc(n);
25051}
25052
25053/*
25054** Each thread may only have a single outstanding allocation from
25055** xScratchMalloc().  We verify this constraint in the single-threaded
25056** case by setting scratchAllocOut to 1 when an allocation
25057** is outstanding clearing it when the allocation is freed.
25058*/
25059#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
25060static int scratchAllocOut = 0;
25061#endif
25062
25063
25064/*
25065** Allocate memory that is to be used and released right away.
25066** This routine is similar to alloca() in that it is not intended
25067** for situations where the memory might be held long-term.  This
25068** routine is intended to get memory to old large transient data
25069** structures that would not normally fit on the stack of an
25070** embedded processor.
25071*/
25072SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
25073  void *p;
25074  assert( n>0 );
25075
25076  sqlite3_mutex_enter(mem0.mutex);
25077  sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
25078  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
25079    p = mem0.pScratchFree;
25080    mem0.pScratchFree = mem0.pScratchFree->pNext;
25081    mem0.nScratchFree--;
25082    sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
25083    sqlite3_mutex_leave(mem0.mutex);
25084  }else{
25085    sqlite3_mutex_leave(mem0.mutex);
25086    p = sqlite3Malloc(n);
25087    if( sqlite3GlobalConfig.bMemstat && p ){
25088      sqlite3_mutex_enter(mem0.mutex);
25089      sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
25090      sqlite3_mutex_leave(mem0.mutex);
25091    }
25092    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
25093  }
25094  assert( sqlite3_mutex_notheld(mem0.mutex) );
25095
25096
25097#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
25098  /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
25099  ** buffers per thread.
25100  **
25101  ** This can only be checked in single-threaded mode.
25102  */
25103  assert( scratchAllocOut==0 );
25104  if( p ) scratchAllocOut++;
25105#endif
25106
25107  return p;
25108}
25109SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
25110  if( p ){
25111
25112#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
25113    /* Verify that no more than two scratch allocation per thread
25114    ** is outstanding at one time.  (This is only checked in the
25115    ** single-threaded case since checking in the multi-threaded case
25116    ** would be much more complicated.) */
25117    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
25118    scratchAllocOut--;
25119#endif
25120
25121    if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
25122      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
25123      ScratchFreeslot *pSlot;
25124      pSlot = (ScratchFreeslot*)p;
25125      sqlite3_mutex_enter(mem0.mutex);
25126      pSlot->pNext = mem0.pScratchFree;
25127      mem0.pScratchFree = pSlot;
25128      mem0.nScratchFree++;
25129      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
25130      sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
25131      sqlite3_mutex_leave(mem0.mutex);
25132    }else{
25133      /* Release memory back to the heap */
25134      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
25135      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
25136      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
25137      if( sqlite3GlobalConfig.bMemstat ){
25138        int iSize = sqlite3MallocSize(p);
25139        sqlite3_mutex_enter(mem0.mutex);
25140        sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
25141        sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
25142        sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
25143        sqlite3GlobalConfig.m.xFree(p);
25144        sqlite3_mutex_leave(mem0.mutex);
25145      }else{
25146        sqlite3GlobalConfig.m.xFree(p);
25147      }
25148    }
25149  }
25150}
25151
25152/*
25153** TRUE if p is a lookaside memory allocation from db
25154*/
25155#ifndef SQLITE_OMIT_LOOKASIDE
25156static int isLookaside(sqlite3 *db, void *p){
25157  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
25158}
25159#else
25160#define isLookaside(A,B) 0
25161#endif
25162
25163/*
25164** Return the size of a memory allocation previously obtained from
25165** sqlite3Malloc() or sqlite3_malloc().
25166*/
25167SQLITE_PRIVATE int sqlite3MallocSize(void *p){
25168  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25169  return sqlite3GlobalConfig.m.xSize(p);
25170}
25171SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
25172  assert( p!=0 );
25173  if( db==0 || !isLookaside(db,p) ){
25174#ifdef SQLITE_DEBUG
25175    if( db==0 ){
25176      assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
25177      assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25178    }else{
25179      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25180      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25181    }
25182#endif
25183    return sqlite3GlobalConfig.m.xSize(p);
25184  }else{
25185    assert( sqlite3_mutex_held(db->mutex) );
25186    return db->lookaside.sz;
25187  }
25188}
25189SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
25190  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
25191  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25192  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
25193}
25194
25195/*
25196** Free memory previously obtained from sqlite3Malloc().
25197*/
25198SQLITE_API void sqlite3_free(void *p){
25199  if( p==0 ) return;  /* IMP: R-49053-54554 */
25200  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
25201  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
25202  if( sqlite3GlobalConfig.bMemstat ){
25203    sqlite3_mutex_enter(mem0.mutex);
25204    sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
25205    sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
25206    sqlite3GlobalConfig.m.xFree(p);
25207    sqlite3_mutex_leave(mem0.mutex);
25208  }else{
25209    sqlite3GlobalConfig.m.xFree(p);
25210  }
25211}
25212
25213/*
25214** Add the size of memory allocation "p" to the count in
25215** *db->pnBytesFreed.
25216*/
25217static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
25218  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
25219}
25220
25221/*
25222** Free memory that might be associated with a particular database
25223** connection.  Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
25224** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
25225*/
25226SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
25227  assert( db==0 || sqlite3_mutex_held(db->mutex) );
25228  assert( p!=0 );
25229  if( db ){
25230    if( db->pnBytesFreed ){
25231      measureAllocationSize(db, p);
25232      return;
25233    }
25234    if( isLookaside(db, p) ){
25235      LookasideSlot *pBuf = (LookasideSlot*)p;
25236#ifdef SQLITE_DEBUG
25237      /* Trash all content in the buffer being freed */
25238      memset(p, 0xaa, db->lookaside.sz);
25239#endif
25240      pBuf->pNext = db->lookaside.pFree;
25241      db->lookaside.pFree = pBuf;
25242      db->lookaside.nOut--;
25243      return;
25244    }
25245  }
25246  assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25247  assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25248  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
25249  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
25250  sqlite3_free(p);
25251}
25252SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
25253  assert( db==0 || sqlite3_mutex_held(db->mutex) );
25254  if( p ) sqlite3DbFreeNN(db, p);
25255}
25256
25257/*
25258** Change the size of an existing memory allocation
25259*/
25260SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
25261  int nOld, nNew, nDiff;
25262  void *pNew;
25263  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
25264  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
25265  if( pOld==0 ){
25266    return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
25267  }
25268  if( nBytes==0 ){
25269    sqlite3_free(pOld); /* IMP: R-26507-47431 */
25270    return 0;
25271  }
25272  if( nBytes>=0x7fffff00 ){
25273    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
25274    return 0;
25275  }
25276  nOld = sqlite3MallocSize(pOld);
25277  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
25278  ** argument to xRealloc is always a value returned by a prior call to
25279  ** xRoundup. */
25280  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
25281  if( nOld==nNew ){
25282    pNew = pOld;
25283  }else if( sqlite3GlobalConfig.bMemstat ){
25284    sqlite3_mutex_enter(mem0.mutex);
25285    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
25286    nDiff = nNew - nOld;
25287    if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
25288          mem0.alarmThreshold-nDiff ){
25289      sqlite3MallocAlarm(nDiff);
25290    }
25291    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
25292    if( pNew==0 && mem0.alarmThreshold>0 ){
25293      sqlite3MallocAlarm((int)nBytes);
25294      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
25295    }
25296    if( pNew ){
25297      nNew = sqlite3MallocSize(pNew);
25298      sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
25299    }
25300    sqlite3_mutex_leave(mem0.mutex);
25301  }else{
25302    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
25303  }
25304  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
25305  return pNew;
25306}
25307
25308/*
25309** The public interface to sqlite3Realloc.  Make sure that the memory
25310** subsystem is initialized prior to invoking sqliteRealloc.
25311*/
25312SQLITE_API void *sqlite3_realloc(void *pOld, int n){
25313#ifndef SQLITE_OMIT_AUTOINIT
25314  if( sqlite3_initialize() ) return 0;
25315#endif
25316  if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
25317  return sqlite3Realloc(pOld, n);
25318}
25319SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
25320#ifndef SQLITE_OMIT_AUTOINIT
25321  if( sqlite3_initialize() ) return 0;
25322#endif
25323  return sqlite3Realloc(pOld, n);
25324}
25325
25326
25327/*
25328** Allocate and zero memory.
25329*/
25330SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
25331  void *p = sqlite3Malloc(n);
25332  if( p ){
25333    memset(p, 0, (size_t)n);
25334  }
25335  return p;
25336}
25337
25338/*
25339** Allocate and zero memory.  If the allocation fails, make
25340** the mallocFailed flag in the connection pointer.
25341*/
25342SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
25343  void *p;
25344  testcase( db==0 );
25345  p = sqlite3DbMallocRaw(db, n);
25346  if( p ) memset(p, 0, (size_t)n);
25347  return p;
25348}
25349
25350
25351/* Finish the work of sqlite3DbMallocRawNN for the unusual and
25352** slower case when the allocation cannot be fulfilled using lookaside.
25353*/
25354static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
25355  void *p;
25356  assert( db!=0 );
25357  p = sqlite3Malloc(n);
25358  if( !p ) sqlite3OomFault(db);
25359  sqlite3MemdebugSetType(p,
25360         (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
25361  return p;
25362}
25363
25364/*
25365** Allocate memory, either lookaside (if possible) or heap.
25366** If the allocation fails, set the mallocFailed flag in
25367** the connection pointer.
25368**
25369** If db!=0 and db->mallocFailed is true (indicating a prior malloc
25370** failure on the same database connection) then always return 0.
25371** Hence for a particular database connection, once malloc starts
25372** failing, it fails consistently until mallocFailed is reset.
25373** This is an important assumption.  There are many places in the
25374** code that do things like this:
25375**
25376**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
25377**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
25378**         if( b ) a[10] = 9;
25379**
25380** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
25381** that all prior mallocs (ex: "a") worked too.
25382**
25383** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
25384** not a NULL pointer.
25385*/
25386SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
25387  void *p;
25388  if( db ) return sqlite3DbMallocRawNN(db, n);
25389  p = sqlite3Malloc(n);
25390  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
25391  return p;
25392}
25393SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
25394#ifndef SQLITE_OMIT_LOOKASIDE
25395  LookasideSlot *pBuf;
25396  assert( db!=0 );
25397  assert( sqlite3_mutex_held(db->mutex) );
25398  assert( db->pnBytesFreed==0 );
25399  if( db->lookaside.bDisable==0 ){
25400    assert( db->mallocFailed==0 );
25401    if( n>db->lookaside.sz ){
25402      db->lookaside.anStat[1]++;
25403    }else if( (pBuf = db->lookaside.pFree)==0 ){
25404      db->lookaside.anStat[2]++;
25405    }else{
25406      db->lookaside.pFree = pBuf->pNext;
25407      db->lookaside.nOut++;
25408      db->lookaside.anStat[0]++;
25409      if( db->lookaside.nOut>db->lookaside.mxOut ){
25410        db->lookaside.mxOut = db->lookaside.nOut;
25411      }
25412      return (void*)pBuf;
25413    }
25414  }else if( db->mallocFailed ){
25415    return 0;
25416  }
25417#else
25418  assert( db!=0 );
25419  assert( sqlite3_mutex_held(db->mutex) );
25420  assert( db->pnBytesFreed==0 );
25421  if( db->mallocFailed ){
25422    return 0;
25423  }
25424#endif
25425  return dbMallocRawFinish(db, n);
25426}
25427
25428/* Forward declaration */
25429static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
25430
25431/*
25432** Resize the block of memory pointed to by p to n bytes. If the
25433** resize fails, set the mallocFailed flag in the connection object.
25434*/
25435SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
25436  assert( db!=0 );
25437  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
25438  assert( sqlite3_mutex_held(db->mutex) );
25439  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
25440  return dbReallocFinish(db, p, n);
25441}
25442static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
25443  void *pNew = 0;
25444  assert( db!=0 );
25445  assert( p!=0 );
25446  if( db->mallocFailed==0 ){
25447    if( isLookaside(db, p) ){
25448      pNew = sqlite3DbMallocRawNN(db, n);
25449      if( pNew ){
25450        memcpy(pNew, p, db->lookaside.sz);
25451        sqlite3DbFree(db, p);
25452      }
25453    }else{
25454      assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25455      assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
25456      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
25457      pNew = sqlite3_realloc64(p, n);
25458      if( !pNew ){
25459        sqlite3OomFault(db);
25460      }
25461      sqlite3MemdebugSetType(pNew,
25462            (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
25463    }
25464  }
25465  return pNew;
25466}
25467
25468/*
25469** Attempt to reallocate p.  If the reallocation fails, then free p
25470** and set the mallocFailed flag in the database connection.
25471*/
25472SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
25473  void *pNew;
25474  pNew = sqlite3DbRealloc(db, p, n);
25475  if( !pNew ){
25476    sqlite3DbFree(db, p);
25477  }
25478  return pNew;
25479}
25480
25481/*
25482** Make a copy of a string in memory obtained from sqliteMalloc(). These
25483** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
25484** is because when memory debugging is turned on, these two functions are
25485** called via macros that record the current file and line number in the
25486** ThreadData structure.
25487*/
25488SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
25489  char *zNew;
25490  size_t n;
25491  if( z==0 ){
25492    return 0;
25493  }
25494  n = strlen(z) + 1;
25495  zNew = sqlite3DbMallocRaw(db, n);
25496  if( zNew ){
25497    memcpy(zNew, z, n);
25498  }
25499  return zNew;
25500}
25501SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
25502  char *zNew;
25503  assert( db!=0 );
25504  if( z==0 ){
25505    return 0;
25506  }
25507  assert( (n&0x7fffffff)==n );
25508  zNew = sqlite3DbMallocRawNN(db, n+1);
25509  if( zNew ){
25510    memcpy(zNew, z, (size_t)n);
25511    zNew[n] = 0;
25512  }
25513  return zNew;
25514}
25515
25516/*
25517** Free any prior content in *pz and replace it with a copy of zNew.
25518*/
25519SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
25520  sqlite3DbFree(db, *pz);
25521  *pz = sqlite3DbStrDup(db, zNew);
25522}
25523
25524/*
25525** Call this routine to record the fact that an OOM (out-of-memory) error
25526** has happened.  This routine will set db->mallocFailed, and also
25527** temporarily disable the lookaside memory allocator and interrupt
25528** any running VDBEs.
25529*/
25530SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
25531  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
25532    db->mallocFailed = 1;
25533    if( db->nVdbeExec>0 ){
25534      db->u1.isInterrupted = 1;
25535    }
25536    db->lookaside.bDisable++;
25537  }
25538}
25539
25540/*
25541** This routine reactivates the memory allocator and clears the
25542** db->mallocFailed flag as necessary.
25543**
25544** The memory allocator is not restarted if there are running
25545** VDBEs.
25546*/
25547SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
25548  if( db->mallocFailed && db->nVdbeExec==0 ){
25549    db->mallocFailed = 0;
25550    db->u1.isInterrupted = 0;
25551    assert( db->lookaside.bDisable>0 );
25552    db->lookaside.bDisable--;
25553  }
25554}
25555
25556/*
25557** Take actions at the end of an API call to indicate an OOM error
25558*/
25559static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
25560  sqlite3OomClear(db);
25561  sqlite3Error(db, SQLITE_NOMEM);
25562  return SQLITE_NOMEM_BKPT;
25563}
25564
25565/*
25566** This function must be called before exiting any API function (i.e.
25567** returning control to the user) that has called sqlite3_malloc or
25568** sqlite3_realloc.
25569**
25570** The returned value is normally a copy of the second argument to this
25571** function. However, if a malloc() failure has occurred since the previous
25572** invocation SQLITE_NOMEM is returned instead.
25573**
25574** If an OOM as occurred, then the connection error-code (the value
25575** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
25576*/
25577SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
25578  /* If the db handle must hold the connection handle mutex here.
25579  ** Otherwise the read (and possible write) of db->mallocFailed
25580  ** is unsafe, as is the call to sqlite3Error().
25581  */
25582  assert( db!=0 );
25583  assert( sqlite3_mutex_held(db->mutex) );
25584  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
25585    return apiOomError(db);
25586  }
25587  return rc & db->errMask;
25588}
25589
25590/************** End of malloc.c **********************************************/
25591/************** Begin file printf.c ******************************************/
25592/*
25593** The "printf" code that follows dates from the 1980's.  It is in
25594** the public domain.
25595**
25596**************************************************************************
25597**
25598** This file contains code for a set of "printf"-like routines.  These
25599** routines format strings much like the printf() from the standard C
25600** library, though the implementation here has enhancements to support
25601** SQLite.
25602*/
25603/* #include "sqliteInt.h" */
25604
25605/*
25606** Conversion types fall into various categories as defined by the
25607** following enumeration.
25608*/
25609#define etRADIX       0 /* non-decimal integer types.  %x %o */
25610#define etFLOAT       1 /* Floating point.  %f */
25611#define etEXP         2 /* Exponentional notation. %e and %E */
25612#define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
25613#define etSIZE        4 /* Return number of characters processed so far. %n */
25614#define etSTRING      5 /* Strings. %s */
25615#define etDYNSTRING   6 /* Dynamically allocated strings. %z */
25616#define etPERCENT     7 /* Percent symbol. %% */
25617#define etCHARX       8 /* Characters. %c */
25618/* The rest are extensions, not normally found in printf() */
25619#define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
25620#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
25621                          NULL pointers replaced by SQL NULL.  %Q */
25622#define etTOKEN      11 /* a pointer to a Token structure */
25623#define etSRCLIST    12 /* a pointer to a SrcList */
25624#define etPOINTER    13 /* The %p conversion */
25625#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
25626#define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
25627#define etDECIMAL    16 /* %d or %u, but not %x, %o */
25628
25629#define etINVALID    17 /* Any unrecognized conversion type */
25630
25631
25632/*
25633** An "etByte" is an 8-bit unsigned value.
25634*/
25635typedef unsigned char etByte;
25636
25637/*
25638** Each builtin conversion character (ex: the 'd' in "%d") is described
25639** by an instance of the following structure
25640*/
25641typedef struct et_info {   /* Information about each format field */
25642  char fmttype;            /* The format field code letter */
25643  etByte base;             /* The base for radix conversion */
25644  etByte flags;            /* One or more of FLAG_ constants below */
25645  etByte type;             /* Conversion paradigm */
25646  etByte charset;          /* Offset into aDigits[] of the digits string */
25647  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
25648} et_info;
25649
25650/*
25651** Allowed values for et_info.flags
25652*/
25653#define FLAG_SIGNED    1     /* True if the value to convert is signed */
25654#define FLAG_STRING    4     /* Allow infinite precision */
25655
25656
25657/*
25658** The following table is searched linearly, so it is good to put the
25659** most frequently used conversion types first.
25660*/
25661static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
25662static const char aPrefix[] = "-x0\000X0";
25663static const et_info fmtinfo[] = {
25664  {  'd', 10, 1, etDECIMAL,    0,  0 },
25665  {  's',  0, 4, etSTRING,     0,  0 },
25666  {  'g',  0, 1, etGENERIC,    30, 0 },
25667  {  'z',  0, 4, etDYNSTRING,  0,  0 },
25668  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
25669  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
25670  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
25671  {  'c',  0, 0, etCHARX,      0,  0 },
25672  {  'o',  8, 0, etRADIX,      0,  2 },
25673  {  'u', 10, 0, etDECIMAL,    0,  0 },
25674  {  'x', 16, 0, etRADIX,      16, 1 },
25675  {  'X', 16, 0, etRADIX,      0,  4 },
25676#ifndef SQLITE_OMIT_FLOATING_POINT
25677  {  'f',  0, 1, etFLOAT,      0,  0 },
25678  {  'e',  0, 1, etEXP,        30, 0 },
25679  {  'E',  0, 1, etEXP,        14, 0 },
25680  {  'G',  0, 1, etGENERIC,    14, 0 },
25681#endif
25682  {  'i', 10, 1, etDECIMAL,    0,  0 },
25683  {  'n',  0, 0, etSIZE,       0,  0 },
25684  {  '%',  0, 0, etPERCENT,    0,  0 },
25685  {  'p', 16, 0, etPOINTER,    0,  1 },
25686
25687  /* All the rest are undocumented and are for internal use only */
25688  {  'T',  0, 0, etTOKEN,      0,  0 },
25689  {  'S',  0, 0, etSRCLIST,    0,  0 },
25690  {  'r', 10, 1, etORDINAL,    0,  0 },
25691};
25692
25693/*
25694** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
25695** conversions will work.
25696*/
25697#ifndef SQLITE_OMIT_FLOATING_POINT
25698/*
25699** "*val" is a double such that 0.1 <= *val < 10.0
25700** Return the ascii code for the leading digit of *val, then
25701** multiply "*val" by 10.0 to renormalize.
25702**
25703** Example:
25704**     input:     *val = 3.14159
25705**     output:    *val = 1.4159    function return = '3'
25706**
25707** The counter *cnt is incremented each time.  After counter exceeds
25708** 16 (the number of significant digits in a 64-bit float) '0' is
25709** always returned.
25710*/
25711static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
25712  int digit;
25713  LONGDOUBLE_TYPE d;
25714  if( (*cnt)<=0 ) return '0';
25715  (*cnt)--;
25716  digit = (int)*val;
25717  d = digit;
25718  digit += '0';
25719  *val = (*val - d)*10.0;
25720  return (char)digit;
25721}
25722#endif /* SQLITE_OMIT_FLOATING_POINT */
25723
25724/*
25725** Set the StrAccum object to an error mode.
25726*/
25727static void setStrAccumError(StrAccum *p, u8 eError){
25728  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
25729  p->accError = eError;
25730  p->nAlloc = 0;
25731}
25732
25733/*
25734** Extra argument values from a PrintfArguments object
25735*/
25736static sqlite3_int64 getIntArg(PrintfArguments *p){
25737  if( p->nArg<=p->nUsed ) return 0;
25738  return sqlite3_value_int64(p->apArg[p->nUsed++]);
25739}
25740static double getDoubleArg(PrintfArguments *p){
25741  if( p->nArg<=p->nUsed ) return 0.0;
25742  return sqlite3_value_double(p->apArg[p->nUsed++]);
25743}
25744static char *getTextArg(PrintfArguments *p){
25745  if( p->nArg<=p->nUsed ) return 0;
25746  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
25747}
25748
25749
25750/*
25751** On machines with a small stack size, you can redefine the
25752** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
25753*/
25754#ifndef SQLITE_PRINT_BUF_SIZE
25755# define SQLITE_PRINT_BUF_SIZE 70
25756#endif
25757#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
25758
25759/*
25760** Render a string given by "fmt" into the StrAccum object.
25761*/
25762SQLITE_PRIVATE void sqlite3VXPrintf(
25763  StrAccum *pAccum,          /* Accumulate results here */
25764  const char *fmt,           /* Format string */
25765  va_list ap                 /* arguments */
25766){
25767  int c;                     /* Next character in the format string */
25768  char *bufpt;               /* Pointer to the conversion buffer */
25769  int precision;             /* Precision of the current field */
25770  int length;                /* Length of the field */
25771  int idx;                   /* A general purpose loop counter */
25772  int width;                 /* Width of the current field */
25773  etByte flag_leftjustify;   /* True if "-" flag is present */
25774  etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
25775  etByte flag_alternateform; /* True if "#" flag is present */
25776  etByte flag_altform2;      /* True if "!" flag is present */
25777  etByte flag_zeropad;       /* True if field width constant starts with zero */
25778  etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
25779  etByte done;               /* Loop termination flag */
25780  etByte cThousand;          /* Thousands separator for %d and %u */
25781  etByte xtype = etINVALID;  /* Conversion paradigm */
25782  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
25783  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
25784  sqlite_uint64 longvalue;   /* Value for integer types */
25785  LONGDOUBLE_TYPE realvalue; /* Value for real types */
25786  const et_info *infop;      /* Pointer to the appropriate info structure */
25787  char *zOut;                /* Rendering buffer */
25788  int nOut;                  /* Size of the rendering buffer */
25789  char *zExtra = 0;          /* Malloced memory used by some conversion */
25790#ifndef SQLITE_OMIT_FLOATING_POINT
25791  int  exp, e2;              /* exponent of real numbers */
25792  int nsd;                   /* Number of significant digits returned */
25793  double rounder;            /* Used for rounding floating point values */
25794  etByte flag_dp;            /* True if decimal point should be shown */
25795  etByte flag_rtz;           /* True if trailing zeros should be removed */
25796#endif
25797  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
25798  char buf[etBUFSIZE];       /* Conversion buffer */
25799
25800  bufpt = 0;
25801  if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
25802    pArgList = va_arg(ap, PrintfArguments*);
25803    bArgList = 1;
25804  }else{
25805    bArgList = 0;
25806  }
25807  for(; (c=(*fmt))!=0; ++fmt){
25808    if( c!='%' ){
25809      bufpt = (char *)fmt;
25810#if HAVE_STRCHRNUL
25811      fmt = strchrnul(fmt, '%');
25812#else
25813      do{ fmt++; }while( *fmt && *fmt != '%' );
25814#endif
25815      sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
25816      if( *fmt==0 ) break;
25817    }
25818    if( (c=(*++fmt))==0 ){
25819      sqlite3StrAccumAppend(pAccum, "%", 1);
25820      break;
25821    }
25822    /* Find out what flags are present */
25823    flag_leftjustify = flag_prefix = cThousand =
25824     flag_alternateform = flag_altform2 = flag_zeropad = 0;
25825    done = 0;
25826    do{
25827      switch( c ){
25828        case '-':   flag_leftjustify = 1;     break;
25829        case '+':   flag_prefix = '+';        break;
25830        case ' ':   flag_prefix = ' ';        break;
25831        case '#':   flag_alternateform = 1;   break;
25832        case '!':   flag_altform2 = 1;        break;
25833        case '0':   flag_zeropad = 1;         break;
25834        case ',':   cThousand = ',';          break;
25835        default:    done = 1;                 break;
25836      }
25837    }while( !done && (c=(*++fmt))!=0 );
25838    /* Get the field width */
25839    if( c=='*' ){
25840      if( bArgList ){
25841        width = (int)getIntArg(pArgList);
25842      }else{
25843        width = va_arg(ap,int);
25844      }
25845      if( width<0 ){
25846        flag_leftjustify = 1;
25847        width = width >= -2147483647 ? -width : 0;
25848      }
25849      c = *++fmt;
25850    }else{
25851      unsigned wx = 0;
25852      while( c>='0' && c<='9' ){
25853        wx = wx*10 + c - '0';
25854        c = *++fmt;
25855      }
25856      testcase( wx>0x7fffffff );
25857      width = wx & 0x7fffffff;
25858    }
25859    assert( width>=0 );
25860#ifdef SQLITE_PRINTF_PRECISION_LIMIT
25861    if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
25862      width = SQLITE_PRINTF_PRECISION_LIMIT;
25863    }
25864#endif
25865
25866    /* Get the precision */
25867    if( c=='.' ){
25868      c = *++fmt;
25869      if( c=='*' ){
25870        if( bArgList ){
25871          precision = (int)getIntArg(pArgList);
25872        }else{
25873          precision = va_arg(ap,int);
25874        }
25875        c = *++fmt;
25876        if( precision<0 ){
25877          precision = precision >= -2147483647 ? -precision : -1;
25878        }
25879      }else{
25880        unsigned px = 0;
25881        while( c>='0' && c<='9' ){
25882          px = px*10 + c - '0';
25883          c = *++fmt;
25884        }
25885        testcase( px>0x7fffffff );
25886        precision = px & 0x7fffffff;
25887      }
25888    }else{
25889      precision = -1;
25890    }
25891    assert( precision>=(-1) );
25892#ifdef SQLITE_PRINTF_PRECISION_LIMIT
25893    if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
25894      precision = SQLITE_PRINTF_PRECISION_LIMIT;
25895    }
25896#endif
25897
25898
25899    /* Get the conversion type modifier */
25900    if( c=='l' ){
25901      flag_long = 1;
25902      c = *++fmt;
25903      if( c=='l' ){
25904        flag_long = 2;
25905        c = *++fmt;
25906      }
25907    }else{
25908      flag_long = 0;
25909    }
25910    /* Fetch the info entry for the field */
25911    infop = &fmtinfo[0];
25912    xtype = etINVALID;
25913    for(idx=0; idx<ArraySize(fmtinfo); idx++){
25914      if( c==fmtinfo[idx].fmttype ){
25915        infop = &fmtinfo[idx];
25916        xtype = infop->type;
25917        break;
25918      }
25919    }
25920
25921    /*
25922    ** At this point, variables are initialized as follows:
25923    **
25924    **   flag_alternateform          TRUE if a '#' is present.
25925    **   flag_altform2               TRUE if a '!' is present.
25926    **   flag_prefix                 '+' or ' ' or zero
25927    **   flag_leftjustify            TRUE if a '-' is present or if the
25928    **                               field width was negative.
25929    **   flag_zeropad                TRUE if the width began with 0.
25930    **   flag_long                   1 for "l", 2 for "ll"
25931    **   width                       The specified field width.  This is
25932    **                               always non-negative.  Zero is the default.
25933    **   precision                   The specified precision.  The default
25934    **                               is -1.
25935    **   xtype                       The class of the conversion.
25936    **   infop                       Pointer to the appropriate info struct.
25937    */
25938    switch( xtype ){
25939      case etPOINTER:
25940        flag_long = sizeof(char*)==sizeof(i64) ? 2 :
25941                     sizeof(char*)==sizeof(long int) ? 1 : 0;
25942        /* Fall through into the next case */
25943      case etORDINAL:
25944      case etRADIX:
25945        cThousand = 0;
25946        /* Fall through into the next case */
25947      case etDECIMAL:
25948        if( infop->flags & FLAG_SIGNED ){
25949          i64 v;
25950          if( bArgList ){
25951            v = getIntArg(pArgList);
25952          }else if( flag_long ){
25953            if( flag_long==2 ){
25954              v = va_arg(ap,i64) ;
25955            }else{
25956              v = va_arg(ap,long int);
25957            }
25958          }else{
25959            v = va_arg(ap,int);
25960          }
25961          if( v<0 ){
25962            if( v==SMALLEST_INT64 ){
25963              longvalue = ((u64)1)<<63;
25964            }else{
25965              longvalue = -v;
25966            }
25967            prefix = '-';
25968          }else{
25969            longvalue = v;
25970            prefix = flag_prefix;
25971          }
25972        }else{
25973          if( bArgList ){
25974            longvalue = (u64)getIntArg(pArgList);
25975          }else if( flag_long ){
25976            if( flag_long==2 ){
25977              longvalue = va_arg(ap,u64);
25978            }else{
25979              longvalue = va_arg(ap,unsigned long int);
25980            }
25981          }else{
25982            longvalue = va_arg(ap,unsigned int);
25983          }
25984          prefix = 0;
25985        }
25986        if( longvalue==0 ) flag_alternateform = 0;
25987        if( flag_zeropad && precision<width-(prefix!=0) ){
25988          precision = width-(prefix!=0);
25989        }
25990        if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
25991          nOut = etBUFSIZE;
25992          zOut = buf;
25993        }else{
25994          u64 n = (u64)precision + 10 + precision/3;
25995          zOut = zExtra = sqlite3Malloc( n );
25996          if( zOut==0 ){
25997            setStrAccumError(pAccum, STRACCUM_NOMEM);
25998            return;
25999          }
26000          nOut = (int)n;
26001        }
26002        bufpt = &zOut[nOut-1];
26003        if( xtype==etORDINAL ){
26004          static const char zOrd[] = "thstndrd";
26005          int x = (int)(longvalue % 10);
26006          if( x>=4 || (longvalue/10)%10==1 ){
26007            x = 0;
26008          }
26009          *(--bufpt) = zOrd[x*2+1];
26010          *(--bufpt) = zOrd[x*2];
26011        }
26012        {
26013          const char *cset = &aDigits[infop->charset];
26014          u8 base = infop->base;
26015          do{                                           /* Convert to ascii */
26016            *(--bufpt) = cset[longvalue%base];
26017            longvalue = longvalue/base;
26018          }while( longvalue>0 );
26019        }
26020        length = (int)(&zOut[nOut-1]-bufpt);
26021        while( precision>length ){
26022          *(--bufpt) = '0';                             /* Zero pad */
26023          length++;
26024        }
26025        if( cThousand ){
26026          int nn = (length - 1)/3;  /* Number of "," to insert */
26027          int ix = (length - 1)%3 + 1;
26028          bufpt -= nn;
26029          for(idx=0; nn>0; idx++){
26030            bufpt[idx] = bufpt[idx+nn];
26031            ix--;
26032            if( ix==0 ){
26033              bufpt[++idx] = cThousand;
26034              nn--;
26035              ix = 3;
26036            }
26037          }
26038        }
26039        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
26040        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
26041          const char *pre;
26042          char x;
26043          pre = &aPrefix[infop->prefix];
26044          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
26045        }
26046        length = (int)(&zOut[nOut-1]-bufpt);
26047        break;
26048      case etFLOAT:
26049      case etEXP:
26050      case etGENERIC:
26051        if( bArgList ){
26052          realvalue = getDoubleArg(pArgList);
26053        }else{
26054          realvalue = va_arg(ap,double);
26055        }
26056#ifdef SQLITE_OMIT_FLOATING_POINT
26057        length = 0;
26058#else
26059        if( precision<0 ) precision = 6;         /* Set default precision */
26060        if( realvalue<0.0 ){
26061          realvalue = -realvalue;
26062          prefix = '-';
26063        }else{
26064          prefix = flag_prefix;
26065        }
26066        if( xtype==etGENERIC && precision>0 ) precision--;
26067        testcase( precision>0xfff );
26068        for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
26069        if( xtype==etFLOAT ) realvalue += rounder;
26070        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
26071        exp = 0;
26072        if( sqlite3IsNaN((double)realvalue) ){
26073          bufpt = "NaN";
26074          length = 3;
26075          break;
26076        }
26077        if( realvalue>0.0 ){
26078          LONGDOUBLE_TYPE scale = 1.0;
26079          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
26080          while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
26081          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
26082          realvalue /= scale;
26083          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
26084          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
26085          if( exp>350 ){
26086            bufpt = buf;
26087            buf[0] = prefix;
26088            memcpy(buf+(prefix!=0),"Inf",4);
26089            length = 3+(prefix!=0);
26090            break;
26091          }
26092        }
26093        bufpt = buf;
26094        /*
26095        ** If the field type is etGENERIC, then convert to either etEXP
26096        ** or etFLOAT, as appropriate.
26097        */
26098        if( xtype!=etFLOAT ){
26099          realvalue += rounder;
26100          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
26101        }
26102        if( xtype==etGENERIC ){
26103          flag_rtz = !flag_alternateform;
26104          if( exp<-4 || exp>precision ){
26105            xtype = etEXP;
26106          }else{
26107            precision = precision - exp;
26108            xtype = etFLOAT;
26109          }
26110        }else{
26111          flag_rtz = flag_altform2;
26112        }
26113        if( xtype==etEXP ){
26114          e2 = 0;
26115        }else{
26116          e2 = exp;
26117        }
26118        if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
26119          bufpt = zExtra
26120              = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
26121          if( bufpt==0 ){
26122            setStrAccumError(pAccum, STRACCUM_NOMEM);
26123            return;
26124          }
26125        }
26126        zOut = bufpt;
26127        nsd = 16 + flag_altform2*10;
26128        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
26129        /* The sign in front of the number */
26130        if( prefix ){
26131          *(bufpt++) = prefix;
26132        }
26133        /* Digits prior to the decimal point */
26134        if( e2<0 ){
26135          *(bufpt++) = '0';
26136        }else{
26137          for(; e2>=0; e2--){
26138            *(bufpt++) = et_getdigit(&realvalue,&nsd);
26139          }
26140        }
26141        /* The decimal point */
26142        if( flag_dp ){
26143          *(bufpt++) = '.';
26144        }
26145        /* "0" digits after the decimal point but before the first
26146        ** significant digit of the number */
26147        for(e2++; e2<0; precision--, e2++){
26148          assert( precision>0 );
26149          *(bufpt++) = '0';
26150        }
26151        /* Significant digits after the decimal point */
26152        while( (precision--)>0 ){
26153          *(bufpt++) = et_getdigit(&realvalue,&nsd);
26154        }
26155        /* Remove trailing zeros and the "." if no digits follow the "." */
26156        if( flag_rtz && flag_dp ){
26157          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
26158          assert( bufpt>zOut );
26159          if( bufpt[-1]=='.' ){
26160            if( flag_altform2 ){
26161              *(bufpt++) = '0';
26162            }else{
26163              *(--bufpt) = 0;
26164            }
26165          }
26166        }
26167        /* Add the "eNNN" suffix */
26168        if( xtype==etEXP ){
26169          *(bufpt++) = aDigits[infop->charset];
26170          if( exp<0 ){
26171            *(bufpt++) = '-'; exp = -exp;
26172          }else{
26173            *(bufpt++) = '+';
26174          }
26175          if( exp>=100 ){
26176            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
26177            exp %= 100;
26178          }
26179          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
26180          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
26181        }
26182        *bufpt = 0;
26183
26184        /* The converted number is in buf[] and zero terminated. Output it.
26185        ** Note that the number is in the usual order, not reversed as with
26186        ** integer conversions. */
26187        length = (int)(bufpt-zOut);
26188        bufpt = zOut;
26189
26190        /* Special case:  Add leading zeros if the flag_zeropad flag is
26191        ** set and we are not left justified */
26192        if( flag_zeropad && !flag_leftjustify && length < width){
26193          int i;
26194          int nPad = width - length;
26195          for(i=width; i>=nPad; i--){
26196            bufpt[i] = bufpt[i-nPad];
26197          }
26198          i = prefix!=0;
26199          while( nPad-- ) bufpt[i++] = '0';
26200          length = width;
26201        }
26202#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
26203        break;
26204      case etSIZE:
26205        if( !bArgList ){
26206          *(va_arg(ap,int*)) = pAccum->nChar;
26207        }
26208        length = width = 0;
26209        break;
26210      case etPERCENT:
26211        buf[0] = '%';
26212        bufpt = buf;
26213        length = 1;
26214        break;
26215      case etCHARX:
26216        if( bArgList ){
26217          bufpt = getTextArg(pArgList);
26218          c = bufpt ? bufpt[0] : 0;
26219        }else{
26220          c = va_arg(ap,int);
26221        }
26222        if( precision>1 ){
26223          width -= precision-1;
26224          if( width>1 && !flag_leftjustify ){
26225            sqlite3AppendChar(pAccum, width-1, ' ');
26226            width = 0;
26227          }
26228          sqlite3AppendChar(pAccum, precision-1, c);
26229        }
26230        length = 1;
26231        buf[0] = c;
26232        bufpt = buf;
26233        break;
26234      case etSTRING:
26235      case etDYNSTRING:
26236        if( bArgList ){
26237          bufpt = getTextArg(pArgList);
26238          xtype = etSTRING;
26239        }else{
26240          bufpt = va_arg(ap,char*);
26241        }
26242        if( bufpt==0 ){
26243          bufpt = "";
26244        }else if( xtype==etDYNSTRING ){
26245          zExtra = bufpt;
26246        }
26247        if( precision>=0 ){
26248          for(length=0; length<precision && bufpt[length]; length++){}
26249        }else{
26250          length = sqlite3Strlen30(bufpt);
26251        }
26252        break;
26253      case etSQLESCAPE:           /* Escape ' characters */
26254      case etSQLESCAPE2:          /* Escape ' and enclose in '...' */
26255      case etSQLESCAPE3: {        /* Escape " characters */
26256        int i, j, k, n, isnull;
26257        int needQuote;
26258        char ch;
26259        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
26260        char *escarg;
26261
26262        if( bArgList ){
26263          escarg = getTextArg(pArgList);
26264        }else{
26265          escarg = va_arg(ap,char*);
26266        }
26267        isnull = escarg==0;
26268        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
26269        k = precision;
26270        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
26271          if( ch==q )  n++;
26272        }
26273        needQuote = !isnull && xtype==etSQLESCAPE2;
26274        n += i + 3;
26275        if( n>etBUFSIZE ){
26276          bufpt = zExtra = sqlite3Malloc( n );
26277          if( bufpt==0 ){
26278            setStrAccumError(pAccum, STRACCUM_NOMEM);
26279            return;
26280          }
26281        }else{
26282          bufpt = buf;
26283        }
26284        j = 0;
26285        if( needQuote ) bufpt[j++] = q;
26286        k = i;
26287        for(i=0; i<k; i++){
26288          bufpt[j++] = ch = escarg[i];
26289          if( ch==q ) bufpt[j++] = ch;
26290        }
26291        if( needQuote ) bufpt[j++] = q;
26292        bufpt[j] = 0;
26293        length = j;
26294        /* The precision in %q and %Q means how many input characters to
26295        ** consume, not the length of the output...
26296        ** if( precision>=0 && precision<length ) length = precision; */
26297        break;
26298      }
26299      case etTOKEN: {
26300        Token *pToken;
26301        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
26302        pToken = va_arg(ap, Token*);
26303        assert( bArgList==0 );
26304        if( pToken && pToken->n ){
26305          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
26306        }
26307        length = width = 0;
26308        break;
26309      }
26310      case etSRCLIST: {
26311        SrcList *pSrc;
26312        int k;
26313        struct SrcList_item *pItem;
26314        if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
26315        pSrc = va_arg(ap, SrcList*);
26316        k = va_arg(ap, int);
26317        pItem = &pSrc->a[k];
26318        assert( bArgList==0 );
26319        assert( k>=0 && k<pSrc->nSrc );
26320        if( pItem->zDatabase ){
26321          sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
26322          sqlite3StrAccumAppend(pAccum, ".", 1);
26323        }
26324        sqlite3StrAccumAppendAll(pAccum, pItem->zName);
26325        length = width = 0;
26326        break;
26327      }
26328      default: {
26329        assert( xtype==etINVALID );
26330        return;
26331      }
26332    }/* End switch over the format type */
26333    /*
26334    ** The text of the conversion is pointed to by "bufpt" and is
26335    ** "length" characters long.  The field width is "width".  Do
26336    ** the output.
26337    */
26338    width -= length;
26339    if( width>0 ){
26340      if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
26341      sqlite3StrAccumAppend(pAccum, bufpt, length);
26342      if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
26343    }else{
26344      sqlite3StrAccumAppend(pAccum, bufpt, length);
26345    }
26346
26347    if( zExtra ){
26348      sqlite3DbFree(pAccum->db, zExtra);
26349      zExtra = 0;
26350    }
26351  }/* End for loop over the format string */
26352} /* End of function */
26353
26354/*
26355** Enlarge the memory allocation on a StrAccum object so that it is
26356** able to accept at least N more bytes of text.
26357**
26358** Return the number of bytes of text that StrAccum is able to accept
26359** after the attempted enlargement.  The value returned might be zero.
26360*/
26361static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
26362  char *zNew;
26363  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
26364  if( p->accError ){
26365    testcase(p->accError==STRACCUM_TOOBIG);
26366    testcase(p->accError==STRACCUM_NOMEM);
26367    return 0;
26368  }
26369  if( p->mxAlloc==0 ){
26370    N = p->nAlloc - p->nChar - 1;
26371    setStrAccumError(p, STRACCUM_TOOBIG);
26372    return N;
26373  }else{
26374    char *zOld = isMalloced(p) ? p->zText : 0;
26375    i64 szNew = p->nChar;
26376    assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
26377    szNew += N + 1;
26378    if( szNew+p->nChar<=p->mxAlloc ){
26379      /* Force exponential buffer size growth as long as it does not overflow,
26380      ** to avoid having to call this routine too often */
26381      szNew += p->nChar;
26382    }
26383    if( szNew > p->mxAlloc ){
26384      sqlite3StrAccumReset(p);
26385      setStrAccumError(p, STRACCUM_TOOBIG);
26386      return 0;
26387    }else{
26388      p->nAlloc = (int)szNew;
26389    }
26390    if( p->db ){
26391      zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
26392    }else{
26393      zNew = sqlite3_realloc64(zOld, p->nAlloc);
26394    }
26395    if( zNew ){
26396      assert( p->zText!=0 || p->nChar==0 );
26397      if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
26398      p->zText = zNew;
26399      p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
26400      p->printfFlags |= SQLITE_PRINTF_MALLOCED;
26401    }else{
26402      sqlite3StrAccumReset(p);
26403      setStrAccumError(p, STRACCUM_NOMEM);
26404      return 0;
26405    }
26406  }
26407  return N;
26408}
26409
26410/*
26411** Append N copies of character c to the given string buffer.
26412*/
26413SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
26414  testcase( p->nChar + (i64)N > 0x7fffffff );
26415  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
26416    return;
26417  }
26418  assert( (p->zText==p->zBase)==!isMalloced(p) );
26419  while( (N--)>0 ) p->zText[p->nChar++] = c;
26420}
26421
26422/*
26423** The StrAccum "p" is not large enough to accept N new bytes of z[].
26424** So enlarge if first, then do the append.
26425**
26426** This is a helper routine to sqlite3StrAccumAppend() that does special-case
26427** work (enlarging the buffer) using tail recursion, so that the
26428** sqlite3StrAccumAppend() routine can use fast calling semantics.
26429*/
26430static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
26431  N = sqlite3StrAccumEnlarge(p, N);
26432  if( N>0 ){
26433    memcpy(&p->zText[p->nChar], z, N);
26434    p->nChar += N;
26435  }
26436  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
26437}
26438
26439/*
26440** Append N bytes of text from z to the StrAccum object.  Increase the
26441** size of the memory allocation for StrAccum if necessary.
26442*/
26443SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
26444  assert( z!=0 || N==0 );
26445  assert( p->zText!=0 || p->nChar==0 || p->accError );
26446  assert( N>=0 );
26447  assert( p->accError==0 || p->nAlloc==0 );
26448  if( p->nChar+N >= p->nAlloc ){
26449    enlargeAndAppend(p,z,N);
26450  }else if( N ){
26451    assert( p->zText );
26452    p->nChar += N;
26453    memcpy(&p->zText[p->nChar-N], z, N);
26454  }
26455}
26456
26457/*
26458** Append the complete text of zero-terminated string z[] to the p string.
26459*/
26460SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
26461  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
26462}
26463
26464
26465/*
26466** Finish off a string by making sure it is zero-terminated.
26467** Return a pointer to the resulting string.  Return a NULL
26468** pointer if any kind of error was encountered.
26469*/
26470static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
26471  assert( p->mxAlloc>0 && !isMalloced(p) );
26472  p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
26473  if( p->zText ){
26474    memcpy(p->zText, p->zBase, p->nChar+1);
26475    p->printfFlags |= SQLITE_PRINTF_MALLOCED;
26476  }else{
26477    setStrAccumError(p, STRACCUM_NOMEM);
26478  }
26479  return p->zText;
26480}
26481SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
26482  if( p->zText ){
26483    assert( (p->zText==p->zBase)==!isMalloced(p) );
26484    p->zText[p->nChar] = 0;
26485    if( p->mxAlloc>0 && !isMalloced(p) ){
26486      return strAccumFinishRealloc(p);
26487    }
26488  }
26489  return p->zText;
26490}
26491
26492/*
26493** Reset an StrAccum string.  Reclaim all malloced memory.
26494*/
26495SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
26496  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
26497  if( isMalloced(p) ){
26498    sqlite3DbFree(p->db, p->zText);
26499    p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
26500  }
26501  p->zText = 0;
26502}
26503
26504/*
26505** Initialize a string accumulator.
26506**
26507** p:     The accumulator to be initialized.
26508** db:    Pointer to a database connection.  May be NULL.  Lookaside
26509**        memory is used if not NULL. db->mallocFailed is set appropriately
26510**        when not NULL.
26511** zBase: An initial buffer.  May be NULL in which case the initial buffer
26512**        is malloced.
26513** n:     Size of zBase in bytes.  If total space requirements never exceed
26514**        n then no memory allocations ever occur.
26515** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
26516**        allocations will ever occur.
26517*/
26518SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
26519  p->zText = p->zBase = zBase;
26520  p->db = db;
26521  p->nChar = 0;
26522  p->nAlloc = n;
26523  p->mxAlloc = mx;
26524  p->accError = 0;
26525  p->printfFlags = 0;
26526}
26527
26528/*
26529** Print into memory obtained from sqliteMalloc().  Use the internal
26530** %-conversion extensions.
26531*/
26532SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
26533  char *z;
26534  char zBase[SQLITE_PRINT_BUF_SIZE];
26535  StrAccum acc;
26536  assert( db!=0 );
26537  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
26538                      db->aLimit[SQLITE_LIMIT_LENGTH]);
26539  acc.printfFlags = SQLITE_PRINTF_INTERNAL;
26540  sqlite3VXPrintf(&acc, zFormat, ap);
26541  z = sqlite3StrAccumFinish(&acc);
26542  if( acc.accError==STRACCUM_NOMEM ){
26543    sqlite3OomFault(db);
26544  }
26545  return z;
26546}
26547
26548/*
26549** Print into memory obtained from sqliteMalloc().  Use the internal
26550** %-conversion extensions.
26551*/
26552SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
26553  va_list ap;
26554  char *z;
26555  va_start(ap, zFormat);
26556  z = sqlite3VMPrintf(db, zFormat, ap);
26557  va_end(ap);
26558  return z;
26559}
26560
26561/*
26562** Print into memory obtained from sqlite3_malloc().  Omit the internal
26563** %-conversion extensions.
26564*/
26565SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
26566  char *z;
26567  char zBase[SQLITE_PRINT_BUF_SIZE];
26568  StrAccum acc;
26569
26570#ifdef SQLITE_ENABLE_API_ARMOR
26571  if( zFormat==0 ){
26572    (void)SQLITE_MISUSE_BKPT;
26573    return 0;
26574  }
26575#endif
26576#ifndef SQLITE_OMIT_AUTOINIT
26577  if( sqlite3_initialize() ) return 0;
26578#endif
26579  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
26580  sqlite3VXPrintf(&acc, zFormat, ap);
26581  z = sqlite3StrAccumFinish(&acc);
26582  return z;
26583}
26584
26585/*
26586** Print into memory obtained from sqlite3_malloc()().  Omit the internal
26587** %-conversion extensions.
26588*/
26589SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
26590  va_list ap;
26591  char *z;
26592#ifndef SQLITE_OMIT_AUTOINIT
26593  if( sqlite3_initialize() ) return 0;
26594#endif
26595  va_start(ap, zFormat);
26596  z = sqlite3_vmprintf(zFormat, ap);
26597  va_end(ap);
26598  return z;
26599}
26600
26601/*
26602** sqlite3_snprintf() works like snprintf() except that it ignores the
26603** current locale settings.  This is important for SQLite because we
26604** are not able to use a "," as the decimal point in place of "." as
26605** specified by some locales.
26606**
26607** Oops:  The first two arguments of sqlite3_snprintf() are backwards
26608** from the snprintf() standard.  Unfortunately, it is too late to change
26609** this without breaking compatibility, so we just have to live with the
26610** mistake.
26611**
26612** sqlite3_vsnprintf() is the varargs version.
26613*/
26614SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
26615  StrAccum acc;
26616  if( n<=0 ) return zBuf;
26617#ifdef SQLITE_ENABLE_API_ARMOR
26618  if( zBuf==0 || zFormat==0 ) {
26619    (void)SQLITE_MISUSE_BKPT;
26620    if( zBuf ) zBuf[0] = 0;
26621    return zBuf;
26622  }
26623#endif
26624  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
26625  sqlite3VXPrintf(&acc, zFormat, ap);
26626  zBuf[acc.nChar] = 0;
26627  return zBuf;
26628}
26629SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
26630  char *z;
26631  va_list ap;
26632  va_start(ap,zFormat);
26633  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
26634  va_end(ap);
26635  return z;
26636}
26637
26638/*
26639** This is the routine that actually formats the sqlite3_log() message.
26640** We house it in a separate routine from sqlite3_log() to avoid using
26641** stack space on small-stack systems when logging is disabled.
26642**
26643** sqlite3_log() must render into a static buffer.  It cannot dynamically
26644** allocate memory because it might be called while the memory allocator
26645** mutex is held.
26646**
26647** sqlite3VXPrintf() might ask for *temporary* memory allocations for
26648** certain format characters (%q) or for very large precisions or widths.
26649** Care must be taken that any sqlite3_log() calls that occur while the
26650** memory mutex is held do not use these mechanisms.
26651*/
26652static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
26653  StrAccum acc;                          /* String accumulator */
26654  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
26655
26656  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
26657  sqlite3VXPrintf(&acc, zFormat, ap);
26658  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
26659                           sqlite3StrAccumFinish(&acc));
26660}
26661
26662/*
26663** Format and write a message to the log if logging is enabled.
26664*/
26665SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
26666  va_list ap;                             /* Vararg list */
26667  if( sqlite3GlobalConfig.xLog ){
26668    va_start(ap, zFormat);
26669    renderLogMsg(iErrCode, zFormat, ap);
26670    va_end(ap);
26671  }
26672}
26673
26674#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
26675/*
26676** A version of printf() that understands %lld.  Used for debugging.
26677** The printf() built into some versions of windows does not understand %lld
26678** and segfaults if you give it a long long int.
26679*/
26680SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
26681  va_list ap;
26682  StrAccum acc;
26683  char zBuf[500];
26684  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
26685  va_start(ap,zFormat);
26686  sqlite3VXPrintf(&acc, zFormat, ap);
26687  va_end(ap);
26688  sqlite3StrAccumFinish(&acc);
26689  fprintf(stdout,"%s", zBuf);
26690  fflush(stdout);
26691}
26692#endif
26693
26694
26695/*
26696** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
26697** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
26698*/
26699SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
26700  va_list ap;
26701  va_start(ap,zFormat);
26702  sqlite3VXPrintf(p, zFormat, ap);
26703  va_end(ap);
26704}
26705
26706/************** End of printf.c **********************************************/
26707/************** Begin file treeview.c ****************************************/
26708/*
26709** 2015-06-08
26710**
26711** The author disclaims copyright to this source code.  In place of
26712** a legal notice, here is a blessing:
26713**
26714**    May you do good and not evil.
26715**    May you find forgiveness for yourself and forgive others.
26716**    May you share freely, never taking more than you give.
26717**
26718*************************************************************************
26719**
26720** This file contains C code to implement the TreeView debugging routines.
26721** These routines print a parse tree to standard output for debugging and
26722** analysis.
26723**
26724** The interfaces in this file is only available when compiling
26725** with SQLITE_DEBUG.
26726*/
26727/* #include "sqliteInt.h" */
26728#ifdef SQLITE_DEBUG
26729
26730/*
26731** Add a new subitem to the tree.  The moreToFollow flag indicates that this
26732** is not the last item in the tree.
26733*/
26734static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
26735  if( p==0 ){
26736    p = sqlite3_malloc64( sizeof(*p) );
26737    if( p==0 ) return 0;
26738    memset(p, 0, sizeof(*p));
26739  }else{
26740    p->iLevel++;
26741  }
26742  assert( moreToFollow==0 || moreToFollow==1 );
26743  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
26744  return p;
26745}
26746
26747/*
26748** Finished with one layer of the tree
26749*/
26750static void sqlite3TreeViewPop(TreeView *p){
26751  if( p==0 ) return;
26752  p->iLevel--;
26753  if( p->iLevel<0 ) sqlite3_free(p);
26754}
26755
26756/*
26757** Generate a single line of output for the tree, with a prefix that contains
26758** all the appropriate tree lines
26759*/
26760static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
26761  va_list ap;
26762  int i;
26763  StrAccum acc;
26764  char zBuf[500];
26765  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
26766  if( p ){
26767    for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
26768      sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
26769    }
26770    sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
26771  }
26772  va_start(ap, zFormat);
26773  sqlite3VXPrintf(&acc, zFormat, ap);
26774  va_end(ap);
26775  assert( acc.nChar>0 );
26776  if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
26777  sqlite3StrAccumFinish(&acc);
26778  fprintf(stdout,"%s", zBuf);
26779  fflush(stdout);
26780}
26781
26782/*
26783** Shorthand for starting a new tree item that consists of a single label
26784*/
26785static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
26786  p = sqlite3TreeViewPush(p, moreFollows);
26787  sqlite3TreeViewLine(p, "%s", zLabel);
26788}
26789
26790/*
26791** Generate a human-readable description of a WITH clause.
26792*/
26793SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
26794  int i;
26795  if( pWith==0 ) return;
26796  if( pWith->nCte==0 ) return;
26797  if( pWith->pOuter ){
26798    sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
26799  }else{
26800    sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
26801  }
26802  if( pWith->nCte>0 ){
26803    pView = sqlite3TreeViewPush(pView, 1);
26804    for(i=0; i<pWith->nCte; i++){
26805      StrAccum x;
26806      char zLine[1000];
26807      const struct Cte *pCte = &pWith->a[i];
26808      sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
26809      sqlite3XPrintf(&x, "%s", pCte->zName);
26810      if( pCte->pCols && pCte->pCols->nExpr>0 ){
26811        char cSep = '(';
26812        int j;
26813        for(j=0; j<pCte->pCols->nExpr; j++){
26814          sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
26815          cSep = ',';
26816        }
26817        sqlite3XPrintf(&x, ")");
26818      }
26819      sqlite3XPrintf(&x, " AS");
26820      sqlite3StrAccumFinish(&x);
26821      sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
26822      sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
26823      sqlite3TreeViewPop(pView);
26824    }
26825    sqlite3TreeViewPop(pView);
26826  }
26827}
26828
26829
26830/*
26831** Generate a human-readable description of a Select object.
26832*/
26833SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
26834  int n = 0;
26835  int cnt = 0;
26836  if( p==0 ){
26837    sqlite3TreeViewLine(pView, "nil-SELECT");
26838    return;
26839  }
26840  pView = sqlite3TreeViewPush(pView, moreToFollow);
26841  if( p->pWith ){
26842    sqlite3TreeViewWith(pView, p->pWith, 1);
26843    cnt = 1;
26844    sqlite3TreeViewPush(pView, 1);
26845  }
26846  do{
26847    sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
26848      ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
26849      ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
26850      (int)p->nSelectRow
26851    );
26852    if( cnt++ ) sqlite3TreeViewPop(pView);
26853    if( p->pPrior ){
26854      n = 1000;
26855    }else{
26856      n = 0;
26857      if( p->pSrc && p->pSrc->nSrc ) n++;
26858      if( p->pWhere ) n++;
26859      if( p->pGroupBy ) n++;
26860      if( p->pHaving ) n++;
26861      if( p->pOrderBy ) n++;
26862      if( p->pLimit ) n++;
26863      if( p->pOffset ) n++;
26864    }
26865    sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
26866    if( p->pSrc && p->pSrc->nSrc ){
26867      int i;
26868      pView = sqlite3TreeViewPush(pView, (n--)>0);
26869      sqlite3TreeViewLine(pView, "FROM");
26870      for(i=0; i<p->pSrc->nSrc; i++){
26871        struct SrcList_item *pItem = &p->pSrc->a[i];
26872        StrAccum x;
26873        char zLine[100];
26874        sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
26875        sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
26876        if( pItem->zDatabase ){
26877          sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
26878        }else if( pItem->zName ){
26879          sqlite3XPrintf(&x, " %s", pItem->zName);
26880        }
26881        if( pItem->pTab ){
26882          sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
26883        }
26884        if( pItem->zAlias ){
26885          sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
26886        }
26887        if( pItem->fg.jointype & JT_LEFT ){
26888          sqlite3XPrintf(&x, " LEFT-JOIN");
26889        }
26890        sqlite3StrAccumFinish(&x);
26891        sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
26892        if( pItem->pSelect ){
26893          sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
26894        }
26895        if( pItem->fg.isTabFunc ){
26896          sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
26897        }
26898        sqlite3TreeViewPop(pView);
26899      }
26900      sqlite3TreeViewPop(pView);
26901    }
26902    if( p->pWhere ){
26903      sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
26904      sqlite3TreeViewExpr(pView, p->pWhere, 0);
26905      sqlite3TreeViewPop(pView);
26906    }
26907    if( p->pGroupBy ){
26908      sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
26909    }
26910    if( p->pHaving ){
26911      sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
26912      sqlite3TreeViewExpr(pView, p->pHaving, 0);
26913      sqlite3TreeViewPop(pView);
26914    }
26915    if( p->pOrderBy ){
26916      sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
26917    }
26918    if( p->pLimit ){
26919      sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
26920      sqlite3TreeViewExpr(pView, p->pLimit, 0);
26921      sqlite3TreeViewPop(pView);
26922    }
26923    if( p->pOffset ){
26924      sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
26925      sqlite3TreeViewExpr(pView, p->pOffset, 0);
26926      sqlite3TreeViewPop(pView);
26927    }
26928    if( p->pPrior ){
26929      const char *zOp = "UNION";
26930      switch( p->op ){
26931        case TK_ALL:         zOp = "UNION ALL";  break;
26932        case TK_INTERSECT:   zOp = "INTERSECT";  break;
26933        case TK_EXCEPT:      zOp = "EXCEPT";     break;
26934      }
26935      sqlite3TreeViewItem(pView, zOp, 1);
26936    }
26937    p = p->pPrior;
26938  }while( p!=0 );
26939  sqlite3TreeViewPop(pView);
26940}
26941
26942/*
26943** Generate a human-readable explanation of an expression tree.
26944*/
26945SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
26946  const char *zBinOp = 0;   /* Binary operator */
26947  const char *zUniOp = 0;   /* Unary operator */
26948  char zFlgs[60];
26949  pView = sqlite3TreeViewPush(pView, moreToFollow);
26950  if( pExpr==0 ){
26951    sqlite3TreeViewLine(pView, "nil");
26952    sqlite3TreeViewPop(pView);
26953    return;
26954  }
26955  if( pExpr->flags ){
26956    if( ExprHasProperty(pExpr, EP_FromJoin) ){
26957      sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x iRJT=%d",
26958                       pExpr->flags, pExpr->iRightJoinTable);
26959    }else{
26960      sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x",pExpr->flags);
26961    }
26962  }else{
26963    zFlgs[0] = 0;
26964  }
26965  switch( pExpr->op ){
26966    case TK_AGG_COLUMN: {
26967      sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
26968            pExpr->iTable, pExpr->iColumn, zFlgs);
26969      break;
26970    }
26971    case TK_COLUMN: {
26972      if( pExpr->iTable<0 ){
26973        /* This only happens when coding check constraints */
26974        sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
26975      }else{
26976        sqlite3TreeViewLine(pView, "{%d:%d}%s",
26977                             pExpr->iTable, pExpr->iColumn, zFlgs);
26978      }
26979      break;
26980    }
26981    case TK_INTEGER: {
26982      if( pExpr->flags & EP_IntValue ){
26983        sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
26984      }else{
26985        sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
26986      }
26987      break;
26988    }
26989#ifndef SQLITE_OMIT_FLOATING_POINT
26990    case TK_FLOAT: {
26991      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26992      break;
26993    }
26994#endif
26995    case TK_STRING: {
26996      sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
26997      break;
26998    }
26999    case TK_NULL: {
27000      sqlite3TreeViewLine(pView,"NULL");
27001      break;
27002    }
27003#ifndef SQLITE_OMIT_BLOB_LITERAL
27004    case TK_BLOB: {
27005      sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
27006      break;
27007    }
27008#endif
27009    case TK_VARIABLE: {
27010      sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
27011                          pExpr->u.zToken, pExpr->iColumn);
27012      break;
27013    }
27014    case TK_REGISTER: {
27015      sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
27016      break;
27017    }
27018    case TK_ID: {
27019      sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
27020      break;
27021    }
27022#ifndef SQLITE_OMIT_CAST
27023    case TK_CAST: {
27024      /* Expressions of the form:   CAST(pLeft AS token) */
27025      sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
27026      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27027      break;
27028    }
27029#endif /* SQLITE_OMIT_CAST */
27030    case TK_LT:      zBinOp = "LT";     break;
27031    case TK_LE:      zBinOp = "LE";     break;
27032    case TK_GT:      zBinOp = "GT";     break;
27033    case TK_GE:      zBinOp = "GE";     break;
27034    case TK_NE:      zBinOp = "NE";     break;
27035    case TK_EQ:      zBinOp = "EQ";     break;
27036    case TK_IS:      zBinOp = "IS";     break;
27037    case TK_ISNOT:   zBinOp = "ISNOT";  break;
27038    case TK_AND:     zBinOp = "AND";    break;
27039    case TK_OR:      zBinOp = "OR";     break;
27040    case TK_PLUS:    zBinOp = "ADD";    break;
27041    case TK_STAR:    zBinOp = "MUL";    break;
27042    case TK_MINUS:   zBinOp = "SUB";    break;
27043    case TK_REM:     zBinOp = "REM";    break;
27044    case TK_BITAND:  zBinOp = "BITAND"; break;
27045    case TK_BITOR:   zBinOp = "BITOR";  break;
27046    case TK_SLASH:   zBinOp = "DIV";    break;
27047    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
27048    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
27049    case TK_CONCAT:  zBinOp = "CONCAT"; break;
27050    case TK_DOT:     zBinOp = "DOT";    break;
27051
27052    case TK_UMINUS:  zUniOp = "UMINUS"; break;
27053    case TK_UPLUS:   zUniOp = "UPLUS";  break;
27054    case TK_BITNOT:  zUniOp = "BITNOT"; break;
27055    case TK_NOT:     zUniOp = "NOT";    break;
27056    case TK_ISNULL:  zUniOp = "ISNULL"; break;
27057    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
27058
27059    case TK_SPAN: {
27060      sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
27061      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27062      break;
27063    }
27064
27065    case TK_COLLATE: {
27066      sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
27067      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27068      break;
27069    }
27070
27071    case TK_AGG_FUNCTION:
27072    case TK_FUNCTION: {
27073      ExprList *pFarg;       /* List of function arguments */
27074      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
27075        pFarg = 0;
27076      }else{
27077        pFarg = pExpr->x.pList;
27078      }
27079      if( pExpr->op==TK_AGG_FUNCTION ){
27080        sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
27081                             pExpr->op2, pExpr->u.zToken);
27082      }else{
27083        sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
27084      }
27085      if( pFarg ){
27086        sqlite3TreeViewExprList(pView, pFarg, 0, 0);
27087      }
27088      break;
27089    }
27090#ifndef SQLITE_OMIT_SUBQUERY
27091    case TK_EXISTS: {
27092      sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
27093      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
27094      break;
27095    }
27096    case TK_SELECT: {
27097      sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
27098      sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
27099      break;
27100    }
27101    case TK_IN: {
27102      sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
27103      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
27104      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
27105        sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
27106      }else{
27107        sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
27108      }
27109      break;
27110    }
27111#endif /* SQLITE_OMIT_SUBQUERY */
27112
27113    /*
27114    **    x BETWEEN y AND z
27115    **
27116    ** This is equivalent to
27117    **
27118    **    x>=y AND x<=z
27119    **
27120    ** X is stored in pExpr->pLeft.
27121    ** Y is stored in pExpr->pList->a[0].pExpr.
27122    ** Z is stored in pExpr->pList->a[1].pExpr.
27123    */
27124    case TK_BETWEEN: {
27125      Expr *pX = pExpr->pLeft;
27126      Expr *pY = pExpr->x.pList->a[0].pExpr;
27127      Expr *pZ = pExpr->x.pList->a[1].pExpr;
27128      sqlite3TreeViewLine(pView, "BETWEEN");
27129      sqlite3TreeViewExpr(pView, pX, 1);
27130      sqlite3TreeViewExpr(pView, pY, 1);
27131      sqlite3TreeViewExpr(pView, pZ, 0);
27132      break;
27133    }
27134    case TK_TRIGGER: {
27135      /* If the opcode is TK_TRIGGER, then the expression is a reference
27136      ** to a column in the new.* or old.* pseudo-tables available to
27137      ** trigger programs. In this case Expr.iTable is set to 1 for the
27138      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
27139      ** is set to the column of the pseudo-table to read, or to -1 to
27140      ** read the rowid field.
27141      */
27142      sqlite3TreeViewLine(pView, "%s(%d)",
27143          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
27144      break;
27145    }
27146    case TK_CASE: {
27147      sqlite3TreeViewLine(pView, "CASE");
27148      sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
27149      sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
27150      break;
27151    }
27152#ifndef SQLITE_OMIT_TRIGGER
27153    case TK_RAISE: {
27154      const char *zType = "unk";
27155      switch( pExpr->affinity ){
27156        case OE_Rollback:   zType = "rollback";  break;
27157        case OE_Abort:      zType = "abort";     break;
27158        case OE_Fail:       zType = "fail";      break;
27159        case OE_Ignore:     zType = "ignore";    break;
27160      }
27161      sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
27162      break;
27163    }
27164#endif
27165    case TK_MATCH: {
27166      sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
27167                          pExpr->iTable, pExpr->iColumn, zFlgs);
27168      sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
27169      break;
27170    }
27171    case TK_VECTOR: {
27172      sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
27173      break;
27174    }
27175    case TK_SELECT_COLUMN: {
27176      sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
27177      sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
27178      break;
27179    }
27180    case TK_IF_NULL_ROW: {
27181      sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
27182      sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27183      break;
27184    }
27185    default: {
27186      sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
27187      break;
27188    }
27189  }
27190  if( zBinOp ){
27191    sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
27192    sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
27193    sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
27194  }else if( zUniOp ){
27195    sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
27196    sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
27197  }
27198  sqlite3TreeViewPop(pView);
27199}
27200
27201
27202/*
27203** Generate a human-readable explanation of an expression list.
27204*/
27205SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
27206  TreeView *pView,
27207  const ExprList *pList,
27208  const char *zLabel
27209){
27210  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
27211  if( pList==0 ){
27212    sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
27213  }else{
27214    int i;
27215    sqlite3TreeViewLine(pView, "%s", zLabel);
27216    for(i=0; i<pList->nExpr; i++){
27217      int j = pList->a[i].u.x.iOrderByCol;
27218      if( j ){
27219        sqlite3TreeViewPush(pView, 0);
27220        sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
27221      }
27222      sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
27223      if( j ) sqlite3TreeViewPop(pView);
27224    }
27225  }
27226}
27227SQLITE_PRIVATE void sqlite3TreeViewExprList(
27228  TreeView *pView,
27229  const ExprList *pList,
27230  u8 moreToFollow,
27231  const char *zLabel
27232){
27233  pView = sqlite3TreeViewPush(pView, moreToFollow);
27234  sqlite3TreeViewBareExprList(pView, pList, zLabel);
27235  sqlite3TreeViewPop(pView);
27236}
27237
27238#endif /* SQLITE_DEBUG */
27239
27240/************** End of treeview.c ********************************************/
27241/************** Begin file random.c ******************************************/
27242/*
27243** 2001 September 15
27244**
27245** The author disclaims copyright to this source code.  In place of
27246** a legal notice, here is a blessing:
27247**
27248**    May you do good and not evil.
27249**    May you find forgiveness for yourself and forgive others.
27250**    May you share freely, never taking more than you give.
27251**
27252*************************************************************************
27253** This file contains code to implement a pseudo-random number
27254** generator (PRNG) for SQLite.
27255**
27256** Random numbers are used by some of the database backends in order
27257** to generate random integer keys for tables or random filenames.
27258*/
27259/* #include "sqliteInt.h" */
27260
27261
27262/* All threads share a single random number generator.
27263** This structure is the current state of the generator.
27264*/
27265static SQLITE_WSD struct sqlite3PrngType {
27266  unsigned char isInit;          /* True if initialized */
27267  unsigned char i, j;            /* State variables */
27268  unsigned char s[256];          /* State variables */
27269} sqlite3Prng;
27270
27271/*
27272** Return N random bytes.
27273*/
27274SQLITE_API void sqlite3_randomness(int N, void *pBuf){
27275  unsigned char t;
27276  unsigned char *zBuf = pBuf;
27277
27278  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
27279  ** state vector.  If writable static data is unsupported on the target,
27280  ** we have to locate the state vector at run-time.  In the more common
27281  ** case where writable static data is supported, wsdPrng can refer directly
27282  ** to the "sqlite3Prng" state vector declared above.
27283  */
27284#ifdef SQLITE_OMIT_WSD
27285  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
27286# define wsdPrng p[0]
27287#else
27288# define wsdPrng sqlite3Prng
27289#endif
27290
27291#if SQLITE_THREADSAFE
27292  sqlite3_mutex *mutex;
27293#endif
27294
27295#ifndef SQLITE_OMIT_AUTOINIT
27296  if( sqlite3_initialize() ) return;
27297#endif
27298
27299#if SQLITE_THREADSAFE
27300  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
27301#endif
27302
27303  sqlite3_mutex_enter(mutex);
27304  if( N<=0 || pBuf==0 ){
27305    wsdPrng.isInit = 0;
27306    sqlite3_mutex_leave(mutex);
27307    return;
27308  }
27309
27310  /* Initialize the state of the random number generator once,
27311  ** the first time this routine is called.  The seed value does
27312  ** not need to contain a lot of randomness since we are not
27313  ** trying to do secure encryption or anything like that...
27314  **
27315  ** Nothing in this file or anywhere else in SQLite does any kind of
27316  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
27317  ** number generator) not as an encryption device.
27318  */
27319  if( !wsdPrng.isInit ){
27320    int i;
27321    char k[256];
27322    wsdPrng.j = 0;
27323    wsdPrng.i = 0;
27324    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
27325    for(i=0; i<256; i++){
27326      wsdPrng.s[i] = (u8)i;
27327    }
27328    for(i=0; i<256; i++){
27329      wsdPrng.j += wsdPrng.s[i] + k[i];
27330      t = wsdPrng.s[wsdPrng.j];
27331      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
27332      wsdPrng.s[i] = t;
27333    }
27334    wsdPrng.isInit = 1;
27335  }
27336
27337  assert( N>0 );
27338  do{
27339    wsdPrng.i++;
27340    t = wsdPrng.s[wsdPrng.i];
27341    wsdPrng.j += t;
27342    wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
27343    wsdPrng.s[wsdPrng.j] = t;
27344    t += wsdPrng.s[wsdPrng.i];
27345    *(zBuf++) = wsdPrng.s[t];
27346  }while( --N );
27347  sqlite3_mutex_leave(mutex);
27348}
27349
27350#ifndef SQLITE_UNTESTABLE
27351/*
27352** For testing purposes, we sometimes want to preserve the state of
27353** PRNG and restore the PRNG to its saved state at a later time, or
27354** to reset the PRNG to its initial state.  These routines accomplish
27355** those tasks.
27356**
27357** The sqlite3_test_control() interface calls these routines to
27358** control the PRNG.
27359*/
27360static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
27361SQLITE_PRIVATE void sqlite3PrngSaveState(void){
27362  memcpy(
27363    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
27364    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
27365    sizeof(sqlite3Prng)
27366  );
27367}
27368SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
27369  memcpy(
27370    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
27371    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
27372    sizeof(sqlite3Prng)
27373  );
27374}
27375#endif /* SQLITE_UNTESTABLE */
27376
27377/************** End of random.c **********************************************/
27378/************** Begin file threads.c *****************************************/
27379/*
27380** 2012 July 21
27381**
27382** The author disclaims copyright to this source code.  In place of
27383** a legal notice, here is a blessing:
27384**
27385**    May you do good and not evil.
27386**    May you find forgiveness for yourself and forgive others.
27387**    May you share freely, never taking more than you give.
27388**
27389******************************************************************************
27390**
27391** This file presents a simple cross-platform threading interface for
27392** use internally by SQLite.
27393**
27394** A "thread" can be created using sqlite3ThreadCreate().  This thread
27395** runs independently of its creator until it is joined using
27396** sqlite3ThreadJoin(), at which point it terminates.
27397**
27398** Threads do not have to be real.  It could be that the work of the
27399** "thread" is done by the main thread at either the sqlite3ThreadCreate()
27400** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
27401** single threaded systems.  Nothing in SQLite requires multiple threads.
27402** This interface exists so that applications that want to take advantage
27403** of multiple cores can do so, while also allowing applications to stay
27404** single-threaded if desired.
27405*/
27406/* #include "sqliteInt.h" */
27407#if SQLITE_OS_WIN
27408/* #  include "os_win.h" */
27409#endif
27410
27411#if SQLITE_MAX_WORKER_THREADS>0
27412
27413/********************************* Unix Pthreads ****************************/
27414#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
27415
27416#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
27417/* #include <pthread.h> */
27418
27419/* A running thread */
27420struct SQLiteThread {
27421  pthread_t tid;                 /* Thread ID */
27422  int done;                      /* Set to true when thread finishes */
27423  void *pOut;                    /* Result returned by the thread */
27424  void *(*xTask)(void*);         /* The thread routine */
27425  void *pIn;                     /* Argument to the thread */
27426};
27427
27428/* Create a new thread */
27429SQLITE_PRIVATE int sqlite3ThreadCreate(
27430  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
27431  void *(*xTask)(void*),    /* Routine to run in a separate thread */
27432  void *pIn                 /* Argument passed into xTask() */
27433){
27434  SQLiteThread *p;
27435  int rc;
27436
27437  assert( ppThread!=0 );
27438  assert( xTask!=0 );
27439  /* This routine is never used in single-threaded mode */
27440  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
27441
27442  *ppThread = 0;
27443  p = sqlite3Malloc(sizeof(*p));
27444  if( p==0 ) return SQLITE_NOMEM_BKPT;
27445  memset(p, 0, sizeof(*p));
27446  p->xTask = xTask;
27447  p->pIn = pIn;
27448  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
27449  ** function that returns SQLITE_ERROR when passed the argument 200, that
27450  ** forces worker threads to run sequentially and deterministically
27451  ** for testing purposes. */
27452  if( sqlite3FaultSim(200) ){
27453    rc = 1;
27454  }else{
27455    rc = pthread_create(&p->tid, 0, xTask, pIn);
27456  }
27457  if( rc ){
27458    p->done = 1;
27459    p->pOut = xTask(pIn);
27460  }
27461  *ppThread = p;
27462  return SQLITE_OK;
27463}
27464
27465/* Get the results of the thread */
27466SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
27467  int rc;
27468
27469  assert( ppOut!=0 );
27470  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
27471  if( p->done ){
27472    *ppOut = p->pOut;
27473    rc = SQLITE_OK;
27474  }else{
27475    rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
27476  }
27477  sqlite3_free(p);
27478  return rc;
27479}
27480
27481#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
27482/******************************** End Unix Pthreads *************************/
27483
27484
27485/********************************* Win32 Threads ****************************/
27486#if SQLITE_OS_WIN_THREADS
27487
27488#define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
27489#include <process.h>
27490
27491/* A running thread */
27492struct SQLiteThread {
27493  void *tid;               /* The thread handle */
27494  unsigned id;             /* The thread identifier */
27495  void *(*xTask)(void*);   /* The routine to run as a thread */
27496  void *pIn;               /* Argument to xTask */
27497  void *pResult;           /* Result of xTask */
27498};
27499
27500/* Thread procedure Win32 compatibility shim */
27501static unsigned __stdcall sqlite3ThreadProc(
27502  void *pArg  /* IN: Pointer to the SQLiteThread structure */
27503){
27504  SQLiteThread *p = (SQLiteThread *)pArg;
27505
27506  assert( p!=0 );
27507#if 0
27508  /*
27509  ** This assert appears to trigger spuriously on certain
27510  ** versions of Windows, possibly due to _beginthreadex()
27511  ** and/or CreateThread() not fully setting their thread
27512  ** ID parameter before starting the thread.
27513  */
27514  assert( p->id==GetCurrentThreadId() );
27515#endif
27516  assert( p->xTask!=0 );
27517  p->pResult = p->xTask(p->pIn);
27518
27519  _endthreadex(0);
27520  return 0; /* NOT REACHED */
27521}
27522
27523/* Create a new thread */
27524SQLITE_PRIVATE int sqlite3ThreadCreate(
27525  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
27526  void *(*xTask)(void*),    /* Routine to run in a separate thread */
27527  void *pIn                 /* Argument passed into xTask() */
27528){
27529  SQLiteThread *p;
27530
27531  assert( ppThread!=0 );
27532  assert( xTask!=0 );
27533  *ppThread = 0;
27534  p = sqlite3Malloc(sizeof(*p));
27535  if( p==0 ) return SQLITE_NOMEM_BKPT;
27536  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
27537  ** function that returns SQLITE_ERROR when passed the argument 200, that
27538  ** forces worker threads to run sequentially and deterministically
27539  ** (via the sqlite3FaultSim() term of the conditional) for testing
27540  ** purposes. */
27541  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
27542    memset(p, 0, sizeof(*p));
27543  }else{
27544    p->xTask = xTask;
27545    p->pIn = pIn;
27546    p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
27547    if( p->tid==0 ){
27548      memset(p, 0, sizeof(*p));
27549    }
27550  }
27551  if( p->xTask==0 ){
27552    p->id = GetCurrentThreadId();
27553    p->pResult = xTask(pIn);
27554  }
27555  *ppThread = p;
27556  return SQLITE_OK;
27557}
27558
27559SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
27560
27561/* Get the results of the thread */
27562SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
27563  DWORD rc;
27564  BOOL bRc;
27565
27566  assert( ppOut!=0 );
27567  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
27568  if( p->xTask==0 ){
27569    /* assert( p->id==GetCurrentThreadId() ); */
27570    rc = WAIT_OBJECT_0;
27571    assert( p->tid==0 );
27572  }else{
27573    assert( p->id!=0 && p->id!=GetCurrentThreadId() );
27574    rc = sqlite3Win32Wait((HANDLE)p->tid);
27575    assert( rc!=WAIT_IO_COMPLETION );
27576    bRc = CloseHandle((HANDLE)p->tid);
27577    assert( bRc );
27578  }
27579  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
27580  sqlite3_free(p);
27581  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
27582}
27583
27584#endif /* SQLITE_OS_WIN_THREADS */
27585/******************************** End Win32 Threads *************************/
27586
27587
27588/********************************* Single-Threaded **************************/
27589#ifndef SQLITE_THREADS_IMPLEMENTED
27590/*
27591** This implementation does not actually create a new thread.  It does the
27592** work of the thread in the main thread, when either the thread is created
27593** or when it is joined
27594*/
27595
27596/* A running thread */
27597struct SQLiteThread {
27598  void *(*xTask)(void*);   /* The routine to run as a thread */
27599  void *pIn;               /* Argument to xTask */
27600  void *pResult;           /* Result of xTask */
27601};
27602
27603/* Create a new thread */
27604SQLITE_PRIVATE int sqlite3ThreadCreate(
27605  SQLiteThread **ppThread,  /* OUT: Write the thread object here */
27606  void *(*xTask)(void*),    /* Routine to run in a separate thread */
27607  void *pIn                 /* Argument passed into xTask() */
27608){
27609  SQLiteThread *p;
27610
27611  assert( ppThread!=0 );
27612  assert( xTask!=0 );
27613  *ppThread = 0;
27614  p = sqlite3Malloc(sizeof(*p));
27615  if( p==0 ) return SQLITE_NOMEM_BKPT;
27616  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
27617    p->xTask = xTask;
27618    p->pIn = pIn;
27619  }else{
27620    p->xTask = 0;
27621    p->pResult = xTask(pIn);
27622  }
27623  *ppThread = p;
27624  return SQLITE_OK;
27625}
27626
27627/* Get the results of the thread */
27628SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
27629
27630  assert( ppOut!=0 );
27631  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
27632  if( p->xTask ){
27633    *ppOut = p->xTask(p->pIn);
27634  }else{
27635    *ppOut = p->pResult;
27636  }
27637  sqlite3_free(p);
27638
27639#if defined(SQLITE_TEST)
27640  {
27641    void *pTstAlloc = sqlite3Malloc(10);
27642    if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
27643    sqlite3_free(pTstAlloc);
27644  }
27645#endif
27646
27647  return SQLITE_OK;
27648}
27649
27650#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
27651/****************************** End Single-Threaded *************************/
27652#endif /* SQLITE_MAX_WORKER_THREADS>0 */
27653
27654/************** End of threads.c *********************************************/
27655/************** Begin file utf.c *********************************************/
27656/*
27657** 2004 April 13
27658**
27659** The author disclaims copyright to this source code.  In place of
27660** a legal notice, here is a blessing:
27661**
27662**    May you do good and not evil.
27663**    May you find forgiveness for yourself and forgive others.
27664**    May you share freely, never taking more than you give.
27665**
27666*************************************************************************
27667** This file contains routines used to translate between UTF-8,
27668** UTF-16, UTF-16BE, and UTF-16LE.
27669**
27670** Notes on UTF-8:
27671**
27672**   Byte-0    Byte-1    Byte-2    Byte-3    Value
27673**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
27674**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
27675**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
27676**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
27677**
27678**
27679** Notes on UTF-16:  (with wwww+1==uuuuu)
27680**
27681**      Word-0               Word-1          Value
27682**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
27683**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
27684**
27685**
27686** BOM or Byte Order Mark:
27687**     0xff 0xfe   little-endian utf-16 follows
27688**     0xfe 0xff   big-endian utf-16 follows
27689**
27690*/
27691/* #include "sqliteInt.h" */
27692/* #include <assert.h> */
27693/* #include "vdbeInt.h" */
27694
27695#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
27696/*
27697** The following constant value is used by the SQLITE_BIGENDIAN and
27698** SQLITE_LITTLEENDIAN macros.
27699*/
27700SQLITE_PRIVATE const int sqlite3one = 1;
27701#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
27702
27703/*
27704** This lookup table is used to help decode the first byte of
27705** a multi-byte UTF8 character.
27706*/
27707static const unsigned char sqlite3Utf8Trans1[] = {
27708  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27709  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
27710  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
27711  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
27712  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27713  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
27714  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
27715  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
27716};
27717
27718
27719#define WRITE_UTF8(zOut, c) {                          \
27720  if( c<0x00080 ){                                     \
27721    *zOut++ = (u8)(c&0xFF);                            \
27722  }                                                    \
27723  else if( c<0x00800 ){                                \
27724    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
27725    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
27726  }                                                    \
27727  else if( c<0x10000 ){                                \
27728    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
27729    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
27730    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
27731  }else{                                               \
27732    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
27733    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
27734    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
27735    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
27736  }                                                    \
27737}
27738
27739#define WRITE_UTF16LE(zOut, c) {                                    \
27740  if( c<=0xFFFF ){                                                  \
27741    *zOut++ = (u8)(c&0x00FF);                                       \
27742    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
27743  }else{                                                            \
27744    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
27745    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
27746    *zOut++ = (u8)(c&0x00FF);                                       \
27747    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
27748  }                                                                 \
27749}
27750
27751#define WRITE_UTF16BE(zOut, c) {                                    \
27752  if( c<=0xFFFF ){                                                  \
27753    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
27754    *zOut++ = (u8)(c&0x00FF);                                       \
27755  }else{                                                            \
27756    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
27757    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
27758    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
27759    *zOut++ = (u8)(c&0x00FF);                                       \
27760  }                                                                 \
27761}
27762
27763#define READ_UTF16LE(zIn, TERM, c){                                   \
27764  c = (*zIn++);                                                       \
27765  c += ((*zIn++)<<8);                                                 \
27766  if( c>=0xD800 && c<0xE000 && TERM ){                                \
27767    int c2 = (*zIn++);                                                \
27768    c2 += ((*zIn++)<<8);                                              \
27769    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
27770  }                                                                   \
27771}
27772
27773#define READ_UTF16BE(zIn, TERM, c){                                   \
27774  c = ((*zIn++)<<8);                                                  \
27775  c += (*zIn++);                                                      \
27776  if( c>=0xD800 && c<0xE000 && TERM ){                                \
27777    int c2 = ((*zIn++)<<8);                                           \
27778    c2 += (*zIn++);                                                   \
27779    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
27780  }                                                                   \
27781}
27782
27783/*
27784** Translate a single UTF-8 character.  Return the unicode value.
27785**
27786** During translation, assume that the byte that zTerm points
27787** is a 0x00.
27788**
27789** Write a pointer to the next unread byte back into *pzNext.
27790**
27791** Notes On Invalid UTF-8:
27792**
27793**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
27794**     be encoded as a multi-byte character.  Any multi-byte character that
27795**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
27796**
27797**  *  This routine never allows a UTF16 surrogate value to be encoded.
27798**     If a multi-byte character attempts to encode a value between
27799**     0xd800 and 0xe000 then it is rendered as 0xfffd.
27800**
27801**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
27802**     byte of a character are interpreted as single-byte characters
27803**     and rendered as themselves even though they are technically
27804**     invalid characters.
27805**
27806**  *  This routine accepts over-length UTF8 encodings
27807**     for unicode values 0x80 and greater.  It does not change over-length
27808**     encodings to 0xfffd as some systems recommend.
27809*/
27810#define READ_UTF8(zIn, zTerm, c)                           \
27811  c = *(zIn++);                                            \
27812  if( c>=0xc0 ){                                           \
27813    c = sqlite3Utf8Trans1[c-0xc0];                         \
27814    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
27815      c = (c<<6) + (0x3f & *(zIn++));                      \
27816    }                                                      \
27817    if( c<0x80                                             \
27818        || (c&0xFFFFF800)==0xD800                          \
27819        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
27820  }
27821SQLITE_PRIVATE u32 sqlite3Utf8Read(
27822  const unsigned char **pz    /* Pointer to string from which to read char */
27823){
27824  unsigned int c;
27825
27826  /* Same as READ_UTF8() above but without the zTerm parameter.
27827  ** For this routine, we assume the UTF8 string is always zero-terminated.
27828  */
27829  c = *((*pz)++);
27830  if( c>=0xc0 ){
27831    c = sqlite3Utf8Trans1[c-0xc0];
27832    while( (*(*pz) & 0xc0)==0x80 ){
27833      c = (c<<6) + (0x3f & *((*pz)++));
27834    }
27835    if( c<0x80
27836        || (c&0xFFFFF800)==0xD800
27837        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
27838  }
27839  return c;
27840}
27841
27842
27843
27844
27845/*
27846** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
27847** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
27848*/
27849/* #define TRANSLATE_TRACE 1 */
27850
27851#ifndef SQLITE_OMIT_UTF16
27852/*
27853** This routine transforms the internal text encoding used by pMem to
27854** desiredEnc. It is an error if the string is already of the desired
27855** encoding, or if *pMem does not contain a string value.
27856*/
27857SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
27858  int len;                    /* Maximum length of output string in bytes */
27859  unsigned char *zOut;                  /* Output buffer */
27860  unsigned char *zIn;                   /* Input iterator */
27861  unsigned char *zTerm;                 /* End of input */
27862  unsigned char *z;                     /* Output iterator */
27863  unsigned int c;
27864
27865  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
27866  assert( pMem->flags&MEM_Str );
27867  assert( pMem->enc!=desiredEnc );
27868  assert( pMem->enc!=0 );
27869  assert( pMem->n>=0 );
27870
27871#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
27872  {
27873    char zBuf[100];
27874    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27875    fprintf(stderr, "INPUT:  %s\n", zBuf);
27876  }
27877#endif
27878
27879  /* If the translation is between UTF-16 little and big endian, then
27880  ** all that is required is to swap the byte order. This case is handled
27881  ** differently from the others.
27882  */
27883  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
27884    u8 temp;
27885    int rc;
27886    rc = sqlite3VdbeMemMakeWriteable(pMem);
27887    if( rc!=SQLITE_OK ){
27888      assert( rc==SQLITE_NOMEM );
27889      return SQLITE_NOMEM_BKPT;
27890    }
27891    zIn = (u8*)pMem->z;
27892    zTerm = &zIn[pMem->n&~1];
27893    while( zIn<zTerm ){
27894      temp = *zIn;
27895      *zIn = *(zIn+1);
27896      zIn++;
27897      *zIn++ = temp;
27898    }
27899    pMem->enc = desiredEnc;
27900    goto translate_out;
27901  }
27902
27903  /* Set len to the maximum number of bytes required in the output buffer. */
27904  if( desiredEnc==SQLITE_UTF8 ){
27905    /* When converting from UTF-16, the maximum growth results from
27906    ** translating a 2-byte character to a 4-byte UTF-8 character.
27907    ** A single byte is required for the output string
27908    ** nul-terminator.
27909    */
27910    pMem->n &= ~1;
27911    len = pMem->n * 2 + 1;
27912  }else{
27913    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
27914    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
27915    ** character. Two bytes are required in the output buffer for the
27916    ** nul-terminator.
27917    */
27918    len = pMem->n * 2 + 2;
27919  }
27920
27921  /* Set zIn to point at the start of the input buffer and zTerm to point 1
27922  ** byte past the end.
27923  **
27924  ** Variable zOut is set to point at the output buffer, space obtained
27925  ** from sqlite3_malloc().
27926  */
27927  zIn = (u8*)pMem->z;
27928  zTerm = &zIn[pMem->n];
27929  zOut = sqlite3DbMallocRaw(pMem->db, len);
27930  if( !zOut ){
27931    return SQLITE_NOMEM_BKPT;
27932  }
27933  z = zOut;
27934
27935  if( pMem->enc==SQLITE_UTF8 ){
27936    if( desiredEnc==SQLITE_UTF16LE ){
27937      /* UTF-8 -> UTF-16 Little-endian */
27938      while( zIn<zTerm ){
27939        READ_UTF8(zIn, zTerm, c);
27940        WRITE_UTF16LE(z, c);
27941      }
27942    }else{
27943      assert( desiredEnc==SQLITE_UTF16BE );
27944      /* UTF-8 -> UTF-16 Big-endian */
27945      while( zIn<zTerm ){
27946        READ_UTF8(zIn, zTerm, c);
27947        WRITE_UTF16BE(z, c);
27948      }
27949    }
27950    pMem->n = (int)(z - zOut);
27951    *z++ = 0;
27952  }else{
27953    assert( desiredEnc==SQLITE_UTF8 );
27954    if( pMem->enc==SQLITE_UTF16LE ){
27955      /* UTF-16 Little-endian -> UTF-8 */
27956      while( zIn<zTerm ){
27957        READ_UTF16LE(zIn, zIn<zTerm, c);
27958        WRITE_UTF8(z, c);
27959      }
27960    }else{
27961      /* UTF-16 Big-endian -> UTF-8 */
27962      while( zIn<zTerm ){
27963        READ_UTF16BE(zIn, zIn<zTerm, c);
27964        WRITE_UTF8(z, c);
27965      }
27966    }
27967    pMem->n = (int)(z - zOut);
27968  }
27969  *z = 0;
27970  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
27971
27972  c = pMem->flags;
27973  sqlite3VdbeMemRelease(pMem);
27974  pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
27975  pMem->enc = desiredEnc;
27976  pMem->z = (char*)zOut;
27977  pMem->zMalloc = pMem->z;
27978  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
27979
27980translate_out:
27981#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
27982  {
27983    char zBuf[100];
27984    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27985    fprintf(stderr, "OUTPUT: %s\n", zBuf);
27986  }
27987#endif
27988  return SQLITE_OK;
27989}
27990#endif /* SQLITE_OMIT_UTF16 */
27991
27992#ifndef SQLITE_OMIT_UTF16
27993/*
27994** This routine checks for a byte-order mark at the beginning of the
27995** UTF-16 string stored in *pMem. If one is present, it is removed and
27996** the encoding of the Mem adjusted. This routine does not do any
27997** byte-swapping, it just sets Mem.enc appropriately.
27998**
27999** The allocation (static, dynamic etc.) and encoding of the Mem may be
28000** changed by this function.
28001*/
28002SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
28003  int rc = SQLITE_OK;
28004  u8 bom = 0;
28005
28006  assert( pMem->n>=0 );
28007  if( pMem->n>1 ){
28008    u8 b1 = *(u8 *)pMem->z;
28009    u8 b2 = *(((u8 *)pMem->z) + 1);
28010    if( b1==0xFE && b2==0xFF ){
28011      bom = SQLITE_UTF16BE;
28012    }
28013    if( b1==0xFF && b2==0xFE ){
28014      bom = SQLITE_UTF16LE;
28015    }
28016  }
28017
28018  if( bom ){
28019    rc = sqlite3VdbeMemMakeWriteable(pMem);
28020    if( rc==SQLITE_OK ){
28021      pMem->n -= 2;
28022      memmove(pMem->z, &pMem->z[2], pMem->n);
28023      pMem->z[pMem->n] = '\0';
28024      pMem->z[pMem->n+1] = '\0';
28025      pMem->flags |= MEM_Term;
28026      pMem->enc = bom;
28027    }
28028  }
28029  return rc;
28030}
28031#endif /* SQLITE_OMIT_UTF16 */
28032
28033/*
28034** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
28035** return the number of unicode characters in pZ up to (but not including)
28036** the first 0x00 byte. If nByte is not less than zero, return the
28037** number of unicode characters in the first nByte of pZ (or up to
28038** the first 0x00, whichever comes first).
28039*/
28040SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
28041  int r = 0;
28042  const u8 *z = (const u8*)zIn;
28043  const u8 *zTerm;
28044  if( nByte>=0 ){
28045    zTerm = &z[nByte];
28046  }else{
28047    zTerm = (const u8*)(-1);
28048  }
28049  assert( z<=zTerm );
28050  while( *z!=0 && z<zTerm ){
28051    SQLITE_SKIP_UTF8(z);
28052    r++;
28053  }
28054  return r;
28055}
28056
28057/* This test function is not currently used by the automated test-suite.
28058** Hence it is only available in debug builds.
28059*/
28060#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
28061/*
28062** Translate UTF-8 to UTF-8.
28063**
28064** This has the effect of making sure that the string is well-formed
28065** UTF-8.  Miscoded characters are removed.
28066**
28067** The translation is done in-place and aborted if the output
28068** overruns the input.
28069*/
28070SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
28071  unsigned char *zOut = zIn;
28072  unsigned char *zStart = zIn;
28073  u32 c;
28074
28075  while( zIn[0] && zOut<=zIn ){
28076    c = sqlite3Utf8Read((const u8**)&zIn);
28077    if( c!=0xfffd ){
28078      WRITE_UTF8(zOut, c);
28079    }
28080  }
28081  *zOut = 0;
28082  return (int)(zOut - zStart);
28083}
28084#endif
28085
28086#ifndef SQLITE_OMIT_UTF16
28087/*
28088** Convert a UTF-16 string in the native encoding into a UTF-8 string.
28089** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
28090** be freed by the calling function.
28091**
28092** NULL is returned if there is an allocation error.
28093*/
28094SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
28095  Mem m;
28096  memset(&m, 0, sizeof(m));
28097  m.db = db;
28098  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
28099  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
28100  if( db->mallocFailed ){
28101    sqlite3VdbeMemRelease(&m);
28102    m.z = 0;
28103  }
28104  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
28105  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
28106  assert( m.z || db->mallocFailed );
28107  return m.z;
28108}
28109
28110/*
28111** zIn is a UTF-16 encoded unicode string at least nChar characters long.
28112** Return the number of bytes in the first nChar unicode characters
28113** in pZ.  nChar must be non-negative.
28114*/
28115SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
28116  int c;
28117  unsigned char const *z = zIn;
28118  int n = 0;
28119
28120  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
28121    while( n<nChar ){
28122      READ_UTF16BE(z, 1, c);
28123      n++;
28124    }
28125  }else{
28126    while( n<nChar ){
28127      READ_UTF16LE(z, 1, c);
28128      n++;
28129    }
28130  }
28131  return (int)(z-(unsigned char const *)zIn);
28132}
28133
28134#if defined(SQLITE_TEST)
28135/*
28136** This routine is called from the TCL test function "translate_selftest".
28137** It checks that the primitives for serializing and deserializing
28138** characters in each encoding are inverses of each other.
28139*/
28140SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
28141  unsigned int i, t;
28142  unsigned char zBuf[20];
28143  unsigned char *z;
28144  int n;
28145  unsigned int c;
28146
28147  for(i=0; i<0x00110000; i++){
28148    z = zBuf;
28149    WRITE_UTF8(z, i);
28150    n = (int)(z-zBuf);
28151    assert( n>0 && n<=4 );
28152    z[0] = 0;
28153    z = zBuf;
28154    c = sqlite3Utf8Read((const u8**)&z);
28155    t = i;
28156    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
28157    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
28158    assert( c==t );
28159    assert( (z-zBuf)==n );
28160  }
28161  for(i=0; i<0x00110000; i++){
28162    if( i>=0xD800 && i<0xE000 ) continue;
28163    z = zBuf;
28164    WRITE_UTF16LE(z, i);
28165    n = (int)(z-zBuf);
28166    assert( n>0 && n<=4 );
28167    z[0] = 0;
28168    z = zBuf;
28169    READ_UTF16LE(z, 1, c);
28170    assert( c==i );
28171    assert( (z-zBuf)==n );
28172  }
28173  for(i=0; i<0x00110000; i++){
28174    if( i>=0xD800 && i<0xE000 ) continue;
28175    z = zBuf;
28176    WRITE_UTF16BE(z, i);
28177    n = (int)(z-zBuf);
28178    assert( n>0 && n<=4 );
28179    z[0] = 0;
28180    z = zBuf;
28181    READ_UTF16BE(z, 1, c);
28182    assert( c==i );
28183    assert( (z-zBuf)==n );
28184  }
28185}
28186#endif /* SQLITE_TEST */
28187#endif /* SQLITE_OMIT_UTF16 */
28188
28189/************** End of utf.c *************************************************/
28190/************** Begin file util.c ********************************************/
28191/*
28192** 2001 September 15
28193**
28194** The author disclaims copyright to this source code.  In place of
28195** a legal notice, here is a blessing:
28196**
28197**    May you do good and not evil.
28198**    May you find forgiveness for yourself and forgive others.
28199**    May you share freely, never taking more than you give.
28200**
28201*************************************************************************
28202** Utility functions used throughout sqlite.
28203**
28204** This file contains functions for allocating memory, comparing
28205** strings, and stuff like that.
28206**
28207*/
28208/* #include "sqliteInt.h" */
28209/* #include <stdarg.h> */
28210#if HAVE_ISNAN || SQLITE_HAVE_ISNAN
28211# include <math.h>
28212#endif
28213
28214/*
28215** Routine needed to support the testcase() macro.
28216*/
28217#ifdef SQLITE_COVERAGE_TEST
28218SQLITE_PRIVATE void sqlite3Coverage(int x){
28219  static unsigned dummy = 0;
28220  dummy += (unsigned)x;
28221}
28222#endif
28223
28224/*
28225** Give a callback to the test harness that can be used to simulate faults
28226** in places where it is difficult or expensive to do so purely by means
28227** of inputs.
28228**
28229** The intent of the integer argument is to let the fault simulator know
28230** which of multiple sqlite3FaultSim() calls has been hit.
28231**
28232** Return whatever integer value the test callback returns, or return
28233** SQLITE_OK if no test callback is installed.
28234*/
28235#ifndef SQLITE_UNTESTABLE
28236SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
28237  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
28238  return xCallback ? xCallback(iTest) : SQLITE_OK;
28239}
28240#endif
28241
28242#ifndef SQLITE_OMIT_FLOATING_POINT
28243/*
28244** Return true if the floating point value is Not a Number (NaN).
28245**
28246** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
28247** Otherwise, we have our own implementation that works on most systems.
28248*/
28249SQLITE_PRIVATE int sqlite3IsNaN(double x){
28250  int rc;   /* The value return */
28251#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
28252  /*
28253  ** Systems that support the isnan() library function should probably
28254  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
28255  ** found that many systems do not have a working isnan() function so
28256  ** this implementation is provided as an alternative.
28257  **
28258  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
28259  ** On the other hand, the use of -ffast-math comes with the following
28260  ** warning:
28261  **
28262  **      This option [-ffast-math] should never be turned on by any
28263  **      -O option since it can result in incorrect output for programs
28264  **      which depend on an exact implementation of IEEE or ISO
28265  **      rules/specifications for math functions.
28266  **
28267  ** Under MSVC, this NaN test may fail if compiled with a floating-
28268  ** point precision mode other than /fp:precise.  From the MSDN
28269  ** documentation:
28270  **
28271  **      The compiler [with /fp:precise] will properly handle comparisons
28272  **      involving NaN. For example, x != x evaluates to true if x is NaN
28273  **      ...
28274  */
28275#ifdef __FAST_MATH__
28276# error SQLite will not work correctly with the -ffast-math option of GCC.
28277#endif
28278  volatile double y = x;
28279  volatile double z = y;
28280  rc = (y!=z);
28281#else  /* if HAVE_ISNAN */
28282  rc = isnan(x);
28283#endif /* HAVE_ISNAN */
28284  testcase( rc );
28285  return rc;
28286}
28287#endif /* SQLITE_OMIT_FLOATING_POINT */
28288
28289/*
28290** Compute a string length that is limited to what can be stored in
28291** lower 30 bits of a 32-bit signed integer.
28292**
28293** The value returned will never be negative.  Nor will it ever be greater
28294** than the actual length of the string.  For very long strings (greater
28295** than 1GiB) the value returned might be less than the true string length.
28296*/
28297SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
28298  if( z==0 ) return 0;
28299  return 0x3fffffff & (int)strlen(z);
28300}
28301
28302/*
28303** Return the declared type of a column.  Or return zDflt if the column
28304** has no declared type.
28305**
28306** The column type is an extra string stored after the zero-terminator on
28307** the column name if and only if the COLFLAG_HASTYPE flag is set.
28308*/
28309SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
28310  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
28311  return pCol->zName + strlen(pCol->zName) + 1;
28312}
28313
28314/*
28315** Helper function for sqlite3Error() - called rarely.  Broken out into
28316** a separate routine to avoid unnecessary register saves on entry to
28317** sqlite3Error().
28318*/
28319static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
28320  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
28321  sqlite3SystemError(db, err_code);
28322}
28323
28324/*
28325** Set the current error code to err_code and clear any prior error message.
28326** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
28327** that would be appropriate.
28328*/
28329SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
28330  assert( db!=0 );
28331  db->errCode = err_code;
28332  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
28333}
28334
28335/*
28336** Load the sqlite3.iSysErrno field if that is an appropriate thing
28337** to do based on the SQLite error code in rc.
28338*/
28339SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
28340  if( rc==SQLITE_IOERR_NOMEM ) return;
28341  rc &= 0xff;
28342  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
28343    db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
28344  }
28345}
28346
28347/*
28348** Set the most recent error code and error string for the sqlite
28349** handle "db". The error code is set to "err_code".
28350**
28351** If it is not NULL, string zFormat specifies the format of the
28352** error string in the style of the printf functions: The following
28353** format characters are allowed:
28354**
28355**      %s      Insert a string
28356**      %z      A string that should be freed after use
28357**      %d      Insert an integer
28358**      %T      Insert a token
28359**      %S      Insert the first element of a SrcList
28360**
28361** zFormat and any string tokens that follow it are assumed to be
28362** encoded in UTF-8.
28363**
28364** To clear the most recent error for sqlite handle "db", sqlite3Error
28365** should be called with err_code set to SQLITE_OK and zFormat set
28366** to NULL.
28367*/
28368SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
28369  assert( db!=0 );
28370  db->errCode = err_code;
28371  sqlite3SystemError(db, err_code);
28372  if( zFormat==0 ){
28373    sqlite3Error(db, err_code);
28374  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
28375    char *z;
28376    va_list ap;
28377    va_start(ap, zFormat);
28378    z = sqlite3VMPrintf(db, zFormat, ap);
28379    va_end(ap);
28380    sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
28381  }
28382}
28383
28384/*
28385** Add an error message to pParse->zErrMsg and increment pParse->nErr.
28386** The following formatting characters are allowed:
28387**
28388**      %s      Insert a string
28389**      %z      A string that should be freed after use
28390**      %d      Insert an integer
28391**      %T      Insert a token
28392**      %S      Insert the first element of a SrcList
28393**
28394** This function should be used to report any error that occurs while
28395** compiling an SQL statement (i.e. within sqlite3_prepare()). The
28396** last thing the sqlite3_prepare() function does is copy the error
28397** stored by this function into the database handle using sqlite3Error().
28398** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
28399** during statement execution (sqlite3_step() etc.).
28400*/
28401SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
28402  char *zMsg;
28403  va_list ap;
28404  sqlite3 *db = pParse->db;
28405  va_start(ap, zFormat);
28406  zMsg = sqlite3VMPrintf(db, zFormat, ap);
28407  va_end(ap);
28408  if( db->suppressErr ){
28409    sqlite3DbFree(db, zMsg);
28410  }else{
28411    pParse->nErr++;
28412    sqlite3DbFree(db, pParse->zErrMsg);
28413    pParse->zErrMsg = zMsg;
28414    pParse->rc = SQLITE_ERROR;
28415  }
28416}
28417
28418/*
28419** Convert an SQL-style quoted string into a normal string by removing
28420** the quote characters.  The conversion is done in-place.  If the
28421** input does not begin with a quote character, then this routine
28422** is a no-op.
28423**
28424** The input string must be zero-terminated.  A new zero-terminator
28425** is added to the dequoted string.
28426**
28427** The return value is -1 if no dequoting occurs or the length of the
28428** dequoted string, exclusive of the zero terminator, if dequoting does
28429** occur.
28430**
28431** 2002-Feb-14: This routine is extended to remove MS-Access style
28432** brackets from around identifiers.  For example:  "[a-b-c]" becomes
28433** "a-b-c".
28434*/
28435SQLITE_PRIVATE void sqlite3Dequote(char *z){
28436  char quote;
28437  int i, j;
28438  if( z==0 ) return;
28439  quote = z[0];
28440  if( !sqlite3Isquote(quote) ) return;
28441  if( quote=='[' ) quote = ']';
28442  for(i=1, j=0;; i++){
28443    assert( z[i] );
28444    if( z[i]==quote ){
28445      if( z[i+1]==quote ){
28446        z[j++] = quote;
28447        i++;
28448      }else{
28449        break;
28450      }
28451    }else{
28452      z[j++] = z[i];
28453    }
28454  }
28455  z[j] = 0;
28456}
28457
28458/*
28459** Generate a Token object from a string
28460*/
28461SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
28462  p->z = z;
28463  p->n = sqlite3Strlen30(z);
28464}
28465
28466/* Convenient short-hand */
28467#define UpperToLower sqlite3UpperToLower
28468
28469/*
28470** Some systems have stricmp().  Others have strcasecmp().  Because
28471** there is no consistency, we will define our own.
28472**
28473** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
28474** sqlite3_strnicmp() APIs allow applications and extensions to compare
28475** the contents of two buffers containing UTF-8 strings in a
28476** case-independent fashion, using the same definition of "case
28477** independence" that SQLite uses internally when comparing identifiers.
28478*/
28479SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
28480  if( zLeft==0 ){
28481    return zRight ? -1 : 0;
28482  }else if( zRight==0 ){
28483    return 1;
28484  }
28485  return sqlite3StrICmp(zLeft, zRight);
28486}
28487SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
28488  unsigned char *a, *b;
28489  int c;
28490  a = (unsigned char *)zLeft;
28491  b = (unsigned char *)zRight;
28492  for(;;){
28493    c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
28494    if( c || *a==0 ) break;
28495    a++;
28496    b++;
28497  }
28498  return c;
28499}
28500SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
28501  register unsigned char *a, *b;
28502  if( zLeft==0 ){
28503    return zRight ? -1 : 0;
28504  }else if( zRight==0 ){
28505    return 1;
28506  }
28507  a = (unsigned char *)zLeft;
28508  b = (unsigned char *)zRight;
28509  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
28510  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
28511}
28512
28513/*
28514** The string z[] is an text representation of a real number.
28515** Convert this string to a double and write it into *pResult.
28516**
28517** The string z[] is length bytes in length (bytes, not characters) and
28518** uses the encoding enc.  The string is not necessarily zero-terminated.
28519**
28520** Return TRUE if the result is a valid real number (or integer) and FALSE
28521** if the string is empty or contains extraneous text.  Valid numbers
28522** are in one of these formats:
28523**
28524**    [+-]digits[E[+-]digits]
28525**    [+-]digits.[digits][E[+-]digits]
28526**    [+-].digits[E[+-]digits]
28527**
28528** Leading and trailing whitespace is ignored for the purpose of determining
28529** validity.
28530**
28531** If some prefix of the input string is a valid number, this routine
28532** returns FALSE but it still converts the prefix and writes the result
28533** into *pResult.
28534*/
28535SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
28536#ifndef SQLITE_OMIT_FLOATING_POINT
28537  int incr;
28538  const char *zEnd = z + length;
28539  /* sign * significand * (10 ^ (esign * exponent)) */
28540  int sign = 1;    /* sign of significand */
28541  i64 s = 0;       /* significand */
28542  int d = 0;       /* adjust exponent for shifting decimal point */
28543  int esign = 1;   /* sign of exponent */
28544  int e = 0;       /* exponent */
28545  int eValid = 1;  /* True exponent is either not used or is well-formed */
28546  double result;
28547  int nDigits = 0;
28548  int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
28549
28550  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
28551  *pResult = 0.0;   /* Default return value, in case of an error */
28552
28553  if( enc==SQLITE_UTF8 ){
28554    incr = 1;
28555  }else{
28556    int i;
28557    incr = 2;
28558    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
28559    for(i=3-enc; i<length && z[i]==0; i+=2){}
28560    nonNum = i<length;
28561    zEnd = &z[i^1];
28562    z += (enc&1);
28563  }
28564
28565  /* skip leading spaces */
28566  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
28567  if( z>=zEnd ) return 0;
28568
28569  /* get sign of significand */
28570  if( *z=='-' ){
28571    sign = -1;
28572    z+=incr;
28573  }else if( *z=='+' ){
28574    z+=incr;
28575  }
28576
28577  /* copy max significant digits to significand */
28578  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
28579    s = s*10 + (*z - '0');
28580    z+=incr, nDigits++;
28581  }
28582
28583  /* skip non-significant significand digits
28584  ** (increase exponent by d to shift decimal left) */
28585  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
28586  if( z>=zEnd ) goto do_atof_calc;
28587
28588  /* if decimal point is present */
28589  if( *z=='.' ){
28590    z+=incr;
28591    /* copy digits from after decimal to significand
28592    ** (decrease exponent by d to shift decimal right) */
28593    while( z<zEnd && sqlite3Isdigit(*z) ){
28594      if( s<((LARGEST_INT64-9)/10) ){
28595        s = s*10 + (*z - '0');
28596        d--;
28597      }
28598      z+=incr, nDigits++;
28599    }
28600  }
28601  if( z>=zEnd ) goto do_atof_calc;
28602
28603  /* if exponent is present */
28604  if( *z=='e' || *z=='E' ){
28605    z+=incr;
28606    eValid = 0;
28607
28608    /* This branch is needed to avoid a (harmless) buffer overread.  The
28609    ** special comment alerts the mutation tester that the correct answer
28610    ** is obtained even if the branch is omitted */
28611    if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
28612
28613    /* get sign of exponent */
28614    if( *z=='-' ){
28615      esign = -1;
28616      z+=incr;
28617    }else if( *z=='+' ){
28618      z+=incr;
28619    }
28620    /* copy digits to exponent */
28621    while( z<zEnd && sqlite3Isdigit(*z) ){
28622      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
28623      z+=incr;
28624      eValid = 1;
28625    }
28626  }
28627
28628  /* skip trailing spaces */
28629  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
28630
28631do_atof_calc:
28632  /* adjust exponent by d, and update sign */
28633  e = (e*esign) + d;
28634  if( e<0 ) {
28635    esign = -1;
28636    e *= -1;
28637  } else {
28638    esign = 1;
28639  }
28640
28641  if( s==0 ) {
28642    /* In the IEEE 754 standard, zero is signed. */
28643    result = sign<0 ? -(double)0 : (double)0;
28644  } else {
28645    /* Attempt to reduce exponent.
28646    **
28647    ** Branches that are not required for the correct answer but which only
28648    ** help to obtain the correct answer faster are marked with special
28649    ** comments, as a hint to the mutation tester.
28650    */
28651    while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
28652      if( esign>0 ){
28653        if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
28654        s *= 10;
28655      }else{
28656        if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
28657        s /= 10;
28658      }
28659      e--;
28660    }
28661
28662    /* adjust the sign of significand */
28663    s = sign<0 ? -s : s;
28664
28665    if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
28666      result = (double)s;
28667    }else{
28668      LONGDOUBLE_TYPE scale = 1.0;
28669      /* attempt to handle extremely small/large numbers better */
28670      if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
28671        if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
28672          while( e%308 ) { scale *= 1.0e+1; e -= 1; }
28673          if( esign<0 ){
28674            result = s / scale;
28675            result /= 1.0e+308;
28676          }else{
28677            result = s * scale;
28678            result *= 1.0e+308;
28679          }
28680        }else{ assert( e>=342 );
28681          if( esign<0 ){
28682            result = 0.0*s;
28683          }else{
28684            result = 1e308*1e308*s;  /* Infinity */
28685          }
28686        }
28687      }else{
28688        /* 1.0e+22 is the largest power of 10 than can be
28689        ** represented exactly. */
28690        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
28691        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
28692        if( esign<0 ){
28693          result = s / scale;
28694        }else{
28695          result = s * scale;
28696        }
28697      }
28698    }
28699  }
28700
28701  /* store the result */
28702  *pResult = result;
28703
28704  /* return true if number and no extra non-whitespace chracters after */
28705  return z==zEnd && nDigits>0 && eValid && nonNum==0;
28706#else
28707  return !sqlite3Atoi64(z, pResult, length, enc);
28708#endif /* SQLITE_OMIT_FLOATING_POINT */
28709}
28710
28711/*
28712** Compare the 19-character string zNum against the text representation
28713** value 2^63:  9223372036854775808.  Return negative, zero, or positive
28714** if zNum is less than, equal to, or greater than the string.
28715** Note that zNum must contain exactly 19 characters.
28716**
28717** Unlike memcmp() this routine is guaranteed to return the difference
28718** in the values of the last digit if the only difference is in the
28719** last digit.  So, for example,
28720**
28721**      compare2pow63("9223372036854775800", 1)
28722**
28723** will return -8.
28724*/
28725static int compare2pow63(const char *zNum, int incr){
28726  int c = 0;
28727  int i;
28728                    /* 012345678901234567 */
28729  const char *pow63 = "922337203685477580";
28730  for(i=0; c==0 && i<18; i++){
28731    c = (zNum[i*incr]-pow63[i])*10;
28732  }
28733  if( c==0 ){
28734    c = zNum[18*incr] - '8';
28735    testcase( c==(-1) );
28736    testcase( c==0 );
28737    testcase( c==(+1) );
28738  }
28739  return c;
28740}
28741
28742/*
28743** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
28744** routine does *not* accept hexadecimal notation.
28745**
28746** If the zNum value is representable as a 64-bit twos-complement
28747** integer, then write that value into *pNum and return 0.
28748**
28749** If zNum is exactly 9223372036854775808, return 2.  This special
28750** case is broken out because while 9223372036854775808 cannot be a
28751** signed 64-bit integer, its negative -9223372036854775808 can be.
28752**
28753** If zNum is too big for a 64-bit integer and is not
28754** 9223372036854775808  or if zNum contains any non-numeric text,
28755** then return 1.
28756**
28757** length is the number of bytes in the string (bytes, not characters).
28758** The string is not necessarily zero-terminated.  The encoding is
28759** given by enc.
28760*/
28761SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
28762  int incr;
28763  u64 u = 0;
28764  int neg = 0; /* assume positive */
28765  int i;
28766  int c = 0;
28767  int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
28768  const char *zStart;
28769  const char *zEnd = zNum + length;
28770  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
28771  if( enc==SQLITE_UTF8 ){
28772    incr = 1;
28773  }else{
28774    incr = 2;
28775    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
28776    for(i=3-enc; i<length && zNum[i]==0; i+=2){}
28777    nonNum = i<length;
28778    zEnd = &zNum[i^1];
28779    zNum += (enc&1);
28780  }
28781  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
28782  if( zNum<zEnd ){
28783    if( *zNum=='-' ){
28784      neg = 1;
28785      zNum+=incr;
28786    }else if( *zNum=='+' ){
28787      zNum+=incr;
28788    }
28789  }
28790  zStart = zNum;
28791  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
28792  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
28793    u = u*10 + c - '0';
28794  }
28795  if( u>LARGEST_INT64 ){
28796    *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
28797  }else if( neg ){
28798    *pNum = -(i64)u;
28799  }else{
28800    *pNum = (i64)u;
28801  }
28802  testcase( i==18 );
28803  testcase( i==19 );
28804  testcase( i==20 );
28805  if( &zNum[i]<zEnd              /* Extra bytes at the end */
28806   || (i==0 && zStart==zNum)     /* No digits */
28807   || i>19*incr                  /* Too many digits */
28808   || nonNum                     /* UTF16 with high-order bytes non-zero */
28809  ){
28810    /* zNum is empty or contains non-numeric text or is longer
28811    ** than 19 digits (thus guaranteeing that it is too large) */
28812    return 1;
28813  }else if( i<19*incr ){
28814    /* Less than 19 digits, so we know that it fits in 64 bits */
28815    assert( u<=LARGEST_INT64 );
28816    return 0;
28817  }else{
28818    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
28819    c = compare2pow63(zNum, incr);
28820    if( c<0 ){
28821      /* zNum is less than 9223372036854775808 so it fits */
28822      assert( u<=LARGEST_INT64 );
28823      return 0;
28824    }else if( c>0 ){
28825      /* zNum is greater than 9223372036854775808 so it overflows */
28826      return 1;
28827    }else{
28828      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
28829      ** special case 2 overflow if positive */
28830      assert( u-1==LARGEST_INT64 );
28831      return neg ? 0 : 2;
28832    }
28833  }
28834}
28835
28836/*
28837** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
28838** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
28839** whereas sqlite3Atoi64() does not.
28840**
28841** Returns:
28842**
28843**     0    Successful transformation.  Fits in a 64-bit signed integer.
28844**     1    Integer too large for a 64-bit signed integer or is malformed
28845**     2    Special case of 9223372036854775808
28846*/
28847SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
28848#ifndef SQLITE_OMIT_HEX_INTEGER
28849  if( z[0]=='0'
28850   && (z[1]=='x' || z[1]=='X')
28851  ){
28852    u64 u = 0;
28853    int i, k;
28854    for(i=2; z[i]=='0'; i++){}
28855    for(k=i; sqlite3Isxdigit(z[k]); k++){
28856      u = u*16 + sqlite3HexToInt(z[k]);
28857    }
28858    memcpy(pOut, &u, 8);
28859    return (z[k]==0 && k-i<=16) ? 0 : 1;
28860  }else
28861#endif /* SQLITE_OMIT_HEX_INTEGER */
28862  {
28863    return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
28864  }
28865}
28866
28867/*
28868** If zNum represents an integer that will fit in 32-bits, then set
28869** *pValue to that integer and return true.  Otherwise return false.
28870**
28871** This routine accepts both decimal and hexadecimal notation for integers.
28872**
28873** Any non-numeric characters that following zNum are ignored.
28874** This is different from sqlite3Atoi64() which requires the
28875** input number to be zero-terminated.
28876*/
28877SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
28878  sqlite_int64 v = 0;
28879  int i, c;
28880  int neg = 0;
28881  if( zNum[0]=='-' ){
28882    neg = 1;
28883    zNum++;
28884  }else if( zNum[0]=='+' ){
28885    zNum++;
28886  }
28887#ifndef SQLITE_OMIT_HEX_INTEGER
28888  else if( zNum[0]=='0'
28889        && (zNum[1]=='x' || zNum[1]=='X')
28890        && sqlite3Isxdigit(zNum[2])
28891  ){
28892    u32 u = 0;
28893    zNum += 2;
28894    while( zNum[0]=='0' ) zNum++;
28895    for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
28896      u = u*16 + sqlite3HexToInt(zNum[i]);
28897    }
28898    if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
28899      memcpy(pValue, &u, 4);
28900      return 1;
28901    }else{
28902      return 0;
28903    }
28904  }
28905#endif
28906  if( !sqlite3Isdigit(zNum[0]) ) return 0;
28907  while( zNum[0]=='0' ) zNum++;
28908  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
28909    v = v*10 + c;
28910  }
28911
28912  /* The longest decimal representation of a 32 bit integer is 10 digits:
28913  **
28914  **             1234567890
28915  **     2^31 -> 2147483648
28916  */
28917  testcase( i==10 );
28918  if( i>10 ){
28919    return 0;
28920  }
28921  testcase( v-neg==2147483647 );
28922  if( v-neg>2147483647 ){
28923    return 0;
28924  }
28925  if( neg ){
28926    v = -v;
28927  }
28928  *pValue = (int)v;
28929  return 1;
28930}
28931
28932/*
28933** Return a 32-bit integer value extracted from a string.  If the
28934** string is not an integer, just return 0.
28935*/
28936SQLITE_PRIVATE int sqlite3Atoi(const char *z){
28937  int x = 0;
28938  if( z ) sqlite3GetInt32(z, &x);
28939  return x;
28940}
28941
28942/*
28943** The variable-length integer encoding is as follows:
28944**
28945** KEY:
28946**         A = 0xxxxxxx    7 bits of data and one flag bit
28947**         B = 1xxxxxxx    7 bits of data and one flag bit
28948**         C = xxxxxxxx    8 bits of data
28949**
28950**  7 bits - A
28951** 14 bits - BA
28952** 21 bits - BBA
28953** 28 bits - BBBA
28954** 35 bits - BBBBA
28955** 42 bits - BBBBBA
28956** 49 bits - BBBBBBA
28957** 56 bits - BBBBBBBA
28958** 64 bits - BBBBBBBBC
28959*/
28960
28961/*
28962** Write a 64-bit variable-length integer to memory starting at p[0].
28963** The length of data write will be between 1 and 9 bytes.  The number
28964** of bytes written is returned.
28965**
28966** A variable-length integer consists of the lower 7 bits of each byte
28967** for all bytes that have the 8th bit set and one byte with the 8th
28968** bit clear.  Except, if we get to the 9th byte, it stores the full
28969** 8 bits and is the last byte.
28970*/
28971static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
28972  int i, j, n;
28973  u8 buf[10];
28974  if( v & (((u64)0xff000000)<<32) ){
28975    p[8] = (u8)v;
28976    v >>= 8;
28977    for(i=7; i>=0; i--){
28978      p[i] = (u8)((v & 0x7f) | 0x80);
28979      v >>= 7;
28980    }
28981    return 9;
28982  }
28983  n = 0;
28984  do{
28985    buf[n++] = (u8)((v & 0x7f) | 0x80);
28986    v >>= 7;
28987  }while( v!=0 );
28988  buf[0] &= 0x7f;
28989  assert( n<=9 );
28990  for(i=0, j=n-1; j>=0; j--, i++){
28991    p[i] = buf[j];
28992  }
28993  return n;
28994}
28995SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
28996  if( v<=0x7f ){
28997    p[0] = v&0x7f;
28998    return 1;
28999  }
29000  if( v<=0x3fff ){
29001    p[0] = ((v>>7)&0x7f)|0x80;
29002    p[1] = v&0x7f;
29003    return 2;
29004  }
29005  return putVarint64(p,v);
29006}
29007
29008/*
29009** Bitmasks used by sqlite3GetVarint().  These precomputed constants
29010** are defined here rather than simply putting the constant expressions
29011** inline in order to work around bugs in the RVT compiler.
29012**
29013** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
29014**
29015** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
29016*/
29017#define SLOT_2_0     0x001fc07f
29018#define SLOT_4_2_0   0xf01fc07f
29019
29020
29021/*
29022** Read a 64-bit variable-length integer from memory starting at p[0].
29023** Return the number of bytes read.  The value is stored in *v.
29024*/
29025SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
29026  u32 a,b,s;
29027
29028  a = *p;
29029  /* a: p0 (unmasked) */
29030  if (!(a&0x80))
29031  {
29032    *v = a;
29033    return 1;
29034  }
29035
29036  p++;
29037  b = *p;
29038  /* b: p1 (unmasked) */
29039  if (!(b&0x80))
29040  {
29041    a &= 0x7f;
29042    a = a<<7;
29043    a |= b;
29044    *v = a;
29045    return 2;
29046  }
29047
29048  /* Verify that constants are precomputed correctly */
29049  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
29050  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
29051
29052  p++;
29053  a = a<<14;
29054  a |= *p;
29055  /* a: p0<<14 | p2 (unmasked) */
29056  if (!(a&0x80))
29057  {
29058    a &= SLOT_2_0;
29059    b &= 0x7f;
29060    b = b<<7;
29061    a |= b;
29062    *v = a;
29063    return 3;
29064  }
29065
29066  /* CSE1 from below */
29067  a &= SLOT_2_0;
29068  p++;
29069  b = b<<14;
29070  b |= *p;
29071  /* b: p1<<14 | p3 (unmasked) */
29072  if (!(b&0x80))
29073  {
29074    b &= SLOT_2_0;
29075    /* moved CSE1 up */
29076    /* a &= (0x7f<<14)|(0x7f); */
29077    a = a<<7;
29078    a |= b;
29079    *v = a;
29080    return 4;
29081  }
29082
29083  /* a: p0<<14 | p2 (masked) */
29084  /* b: p1<<14 | p3 (unmasked) */
29085  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
29086  /* moved CSE1 up */
29087  /* a &= (0x7f<<14)|(0x7f); */
29088  b &= SLOT_2_0;
29089  s = a;
29090  /* s: p0<<14 | p2 (masked) */
29091
29092  p++;
29093  a = a<<14;
29094  a |= *p;
29095  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
29096  if (!(a&0x80))
29097  {
29098    /* we can skip these cause they were (effectively) done above
29099    ** while calculating s */
29100    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
29101    /* b &= (0x7f<<14)|(0x7f); */
29102    b = b<<7;
29103    a |= b;
29104    s = s>>18;
29105    *v = ((u64)s)<<32 | a;
29106    return 5;
29107  }
29108
29109  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
29110  s = s<<7;
29111  s |= b;
29112  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
29113
29114  p++;
29115  b = b<<14;
29116  b |= *p;
29117  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
29118  if (!(b&0x80))
29119  {
29120    /* we can skip this cause it was (effectively) done above in calc'ing s */
29121    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
29122    a &= SLOT_2_0;
29123    a = a<<7;
29124    a |= b;
29125    s = s>>18;
29126    *v = ((u64)s)<<32 | a;
29127    return 6;
29128  }
29129
29130  p++;
29131  a = a<<14;
29132  a |= *p;
29133  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
29134  if (!(a&0x80))
29135  {
29136    a &= SLOT_4_2_0;
29137    b &= SLOT_2_0;
29138    b = b<<7;
29139    a |= b;
29140    s = s>>11;
29141    *v = ((u64)s)<<32 | a;
29142    return 7;
29143  }
29144
29145  /* CSE2 from below */
29146  a &= SLOT_2_0;
29147  p++;
29148  b = b<<14;
29149  b |= *p;
29150  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
29151  if (!(b&0x80))
29152  {
29153    b &= SLOT_4_2_0;
29154    /* moved CSE2 up */
29155    /* a &= (0x7f<<14)|(0x7f); */
29156    a = a<<7;
29157    a |= b;
29158    s = s>>4;
29159    *v = ((u64)s)<<32 | a;
29160    return 8;
29161  }
29162
29163  p++;
29164  a = a<<15;
29165  a |= *p;
29166  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
29167
29168  /* moved CSE2 up */
29169  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
29170  b &= SLOT_2_0;
29171  b = b<<8;
29172  a |= b;
29173
29174  s = s<<4;
29175  b = p[-4];
29176  b &= 0x7f;
29177  b = b>>3;
29178  s |= b;
29179
29180  *v = ((u64)s)<<32 | a;
29181
29182  return 9;
29183}
29184
29185/*
29186** Read a 32-bit variable-length integer from memory starting at p[0].
29187** Return the number of bytes read.  The value is stored in *v.
29188**
29189** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
29190** integer, then set *v to 0xffffffff.
29191**
29192** A MACRO version, getVarint32, is provided which inlines the
29193** single-byte case.  All code should use the MACRO version as
29194** this function assumes the single-byte case has already been handled.
29195*/
29196SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
29197  u32 a,b;
29198
29199  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
29200  ** by the getVarin32() macro */
29201  a = *p;
29202  /* a: p0 (unmasked) */
29203#ifndef getVarint32
29204  if (!(a&0x80))
29205  {
29206    /* Values between 0 and 127 */
29207    *v = a;
29208    return 1;
29209  }
29210#endif
29211
29212  /* The 2-byte case */
29213  p++;
29214  b = *p;
29215  /* b: p1 (unmasked) */
29216  if (!(b&0x80))
29217  {
29218    /* Values between 128 and 16383 */
29219    a &= 0x7f;
29220    a = a<<7;
29221    *v = a | b;
29222    return 2;
29223  }
29224
29225  /* The 3-byte case */
29226  p++;
29227  a = a<<14;
29228  a |= *p;
29229  /* a: p0<<14 | p2 (unmasked) */
29230  if (!(a&0x80))
29231  {
29232    /* Values between 16384 and 2097151 */
29233    a &= (0x7f<<14)|(0x7f);
29234    b &= 0x7f;
29235    b = b<<7;
29236    *v = a | b;
29237    return 3;
29238  }
29239
29240  /* A 32-bit varint is used to store size information in btrees.
29241  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
29242  ** A 3-byte varint is sufficient, for example, to record the size
29243  ** of a 1048569-byte BLOB or string.
29244  **
29245  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
29246  ** rare larger cases can be handled by the slower 64-bit varint
29247  ** routine.
29248  */
29249#if 1
29250  {
29251    u64 v64;
29252    u8 n;
29253
29254    p -= 2;
29255    n = sqlite3GetVarint(p, &v64);
29256    assert( n>3 && n<=9 );
29257    if( (v64 & SQLITE_MAX_U32)!=v64 ){
29258      *v = 0xffffffff;
29259    }else{
29260      *v = (u32)v64;
29261    }
29262    return n;
29263  }
29264
29265#else
29266  /* For following code (kept for historical record only) shows an
29267  ** unrolling for the 3- and 4-byte varint cases.  This code is
29268  ** slightly faster, but it is also larger and much harder to test.
29269  */
29270  p++;
29271  b = b<<14;
29272  b |= *p;
29273  /* b: p1<<14 | p3 (unmasked) */
29274  if (!(b&0x80))
29275  {
29276    /* Values between 2097152 and 268435455 */
29277    b &= (0x7f<<14)|(0x7f);
29278    a &= (0x7f<<14)|(0x7f);
29279    a = a<<7;
29280    *v = a | b;
29281    return 4;
29282  }
29283
29284  p++;
29285  a = a<<14;
29286  a |= *p;
29287  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
29288  if (!(a&0x80))
29289  {
29290    /* Values  between 268435456 and 34359738367 */
29291    a &= SLOT_4_2_0;
29292    b &= SLOT_4_2_0;
29293    b = b<<7;
29294    *v = a | b;
29295    return 5;
29296  }
29297
29298  /* We can only reach this point when reading a corrupt database
29299  ** file.  In that case we are not in any hurry.  Use the (relatively
29300  ** slow) general-purpose sqlite3GetVarint() routine to extract the
29301  ** value. */
29302  {
29303    u64 v64;
29304    u8 n;
29305
29306    p -= 4;
29307    n = sqlite3GetVarint(p, &v64);
29308    assert( n>5 && n<=9 );
29309    *v = (u32)v64;
29310    return n;
29311  }
29312#endif
29313}
29314
29315/*
29316** Return the number of bytes that will be needed to store the given
29317** 64-bit integer.
29318*/
29319SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
29320  int i;
29321  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
29322  return i;
29323}
29324
29325
29326/*
29327** Read or write a four-byte big-endian integer value.
29328*/
29329SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
29330#if SQLITE_BYTEORDER==4321
29331  u32 x;
29332  memcpy(&x,p,4);
29333  return x;
29334#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
29335  u32 x;
29336  memcpy(&x,p,4);
29337  return __builtin_bswap32(x);
29338#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
29339  u32 x;
29340  memcpy(&x,p,4);
29341  return _byteswap_ulong(x);
29342#else
29343  testcase( p[0]&0x80 );
29344  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
29345#endif
29346}
29347SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
29348#if SQLITE_BYTEORDER==4321
29349  memcpy(p,&v,4);
29350#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
29351  u32 x = __builtin_bswap32(v);
29352  memcpy(p,&x,4);
29353#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
29354  u32 x = _byteswap_ulong(v);
29355  memcpy(p,&x,4);
29356#else
29357  p[0] = (u8)(v>>24);
29358  p[1] = (u8)(v>>16);
29359  p[2] = (u8)(v>>8);
29360  p[3] = (u8)v;
29361#endif
29362}
29363
29364
29365
29366/*
29367** Translate a single byte of Hex into an integer.
29368** This routine only works if h really is a valid hexadecimal
29369** character:  0..9a..fA..F
29370*/
29371SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
29372  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
29373#ifdef SQLITE_ASCII
29374  h += 9*(1&(h>>6));
29375#endif
29376#ifdef SQLITE_EBCDIC
29377  h += 9*(1&~(h>>4));
29378#endif
29379  return (u8)(h & 0xf);
29380}
29381
29382#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
29383/*
29384** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
29385** value.  Return a pointer to its binary value.  Space to hold the
29386** binary value has been obtained from malloc and must be freed by
29387** the calling routine.
29388*/
29389SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
29390  char *zBlob;
29391  int i;
29392
29393  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
29394  n--;
29395  if( zBlob ){
29396    for(i=0; i<n; i+=2){
29397      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
29398    }
29399    zBlob[i/2] = 0;
29400  }
29401  return zBlob;
29402}
29403#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
29404
29405/*
29406** Log an error that is an API call on a connection pointer that should
29407** not have been used.  The "type" of connection pointer is given as the
29408** argument.  The zType is a word like "NULL" or "closed" or "invalid".
29409*/
29410static void logBadConnection(const char *zType){
29411  sqlite3_log(SQLITE_MISUSE,
29412     "API call with %s database connection pointer",
29413     zType
29414  );
29415}
29416
29417/*
29418** Check to make sure we have a valid db pointer.  This test is not
29419** foolproof but it does provide some measure of protection against
29420** misuse of the interface such as passing in db pointers that are
29421** NULL or which have been previously closed.  If this routine returns
29422** 1 it means that the db pointer is valid and 0 if it should not be
29423** dereferenced for any reason.  The calling function should invoke
29424** SQLITE_MISUSE immediately.
29425**
29426** sqlite3SafetyCheckOk() requires that the db pointer be valid for
29427** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
29428** open properly and is not fit for general use but which can be
29429** used as an argument to sqlite3_errmsg() or sqlite3_close().
29430*/
29431SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
29432  u32 magic;
29433  if( db==0 ){
29434    logBadConnection("NULL");
29435    return 0;
29436  }
29437  magic = db->magic;
29438  if( magic!=SQLITE_MAGIC_OPEN ){
29439    if( sqlite3SafetyCheckSickOrOk(db) ){
29440      testcase( sqlite3GlobalConfig.xLog!=0 );
29441      logBadConnection("unopened");
29442    }
29443    return 0;
29444  }else{
29445    return 1;
29446  }
29447}
29448SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
29449  u32 magic;
29450  magic = db->magic;
29451  if( magic!=SQLITE_MAGIC_SICK &&
29452      magic!=SQLITE_MAGIC_OPEN &&
29453      magic!=SQLITE_MAGIC_BUSY ){
29454    testcase( sqlite3GlobalConfig.xLog!=0 );
29455    logBadConnection("invalid");
29456    return 0;
29457  }else{
29458    return 1;
29459  }
29460}
29461
29462/*
29463** Attempt to add, substract, or multiply the 64-bit signed value iB against
29464** the other 64-bit signed integer at *pA and store the result in *pA.
29465** Return 0 on success.  Or if the operation would have resulted in an
29466** overflow, leave *pA unchanged and return 1.
29467*/
29468SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
29469#if GCC_VERSION>=5004000
29470  return __builtin_add_overflow(*pA, iB, pA);
29471#else
29472  i64 iA = *pA;
29473  testcase( iA==0 ); testcase( iA==1 );
29474  testcase( iB==-1 ); testcase( iB==0 );
29475  if( iB>=0 ){
29476    testcase( iA>0 && LARGEST_INT64 - iA == iB );
29477    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
29478    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
29479  }else{
29480    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
29481    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
29482    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
29483  }
29484  *pA += iB;
29485  return 0;
29486#endif
29487}
29488SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
29489#if GCC_VERSION>=5004000
29490  return __builtin_sub_overflow(*pA, iB, pA);
29491#else
29492  testcase( iB==SMALLEST_INT64+1 );
29493  if( iB==SMALLEST_INT64 ){
29494    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
29495    if( (*pA)>=0 ) return 1;
29496    *pA -= iB;
29497    return 0;
29498  }else{
29499    return sqlite3AddInt64(pA, -iB);
29500  }
29501#endif
29502}
29503SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
29504#if GCC_VERSION>=5004000
29505  return __builtin_mul_overflow(*pA, iB, pA);
29506#else
29507  i64 iA = *pA;
29508  if( iB>0 ){
29509    if( iA>LARGEST_INT64/iB ) return 1;
29510    if( iA<SMALLEST_INT64/iB ) return 1;
29511  }else if( iB<0 ){
29512    if( iA>0 ){
29513      if( iB<SMALLEST_INT64/iA ) return 1;
29514    }else if( iA<0 ){
29515      if( iB==SMALLEST_INT64 ) return 1;
29516      if( iA==SMALLEST_INT64 ) return 1;
29517      if( -iA>LARGEST_INT64/-iB ) return 1;
29518    }
29519  }
29520  *pA = iA*iB;
29521  return 0;
29522#endif
29523}
29524
29525/*
29526** Compute the absolute value of a 32-bit signed integer, of possible.  Or
29527** if the integer has a value of -2147483648, return +2147483647
29528*/
29529SQLITE_PRIVATE int sqlite3AbsInt32(int x){
29530  if( x>=0 ) return x;
29531  if( x==(int)0x80000000 ) return 0x7fffffff;
29532  return -x;
29533}
29534
29535#ifdef SQLITE_ENABLE_8_3_NAMES
29536/*
29537** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
29538** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
29539** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
29540** three characters, then shorten the suffix on z[] to be the last three
29541** characters of the original suffix.
29542**
29543** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
29544** do the suffix shortening regardless of URI parameter.
29545**
29546** Examples:
29547**
29548**     test.db-journal    =>   test.nal
29549**     test.db-wal        =>   test.wal
29550**     test.db-shm        =>   test.shm
29551**     test.db-mj7f3319fa =>   test.9fa
29552*/
29553SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
29554#if SQLITE_ENABLE_8_3_NAMES<2
29555  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
29556#endif
29557  {
29558    int i, sz;
29559    sz = sqlite3Strlen30(z);
29560    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
29561    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
29562  }
29563}
29564#endif
29565
29566/*
29567** Find (an approximate) sum of two LogEst values.  This computation is
29568** not a simple "+" operator because LogEst is stored as a logarithmic
29569** value.
29570**
29571*/
29572SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
29573  static const unsigned char x[] = {
29574     10, 10,                         /* 0,1 */
29575      9, 9,                          /* 2,3 */
29576      8, 8,                          /* 4,5 */
29577      7, 7, 7,                       /* 6,7,8 */
29578      6, 6, 6,                       /* 9,10,11 */
29579      5, 5, 5,                       /* 12-14 */
29580      4, 4, 4, 4,                    /* 15-18 */
29581      3, 3, 3, 3, 3, 3,              /* 19-24 */
29582      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
29583  };
29584  if( a>=b ){
29585    if( a>b+49 ) return a;
29586    if( a>b+31 ) return a+1;
29587    return a+x[a-b];
29588  }else{
29589    if( b>a+49 ) return b;
29590    if( b>a+31 ) return b+1;
29591    return b+x[b-a];
29592  }
29593}
29594
29595/*
29596** Convert an integer into a LogEst.  In other words, compute an
29597** approximation for 10*log2(x).
29598*/
29599SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
29600  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
29601  LogEst y = 40;
29602  if( x<8 ){
29603    if( x<2 ) return 0;
29604    while( x<8 ){  y -= 10; x <<= 1; }
29605  }else{
29606    while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
29607    while( x>15 ){  y += 10; x >>= 1; }
29608  }
29609  return a[x&7] + y - 10;
29610}
29611
29612#ifndef SQLITE_OMIT_VIRTUALTABLE
29613/*
29614** Convert a double into a LogEst
29615** In other words, compute an approximation for 10*log2(x).
29616*/
29617SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
29618  u64 a;
29619  LogEst e;
29620  assert( sizeof(x)==8 && sizeof(a)==8 );
29621  if( x<=1 ) return 0;
29622  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
29623  memcpy(&a, &x, 8);
29624  e = (a>>52) - 1022;
29625  return e*10;
29626}
29627#endif /* SQLITE_OMIT_VIRTUALTABLE */
29628
29629#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
29630    defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
29631    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
29632/*
29633** Convert a LogEst into an integer.
29634**
29635** Note that this routine is only used when one or more of various
29636** non-standard compile-time options is enabled.
29637*/
29638SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
29639  u64 n;
29640  n = x%10;
29641  x /= 10;
29642  if( n>=5 ) n -= 2;
29643  else if( n>=1 ) n -= 1;
29644#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
29645    defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
29646  if( x>60 ) return (u64)LARGEST_INT64;
29647#else
29648  /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
29649  ** possible to this routine is 310, resulting in a maximum x of 31 */
29650  assert( x<=60 );
29651#endif
29652  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
29653}
29654#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
29655
29656/*
29657** Add a new name/number pair to a VList.  This might require that the
29658** VList object be reallocated, so return the new VList.  If an OOM
29659** error occurs, the original VList returned and the
29660** db->mallocFailed flag is set.
29661**
29662** A VList is really just an array of integers.  To destroy a VList,
29663** simply pass it to sqlite3DbFree().
29664**
29665** The first integer is the number of integers allocated for the whole
29666** VList.  The second integer is the number of integers actually used.
29667** Each name/number pair is encoded by subsequent groups of 3 or more
29668** integers.
29669**
29670** Each name/number pair starts with two integers which are the numeric
29671** value for the pair and the size of the name/number pair, respectively.
29672** The text name overlays one or more following integers.  The text name
29673** is always zero-terminated.
29674**
29675** Conceptually:
29676**
29677**    struct VList {
29678**      int nAlloc;   // Number of allocated slots
29679**      int nUsed;    // Number of used slots
29680**      struct VListEntry {
29681**        int iValue;    // Value for this entry
29682**        int nSlot;     // Slots used by this entry
29683**        // ... variable name goes here
29684**      } a[0];
29685**    }
29686**
29687** During code generation, pointers to the variable names within the
29688** VList are taken.  When that happens, nAlloc is set to zero as an
29689** indication that the VList may never again be enlarged, since the
29690** accompanying realloc() would invalidate the pointers.
29691*/
29692SQLITE_PRIVATE VList *sqlite3VListAdd(
29693  sqlite3 *db,           /* The database connection used for malloc() */
29694  VList *pIn,            /* The input VList.  Might be NULL */
29695  const char *zName,     /* Name of symbol to add */
29696  int nName,             /* Bytes of text in zName */
29697  int iVal               /* Value to associate with zName */
29698){
29699  int nInt;              /* number of sizeof(int) objects needed for zName */
29700  char *z;               /* Pointer to where zName will be stored */
29701  int i;                 /* Index in pIn[] where zName is stored */
29702
29703  nInt = nName/4 + 3;
29704  assert( pIn==0 || pIn[0]>=3 );  /* Verify ok to add new elements */
29705  if( pIn==0 || pIn[1]+nInt > pIn[0] ){
29706    /* Enlarge the allocation */
29707    int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
29708    VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
29709    if( pOut==0 ) return pIn;
29710    if( pIn==0 ) pOut[1] = 2;
29711    pIn = pOut;
29712    pIn[0] = nAlloc;
29713  }
29714  i = pIn[1];
29715  pIn[i] = iVal;
29716  pIn[i+1] = nInt;
29717  z = (char*)&pIn[i+2];
29718  pIn[1] = i+nInt;
29719  assert( pIn[1]<=pIn[0] );
29720  memcpy(z, zName, nName);
29721  z[nName] = 0;
29722  return pIn;
29723}
29724
29725/*
29726** Return a pointer to the name of a variable in the given VList that
29727** has the value iVal.  Or return a NULL if there is no such variable in
29728** the list
29729*/
29730SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
29731  int i, mx;
29732  if( pIn==0 ) return 0;
29733  mx = pIn[1];
29734  i = 2;
29735  do{
29736    if( pIn[i]==iVal ) return (char*)&pIn[i+2];
29737    i += pIn[i+1];
29738  }while( i<mx );
29739  return 0;
29740}
29741
29742/*
29743** Return the number of the variable named zName, if it is in VList.
29744** or return 0 if there is no such variable.
29745*/
29746SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
29747  int i, mx;
29748  if( pIn==0 ) return 0;
29749  mx = pIn[1];
29750  i = 2;
29751  do{
29752    const char *z = (const char*)&pIn[i+2];
29753    if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
29754    i += pIn[i+1];
29755  }while( i<mx );
29756  return 0;
29757}
29758
29759/************** End of util.c ************************************************/
29760/************** Begin file hash.c ********************************************/
29761/*
29762** 2001 September 22
29763**
29764** The author disclaims copyright to this source code.  In place of
29765** a legal notice, here is a blessing:
29766**
29767**    May you do good and not evil.
29768**    May you find forgiveness for yourself and forgive others.
29769**    May you share freely, never taking more than you give.
29770**
29771*************************************************************************
29772** This is the implementation of generic hash-tables
29773** used in SQLite.
29774*/
29775/* #include "sqliteInt.h" */
29776/* #include <assert.h> */
29777
29778/* Turn bulk memory into a hash table object by initializing the
29779** fields of the Hash structure.
29780**
29781** "pNew" is a pointer to the hash table that is to be initialized.
29782*/
29783SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
29784  assert( pNew!=0 );
29785  pNew->first = 0;
29786  pNew->count = 0;
29787  pNew->htsize = 0;
29788  pNew->ht = 0;
29789}
29790
29791/* Remove all entries from a hash table.  Reclaim all memory.
29792** Call this routine to delete a hash table or to reset a hash table
29793** to the empty state.
29794*/
29795SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
29796  HashElem *elem;         /* For looping over all elements of the table */
29797
29798  assert( pH!=0 );
29799  elem = pH->first;
29800  pH->first = 0;
29801  sqlite3_free(pH->ht);
29802  pH->ht = 0;
29803  pH->htsize = 0;
29804  while( elem ){
29805    HashElem *next_elem = elem->next;
29806    sqlite3_free(elem);
29807    elem = next_elem;
29808  }
29809  pH->count = 0;
29810}
29811
29812/*
29813** The hashing function.
29814*/
29815static unsigned int strHash(const char *z){
29816  unsigned int h = 0;
29817  unsigned char c;
29818  while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/
29819    /* Knuth multiplicative hashing.  (Sorting & Searching, p. 510).
29820    ** 0x9e3779b1 is 2654435761 which is the closest prime number to
29821    ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
29822    h += sqlite3UpperToLower[c];
29823    h *= 0x9e3779b1;
29824  }
29825  return h;
29826}
29827
29828
29829/* Link pNew element into the hash table pH.  If pEntry!=0 then also
29830** insert pNew into the pEntry hash bucket.
29831*/
29832static void insertElement(
29833  Hash *pH,              /* The complete hash table */
29834  struct _ht *pEntry,    /* The entry into which pNew is inserted */
29835  HashElem *pNew         /* The element to be inserted */
29836){
29837  HashElem *pHead;       /* First element already in pEntry */
29838  if( pEntry ){
29839    pHead = pEntry->count ? pEntry->chain : 0;
29840    pEntry->count++;
29841    pEntry->chain = pNew;
29842  }else{
29843    pHead = 0;
29844  }
29845  if( pHead ){
29846    pNew->next = pHead;
29847    pNew->prev = pHead->prev;
29848    if( pHead->prev ){ pHead->prev->next = pNew; }
29849    else             { pH->first = pNew; }
29850    pHead->prev = pNew;
29851  }else{
29852    pNew->next = pH->first;
29853    if( pH->first ){ pH->first->prev = pNew; }
29854    pNew->prev = 0;
29855    pH->first = pNew;
29856  }
29857}
29858
29859
29860/* Resize the hash table so that it cantains "new_size" buckets.
29861**
29862** The hash table might fail to resize if sqlite3_malloc() fails or
29863** if the new size is the same as the prior size.
29864** Return TRUE if the resize occurs and false if not.
29865*/
29866static int rehash(Hash *pH, unsigned int new_size){
29867  struct _ht *new_ht;            /* The new hash table */
29868  HashElem *elem, *next_elem;    /* For looping over existing elements */
29869
29870#if SQLITE_MALLOC_SOFT_LIMIT>0
29871  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
29872    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
29873  }
29874  if( new_size==pH->htsize ) return 0;
29875#endif
29876
29877  /* The inability to allocates space for a larger hash table is
29878  ** a performance hit but it is not a fatal error.  So mark the
29879  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
29880  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
29881  ** only zeroes the requested number of bytes whereas this module will
29882  ** use the actual amount of space allocated for the hash table (which
29883  ** may be larger than the requested amount).
29884  */
29885  sqlite3BeginBenignMalloc();
29886  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
29887  sqlite3EndBenignMalloc();
29888
29889  if( new_ht==0 ) return 0;
29890  sqlite3_free(pH->ht);
29891  pH->ht = new_ht;
29892  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
29893  memset(new_ht, 0, new_size*sizeof(struct _ht));
29894  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
29895    unsigned int h = strHash(elem->pKey) % new_size;
29896    next_elem = elem->next;
29897    insertElement(pH, &new_ht[h], elem);
29898  }
29899  return 1;
29900}
29901
29902/* This function (for internal use only) locates an element in an
29903** hash table that matches the given key.  If no element is found,
29904** a pointer to a static null element with HashElem.data==0 is returned.
29905** If pH is not NULL, then the hash for this key is written to *pH.
29906*/
29907static HashElem *findElementWithHash(
29908  const Hash *pH,     /* The pH to be searched */
29909  const char *pKey,   /* The key we are searching for */
29910  unsigned int *pHash /* Write the hash value here */
29911){
29912  HashElem *elem;                /* Used to loop thru the element list */
29913  int count;                     /* Number of elements left to test */
29914  unsigned int h;                /* The computed hash */
29915  static HashElem nullElement = { 0, 0, 0, 0 };
29916
29917  if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
29918    struct _ht *pEntry;
29919    h = strHash(pKey) % pH->htsize;
29920    pEntry = &pH->ht[h];
29921    elem = pEntry->chain;
29922    count = pEntry->count;
29923  }else{
29924    h = 0;
29925    elem = pH->first;
29926    count = pH->count;
29927  }
29928  if( pHash ) *pHash = h;
29929  while( count-- ){
29930    assert( elem!=0 );
29931    if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
29932      return elem;
29933    }
29934    elem = elem->next;
29935  }
29936  return &nullElement;
29937}
29938
29939/* Remove a single entry from the hash table given a pointer to that
29940** element and a hash on the element's key.
29941*/
29942static void removeElementGivenHash(
29943  Hash *pH,         /* The pH containing "elem" */
29944  HashElem* elem,   /* The element to be removed from the pH */
29945  unsigned int h    /* Hash value for the element */
29946){
29947  struct _ht *pEntry;
29948  if( elem->prev ){
29949    elem->prev->next = elem->next;
29950  }else{
29951    pH->first = elem->next;
29952  }
29953  if( elem->next ){
29954    elem->next->prev = elem->prev;
29955  }
29956  if( pH->ht ){
29957    pEntry = &pH->ht[h];
29958    if( pEntry->chain==elem ){
29959      pEntry->chain = elem->next;
29960    }
29961    pEntry->count--;
29962    assert( pEntry->count>=0 );
29963  }
29964  sqlite3_free( elem );
29965  pH->count--;
29966  if( pH->count==0 ){
29967    assert( pH->first==0 );
29968    assert( pH->count==0 );
29969    sqlite3HashClear(pH);
29970  }
29971}
29972
29973/* Attempt to locate an element of the hash table pH with a key
29974** that matches pKey.  Return the data for this element if it is
29975** found, or NULL if there is no match.
29976*/
29977SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
29978  assert( pH!=0 );
29979  assert( pKey!=0 );
29980  return findElementWithHash(pH, pKey, 0)->data;
29981}
29982
29983/* Insert an element into the hash table pH.  The key is pKey
29984** and the data is "data".
29985**
29986** If no element exists with a matching key, then a new
29987** element is created and NULL is returned.
29988**
29989** If another element already exists with the same key, then the
29990** new data replaces the old data and the old data is returned.
29991** The key is not copied in this instance.  If a malloc fails, then
29992** the new data is returned and the hash table is unchanged.
29993**
29994** If the "data" parameter to this function is NULL, then the
29995** element corresponding to "key" is removed from the hash table.
29996*/
29997SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
29998  unsigned int h;       /* the hash of the key modulo hash table size */
29999  HashElem *elem;       /* Used to loop thru the element list */
30000  HashElem *new_elem;   /* New element added to the pH */
30001
30002  assert( pH!=0 );
30003  assert( pKey!=0 );
30004  elem = findElementWithHash(pH,pKey,&h);
30005  if( elem->data ){
30006    void *old_data = elem->data;
30007    if( data==0 ){
30008      removeElementGivenHash(pH,elem,h);
30009    }else{
30010      elem->data = data;
30011      elem->pKey = pKey;
30012    }
30013    return old_data;
30014  }
30015  if( data==0 ) return 0;
30016  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
30017  if( new_elem==0 ) return data;
30018  new_elem->pKey = pKey;
30019  new_elem->data = data;
30020  pH->count++;
30021  if( pH->count>=10 && pH->count > 2*pH->htsize ){
30022    if( rehash(pH, pH->count*2) ){
30023      assert( pH->htsize>0 );
30024      h = strHash(pKey) % pH->htsize;
30025    }
30026  }
30027  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
30028  return 0;
30029}
30030
30031/************** End of hash.c ************************************************/
30032/************** Begin file opcodes.c *****************************************/
30033/* Automatically generated.  Do not edit */
30034/* See the tool/mkopcodec.tcl script for details. */
30035#if !defined(SQLITE_OMIT_EXPLAIN) \
30036 || defined(VDBE_PROFILE) \
30037 || defined(SQLITE_DEBUG)
30038#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
30039# define OpHelp(X) "\0" X
30040#else
30041# define OpHelp(X)
30042#endif
30043SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
30044 static const char *const azName[] = {
30045    /*   0 */ "Savepoint"        OpHelp(""),
30046    /*   1 */ "AutoCommit"       OpHelp(""),
30047    /*   2 */ "Transaction"      OpHelp(""),
30048    /*   3 */ "SorterNext"       OpHelp(""),
30049    /*   4 */ "PrevIfOpen"       OpHelp(""),
30050    /*   5 */ "NextIfOpen"       OpHelp(""),
30051    /*   6 */ "Prev"             OpHelp(""),
30052    /*   7 */ "Next"             OpHelp(""),
30053    /*   8 */ "Checkpoint"       OpHelp(""),
30054    /*   9 */ "JournalMode"      OpHelp(""),
30055    /*  10 */ "Vacuum"           OpHelp(""),
30056    /*  11 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
30057    /*  12 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
30058    /*  13 */ "Goto"             OpHelp(""),
30059    /*  14 */ "Gosub"            OpHelp(""),
30060    /*  15 */ "InitCoroutine"    OpHelp(""),
30061    /*  16 */ "Yield"            OpHelp(""),
30062    /*  17 */ "MustBeInt"        OpHelp(""),
30063    /*  18 */ "Jump"             OpHelp(""),
30064    /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
30065    /*  20 */ "Once"             OpHelp(""),
30066    /*  21 */ "If"               OpHelp(""),
30067    /*  22 */ "IfNot"            OpHelp(""),
30068    /*  23 */ "IfNullRow"        OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
30069    /*  24 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
30070    /*  25 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
30071    /*  26 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
30072    /*  27 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
30073    /*  28 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
30074    /*  29 */ "NotFound"         OpHelp("key=r[P3@P4]"),
30075    /*  30 */ "Found"            OpHelp("key=r[P3@P4]"),
30076    /*  31 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
30077    /*  32 */ "NotExists"        OpHelp("intkey=r[P3]"),
30078    /*  33 */ "Last"             OpHelp(""),
30079    /*  34 */ "IfSmaller"        OpHelp(""),
30080    /*  35 */ "SorterSort"       OpHelp(""),
30081    /*  36 */ "Sort"             OpHelp(""),
30082    /*  37 */ "Rewind"           OpHelp(""),
30083    /*  38 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
30084    /*  39 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
30085    /*  40 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
30086    /*  41 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
30087    /*  42 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
30088    /*  43 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
30089    /*  44 */ "Program"          OpHelp(""),
30090    /*  45 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
30091    /*  46 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
30092    /*  47 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
30093    /*  48 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
30094    /*  49 */ "IncrVacuum"       OpHelp(""),
30095    /*  50 */ "VNext"            OpHelp(""),
30096    /*  51 */ "Init"             OpHelp("Start at P2"),
30097    /*  52 */ "Return"           OpHelp(""),
30098    /*  53 */ "EndCoroutine"     OpHelp(""),
30099    /*  54 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
30100    /*  55 */ "Halt"             OpHelp(""),
30101    /*  56 */ "Integer"          OpHelp("r[P2]=P1"),
30102    /*  57 */ "Int64"            OpHelp("r[P2]=P4"),
30103    /*  58 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
30104    /*  59 */ "Null"             OpHelp("r[P2..P3]=NULL"),
30105    /*  60 */ "SoftNull"         OpHelp("r[P1]=NULL"),
30106    /*  61 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
30107    /*  62 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
30108    /*  63 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
30109    /*  64 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
30110    /*  65 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
30111    /*  66 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
30112    /*  67 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
30113    /*  68 */ "CollSeq"          OpHelp(""),
30114    /*  69 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
30115    /*  70 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
30116    /*  71 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
30117    /*  72 */ "RealAffinity"     OpHelp(""),
30118    /*  73 */ "Cast"             OpHelp("affinity(r[P1])"),
30119    /*  74 */ "Permutation"      OpHelp(""),
30120    /*  75 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
30121    /*  76 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
30122    /*  77 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
30123    /*  78 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
30124    /*  79 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
30125    /*  80 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
30126    /*  81 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
30127    /*  82 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
30128    /*  83 */ "ElseNotEq"        OpHelp(""),
30129    /*  84 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
30130    /*  85 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
30131    /*  86 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
30132    /*  87 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
30133    /*  88 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
30134    /*  89 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
30135    /*  90 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
30136    /*  91 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
30137    /*  92 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
30138    /*  93 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
30139    /*  94 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
30140    /*  95 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
30141    /*  96 */ "Column"           OpHelp("r[P3]=PX"),
30142    /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
30143    /*  98 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
30144    /*  99 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
30145    /* 100 */ "Count"            OpHelp("r[P2]=count()"),
30146    /* 101 */ "ReadCookie"       OpHelp(""),
30147    /* 102 */ "SetCookie"        OpHelp(""),
30148    /* 103 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
30149    /* 104 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
30150    /* 105 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
30151    /* 106 */ "OpenDup"          OpHelp(""),
30152    /* 107 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
30153    /* 108 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
30154    /* 109 */ "SorterOpen"       OpHelp(""),
30155    /* 110 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
30156    /* 111 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
30157    /* 112 */ "Close"            OpHelp(""),
30158    /* 113 */ "ColumnsUsed"      OpHelp(""),
30159    /* 114 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
30160    /* 115 */ "NewRowid"         OpHelp("r[P2]=rowid"),
30161    /* 116 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
30162    /* 117 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
30163    /* 118 */ "Delete"           OpHelp(""),
30164    /* 119 */ "ResetCount"       OpHelp(""),
30165    /* 120 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
30166    /* 121 */ "SorterData"       OpHelp("r[P2]=data"),
30167    /* 122 */ "RowData"          OpHelp("r[P2]=data"),
30168    /* 123 */ "Rowid"            OpHelp("r[P2]=rowid"),
30169    /* 124 */ "NullRow"          OpHelp(""),
30170    /* 125 */ "SorterInsert"     OpHelp("key=r[P2]"),
30171    /* 126 */ "IdxInsert"        OpHelp("key=r[P2]"),
30172    /* 127 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
30173    /* 128 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
30174    /* 129 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
30175    /* 130 */ "Destroy"          OpHelp(""),
30176    /* 131 */ "Clear"            OpHelp(""),
30177    /* 132 */ "Real"             OpHelp("r[P2]=P4"),
30178    /* 133 */ "ResetSorter"      OpHelp(""),
30179    /* 134 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
30180    /* 135 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
30181    /* 136 */ "SqlExec"          OpHelp(""),
30182    /* 137 */ "ParseSchema"      OpHelp(""),
30183    /* 138 */ "LoadAnalysis"     OpHelp(""),
30184    /* 139 */ "DropTable"        OpHelp(""),
30185    /* 140 */ "DropIndex"        OpHelp(""),
30186    /* 141 */ "DropTrigger"      OpHelp(""),
30187    /* 142 */ "IntegrityCk"      OpHelp(""),
30188    /* 143 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
30189    /* 144 */ "Param"            OpHelp(""),
30190    /* 145 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
30191    /* 146 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
30192    /* 147 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
30193    /* 148 */ "AggStep0"         OpHelp("accum=r[P3] step(r[P2@P5])"),
30194    /* 149 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
30195    /* 150 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
30196    /* 151 */ "Expire"           OpHelp(""),
30197    /* 152 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
30198    /* 153 */ "VBegin"           OpHelp(""),
30199    /* 154 */ "VCreate"          OpHelp(""),
30200    /* 155 */ "VDestroy"         OpHelp(""),
30201    /* 156 */ "VOpen"            OpHelp(""),
30202    /* 157 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
30203    /* 158 */ "VRename"          OpHelp(""),
30204    /* 159 */ "Pagecount"        OpHelp(""),
30205    /* 160 */ "MaxPgcnt"         OpHelp(""),
30206    /* 161 */ "PureFunc0"        OpHelp(""),
30207    /* 162 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
30208    /* 163 */ "PureFunc"         OpHelp(""),
30209    /* 164 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
30210    /* 165 */ "CursorHint"       OpHelp(""),
30211    /* 166 */ "Noop"             OpHelp(""),
30212    /* 167 */ "Explain"          OpHelp(""),
30213  };
30214  return azName[i];
30215}
30216#endif
30217
30218/************** End of opcodes.c *********************************************/
30219/************** Begin file os_unix.c *****************************************/
30220/*
30221** 2004 May 22
30222**
30223** The author disclaims copyright to this source code.  In place of
30224** a legal notice, here is a blessing:
30225**
30226**    May you do good and not evil.
30227**    May you find forgiveness for yourself and forgive others.
30228**    May you share freely, never taking more than you give.
30229**
30230******************************************************************************
30231**
30232** This file contains the VFS implementation for unix-like operating systems
30233** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
30234**
30235** There are actually several different VFS implementations in this file.
30236** The differences are in the way that file locking is done.  The default
30237** implementation uses Posix Advisory Locks.  Alternative implementations
30238** use flock(), dot-files, various proprietary locking schemas, or simply
30239** skip locking all together.
30240**
30241** This source file is organized into divisions where the logic for various
30242** subfunctions is contained within the appropriate division.  PLEASE
30243** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
30244** in the correct division and should be clearly labeled.
30245**
30246** The layout of divisions is as follows:
30247**
30248**   *  General-purpose declarations and utility functions.
30249**   *  Unique file ID logic used by VxWorks.
30250**   *  Various locking primitive implementations (all except proxy locking):
30251**      + for Posix Advisory Locks
30252**      + for no-op locks
30253**      + for dot-file locks
30254**      + for flock() locking
30255**      + for named semaphore locks (VxWorks only)
30256**      + for AFP filesystem locks (MacOSX only)
30257**   *  sqlite3_file methods not associated with locking.
30258**   *  Definitions of sqlite3_io_methods objects for all locking
30259**      methods plus "finder" functions for each locking method.
30260**   *  sqlite3_vfs method implementations.
30261**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
30262**   *  Definitions of sqlite3_vfs objects for all locking methods
30263**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
30264*/
30265/* #include "sqliteInt.h" */
30266#if SQLITE_OS_UNIX              /* This file is used on unix only */
30267
30268/*
30269** There are various methods for file locking used for concurrency
30270** control:
30271**
30272**   1. POSIX locking (the default),
30273**   2. No locking,
30274**   3. Dot-file locking,
30275**   4. flock() locking,
30276**   5. AFP locking (OSX only),
30277**   6. Named POSIX semaphores (VXWorks only),
30278**   7. proxy locking. (OSX only)
30279**
30280** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
30281** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
30282** selection of the appropriate locking style based on the filesystem
30283** where the database is located.
30284*/
30285#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
30286#  if defined(__APPLE__)
30287#    define SQLITE_ENABLE_LOCKING_STYLE 1
30288#  else
30289#    define SQLITE_ENABLE_LOCKING_STYLE 0
30290#  endif
30291#endif
30292
30293/* Use pread() and pwrite() if they are available */
30294#if defined(__APPLE__)
30295# define HAVE_PREAD 1
30296# define HAVE_PWRITE 1
30297#endif
30298#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
30299# undef USE_PREAD
30300# define USE_PREAD64 1
30301#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
30302# undef USE_PREAD64
30303# define USE_PREAD 1
30304#endif
30305
30306/*
30307** standard include files.
30308*/
30309#include <sys/types.h>
30310#include <sys/stat.h>
30311#include <fcntl.h>
30312#include <unistd.h>
30313/* #include <time.h> */
30314#include <sys/time.h>
30315#include <errno.h>
30316#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30317# include <sys/mman.h>
30318#endif
30319
30320#if SQLITE_ENABLE_LOCKING_STYLE
30321# include <sys/ioctl.h>
30322# include <sys/file.h>
30323# include <sys/param.h>
30324#endif /* SQLITE_ENABLE_LOCKING_STYLE */
30325
30326#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
30327                           (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
30328#  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
30329       && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
30330#    define HAVE_GETHOSTUUID 1
30331#  else
30332#    warning "gethostuuid() is disabled."
30333#  endif
30334#endif
30335
30336
30337#if OS_VXWORKS
30338/* # include <sys/ioctl.h> */
30339# include <semaphore.h>
30340# include <limits.h>
30341#endif /* OS_VXWORKS */
30342
30343#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30344# include <sys/mount.h>
30345#endif
30346
30347#ifdef HAVE_UTIME
30348# include <utime.h>
30349#endif
30350
30351/*
30352** Allowed values of unixFile.fsFlags
30353*/
30354#define SQLITE_FSFLAGS_IS_MSDOS     0x1
30355
30356/*
30357** If we are to be thread-safe, include the pthreads header and define
30358** the SQLITE_UNIX_THREADS macro.
30359*/
30360#if SQLITE_THREADSAFE
30361/* # include <pthread.h> */
30362# define SQLITE_UNIX_THREADS 1
30363#endif
30364
30365/*
30366** Default permissions when creating a new file
30367*/
30368#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
30369# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
30370#endif
30371
30372/*
30373** Default permissions when creating auto proxy dir
30374*/
30375#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30376# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
30377#endif
30378
30379/*
30380** Maximum supported path-length.
30381*/
30382#define MAX_PATHNAME 512
30383
30384/*
30385** Maximum supported symbolic links
30386*/
30387#define SQLITE_MAX_SYMLINKS 100
30388
30389/* Always cast the getpid() return type for compatibility with
30390** kernel modules in VxWorks. */
30391#define osGetpid(X) (pid_t)getpid()
30392
30393/*
30394** Only set the lastErrno if the error code is a real error and not
30395** a normal expected return code of SQLITE_BUSY or SQLITE_OK
30396*/
30397#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
30398
30399/* Forward references */
30400typedef struct unixShm unixShm;               /* Connection shared memory */
30401typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
30402typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
30403typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
30404
30405/*
30406** Sometimes, after a file handle is closed by SQLite, the file descriptor
30407** cannot be closed immediately. In these cases, instances of the following
30408** structure are used to store the file descriptor while waiting for an
30409** opportunity to either close or reuse it.
30410*/
30411struct UnixUnusedFd {
30412  int fd;                   /* File descriptor to close */
30413  int flags;                /* Flags this file descriptor was opened with */
30414  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
30415};
30416
30417/*
30418** The unixFile structure is subclass of sqlite3_file specific to the unix
30419** VFS implementations.
30420*/
30421typedef struct unixFile unixFile;
30422struct unixFile {
30423  sqlite3_io_methods const *pMethod;  /* Always the first entry */
30424  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
30425  unixInodeInfo *pInode;              /* Info about locks on this inode */
30426  int h;                              /* The file descriptor */
30427  unsigned char eFileLock;            /* The type of lock held on this fd */
30428  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
30429  int lastErrno;                      /* The unix errno from last I/O error */
30430  void *lockingContext;               /* Locking style specific state */
30431  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
30432  const char *zPath;                  /* Name of the file */
30433  unixShm *pShm;                      /* Shared memory segment information */
30434  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
30435#if SQLITE_MAX_MMAP_SIZE>0
30436  int nFetchOut;                      /* Number of outstanding xFetch refs */
30437  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
30438  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
30439  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
30440  void *pMapRegion;                   /* Memory mapped region */
30441#endif
30442#ifdef __QNXNTO__
30443  int sectorSize;                     /* Device sector size */
30444  int deviceCharacteristics;          /* Precomputed device characteristics */
30445#endif
30446#if SQLITE_ENABLE_LOCKING_STYLE
30447  int openFlags;                      /* The flags specified at open() */
30448#endif
30449#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
30450  unsigned fsFlags;                   /* cached details from statfs() */
30451#endif
30452#if OS_VXWORKS
30453  struct vxworksFileId *pId;          /* Unique file ID */
30454#endif
30455#ifdef SQLITE_DEBUG
30456  /* The next group of variables are used to track whether or not the
30457  ** transaction counter in bytes 24-27 of database files are updated
30458  ** whenever any part of the database changes.  An assertion fault will
30459  ** occur if a file is updated without also updating the transaction
30460  ** counter.  This test is made to avoid new problems similar to the
30461  ** one described by ticket #3584.
30462  */
30463  unsigned char transCntrChng;   /* True if the transaction counter changed */
30464  unsigned char dbUpdate;        /* True if any part of database file changed */
30465  unsigned char inNormalWrite;   /* True if in a normal write operation */
30466
30467#endif
30468
30469#ifdef SQLITE_TEST
30470  /* In test mode, increase the size of this structure a bit so that
30471  ** it is larger than the struct CrashFile defined in test6.c.
30472  */
30473  char aPadding[32];
30474#endif
30475};
30476
30477/* This variable holds the process id (pid) from when the xRandomness()
30478** method was called.  If xOpen() is called from a different process id,
30479** indicating that a fork() has occurred, the PRNG will be reset.
30480*/
30481static pid_t randomnessPid = 0;
30482
30483/*
30484** Allowed values for the unixFile.ctrlFlags bitmask:
30485*/
30486#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
30487#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
30488#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
30489#ifndef SQLITE_DISABLE_DIRSYNC
30490# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
30491#else
30492# define UNIXFILE_DIRSYNC    0x00
30493#endif
30494#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
30495#define UNIXFILE_DELETE      0x20     /* Delete on close */
30496#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
30497#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
30498
30499/*
30500** Include code that is common to all os_*.c files
30501*/
30502/************** Include os_common.h in the middle of os_unix.c ***************/
30503/************** Begin file os_common.h ***************************************/
30504/*
30505** 2004 May 22
30506**
30507** The author disclaims copyright to this source code.  In place of
30508** a legal notice, here is a blessing:
30509**
30510**    May you do good and not evil.
30511**    May you find forgiveness for yourself and forgive others.
30512**    May you share freely, never taking more than you give.
30513**
30514******************************************************************************
30515**
30516** This file contains macros and a little bit of code that is common to
30517** all of the platform-specific files (os_*.c) and is #included into those
30518** files.
30519**
30520** This file should be #included by the os_*.c files only.  It is not a
30521** general purpose header file.
30522*/
30523#ifndef _OS_COMMON_H_
30524#define _OS_COMMON_H_
30525
30526/*
30527** At least two bugs have slipped in because we changed the MEMORY_DEBUG
30528** macro to SQLITE_DEBUG and some older makefiles have not yet made the
30529** switch.  The following code should catch this problem at compile-time.
30530*/
30531#ifdef MEMORY_DEBUG
30532# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
30533#endif
30534
30535/*
30536** Macros for performance tracing.  Normally turned off.  Only works
30537** on i486 hardware.
30538*/
30539#ifdef SQLITE_PERFORMANCE_TRACE
30540
30541/*
30542** hwtime.h contains inline assembler code for implementing
30543** high-performance timing routines.
30544*/
30545/************** Include hwtime.h in the middle of os_common.h ****************/
30546/************** Begin file hwtime.h ******************************************/
30547/*
30548** 2008 May 27
30549**
30550** The author disclaims copyright to this source code.  In place of
30551** a legal notice, here is a blessing:
30552**
30553**    May you do good and not evil.
30554**    May you find forgiveness for yourself and forgive others.
30555**    May you share freely, never taking more than you give.
30556**
30557******************************************************************************
30558**
30559** This file contains inline asm code for retrieving "high-performance"
30560** counters for x86 class CPUs.
30561*/
30562#ifndef SQLITE_HWTIME_H
30563#define SQLITE_HWTIME_H
30564
30565/*
30566** The following routine only works on pentium-class (or newer) processors.
30567** It uses the RDTSC opcode to read the cycle count value out of the
30568** processor and returns that value.  This can be used for high-res
30569** profiling.
30570*/
30571#if (defined(__GNUC__) || defined(_MSC_VER)) && \
30572      (defined(i386) || defined(__i386__) || defined(_M_IX86))
30573
30574  #if defined(__GNUC__)
30575
30576  __inline__ sqlite_uint64 sqlite3Hwtime(void){
30577     unsigned int lo, hi;
30578     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30579     return (sqlite_uint64)hi << 32 | lo;
30580  }
30581
30582  #elif defined(_MSC_VER)
30583
30584  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30585     __asm {
30586        rdtsc
30587        ret       ; return value at EDX:EAX
30588     }
30589  }
30590
30591  #endif
30592
30593#elif (defined(__GNUC__) && defined(__x86_64__))
30594
30595  __inline__ sqlite_uint64 sqlite3Hwtime(void){
30596      unsigned long val;
30597      __asm__ __volatile__ ("rdtsc" : "=A" (val));
30598      return val;
30599  }
30600
30601#elif (defined(__GNUC__) && defined(__ppc__))
30602
30603  __inline__ sqlite_uint64 sqlite3Hwtime(void){
30604      unsigned long long retval;
30605      unsigned long junk;
30606      __asm__ __volatile__ ("\n\
30607          1:      mftbu   %1\n\
30608                  mftb    %L0\n\
30609                  mftbu   %0\n\
30610                  cmpw    %0,%1\n\
30611                  bne     1b"
30612                  : "=r" (retval), "=r" (junk));
30613      return retval;
30614  }
30615
30616#else
30617
30618  #error Need implementation of sqlite3Hwtime() for your platform.
30619
30620  /*
30621  ** To compile without implementing sqlite3Hwtime() for your platform,
30622  ** you can remove the above #error and use the following
30623  ** stub function.  You will lose timing support for many
30624  ** of the debugging and testing utilities, but it should at
30625  ** least compile and run.
30626  */
30627SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30628
30629#endif
30630
30631#endif /* !defined(SQLITE_HWTIME_H) */
30632
30633/************** End of hwtime.h **********************************************/
30634/************** Continuing where we left off in os_common.h ******************/
30635
30636static sqlite_uint64 g_start;
30637static sqlite_uint64 g_elapsed;
30638#define TIMER_START       g_start=sqlite3Hwtime()
30639#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
30640#define TIMER_ELAPSED     g_elapsed
30641#else
30642#define TIMER_START
30643#define TIMER_END
30644#define TIMER_ELAPSED     ((sqlite_uint64)0)
30645#endif
30646
30647/*
30648** If we compile with the SQLITE_TEST macro set, then the following block
30649** of code will give us the ability to simulate a disk I/O error.  This
30650** is used for testing the I/O recovery logic.
30651*/
30652#if defined(SQLITE_TEST)
30653SQLITE_API extern int sqlite3_io_error_hit;
30654SQLITE_API extern int sqlite3_io_error_hardhit;
30655SQLITE_API extern int sqlite3_io_error_pending;
30656SQLITE_API extern int sqlite3_io_error_persist;
30657SQLITE_API extern int sqlite3_io_error_benign;
30658SQLITE_API extern int sqlite3_diskfull_pending;
30659SQLITE_API extern int sqlite3_diskfull;
30660#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30661#define SimulateIOError(CODE)  \
30662  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30663       || sqlite3_io_error_pending-- == 1 )  \
30664              { local_ioerr(); CODE; }
30665static void local_ioerr(){
30666  IOTRACE(("IOERR\n"));
30667  sqlite3_io_error_hit++;
30668  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30669}
30670#define SimulateDiskfullError(CODE) \
30671   if( sqlite3_diskfull_pending ){ \
30672     if( sqlite3_diskfull_pending == 1 ){ \
30673       local_ioerr(); \
30674       sqlite3_diskfull = 1; \
30675       sqlite3_io_error_hit = 1; \
30676       CODE; \
30677     }else{ \
30678       sqlite3_diskfull_pending--; \
30679     } \
30680   }
30681#else
30682#define SimulateIOErrorBenign(X)
30683#define SimulateIOError(A)
30684#define SimulateDiskfullError(A)
30685#endif /* defined(SQLITE_TEST) */
30686
30687/*
30688** When testing, keep a count of the number of open files.
30689*/
30690#if defined(SQLITE_TEST)
30691SQLITE_API extern int sqlite3_open_file_count;
30692#define OpenCounter(X)  sqlite3_open_file_count+=(X)
30693#else
30694#define OpenCounter(X)
30695#endif /* defined(SQLITE_TEST) */
30696
30697#endif /* !defined(_OS_COMMON_H_) */
30698
30699/************** End of os_common.h *******************************************/
30700/************** Continuing where we left off in os_unix.c ********************/
30701
30702/*
30703** Define various macros that are missing from some systems.
30704*/
30705#ifndef O_LARGEFILE
30706# define O_LARGEFILE 0
30707#endif
30708#ifdef SQLITE_DISABLE_LFS
30709# undef O_LARGEFILE
30710# define O_LARGEFILE 0
30711#endif
30712#ifndef O_NOFOLLOW
30713# define O_NOFOLLOW 0
30714#endif
30715#ifndef O_BINARY
30716# define O_BINARY 0
30717#endif
30718
30719/*
30720** The threadid macro resolves to the thread-id or to 0.  Used for
30721** testing and debugging only.
30722*/
30723#if SQLITE_THREADSAFE
30724#define threadid pthread_self()
30725#else
30726#define threadid 0
30727#endif
30728
30729/*
30730** HAVE_MREMAP defaults to true on Linux and false everywhere else.
30731*/
30732#if !defined(HAVE_MREMAP)
30733# if defined(__linux__) && defined(_GNU_SOURCE)
30734#  define HAVE_MREMAP 1
30735# else
30736#  define HAVE_MREMAP 0
30737# endif
30738#endif
30739
30740/*
30741** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
30742** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
30743*/
30744#ifdef __ANDROID__
30745# define lseek lseek64
30746#endif
30747
30748/*
30749** Different Unix systems declare open() in different ways.  Same use
30750** open(const char*,int,mode_t).  Others use open(const char*,int,...).
30751** The difference is important when using a pointer to the function.
30752**
30753** The safest way to deal with the problem is to always use this wrapper
30754** which always has the same well-defined interface.
30755*/
30756static int posixOpen(const char *zFile, int flags, int mode){
30757  return open(zFile, flags, mode);
30758}
30759
30760/* Forward reference */
30761static int openDirectory(const char*, int*);
30762static int unixGetpagesize(void);
30763
30764/*
30765** Many system calls are accessed through pointer-to-functions so that
30766** they may be overridden at runtime to facilitate fault injection during
30767** testing and sandboxing.  The following array holds the names and pointers
30768** to all overrideable system calls.
30769*/
30770static struct unix_syscall {
30771  const char *zName;            /* Name of the system call */
30772  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
30773  sqlite3_syscall_ptr pDefault; /* Default value */
30774} aSyscall[] = {
30775  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
30776#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
30777
30778  { "close",        (sqlite3_syscall_ptr)close,      0  },
30779#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
30780
30781  { "access",       (sqlite3_syscall_ptr)access,     0  },
30782#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
30783
30784  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
30785#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
30786
30787  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
30788#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
30789
30790/*
30791** The DJGPP compiler environment looks mostly like Unix, but it
30792** lacks the fcntl() system call.  So redefine fcntl() to be something
30793** that always succeeds.  This means that locking does not occur under
30794** DJGPP.  But it is DOS - what did you expect?
30795*/
30796#ifdef __DJGPP__
30797  { "fstat",        0,                 0  },
30798#define osFstat(a,b,c)    0
30799#else
30800  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
30801#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
30802#endif
30803
30804  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
30805#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
30806
30807  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
30808#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
30809
30810  { "read",         (sqlite3_syscall_ptr)read,       0  },
30811#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
30812
30813#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
30814  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
30815#else
30816  { "pread",        (sqlite3_syscall_ptr)0,          0  },
30817#endif
30818#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
30819
30820#if defined(USE_PREAD64)
30821  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
30822#else
30823  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
30824#endif
30825#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
30826
30827  { "write",        (sqlite3_syscall_ptr)write,      0  },
30828#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
30829
30830#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
30831  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
30832#else
30833  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
30834#endif
30835#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
30836                    aSyscall[12].pCurrent)
30837
30838#if defined(USE_PREAD64)
30839  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
30840#else
30841  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
30842#endif
30843#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
30844                    aSyscall[13].pCurrent)
30845
30846  { "fchmod",       (sqlite3_syscall_ptr)fchmod,          0  },
30847#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
30848
30849#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
30850  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
30851#else
30852  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
30853#endif
30854#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
30855
30856  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
30857#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
30858
30859  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
30860#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
30861
30862  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
30863#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
30864
30865  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
30866#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
30867
30868#if defined(HAVE_FCHOWN)
30869  { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
30870#else
30871  { "fchown",       (sqlite3_syscall_ptr)0,               0 },
30872#endif
30873#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
30874
30875  { "geteuid",      (sqlite3_syscall_ptr)geteuid,         0 },
30876#define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)
30877
30878#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30879  { "mmap",         (sqlite3_syscall_ptr)mmap,            0 },
30880#else
30881  { "mmap",         (sqlite3_syscall_ptr)0,               0 },
30882#endif
30883#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
30884
30885#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30886  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
30887#else
30888  { "munmap",       (sqlite3_syscall_ptr)0,               0 },
30889#endif
30890#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
30891
30892#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
30893  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
30894#else
30895  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
30896#endif
30897#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
30898
30899#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
30900  { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
30901#else
30902  { "getpagesize",  (sqlite3_syscall_ptr)0,               0 },
30903#endif
30904#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
30905
30906#if defined(HAVE_READLINK)
30907  { "readlink",     (sqlite3_syscall_ptr)readlink,        0 },
30908#else
30909  { "readlink",     (sqlite3_syscall_ptr)0,               0 },
30910#endif
30911#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
30912
30913#if defined(HAVE_LSTAT)
30914  { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
30915#else
30916  { "lstat",         (sqlite3_syscall_ptr)0,              0 },
30917#endif
30918#define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
30919
30920}; /* End of the overrideable system calls */
30921
30922
30923/*
30924** On some systems, calls to fchown() will trigger a message in a security
30925** log if they come from non-root processes.  So avoid calling fchown() if
30926** we are not running as root.
30927*/
30928static int robustFchown(int fd, uid_t uid, gid_t gid){
30929#if defined(HAVE_FCHOWN)
30930  return osGeteuid() ? 0 : osFchown(fd,uid,gid);
30931#else
30932  return 0;
30933#endif
30934}
30935
30936/*
30937** This is the xSetSystemCall() method of sqlite3_vfs for all of the
30938** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
30939** system call pointer, or SQLITE_NOTFOUND if there is no configurable
30940** system call named zName.
30941*/
30942static int unixSetSystemCall(
30943  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
30944  const char *zName,            /* Name of system call to override */
30945  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
30946){
30947  unsigned int i;
30948  int rc = SQLITE_NOTFOUND;
30949
30950  UNUSED_PARAMETER(pNotUsed);
30951  if( zName==0 ){
30952    /* If no zName is given, restore all system calls to their default
30953    ** settings and return NULL
30954    */
30955    rc = SQLITE_OK;
30956    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30957      if( aSyscall[i].pDefault ){
30958        aSyscall[i].pCurrent = aSyscall[i].pDefault;
30959      }
30960    }
30961  }else{
30962    /* If zName is specified, operate on only the one system call
30963    ** specified.
30964    */
30965    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30966      if( strcmp(zName, aSyscall[i].zName)==0 ){
30967        if( aSyscall[i].pDefault==0 ){
30968          aSyscall[i].pDefault = aSyscall[i].pCurrent;
30969        }
30970        rc = SQLITE_OK;
30971        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
30972        aSyscall[i].pCurrent = pNewFunc;
30973        break;
30974      }
30975    }
30976  }
30977  return rc;
30978}
30979
30980/*
30981** Return the value of a system call.  Return NULL if zName is not a
30982** recognized system call name.  NULL is also returned if the system call
30983** is currently undefined.
30984*/
30985static sqlite3_syscall_ptr unixGetSystemCall(
30986  sqlite3_vfs *pNotUsed,
30987  const char *zName
30988){
30989  unsigned int i;
30990
30991  UNUSED_PARAMETER(pNotUsed);
30992  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
30993    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
30994  }
30995  return 0;
30996}
30997
30998/*
30999** Return the name of the first system call after zName.  If zName==NULL
31000** then return the name of the first system call.  Return NULL if zName
31001** is the last system call or if zName is not the name of a valid
31002** system call.
31003*/
31004static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
31005  int i = -1;
31006
31007  UNUSED_PARAMETER(p);
31008  if( zName ){
31009    for(i=0; i<ArraySize(aSyscall)-1; i++){
31010      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
31011    }
31012  }
31013  for(i++; i<ArraySize(aSyscall); i++){
31014    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
31015  }
31016  return 0;
31017}
31018
31019/*
31020** Do not accept any file descriptor less than this value, in order to avoid
31021** opening database file using file descriptors that are commonly used for
31022** standard input, output, and error.
31023*/
31024#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
31025# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
31026#endif
31027
31028/*
31029** Invoke open().  Do so multiple times, until it either succeeds or
31030** fails for some reason other than EINTR.
31031**
31032** If the file creation mode "m" is 0 then set it to the default for
31033** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
31034** 0644) as modified by the system umask.  If m is not 0, then
31035** make the file creation mode be exactly m ignoring the umask.
31036**
31037** The m parameter will be non-zero only when creating -wal, -journal,
31038** and -shm files.  We want those files to have *exactly* the same
31039** permissions as their original database, unadulterated by the umask.
31040** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
31041** transaction crashes and leaves behind hot journals, then any
31042** process that is able to write to the database will also be able to
31043** recover the hot journals.
31044*/
31045static int robust_open(const char *z, int f, mode_t m){
31046  int fd;
31047  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
31048  while(1){
31049#if defined(O_CLOEXEC)
31050    fd = osOpen(z,f|O_CLOEXEC,m2);
31051#else
31052    fd = osOpen(z,f,m2);
31053#endif
31054    if( fd<0 ){
31055      if( errno==EINTR ) continue;
31056      break;
31057    }
31058    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
31059    osClose(fd);
31060    sqlite3_log(SQLITE_WARNING,
31061                "attempt to open \"%s\" as file descriptor %d", z, fd);
31062    fd = -1;
31063    if( osOpen("/dev/null", f, m)<0 ) break;
31064  }
31065  if( fd>=0 ){
31066    if( m!=0 ){
31067      struct stat statbuf;
31068      if( osFstat(fd, &statbuf)==0
31069       && statbuf.st_size==0
31070       && (statbuf.st_mode&0777)!=m
31071      ){
31072        osFchmod(fd, m);
31073      }
31074    }
31075#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
31076    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
31077#endif
31078  }
31079  return fd;
31080}
31081
31082/*
31083** Helper functions to obtain and relinquish the global mutex. The
31084** global mutex is used to protect the unixInodeInfo and
31085** vxworksFileId objects used by this file, all of which may be
31086** shared by multiple threads.
31087**
31088** Function unixMutexHeld() is used to assert() that the global mutex
31089** is held when required. This function is only used as part of assert()
31090** statements. e.g.
31091**
31092**   unixEnterMutex()
31093**     assert( unixMutexHeld() );
31094**   unixEnterLeave()
31095*/
31096static void unixEnterMutex(void){
31097  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
31098}
31099static void unixLeaveMutex(void){
31100  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
31101}
31102#ifdef SQLITE_DEBUG
31103static int unixMutexHeld(void) {
31104  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
31105}
31106#endif
31107
31108
31109#ifdef SQLITE_HAVE_OS_TRACE
31110/*
31111** Helper function for printing out trace information from debugging
31112** binaries. This returns the string representation of the supplied
31113** integer lock-type.
31114*/
31115static const char *azFileLock(int eFileLock){
31116  switch( eFileLock ){
31117    case NO_LOCK: return "NONE";
31118    case SHARED_LOCK: return "SHARED";
31119    case RESERVED_LOCK: return "RESERVED";
31120    case PENDING_LOCK: return "PENDING";
31121    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
31122  }
31123  return "ERROR";
31124}
31125#endif
31126
31127#ifdef SQLITE_LOCK_TRACE
31128/*
31129** Print out information about all locking operations.
31130**
31131** This routine is used for troubleshooting locks on multithreaded
31132** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
31133** command-line option on the compiler.  This code is normally
31134** turned off.
31135*/
31136static int lockTrace(int fd, int op, struct flock *p){
31137  char *zOpName, *zType;
31138  int s;
31139  int savedErrno;
31140  if( op==F_GETLK ){
31141    zOpName = "GETLK";
31142  }else if( op==F_SETLK ){
31143    zOpName = "SETLK";
31144  }else{
31145    s = osFcntl(fd, op, p);
31146    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
31147    return s;
31148  }
31149  if( p->l_type==F_RDLCK ){
31150    zType = "RDLCK";
31151  }else if( p->l_type==F_WRLCK ){
31152    zType = "WRLCK";
31153  }else if( p->l_type==F_UNLCK ){
31154    zType = "UNLCK";
31155  }else{
31156    assert( 0 );
31157  }
31158  assert( p->l_whence==SEEK_SET );
31159  s = osFcntl(fd, op, p);
31160  savedErrno = errno;
31161  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
31162     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
31163     (int)p->l_pid, s);
31164  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
31165    struct flock l2;
31166    l2 = *p;
31167    osFcntl(fd, F_GETLK, &l2);
31168    if( l2.l_type==F_RDLCK ){
31169      zType = "RDLCK";
31170    }else if( l2.l_type==F_WRLCK ){
31171      zType = "WRLCK";
31172    }else if( l2.l_type==F_UNLCK ){
31173      zType = "UNLCK";
31174    }else{
31175      assert( 0 );
31176    }
31177    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
31178       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
31179  }
31180  errno = savedErrno;
31181  return s;
31182}
31183#undef osFcntl
31184#define osFcntl lockTrace
31185#endif /* SQLITE_LOCK_TRACE */
31186
31187/*
31188** Retry ftruncate() calls that fail due to EINTR
31189**
31190** All calls to ftruncate() within this file should be made through
31191** this wrapper.  On the Android platform, bypassing the logic below
31192** could lead to a corrupt database.
31193*/
31194static int robust_ftruncate(int h, sqlite3_int64 sz){
31195  int rc;
31196#ifdef __ANDROID__
31197  /* On Android, ftruncate() always uses 32-bit offsets, even if
31198  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
31199  ** truncate a file to any size larger than 2GiB. Silently ignore any
31200  ** such attempts.  */
31201  if( sz>(sqlite3_int64)0x7FFFFFFF ){
31202    rc = SQLITE_OK;
31203  }else
31204#endif
31205  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
31206  return rc;
31207}
31208
31209/*
31210** This routine translates a standard POSIX errno code into something
31211** useful to the clients of the sqlite3 functions.  Specifically, it is
31212** intended to translate a variety of "try again" errors into SQLITE_BUSY
31213** and a variety of "please close the file descriptor NOW" errors into
31214** SQLITE_IOERR
31215**
31216** Errors during initialization of locks, or file system support for locks,
31217** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
31218*/
31219static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
31220  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
31221          (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
31222          (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
31223          (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
31224  switch (posixError) {
31225  case EACCES:
31226  case EAGAIN:
31227  case ETIMEDOUT:
31228  case EBUSY:
31229  case EINTR:
31230  case ENOLCK:
31231    /* random NFS retry error, unless during file system support
31232     * introspection, in which it actually means what it says */
31233    return SQLITE_BUSY;
31234
31235  case EPERM:
31236    return SQLITE_PERM;
31237
31238  default:
31239    return sqliteIOErr;
31240  }
31241}
31242
31243
31244/******************************************************************************
31245****************** Begin Unique File ID Utility Used By VxWorks ***************
31246**
31247** On most versions of unix, we can get a unique ID for a file by concatenating
31248** the device number and the inode number.  But this does not work on VxWorks.
31249** On VxWorks, a unique file id must be based on the canonical filename.
31250**
31251** A pointer to an instance of the following structure can be used as a
31252** unique file ID in VxWorks.  Each instance of this structure contains
31253** a copy of the canonical filename.  There is also a reference count.
31254** The structure is reclaimed when the number of pointers to it drops to
31255** zero.
31256**
31257** There are never very many files open at one time and lookups are not
31258** a performance-critical path, so it is sufficient to put these
31259** structures on a linked list.
31260*/
31261struct vxworksFileId {
31262  struct vxworksFileId *pNext;  /* Next in a list of them all */
31263  int nRef;                     /* Number of references to this one */
31264  int nName;                    /* Length of the zCanonicalName[] string */
31265  char *zCanonicalName;         /* Canonical filename */
31266};
31267
31268#if OS_VXWORKS
31269/*
31270** All unique filenames are held on a linked list headed by this
31271** variable:
31272*/
31273static struct vxworksFileId *vxworksFileList = 0;
31274
31275/*
31276** Simplify a filename into its canonical form
31277** by making the following changes:
31278**
31279**  * removing any trailing and duplicate /
31280**  * convert /./ into just /
31281**  * convert /A/../ where A is any simple name into just /
31282**
31283** Changes are made in-place.  Return the new name length.
31284**
31285** The original filename is in z[0..n-1].  Return the number of
31286** characters in the simplified name.
31287*/
31288static int vxworksSimplifyName(char *z, int n){
31289  int i, j;
31290  while( n>1 && z[n-1]=='/' ){ n--; }
31291  for(i=j=0; i<n; i++){
31292    if( z[i]=='/' ){
31293      if( z[i+1]=='/' ) continue;
31294      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
31295        i += 1;
31296        continue;
31297      }
31298      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
31299        while( j>0 && z[j-1]!='/' ){ j--; }
31300        if( j>0 ){ j--; }
31301        i += 2;
31302        continue;
31303      }
31304    }
31305    z[j++] = z[i];
31306  }
31307  z[j] = 0;
31308  return j;
31309}
31310
31311/*
31312** Find a unique file ID for the given absolute pathname.  Return
31313** a pointer to the vxworksFileId object.  This pointer is the unique
31314** file ID.
31315**
31316** The nRef field of the vxworksFileId object is incremented before
31317** the object is returned.  A new vxworksFileId object is created
31318** and added to the global list if necessary.
31319**
31320** If a memory allocation error occurs, return NULL.
31321*/
31322static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
31323  struct vxworksFileId *pNew;         /* search key and new file ID */
31324  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
31325  int n;                              /* Length of zAbsoluteName string */
31326
31327  assert( zAbsoluteName[0]=='/' );
31328  n = (int)strlen(zAbsoluteName);
31329  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
31330  if( pNew==0 ) return 0;
31331  pNew->zCanonicalName = (char*)&pNew[1];
31332  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
31333  n = vxworksSimplifyName(pNew->zCanonicalName, n);
31334
31335  /* Search for an existing entry that matching the canonical name.
31336  ** If found, increment the reference count and return a pointer to
31337  ** the existing file ID.
31338  */
31339  unixEnterMutex();
31340  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
31341    if( pCandidate->nName==n
31342     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
31343    ){
31344       sqlite3_free(pNew);
31345       pCandidate->nRef++;
31346       unixLeaveMutex();
31347       return pCandidate;
31348    }
31349  }
31350
31351  /* No match was found.  We will make a new file ID */
31352  pNew->nRef = 1;
31353  pNew->nName = n;
31354  pNew->pNext = vxworksFileList;
31355  vxworksFileList = pNew;
31356  unixLeaveMutex();
31357  return pNew;
31358}
31359
31360/*
31361** Decrement the reference count on a vxworksFileId object.  Free
31362** the object when the reference count reaches zero.
31363*/
31364static void vxworksReleaseFileId(struct vxworksFileId *pId){
31365  unixEnterMutex();
31366  assert( pId->nRef>0 );
31367  pId->nRef--;
31368  if( pId->nRef==0 ){
31369    struct vxworksFileId **pp;
31370    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
31371    assert( *pp==pId );
31372    *pp = pId->pNext;
31373    sqlite3_free(pId);
31374  }
31375  unixLeaveMutex();
31376}
31377#endif /* OS_VXWORKS */
31378/*************** End of Unique File ID Utility Used By VxWorks ****************
31379******************************************************************************/
31380
31381
31382/******************************************************************************
31383*************************** Posix Advisory Locking ****************************
31384**
31385** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
31386** section 6.5.2.2 lines 483 through 490 specify that when a process
31387** sets or clears a lock, that operation overrides any prior locks set
31388** by the same process.  It does not explicitly say so, but this implies
31389** that it overrides locks set by the same process using a different
31390** file descriptor.  Consider this test case:
31391**
31392**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
31393**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
31394**
31395** Suppose ./file1 and ./file2 are really the same file (because
31396** one is a hard or symbolic link to the other) then if you set
31397** an exclusive lock on fd1, then try to get an exclusive lock
31398** on fd2, it works.  I would have expected the second lock to
31399** fail since there was already a lock on the file due to fd1.
31400** But not so.  Since both locks came from the same process, the
31401** second overrides the first, even though they were on different
31402** file descriptors opened on different file names.
31403**
31404** This means that we cannot use POSIX locks to synchronize file access
31405** among competing threads of the same process.  POSIX locks will work fine
31406** to synchronize access for threads in separate processes, but not
31407** threads within the same process.
31408**
31409** To work around the problem, SQLite has to manage file locks internally
31410** on its own.  Whenever a new database is opened, we have to find the
31411** specific inode of the database file (the inode is determined by the
31412** st_dev and st_ino fields of the stat structure that fstat() fills in)
31413** and check for locks already existing on that inode.  When locks are
31414** created or removed, we have to look at our own internal record of the
31415** locks to see if another thread has previously set a lock on that same
31416** inode.
31417**
31418** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
31419** For VxWorks, we have to use the alternative unique ID system based on
31420** canonical filename and implemented in the previous division.)
31421**
31422** The sqlite3_file structure for POSIX is no longer just an integer file
31423** descriptor.  It is now a structure that holds the integer file
31424** descriptor and a pointer to a structure that describes the internal
31425** locks on the corresponding inode.  There is one locking structure
31426** per inode, so if the same inode is opened twice, both unixFile structures
31427** point to the same locking structure.  The locking structure keeps
31428** a reference count (so we will know when to delete it) and a "cnt"
31429** field that tells us its internal lock status.  cnt==0 means the
31430** file is unlocked.  cnt==-1 means the file has an exclusive lock.
31431** cnt>0 means there are cnt shared locks on the file.
31432**
31433** Any attempt to lock or unlock a file first checks the locking
31434** structure.  The fcntl() system call is only invoked to set a
31435** POSIX lock if the internal lock structure transitions between
31436** a locked and an unlocked state.
31437**
31438** But wait:  there are yet more problems with POSIX advisory locks.
31439**
31440** If you close a file descriptor that points to a file that has locks,
31441** all locks on that file that are owned by the current process are
31442** released.  To work around this problem, each unixInodeInfo object
31443** maintains a count of the number of pending locks on tha inode.
31444** When an attempt is made to close an unixFile, if there are
31445** other unixFile open on the same inode that are holding locks, the call
31446** to close() the file descriptor is deferred until all of the locks clear.
31447** The unixInodeInfo structure keeps a list of file descriptors that need to
31448** be closed and that list is walked (and cleared) when the last lock
31449** clears.
31450**
31451** Yet another problem:  LinuxThreads do not play well with posix locks.
31452**
31453** Many older versions of linux use the LinuxThreads library which is
31454** not posix compliant.  Under LinuxThreads, a lock created by thread
31455** A cannot be modified or overridden by a different thread B.
31456** Only thread A can modify the lock.  Locking behavior is correct
31457** if the appliation uses the newer Native Posix Thread Library (NPTL)
31458** on linux - with NPTL a lock created by thread A can override locks
31459** in thread B.  But there is no way to know at compile-time which
31460** threading library is being used.  So there is no way to know at
31461** compile-time whether or not thread A can override locks on thread B.
31462** One has to do a run-time check to discover the behavior of the
31463** current process.
31464**
31465** SQLite used to support LinuxThreads.  But support for LinuxThreads
31466** was dropped beginning with version 3.7.0.  SQLite will still work with
31467** LinuxThreads provided that (1) there is no more than one connection
31468** per database file in the same process and (2) database connections
31469** do not move across threads.
31470*/
31471
31472/*
31473** An instance of the following structure serves as the key used
31474** to locate a particular unixInodeInfo object.
31475*/
31476struct unixFileId {
31477  dev_t dev;                  /* Device number */
31478#if OS_VXWORKS
31479  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
31480#else
31481  /* We are told that some versions of Android contain a bug that
31482  ** sizes ino_t at only 32-bits instead of 64-bits. (See
31483  ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
31484  ** To work around this, always allocate 64-bits for the inode number.
31485  ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
31486  ** but that should not be a big deal. */
31487  /* WAS:  ino_t ino;   */
31488  u64 ino;                   /* Inode number */
31489#endif
31490};
31491
31492/*
31493** An instance of the following structure is allocated for each open
31494** inode.  Or, on LinuxThreads, there is one of these structures for
31495** each inode opened by each thread.
31496**
31497** A single inode can have multiple file descriptors, so each unixFile
31498** structure contains a pointer to an instance of this object and this
31499** object keeps a count of the number of unixFile pointing to it.
31500*/
31501struct unixInodeInfo {
31502  struct unixFileId fileId;       /* The lookup key */
31503  int nShared;                    /* Number of SHARED locks held */
31504  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
31505  unsigned char bProcessLock;     /* An exclusive process lock is held */
31506  int nRef;                       /* Number of pointers to this structure */
31507  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
31508  int nLock;                      /* Number of outstanding file locks */
31509  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
31510  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
31511  unixInodeInfo *pPrev;           /*    .... doubly linked */
31512#if SQLITE_ENABLE_LOCKING_STYLE
31513  unsigned long long sharedByte;  /* for AFP simulated shared lock */
31514#endif
31515#if OS_VXWORKS
31516  sem_t *pSem;                    /* Named POSIX semaphore */
31517  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
31518#endif
31519};
31520
31521/*
31522** A lists of all unixInodeInfo objects.
31523*/
31524static unixInodeInfo *inodeList = 0;
31525
31526/*
31527**
31528** This function - unixLogErrorAtLine(), is only ever called via the macro
31529** unixLogError().
31530**
31531** It is invoked after an error occurs in an OS function and errno has been
31532** set. It logs a message using sqlite3_log() containing the current value of
31533** errno and, if possible, the human-readable equivalent from strerror() or
31534** strerror_r().
31535**
31536** The first argument passed to the macro should be the error code that
31537** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
31538** The two subsequent arguments should be the name of the OS function that
31539** failed (e.g. "unlink", "open") and the associated file-system path,
31540** if any.
31541*/
31542#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
31543static int unixLogErrorAtLine(
31544  int errcode,                    /* SQLite error code */
31545  const char *zFunc,              /* Name of OS function that failed */
31546  const char *zPath,              /* File path associated with error */
31547  int iLine                       /* Source line number where error occurred */
31548){
31549  char *zErr;                     /* Message from strerror() or equivalent */
31550  int iErrno = errno;             /* Saved syscall error number */
31551
31552  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
31553  ** the strerror() function to obtain the human-readable error message
31554  ** equivalent to errno. Otherwise, use strerror_r().
31555  */
31556#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
31557  char aErr[80];
31558  memset(aErr, 0, sizeof(aErr));
31559  zErr = aErr;
31560
31561  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
31562  ** assume that the system provides the GNU version of strerror_r() that
31563  ** returns a pointer to a buffer containing the error message. That pointer
31564  ** may point to aErr[], or it may point to some static storage somewhere.
31565  ** Otherwise, assume that the system provides the POSIX version of
31566  ** strerror_r(), which always writes an error message into aErr[].
31567  **
31568  ** If the code incorrectly assumes that it is the POSIX version that is
31569  ** available, the error message will often be an empty string. Not a
31570  ** huge problem. Incorrectly concluding that the GNU version is available
31571  ** could lead to a segfault though.
31572  */
31573#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
31574  zErr =
31575# endif
31576  strerror_r(iErrno, aErr, sizeof(aErr)-1);
31577
31578#elif SQLITE_THREADSAFE
31579  /* This is a threadsafe build, but strerror_r() is not available. */
31580  zErr = "";
31581#else
31582  /* Non-threadsafe build, use strerror(). */
31583  zErr = strerror(iErrno);
31584#endif
31585
31586  if( zPath==0 ) zPath = "";
31587  sqlite3_log(errcode,
31588      "os_unix.c:%d: (%d) %s(%s) - %s",
31589      iLine, iErrno, zFunc, zPath, zErr
31590  );
31591
31592  return errcode;
31593}
31594
31595/*
31596** Close a file descriptor.
31597**
31598** We assume that close() almost always works, since it is only in a
31599** very sick application or on a very sick platform that it might fail.
31600** If it does fail, simply leak the file descriptor, but do log the
31601** error.
31602**
31603** Note that it is not safe to retry close() after EINTR since the
31604** file descriptor might have already been reused by another thread.
31605** So we don't even try to recover from an EINTR.  Just log the error
31606** and move on.
31607*/
31608static void robust_close(unixFile *pFile, int h, int lineno){
31609  if( osClose(h) ){
31610    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
31611                       pFile ? pFile->zPath : 0, lineno);
31612  }
31613}
31614
31615/*
31616** Set the pFile->lastErrno.  Do this in a subroutine as that provides
31617** a convenient place to set a breakpoint.
31618*/
31619static void storeLastErrno(unixFile *pFile, int error){
31620  pFile->lastErrno = error;
31621}
31622
31623/*
31624** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
31625*/
31626static void closePendingFds(unixFile *pFile){
31627  unixInodeInfo *pInode = pFile->pInode;
31628  UnixUnusedFd *p;
31629  UnixUnusedFd *pNext;
31630  for(p=pInode->pUnused; p; p=pNext){
31631    pNext = p->pNext;
31632    robust_close(pFile, p->fd, __LINE__);
31633    sqlite3_free(p);
31634  }
31635  pInode->pUnused = 0;
31636}
31637
31638/*
31639** Release a unixInodeInfo structure previously allocated by findInodeInfo().
31640**
31641** The mutex entered using the unixEnterMutex() function must be held
31642** when this function is called.
31643*/
31644static void releaseInodeInfo(unixFile *pFile){
31645  unixInodeInfo *pInode = pFile->pInode;
31646  assert( unixMutexHeld() );
31647  if( ALWAYS(pInode) ){
31648    pInode->nRef--;
31649    if( pInode->nRef==0 ){
31650      assert( pInode->pShmNode==0 );
31651      closePendingFds(pFile);
31652      if( pInode->pPrev ){
31653        assert( pInode->pPrev->pNext==pInode );
31654        pInode->pPrev->pNext = pInode->pNext;
31655      }else{
31656        assert( inodeList==pInode );
31657        inodeList = pInode->pNext;
31658      }
31659      if( pInode->pNext ){
31660        assert( pInode->pNext->pPrev==pInode );
31661        pInode->pNext->pPrev = pInode->pPrev;
31662      }
31663      sqlite3_free(pInode);
31664    }
31665  }
31666}
31667
31668/*
31669** Given a file descriptor, locate the unixInodeInfo object that
31670** describes that file descriptor.  Create a new one if necessary.  The
31671** return value might be uninitialized if an error occurs.
31672**
31673** The mutex entered using the unixEnterMutex() function must be held
31674** when this function is called.
31675**
31676** Return an appropriate error code.
31677*/
31678static int findInodeInfo(
31679  unixFile *pFile,               /* Unix file with file desc used in the key */
31680  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
31681){
31682  int rc;                        /* System call return code */
31683  int fd;                        /* The file descriptor for pFile */
31684  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
31685  struct stat statbuf;           /* Low-level file information */
31686  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
31687
31688  assert( unixMutexHeld() );
31689
31690  /* Get low-level information about the file that we can used to
31691  ** create a unique name for the file.
31692  */
31693  fd = pFile->h;
31694  rc = osFstat(fd, &statbuf);
31695  if( rc!=0 ){
31696    storeLastErrno(pFile, errno);
31697#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
31698    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
31699#endif
31700    return SQLITE_IOERR;
31701  }
31702
31703#ifdef __APPLE__
31704  /* On OS X on an msdos filesystem, the inode number is reported
31705  ** incorrectly for zero-size files.  See ticket #3260.  To work
31706  ** around this problem (we consider it a bug in OS X, not SQLite)
31707  ** we always increase the file size to 1 by writing a single byte
31708  ** prior to accessing the inode number.  The one byte written is
31709  ** an ASCII 'S' character which also happens to be the first byte
31710  ** in the header of every SQLite database.  In this way, if there
31711  ** is a race condition such that another thread has already populated
31712  ** the first page of the database, no damage is done.
31713  */
31714  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
31715    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
31716    if( rc!=1 ){
31717      storeLastErrno(pFile, errno);
31718      return SQLITE_IOERR;
31719    }
31720    rc = osFstat(fd, &statbuf);
31721    if( rc!=0 ){
31722      storeLastErrno(pFile, errno);
31723      return SQLITE_IOERR;
31724    }
31725  }
31726#endif
31727
31728  memset(&fileId, 0, sizeof(fileId));
31729  fileId.dev = statbuf.st_dev;
31730#if OS_VXWORKS
31731  fileId.pId = pFile->pId;
31732#else
31733  fileId.ino = (u64)statbuf.st_ino;
31734#endif
31735  pInode = inodeList;
31736  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
31737    pInode = pInode->pNext;
31738  }
31739  if( pInode==0 ){
31740    pInode = sqlite3_malloc64( sizeof(*pInode) );
31741    if( pInode==0 ){
31742      return SQLITE_NOMEM_BKPT;
31743    }
31744    memset(pInode, 0, sizeof(*pInode));
31745    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
31746    pInode->nRef = 1;
31747    pInode->pNext = inodeList;
31748    pInode->pPrev = 0;
31749    if( inodeList ) inodeList->pPrev = pInode;
31750    inodeList = pInode;
31751  }else{
31752    pInode->nRef++;
31753  }
31754  *ppInode = pInode;
31755  return SQLITE_OK;
31756}
31757
31758/*
31759** Return TRUE if pFile has been renamed or unlinked since it was first opened.
31760*/
31761static int fileHasMoved(unixFile *pFile){
31762#if OS_VXWORKS
31763  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
31764#else
31765  struct stat buf;
31766  return pFile->pInode!=0 &&
31767      (osStat(pFile->zPath, &buf)!=0
31768         || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
31769#endif
31770}
31771
31772
31773/*
31774** Check a unixFile that is a database.  Verify the following:
31775**
31776** (1) There is exactly one hard link on the file
31777** (2) The file is not a symbolic link
31778** (3) The file has not been renamed or unlinked
31779**
31780** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
31781*/
31782static void verifyDbFile(unixFile *pFile){
31783  struct stat buf;
31784  int rc;
31785
31786  /* These verifications occurs for the main database only */
31787  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
31788
31789  rc = osFstat(pFile->h, &buf);
31790  if( rc!=0 ){
31791    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
31792    return;
31793  }
31794  if( buf.st_nlink==0 ){
31795    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
31796    return;
31797  }
31798  if( buf.st_nlink>1 ){
31799    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
31800    return;
31801  }
31802  if( fileHasMoved(pFile) ){
31803    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
31804    return;
31805  }
31806}
31807
31808
31809/*
31810** This routine checks if there is a RESERVED lock held on the specified
31811** file by this or any other process. If such a lock is held, set *pResOut
31812** to a non-zero value otherwise *pResOut is set to zero.  The return value
31813** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31814*/
31815static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
31816  int rc = SQLITE_OK;
31817  int reserved = 0;
31818  unixFile *pFile = (unixFile*)id;
31819
31820  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31821
31822  assert( pFile );
31823  assert( pFile->eFileLock<=SHARED_LOCK );
31824  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
31825
31826  /* Check if a thread in this process holds such a lock */
31827  if( pFile->pInode->eFileLock>SHARED_LOCK ){
31828    reserved = 1;
31829  }
31830
31831  /* Otherwise see if some other process holds it.
31832  */
31833#ifndef __DJGPP__
31834  if( !reserved && !pFile->pInode->bProcessLock ){
31835    struct flock lock;
31836    lock.l_whence = SEEK_SET;
31837    lock.l_start = RESERVED_BYTE;
31838    lock.l_len = 1;
31839    lock.l_type = F_WRLCK;
31840    if( osFcntl(pFile->h, F_GETLK, &lock) ){
31841      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
31842      storeLastErrno(pFile, errno);
31843    } else if( lock.l_type!=F_UNLCK ){
31844      reserved = 1;
31845    }
31846  }
31847#endif
31848
31849  unixLeaveMutex();
31850  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
31851
31852  *pResOut = reserved;
31853  return rc;
31854}
31855
31856/*
31857** Attempt to set a system-lock on the file pFile.  The lock is
31858** described by pLock.
31859**
31860** If the pFile was opened read/write from unix-excl, then the only lock
31861** ever obtained is an exclusive lock, and it is obtained exactly once
31862** the first time any lock is attempted.  All subsequent system locking
31863** operations become no-ops.  Locking operations still happen internally,
31864** in order to coordinate access between separate database connections
31865** within this process, but all of that is handled in memory and the
31866** operating system does not participate.
31867**
31868** This function is a pass-through to fcntl(F_SETLK) if pFile is using
31869** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
31870** and is read-only.
31871**
31872** Zero is returned if the call completes successfully, or -1 if a call
31873** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
31874*/
31875static int unixFileLock(unixFile *pFile, struct flock *pLock){
31876  int rc;
31877  unixInodeInfo *pInode = pFile->pInode;
31878  assert( unixMutexHeld() );
31879  assert( pInode!=0 );
31880  if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
31881    if( pInode->bProcessLock==0 ){
31882      struct flock lock;
31883      assert( pInode->nLock==0 );
31884      lock.l_whence = SEEK_SET;
31885      lock.l_start = SHARED_FIRST;
31886      lock.l_len = SHARED_SIZE;
31887      lock.l_type = F_WRLCK;
31888      rc = osFcntl(pFile->h, F_SETLK, &lock);
31889      if( rc<0 ) return rc;
31890      pInode->bProcessLock = 1;
31891      pInode->nLock++;
31892    }else{
31893      rc = 0;
31894    }
31895  }else{
31896    rc = osFcntl(pFile->h, F_SETLK, pLock);
31897  }
31898  return rc;
31899}
31900
31901/*
31902** Lock the file with the lock specified by parameter eFileLock - one
31903** of the following:
31904**
31905**     (1) SHARED_LOCK
31906**     (2) RESERVED_LOCK
31907**     (3) PENDING_LOCK
31908**     (4) EXCLUSIVE_LOCK
31909**
31910** Sometimes when requesting one lock state, additional lock states
31911** are inserted in between.  The locking might fail on one of the later
31912** transitions leaving the lock state different from what it started but
31913** still short of its goal.  The following chart shows the allowed
31914** transitions and the inserted intermediate states:
31915**
31916**    UNLOCKED -> SHARED
31917**    SHARED -> RESERVED
31918**    SHARED -> (PENDING) -> EXCLUSIVE
31919**    RESERVED -> (PENDING) -> EXCLUSIVE
31920**    PENDING -> EXCLUSIVE
31921**
31922** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31923** routine to lower a locking level.
31924*/
31925static int unixLock(sqlite3_file *id, int eFileLock){
31926  /* The following describes the implementation of the various locks and
31927  ** lock transitions in terms of the POSIX advisory shared and exclusive
31928  ** lock primitives (called read-locks and write-locks below, to avoid
31929  ** confusion with SQLite lock names). The algorithms are complicated
31930  ** slightly in order to be compatible with Windows95 systems simultaneously
31931  ** accessing the same database file, in case that is ever required.
31932  **
31933  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
31934  ** byte', each single bytes at well known offsets, and the 'shared byte
31935  ** range', a range of 510 bytes at a well known offset.
31936  **
31937  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
31938  ** byte'.  If this is successful, 'shared byte range' is read-locked
31939  ** and the lock on the 'pending byte' released.  (Legacy note:  When
31940  ** SQLite was first developed, Windows95 systems were still very common,
31941  ** and Widnows95 lacks a shared-lock capability.  So on Windows95, a
31942  ** single randomly selected by from the 'shared byte range' is locked.
31943  ** Windows95 is now pretty much extinct, but this work-around for the
31944  ** lack of shared-locks on Windows95 lives on, for backwards
31945  ** compatibility.)
31946  **
31947  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
31948  ** A RESERVED lock is implemented by grabbing a write-lock on the
31949  ** 'reserved byte'.
31950  **
31951  ** A process may only obtain a PENDING lock after it has obtained a
31952  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
31953  ** on the 'pending byte'. This ensures that no new SHARED locks can be
31954  ** obtained, but existing SHARED locks are allowed to persist. A process
31955  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
31956  ** This property is used by the algorithm for rolling back a journal file
31957  ** after a crash.
31958  **
31959  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
31960  ** implemented by obtaining a write-lock on the entire 'shared byte
31961  ** range'. Since all other locks require a read-lock on one of the bytes
31962  ** within this range, this ensures that no other locks are held on the
31963  ** database.
31964  */
31965  int rc = SQLITE_OK;
31966  unixFile *pFile = (unixFile*)id;
31967  unixInodeInfo *pInode;
31968  struct flock lock;
31969  int tErrno = 0;
31970
31971  assert( pFile );
31972  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
31973      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
31974      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
31975      osGetpid(0)));
31976
31977  /* If there is already a lock of this type or more restrictive on the
31978  ** unixFile, do nothing. Don't use the end_lock: exit path, as
31979  ** unixEnterMutex() hasn't been called yet.
31980  */
31981  if( pFile->eFileLock>=eFileLock ){
31982    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
31983            azFileLock(eFileLock)));
31984    return SQLITE_OK;
31985  }
31986
31987  /* Make sure the locking sequence is correct.
31988  **  (1) We never move from unlocked to anything higher than shared lock.
31989  **  (2) SQLite never explicitly requests a pendig lock.
31990  **  (3) A shared lock is always held when a reserve lock is requested.
31991  */
31992  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
31993  assert( eFileLock!=PENDING_LOCK );
31994  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
31995
31996  /* This mutex is needed because pFile->pInode is shared across threads
31997  */
31998  unixEnterMutex();
31999  pInode = pFile->pInode;
32000
32001  /* If some thread using this PID has a lock via a different unixFile*
32002  ** handle that precludes the requested lock, return BUSY.
32003  */
32004  if( (pFile->eFileLock!=pInode->eFileLock &&
32005          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
32006  ){
32007    rc = SQLITE_BUSY;
32008    goto end_lock;
32009  }
32010
32011  /* If a SHARED lock is requested, and some thread using this PID already
32012  ** has a SHARED or RESERVED lock, then increment reference counts and
32013  ** return SQLITE_OK.
32014  */
32015  if( eFileLock==SHARED_LOCK &&
32016      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
32017    assert( eFileLock==SHARED_LOCK );
32018    assert( pFile->eFileLock==0 );
32019    assert( pInode->nShared>0 );
32020    pFile->eFileLock = SHARED_LOCK;
32021    pInode->nShared++;
32022    pInode->nLock++;
32023    goto end_lock;
32024  }
32025
32026
32027  /* A PENDING lock is needed before acquiring a SHARED lock and before
32028  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
32029  ** be released.
32030  */
32031  lock.l_len = 1L;
32032  lock.l_whence = SEEK_SET;
32033  if( eFileLock==SHARED_LOCK
32034      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
32035  ){
32036    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
32037    lock.l_start = PENDING_BYTE;
32038    if( unixFileLock(pFile, &lock) ){
32039      tErrno = errno;
32040      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32041      if( rc!=SQLITE_BUSY ){
32042        storeLastErrno(pFile, tErrno);
32043      }
32044      goto end_lock;
32045    }
32046  }
32047
32048
32049  /* If control gets to this point, then actually go ahead and make
32050  ** operating system calls for the specified lock.
32051  */
32052  if( eFileLock==SHARED_LOCK ){
32053    assert( pInode->nShared==0 );
32054    assert( pInode->eFileLock==0 );
32055    assert( rc==SQLITE_OK );
32056
32057    /* Now get the read-lock */
32058    lock.l_start = SHARED_FIRST;
32059    lock.l_len = SHARED_SIZE;
32060    if( unixFileLock(pFile, &lock) ){
32061      tErrno = errno;
32062      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32063    }
32064
32065    /* Drop the temporary PENDING lock */
32066    lock.l_start = PENDING_BYTE;
32067    lock.l_len = 1L;
32068    lock.l_type = F_UNLCK;
32069    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
32070      /* This could happen with a network mount */
32071      tErrno = errno;
32072      rc = SQLITE_IOERR_UNLOCK;
32073    }
32074
32075    if( rc ){
32076      if( rc!=SQLITE_BUSY ){
32077        storeLastErrno(pFile, tErrno);
32078      }
32079      goto end_lock;
32080    }else{
32081      pFile->eFileLock = SHARED_LOCK;
32082      pInode->nLock++;
32083      pInode->nShared = 1;
32084    }
32085  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
32086    /* We are trying for an exclusive lock but another thread in this
32087    ** same process is still holding a shared lock. */
32088    rc = SQLITE_BUSY;
32089  }else{
32090    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
32091    ** assumed that there is a SHARED or greater lock on the file
32092    ** already.
32093    */
32094    assert( 0!=pFile->eFileLock );
32095    lock.l_type = F_WRLCK;
32096
32097    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
32098    if( eFileLock==RESERVED_LOCK ){
32099      lock.l_start = RESERVED_BYTE;
32100      lock.l_len = 1L;
32101    }else{
32102      lock.l_start = SHARED_FIRST;
32103      lock.l_len = SHARED_SIZE;
32104    }
32105
32106    if( unixFileLock(pFile, &lock) ){
32107      tErrno = errno;
32108      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32109      if( rc!=SQLITE_BUSY ){
32110        storeLastErrno(pFile, tErrno);
32111      }
32112    }
32113  }
32114
32115
32116#ifdef SQLITE_DEBUG
32117  /* Set up the transaction-counter change checking flags when
32118  ** transitioning from a SHARED to a RESERVED lock.  The change
32119  ** from SHARED to RESERVED marks the beginning of a normal
32120  ** write operation (not a hot journal rollback).
32121  */
32122  if( rc==SQLITE_OK
32123   && pFile->eFileLock<=SHARED_LOCK
32124   && eFileLock==RESERVED_LOCK
32125  ){
32126    pFile->transCntrChng = 0;
32127    pFile->dbUpdate = 0;
32128    pFile->inNormalWrite = 1;
32129  }
32130#endif
32131
32132
32133  if( rc==SQLITE_OK ){
32134    pFile->eFileLock = eFileLock;
32135    pInode->eFileLock = eFileLock;
32136  }else if( eFileLock==EXCLUSIVE_LOCK ){
32137    pFile->eFileLock = PENDING_LOCK;
32138    pInode->eFileLock = PENDING_LOCK;
32139  }
32140
32141end_lock:
32142  unixLeaveMutex();
32143  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
32144      rc==SQLITE_OK ? "ok" : "failed"));
32145  return rc;
32146}
32147
32148/*
32149** Add the file descriptor used by file handle pFile to the corresponding
32150** pUnused list.
32151*/
32152static void setPendingFd(unixFile *pFile){
32153  unixInodeInfo *pInode = pFile->pInode;
32154  UnixUnusedFd *p = pFile->pUnused;
32155  p->pNext = pInode->pUnused;
32156  pInode->pUnused = p;
32157  pFile->h = -1;
32158  pFile->pUnused = 0;
32159}
32160
32161/*
32162** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32163** must be either NO_LOCK or SHARED_LOCK.
32164**
32165** If the locking level of the file descriptor is already at or below
32166** the requested locking level, this routine is a no-op.
32167**
32168** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
32169** the byte range is divided into 2 parts and the first part is unlocked then
32170** set to a read lock, then the other part is simply unlocked.  This works
32171** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
32172** remove the write lock on a region when a read lock is set.
32173*/
32174static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
32175  unixFile *pFile = (unixFile*)id;
32176  unixInodeInfo *pInode;
32177  struct flock lock;
32178  int rc = SQLITE_OK;
32179
32180  assert( pFile );
32181  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
32182      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32183      osGetpid(0)));
32184
32185  assert( eFileLock<=SHARED_LOCK );
32186  if( pFile->eFileLock<=eFileLock ){
32187    return SQLITE_OK;
32188  }
32189  unixEnterMutex();
32190  pInode = pFile->pInode;
32191  assert( pInode->nShared!=0 );
32192  if( pFile->eFileLock>SHARED_LOCK ){
32193    assert( pInode->eFileLock==pFile->eFileLock );
32194
32195#ifdef SQLITE_DEBUG
32196    /* When reducing a lock such that other processes can start
32197    ** reading the database file again, make sure that the
32198    ** transaction counter was updated if any part of the database
32199    ** file changed.  If the transaction counter is not updated,
32200    ** other connections to the same file might not realize that
32201    ** the file has changed and hence might not know to flush their
32202    ** cache.  The use of a stale cache can lead to database corruption.
32203    */
32204    pFile->inNormalWrite = 0;
32205#endif
32206
32207    /* downgrading to a shared lock on NFS involves clearing the write lock
32208    ** before establishing the readlock - to avoid a race condition we downgrade
32209    ** the lock in 2 blocks, so that part of the range will be covered by a
32210    ** write lock until the rest is covered by a read lock:
32211    **  1:   [WWWWW]
32212    **  2:   [....W]
32213    **  3:   [RRRRW]
32214    **  4:   [RRRR.]
32215    */
32216    if( eFileLock==SHARED_LOCK ){
32217#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
32218      (void)handleNFSUnlock;
32219      assert( handleNFSUnlock==0 );
32220#endif
32221#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32222      if( handleNFSUnlock ){
32223        int tErrno;               /* Error code from system call errors */
32224        off_t divSize = SHARED_SIZE - 1;
32225
32226        lock.l_type = F_UNLCK;
32227        lock.l_whence = SEEK_SET;
32228        lock.l_start = SHARED_FIRST;
32229        lock.l_len = divSize;
32230        if( unixFileLock(pFile, &lock)==(-1) ){
32231          tErrno = errno;
32232          rc = SQLITE_IOERR_UNLOCK;
32233          storeLastErrno(pFile, tErrno);
32234          goto end_unlock;
32235        }
32236        lock.l_type = F_RDLCK;
32237        lock.l_whence = SEEK_SET;
32238        lock.l_start = SHARED_FIRST;
32239        lock.l_len = divSize;
32240        if( unixFileLock(pFile, &lock)==(-1) ){
32241          tErrno = errno;
32242          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
32243          if( IS_LOCK_ERROR(rc) ){
32244            storeLastErrno(pFile, tErrno);
32245          }
32246          goto end_unlock;
32247        }
32248        lock.l_type = F_UNLCK;
32249        lock.l_whence = SEEK_SET;
32250        lock.l_start = SHARED_FIRST+divSize;
32251        lock.l_len = SHARED_SIZE-divSize;
32252        if( unixFileLock(pFile, &lock)==(-1) ){
32253          tErrno = errno;
32254          rc = SQLITE_IOERR_UNLOCK;
32255          storeLastErrno(pFile, tErrno);
32256          goto end_unlock;
32257        }
32258      }else
32259#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32260      {
32261        lock.l_type = F_RDLCK;
32262        lock.l_whence = SEEK_SET;
32263        lock.l_start = SHARED_FIRST;
32264        lock.l_len = SHARED_SIZE;
32265        if( unixFileLock(pFile, &lock) ){
32266          /* In theory, the call to unixFileLock() cannot fail because another
32267          ** process is holding an incompatible lock. If it does, this
32268          ** indicates that the other process is not following the locking
32269          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
32270          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
32271          ** an assert to fail). */
32272          rc = SQLITE_IOERR_RDLOCK;
32273          storeLastErrno(pFile, errno);
32274          goto end_unlock;
32275        }
32276      }
32277    }
32278    lock.l_type = F_UNLCK;
32279    lock.l_whence = SEEK_SET;
32280    lock.l_start = PENDING_BYTE;
32281    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
32282    if( unixFileLock(pFile, &lock)==0 ){
32283      pInode->eFileLock = SHARED_LOCK;
32284    }else{
32285      rc = SQLITE_IOERR_UNLOCK;
32286      storeLastErrno(pFile, errno);
32287      goto end_unlock;
32288    }
32289  }
32290  if( eFileLock==NO_LOCK ){
32291    /* Decrement the shared lock counter.  Release the lock using an
32292    ** OS call only when all threads in this same process have released
32293    ** the lock.
32294    */
32295    pInode->nShared--;
32296    if( pInode->nShared==0 ){
32297      lock.l_type = F_UNLCK;
32298      lock.l_whence = SEEK_SET;
32299      lock.l_start = lock.l_len = 0L;
32300      if( unixFileLock(pFile, &lock)==0 ){
32301        pInode->eFileLock = NO_LOCK;
32302      }else{
32303        rc = SQLITE_IOERR_UNLOCK;
32304        storeLastErrno(pFile, errno);
32305        pInode->eFileLock = NO_LOCK;
32306        pFile->eFileLock = NO_LOCK;
32307      }
32308    }
32309
32310    /* Decrement the count of locks against this same file.  When the
32311    ** count reaches zero, close any other file descriptors whose close
32312    ** was deferred because of outstanding locks.
32313    */
32314    pInode->nLock--;
32315    assert( pInode->nLock>=0 );
32316    if( pInode->nLock==0 ){
32317      closePendingFds(pFile);
32318    }
32319  }
32320
32321end_unlock:
32322  unixLeaveMutex();
32323  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32324  return rc;
32325}
32326
32327/*
32328** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32329** must be either NO_LOCK or SHARED_LOCK.
32330**
32331** If the locking level of the file descriptor is already at or below
32332** the requested locking level, this routine is a no-op.
32333*/
32334static int unixUnlock(sqlite3_file *id, int eFileLock){
32335#if SQLITE_MAX_MMAP_SIZE>0
32336  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
32337#endif
32338  return posixUnlock(id, eFileLock, 0);
32339}
32340
32341#if SQLITE_MAX_MMAP_SIZE>0
32342static int unixMapfile(unixFile *pFd, i64 nByte);
32343static void unixUnmapfile(unixFile *pFd);
32344#endif
32345
32346/*
32347** This function performs the parts of the "close file" operation
32348** common to all locking schemes. It closes the directory and file
32349** handles, if they are valid, and sets all fields of the unixFile
32350** structure to 0.
32351**
32352** It is *not* necessary to hold the mutex when this routine is called,
32353** even on VxWorks.  A mutex will be acquired on VxWorks by the
32354** vxworksReleaseFileId() routine.
32355*/
32356static int closeUnixFile(sqlite3_file *id){
32357  unixFile *pFile = (unixFile*)id;
32358#if SQLITE_MAX_MMAP_SIZE>0
32359  unixUnmapfile(pFile);
32360#endif
32361  if( pFile->h>=0 ){
32362    robust_close(pFile, pFile->h, __LINE__);
32363    pFile->h = -1;
32364  }
32365#if OS_VXWORKS
32366  if( pFile->pId ){
32367    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
32368      osUnlink(pFile->pId->zCanonicalName);
32369    }
32370    vxworksReleaseFileId(pFile->pId);
32371    pFile->pId = 0;
32372  }
32373#endif
32374#ifdef SQLITE_UNLINK_AFTER_CLOSE
32375  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
32376    osUnlink(pFile->zPath);
32377    sqlite3_free(*(char**)&pFile->zPath);
32378    pFile->zPath = 0;
32379  }
32380#endif
32381  OSTRACE(("CLOSE   %-3d\n", pFile->h));
32382  OpenCounter(-1);
32383  sqlite3_free(pFile->pUnused);
32384  memset(pFile, 0, sizeof(unixFile));
32385  return SQLITE_OK;
32386}
32387
32388/*
32389** Close a file.
32390*/
32391static int unixClose(sqlite3_file *id){
32392  int rc = SQLITE_OK;
32393  unixFile *pFile = (unixFile *)id;
32394  verifyDbFile(pFile);
32395  unixUnlock(id, NO_LOCK);
32396  unixEnterMutex();
32397
32398  /* unixFile.pInode is always valid here. Otherwise, a different close
32399  ** routine (e.g. nolockClose()) would be called instead.
32400  */
32401  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
32402  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
32403    /* If there are outstanding locks, do not actually close the file just
32404    ** yet because that would clear those locks.  Instead, add the file
32405    ** descriptor to pInode->pUnused list.  It will be automatically closed
32406    ** when the last lock is cleared.
32407    */
32408    setPendingFd(pFile);
32409  }
32410  releaseInodeInfo(pFile);
32411  rc = closeUnixFile(id);
32412  unixLeaveMutex();
32413  return rc;
32414}
32415
32416/************** End of the posix advisory lock implementation *****************
32417******************************************************************************/
32418
32419/******************************************************************************
32420****************************** No-op Locking **********************************
32421**
32422** Of the various locking implementations available, this is by far the
32423** simplest:  locking is ignored.  No attempt is made to lock the database
32424** file for reading or writing.
32425**
32426** This locking mode is appropriate for use on read-only databases
32427** (ex: databases that are burned into CD-ROM, for example.)  It can
32428** also be used if the application employs some external mechanism to
32429** prevent simultaneous access of the same database by two or more
32430** database connections.  But there is a serious risk of database
32431** corruption if this locking mode is used in situations where multiple
32432** database connections are accessing the same database file at the same
32433** time and one or more of those connections are writing.
32434*/
32435
32436static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
32437  UNUSED_PARAMETER(NotUsed);
32438  *pResOut = 0;
32439  return SQLITE_OK;
32440}
32441static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
32442  UNUSED_PARAMETER2(NotUsed, NotUsed2);
32443  return SQLITE_OK;
32444}
32445static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
32446  UNUSED_PARAMETER2(NotUsed, NotUsed2);
32447  return SQLITE_OK;
32448}
32449
32450/*
32451** Close the file.
32452*/
32453static int nolockClose(sqlite3_file *id) {
32454  return closeUnixFile(id);
32455}
32456
32457/******************* End of the no-op lock implementation *********************
32458******************************************************************************/
32459
32460/******************************************************************************
32461************************* Begin dot-file Locking ******************************
32462**
32463** The dotfile locking implementation uses the existence of separate lock
32464** files (really a directory) to control access to the database.  This works
32465** on just about every filesystem imaginable.  But there are serious downsides:
32466**
32467**    (1)  There is zero concurrency.  A single reader blocks all other
32468**         connections from reading or writing the database.
32469**
32470**    (2)  An application crash or power loss can leave stale lock files
32471**         sitting around that need to be cleared manually.
32472**
32473** Nevertheless, a dotlock is an appropriate locking mode for use if no
32474** other locking strategy is available.
32475**
32476** Dotfile locking works by creating a subdirectory in the same directory as
32477** the database and with the same name but with a ".lock" extension added.
32478** The existence of a lock directory implies an EXCLUSIVE lock.  All other
32479** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
32480*/
32481
32482/*
32483** The file suffix added to the data base filename in order to create the
32484** lock directory.
32485*/
32486#define DOTLOCK_SUFFIX ".lock"
32487
32488/*
32489** This routine checks if there is a RESERVED lock held on the specified
32490** file by this or any other process. If such a lock is held, set *pResOut
32491** to a non-zero value otherwise *pResOut is set to zero.  The return value
32492** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32493**
32494** In dotfile locking, either a lock exists or it does not.  So in this
32495** variation of CheckReservedLock(), *pResOut is set to true if any lock
32496** is held on the file and false if the file is unlocked.
32497*/
32498static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
32499  int rc = SQLITE_OK;
32500  int reserved = 0;
32501  unixFile *pFile = (unixFile*)id;
32502
32503  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32504
32505  assert( pFile );
32506  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
32507  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
32508  *pResOut = reserved;
32509  return rc;
32510}
32511
32512/*
32513** Lock the file with the lock specified by parameter eFileLock - one
32514** of the following:
32515**
32516**     (1) SHARED_LOCK
32517**     (2) RESERVED_LOCK
32518**     (3) PENDING_LOCK
32519**     (4) EXCLUSIVE_LOCK
32520**
32521** Sometimes when requesting one lock state, additional lock states
32522** are inserted in between.  The locking might fail on one of the later
32523** transitions leaving the lock state different from what it started but
32524** still short of its goal.  The following chart shows the allowed
32525** transitions and the inserted intermediate states:
32526**
32527**    UNLOCKED -> SHARED
32528**    SHARED -> RESERVED
32529**    SHARED -> (PENDING) -> EXCLUSIVE
32530**    RESERVED -> (PENDING) -> EXCLUSIVE
32531**    PENDING -> EXCLUSIVE
32532**
32533** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32534** routine to lower a locking level.
32535**
32536** With dotfile locking, we really only support state (4): EXCLUSIVE.
32537** But we track the other locking levels internally.
32538*/
32539static int dotlockLock(sqlite3_file *id, int eFileLock) {
32540  unixFile *pFile = (unixFile*)id;
32541  char *zLockFile = (char *)pFile->lockingContext;
32542  int rc = SQLITE_OK;
32543
32544
32545  /* If we have any lock, then the lock file already exists.  All we have
32546  ** to do is adjust our internal record of the lock level.
32547  */
32548  if( pFile->eFileLock > NO_LOCK ){
32549    pFile->eFileLock = eFileLock;
32550    /* Always update the timestamp on the old file */
32551#ifdef HAVE_UTIME
32552    utime(zLockFile, NULL);
32553#else
32554    utimes(zLockFile, NULL);
32555#endif
32556    return SQLITE_OK;
32557  }
32558
32559  /* grab an exclusive lock */
32560  rc = osMkdir(zLockFile, 0777);
32561  if( rc<0 ){
32562    /* failed to open/create the lock directory */
32563    int tErrno = errno;
32564    if( EEXIST == tErrno ){
32565      rc = SQLITE_BUSY;
32566    } else {
32567      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32568      if( rc!=SQLITE_BUSY ){
32569        storeLastErrno(pFile, tErrno);
32570      }
32571    }
32572    return rc;
32573  }
32574
32575  /* got it, set the type and return ok */
32576  pFile->eFileLock = eFileLock;
32577  return rc;
32578}
32579
32580/*
32581** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32582** must be either NO_LOCK or SHARED_LOCK.
32583**
32584** If the locking level of the file descriptor is already at or below
32585** the requested locking level, this routine is a no-op.
32586**
32587** When the locking level reaches NO_LOCK, delete the lock file.
32588*/
32589static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
32590  unixFile *pFile = (unixFile*)id;
32591  char *zLockFile = (char *)pFile->lockingContext;
32592  int rc;
32593
32594  assert( pFile );
32595  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
32596           pFile->eFileLock, osGetpid(0)));
32597  assert( eFileLock<=SHARED_LOCK );
32598
32599  /* no-op if possible */
32600  if( pFile->eFileLock==eFileLock ){
32601    return SQLITE_OK;
32602  }
32603
32604  /* To downgrade to shared, simply update our internal notion of the
32605  ** lock state.  No need to mess with the file on disk.
32606  */
32607  if( eFileLock==SHARED_LOCK ){
32608    pFile->eFileLock = SHARED_LOCK;
32609    return SQLITE_OK;
32610  }
32611
32612  /* To fully unlock the database, delete the lock file */
32613  assert( eFileLock==NO_LOCK );
32614  rc = osRmdir(zLockFile);
32615  if( rc<0 ){
32616    int tErrno = errno;
32617    if( tErrno==ENOENT ){
32618      rc = SQLITE_OK;
32619    }else{
32620      rc = SQLITE_IOERR_UNLOCK;
32621      storeLastErrno(pFile, tErrno);
32622    }
32623    return rc;
32624  }
32625  pFile->eFileLock = NO_LOCK;
32626  return SQLITE_OK;
32627}
32628
32629/*
32630** Close a file.  Make sure the lock has been released before closing.
32631*/
32632static int dotlockClose(sqlite3_file *id) {
32633  unixFile *pFile = (unixFile*)id;
32634  assert( id!=0 );
32635  dotlockUnlock(id, NO_LOCK);
32636  sqlite3_free(pFile->lockingContext);
32637  return closeUnixFile(id);
32638}
32639/****************** End of the dot-file lock implementation *******************
32640******************************************************************************/
32641
32642/******************************************************************************
32643************************** Begin flock Locking ********************************
32644**
32645** Use the flock() system call to do file locking.
32646**
32647** flock() locking is like dot-file locking in that the various
32648** fine-grain locking levels supported by SQLite are collapsed into
32649** a single exclusive lock.  In other words, SHARED, RESERVED, and
32650** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
32651** still works when you do this, but concurrency is reduced since
32652** only a single process can be reading the database at a time.
32653**
32654** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
32655*/
32656#if SQLITE_ENABLE_LOCKING_STYLE
32657
32658/*
32659** Retry flock() calls that fail with EINTR
32660*/
32661#ifdef EINTR
32662static int robust_flock(int fd, int op){
32663  int rc;
32664  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
32665  return rc;
32666}
32667#else
32668# define robust_flock(a,b) flock(a,b)
32669#endif
32670
32671
32672/*
32673** This routine checks if there is a RESERVED lock held on the specified
32674** file by this or any other process. If such a lock is held, set *pResOut
32675** to a non-zero value otherwise *pResOut is set to zero.  The return value
32676** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32677*/
32678static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
32679  int rc = SQLITE_OK;
32680  int reserved = 0;
32681  unixFile *pFile = (unixFile*)id;
32682
32683  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32684
32685  assert( pFile );
32686
32687  /* Check if a thread in this process holds such a lock */
32688  if( pFile->eFileLock>SHARED_LOCK ){
32689    reserved = 1;
32690  }
32691
32692  /* Otherwise see if some other process holds it. */
32693  if( !reserved ){
32694    /* attempt to get the lock */
32695    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
32696    if( !lrc ){
32697      /* got the lock, unlock it */
32698      lrc = robust_flock(pFile->h, LOCK_UN);
32699      if ( lrc ) {
32700        int tErrno = errno;
32701        /* unlock failed with an error */
32702        lrc = SQLITE_IOERR_UNLOCK;
32703        storeLastErrno(pFile, tErrno);
32704        rc = lrc;
32705      }
32706    } else {
32707      int tErrno = errno;
32708      reserved = 1;
32709      /* someone else might have it reserved */
32710      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32711      if( IS_LOCK_ERROR(lrc) ){
32712        storeLastErrno(pFile, tErrno);
32713        rc = lrc;
32714      }
32715    }
32716  }
32717  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
32718
32719#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32720  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
32721    rc = SQLITE_OK;
32722    reserved=1;
32723  }
32724#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32725  *pResOut = reserved;
32726  return rc;
32727}
32728
32729/*
32730** Lock the file with the lock specified by parameter eFileLock - one
32731** of the following:
32732**
32733**     (1) SHARED_LOCK
32734**     (2) RESERVED_LOCK
32735**     (3) PENDING_LOCK
32736**     (4) EXCLUSIVE_LOCK
32737**
32738** Sometimes when requesting one lock state, additional lock states
32739** are inserted in between.  The locking might fail on one of the later
32740** transitions leaving the lock state different from what it started but
32741** still short of its goal.  The following chart shows the allowed
32742** transitions and the inserted intermediate states:
32743**
32744**    UNLOCKED -> SHARED
32745**    SHARED -> RESERVED
32746**    SHARED -> (PENDING) -> EXCLUSIVE
32747**    RESERVED -> (PENDING) -> EXCLUSIVE
32748**    PENDING -> EXCLUSIVE
32749**
32750** flock() only really support EXCLUSIVE locks.  We track intermediate
32751** lock states in the sqlite3_file structure, but all locks SHARED or
32752** above are really EXCLUSIVE locks and exclude all other processes from
32753** access the file.
32754**
32755** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32756** routine to lower a locking level.
32757*/
32758static int flockLock(sqlite3_file *id, int eFileLock) {
32759  int rc = SQLITE_OK;
32760  unixFile *pFile = (unixFile*)id;
32761
32762  assert( pFile );
32763
32764  /* if we already have a lock, it is exclusive.
32765  ** Just adjust level and punt on outta here. */
32766  if (pFile->eFileLock > NO_LOCK) {
32767    pFile->eFileLock = eFileLock;
32768    return SQLITE_OK;
32769  }
32770
32771  /* grab an exclusive lock */
32772
32773  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
32774    int tErrno = errno;
32775    /* didn't get, must be busy */
32776    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
32777    if( IS_LOCK_ERROR(rc) ){
32778      storeLastErrno(pFile, tErrno);
32779    }
32780  } else {
32781    /* got it, set the type and return ok */
32782    pFile->eFileLock = eFileLock;
32783  }
32784  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
32785           rc==SQLITE_OK ? "ok" : "failed"));
32786#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32787  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
32788    rc = SQLITE_BUSY;
32789  }
32790#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32791  return rc;
32792}
32793
32794
32795/*
32796** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32797** must be either NO_LOCK or SHARED_LOCK.
32798**
32799** If the locking level of the file descriptor is already at or below
32800** the requested locking level, this routine is a no-op.
32801*/
32802static int flockUnlock(sqlite3_file *id, int eFileLock) {
32803  unixFile *pFile = (unixFile*)id;
32804
32805  assert( pFile );
32806  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
32807           pFile->eFileLock, osGetpid(0)));
32808  assert( eFileLock<=SHARED_LOCK );
32809
32810  /* no-op if possible */
32811  if( pFile->eFileLock==eFileLock ){
32812    return SQLITE_OK;
32813  }
32814
32815  /* shared can just be set because we always have an exclusive */
32816  if (eFileLock==SHARED_LOCK) {
32817    pFile->eFileLock = eFileLock;
32818    return SQLITE_OK;
32819  }
32820
32821  /* no, really, unlock. */
32822  if( robust_flock(pFile->h, LOCK_UN) ){
32823#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
32824    return SQLITE_OK;
32825#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
32826    return SQLITE_IOERR_UNLOCK;
32827  }else{
32828    pFile->eFileLock = NO_LOCK;
32829    return SQLITE_OK;
32830  }
32831}
32832
32833/*
32834** Close a file.
32835*/
32836static int flockClose(sqlite3_file *id) {
32837  assert( id!=0 );
32838  flockUnlock(id, NO_LOCK);
32839  return closeUnixFile(id);
32840}
32841
32842#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
32843
32844/******************* End of the flock lock implementation *********************
32845******************************************************************************/
32846
32847/******************************************************************************
32848************************ Begin Named Semaphore Locking ************************
32849**
32850** Named semaphore locking is only supported on VxWorks.
32851**
32852** Semaphore locking is like dot-lock and flock in that it really only
32853** supports EXCLUSIVE locking.  Only a single process can read or write
32854** the database file at a time.  This reduces potential concurrency, but
32855** makes the lock implementation much easier.
32856*/
32857#if OS_VXWORKS
32858
32859/*
32860** This routine checks if there is a RESERVED lock held on the specified
32861** file by this or any other process. If such a lock is held, set *pResOut
32862** to a non-zero value otherwise *pResOut is set to zero.  The return value
32863** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32864*/
32865static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
32866  int rc = SQLITE_OK;
32867  int reserved = 0;
32868  unixFile *pFile = (unixFile*)id;
32869
32870  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32871
32872  assert( pFile );
32873
32874  /* Check if a thread in this process holds such a lock */
32875  if( pFile->eFileLock>SHARED_LOCK ){
32876    reserved = 1;
32877  }
32878
32879  /* Otherwise see if some other process holds it. */
32880  if( !reserved ){
32881    sem_t *pSem = pFile->pInode->pSem;
32882
32883    if( sem_trywait(pSem)==-1 ){
32884      int tErrno = errno;
32885      if( EAGAIN != tErrno ){
32886        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
32887        storeLastErrno(pFile, tErrno);
32888      } else {
32889        /* someone else has the lock when we are in NO_LOCK */
32890        reserved = (pFile->eFileLock < SHARED_LOCK);
32891      }
32892    }else{
32893      /* we could have it if we want it */
32894      sem_post(pSem);
32895    }
32896  }
32897  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
32898
32899  *pResOut = reserved;
32900  return rc;
32901}
32902
32903/*
32904** Lock the file with the lock specified by parameter eFileLock - one
32905** of the following:
32906**
32907**     (1) SHARED_LOCK
32908**     (2) RESERVED_LOCK
32909**     (3) PENDING_LOCK
32910**     (4) EXCLUSIVE_LOCK
32911**
32912** Sometimes when requesting one lock state, additional lock states
32913** are inserted in between.  The locking might fail on one of the later
32914** transitions leaving the lock state different from what it started but
32915** still short of its goal.  The following chart shows the allowed
32916** transitions and the inserted intermediate states:
32917**
32918**    UNLOCKED -> SHARED
32919**    SHARED -> RESERVED
32920**    SHARED -> (PENDING) -> EXCLUSIVE
32921**    RESERVED -> (PENDING) -> EXCLUSIVE
32922**    PENDING -> EXCLUSIVE
32923**
32924** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
32925** lock states in the sqlite3_file structure, but all locks SHARED or
32926** above are really EXCLUSIVE locks and exclude all other processes from
32927** access the file.
32928**
32929** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32930** routine to lower a locking level.
32931*/
32932static int semXLock(sqlite3_file *id, int eFileLock) {
32933  unixFile *pFile = (unixFile*)id;
32934  sem_t *pSem = pFile->pInode->pSem;
32935  int rc = SQLITE_OK;
32936
32937  /* if we already have a lock, it is exclusive.
32938  ** Just adjust level and punt on outta here. */
32939  if (pFile->eFileLock > NO_LOCK) {
32940    pFile->eFileLock = eFileLock;
32941    rc = SQLITE_OK;
32942    goto sem_end_lock;
32943  }
32944
32945  /* lock semaphore now but bail out when already locked. */
32946  if( sem_trywait(pSem)==-1 ){
32947    rc = SQLITE_BUSY;
32948    goto sem_end_lock;
32949  }
32950
32951  /* got it, set the type and return ok */
32952  pFile->eFileLock = eFileLock;
32953
32954 sem_end_lock:
32955  return rc;
32956}
32957
32958/*
32959** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32960** must be either NO_LOCK or SHARED_LOCK.
32961**
32962** If the locking level of the file descriptor is already at or below
32963** the requested locking level, this routine is a no-op.
32964*/
32965static int semXUnlock(sqlite3_file *id, int eFileLock) {
32966  unixFile *pFile = (unixFile*)id;
32967  sem_t *pSem = pFile->pInode->pSem;
32968
32969  assert( pFile );
32970  assert( pSem );
32971  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
32972           pFile->eFileLock, osGetpid(0)));
32973  assert( eFileLock<=SHARED_LOCK );
32974
32975  /* no-op if possible */
32976  if( pFile->eFileLock==eFileLock ){
32977    return SQLITE_OK;
32978  }
32979
32980  /* shared can just be set because we always have an exclusive */
32981  if (eFileLock==SHARED_LOCK) {
32982    pFile->eFileLock = eFileLock;
32983    return SQLITE_OK;
32984  }
32985
32986  /* no, really unlock. */
32987  if ( sem_post(pSem)==-1 ) {
32988    int rc, tErrno = errno;
32989    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
32990    if( IS_LOCK_ERROR(rc) ){
32991      storeLastErrno(pFile, tErrno);
32992    }
32993    return rc;
32994  }
32995  pFile->eFileLock = NO_LOCK;
32996  return SQLITE_OK;
32997}
32998
32999/*
33000 ** Close a file.
33001 */
33002static int semXClose(sqlite3_file *id) {
33003  if( id ){
33004    unixFile *pFile = (unixFile*)id;
33005    semXUnlock(id, NO_LOCK);
33006    assert( pFile );
33007    unixEnterMutex();
33008    releaseInodeInfo(pFile);
33009    unixLeaveMutex();
33010    closeUnixFile(id);
33011  }
33012  return SQLITE_OK;
33013}
33014
33015#endif /* OS_VXWORKS */
33016/*
33017** Named semaphore locking is only available on VxWorks.
33018**
33019*************** End of the named semaphore lock implementation ****************
33020******************************************************************************/
33021
33022
33023/******************************************************************************
33024*************************** Begin AFP Locking *********************************
33025**
33026** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
33027** on Apple Macintosh computers - both OS9 and OSX.
33028**
33029** Third-party implementations of AFP are available.  But this code here
33030** only works on OSX.
33031*/
33032
33033#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
33034/*
33035** The afpLockingContext structure contains all afp lock specific state
33036*/
33037typedef struct afpLockingContext afpLockingContext;
33038struct afpLockingContext {
33039  int reserved;
33040  const char *dbPath;             /* Name of the open file */
33041};
33042
33043struct ByteRangeLockPB2
33044{
33045  unsigned long long offset;        /* offset to first byte to lock */
33046  unsigned long long length;        /* nbr of bytes to lock */
33047  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
33048  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
33049  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
33050  int fd;                           /* file desc to assoc this lock with */
33051};
33052
33053#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
33054
33055/*
33056** This is a utility for setting or clearing a bit-range lock on an
33057** AFP filesystem.
33058**
33059** Return SQLITE_OK on success, SQLITE_BUSY on failure.
33060*/
33061static int afpSetLock(
33062  const char *path,              /* Name of the file to be locked or unlocked */
33063  unixFile *pFile,               /* Open file descriptor on path */
33064  unsigned long long offset,     /* First byte to be locked */
33065  unsigned long long length,     /* Number of bytes to lock */
33066  int setLockFlag                /* True to set lock.  False to clear lock */
33067){
33068  struct ByteRangeLockPB2 pb;
33069  int err;
33070
33071  pb.unLockFlag = setLockFlag ? 0 : 1;
33072  pb.startEndFlag = 0;
33073  pb.offset = offset;
33074  pb.length = length;
33075  pb.fd = pFile->h;
33076
33077  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
33078    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
33079    offset, length));
33080  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
33081  if ( err==-1 ) {
33082    int rc;
33083    int tErrno = errno;
33084    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
33085             path, tErrno, strerror(tErrno)));
33086#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
33087    rc = SQLITE_BUSY;
33088#else
33089    rc = sqliteErrorFromPosixError(tErrno,
33090                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
33091#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
33092    if( IS_LOCK_ERROR(rc) ){
33093      storeLastErrno(pFile, tErrno);
33094    }
33095    return rc;
33096  } else {
33097    return SQLITE_OK;
33098  }
33099}
33100
33101/*
33102** This routine checks if there is a RESERVED lock held on the specified
33103** file by this or any other process. If such a lock is held, set *pResOut
33104** to a non-zero value otherwise *pResOut is set to zero.  The return value
33105** is set to SQLITE_OK unless an I/O error occurs during lock checking.
33106*/
33107static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
33108  int rc = SQLITE_OK;
33109  int reserved = 0;
33110  unixFile *pFile = (unixFile*)id;
33111  afpLockingContext *context;
33112
33113  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
33114
33115  assert( pFile );
33116  context = (afpLockingContext *) pFile->lockingContext;
33117  if( context->reserved ){
33118    *pResOut = 1;
33119    return SQLITE_OK;
33120  }
33121  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
33122
33123  /* Check if a thread in this process holds such a lock */
33124  if( pFile->pInode->eFileLock>SHARED_LOCK ){
33125    reserved = 1;
33126  }
33127
33128  /* Otherwise see if some other process holds it.
33129   */
33130  if( !reserved ){
33131    /* lock the RESERVED byte */
33132    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
33133    if( SQLITE_OK==lrc ){
33134      /* if we succeeded in taking the reserved lock, unlock it to restore
33135      ** the original state */
33136      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
33137    } else {
33138      /* if we failed to get the lock then someone else must have it */
33139      reserved = 1;
33140    }
33141    if( IS_LOCK_ERROR(lrc) ){
33142      rc=lrc;
33143    }
33144  }
33145
33146  unixLeaveMutex();
33147  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
33148
33149  *pResOut = reserved;
33150  return rc;
33151}
33152
33153/*
33154** Lock the file with the lock specified by parameter eFileLock - one
33155** of the following:
33156**
33157**     (1) SHARED_LOCK
33158**     (2) RESERVED_LOCK
33159**     (3) PENDING_LOCK
33160**     (4) EXCLUSIVE_LOCK
33161**
33162** Sometimes when requesting one lock state, additional lock states
33163** are inserted in between.  The locking might fail on one of the later
33164** transitions leaving the lock state different from what it started but
33165** still short of its goal.  The following chart shows the allowed
33166** transitions and the inserted intermediate states:
33167**
33168**    UNLOCKED -> SHARED
33169**    SHARED -> RESERVED
33170**    SHARED -> (PENDING) -> EXCLUSIVE
33171**    RESERVED -> (PENDING) -> EXCLUSIVE
33172**    PENDING -> EXCLUSIVE
33173**
33174** This routine will only increase a lock.  Use the sqlite3OsUnlock()
33175** routine to lower a locking level.
33176*/
33177static int afpLock(sqlite3_file *id, int eFileLock){
33178  int rc = SQLITE_OK;
33179  unixFile *pFile = (unixFile*)id;
33180  unixInodeInfo *pInode = pFile->pInode;
33181  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
33182
33183  assert( pFile );
33184  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
33185           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
33186           azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
33187
33188  /* If there is already a lock of this type or more restrictive on the
33189  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
33190  ** unixEnterMutex() hasn't been called yet.
33191  */
33192  if( pFile->eFileLock>=eFileLock ){
33193    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
33194           azFileLock(eFileLock)));
33195    return SQLITE_OK;
33196  }
33197
33198  /* Make sure the locking sequence is correct
33199  **  (1) We never move from unlocked to anything higher than shared lock.
33200  **  (2) SQLite never explicitly requests a pendig lock.
33201  **  (3) A shared lock is always held when a reserve lock is requested.
33202  */
33203  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
33204  assert( eFileLock!=PENDING_LOCK );
33205  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
33206
33207  /* This mutex is needed because pFile->pInode is shared across threads
33208  */
33209  unixEnterMutex();
33210  pInode = pFile->pInode;
33211
33212  /* If some thread using this PID has a lock via a different unixFile*
33213  ** handle that precludes the requested lock, return BUSY.
33214  */
33215  if( (pFile->eFileLock!=pInode->eFileLock &&
33216       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
33217     ){
33218    rc = SQLITE_BUSY;
33219    goto afp_end_lock;
33220  }
33221
33222  /* If a SHARED lock is requested, and some thread using this PID already
33223  ** has a SHARED or RESERVED lock, then increment reference counts and
33224  ** return SQLITE_OK.
33225  */
33226  if( eFileLock==SHARED_LOCK &&
33227     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
33228    assert( eFileLock==SHARED_LOCK );
33229    assert( pFile->eFileLock==0 );
33230    assert( pInode->nShared>0 );
33231    pFile->eFileLock = SHARED_LOCK;
33232    pInode->nShared++;
33233    pInode->nLock++;
33234    goto afp_end_lock;
33235  }
33236
33237  /* A PENDING lock is needed before acquiring a SHARED lock and before
33238  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
33239  ** be released.
33240  */
33241  if( eFileLock==SHARED_LOCK
33242      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
33243  ){
33244    int failed;
33245    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
33246    if (failed) {
33247      rc = failed;
33248      goto afp_end_lock;
33249    }
33250  }
33251
33252  /* If control gets to this point, then actually go ahead and make
33253  ** operating system calls for the specified lock.
33254  */
33255  if( eFileLock==SHARED_LOCK ){
33256    int lrc1, lrc2, lrc1Errno = 0;
33257    long lk, mask;
33258
33259    assert( pInode->nShared==0 );
33260    assert( pInode->eFileLock==0 );
33261
33262    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
33263    /* Now get the read-lock SHARED_LOCK */
33264    /* note that the quality of the randomness doesn't matter that much */
33265    lk = random();
33266    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
33267    lrc1 = afpSetLock(context->dbPath, pFile,
33268          SHARED_FIRST+pInode->sharedByte, 1, 1);
33269    if( IS_LOCK_ERROR(lrc1) ){
33270      lrc1Errno = pFile->lastErrno;
33271    }
33272    /* Drop the temporary PENDING lock */
33273    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
33274
33275    if( IS_LOCK_ERROR(lrc1) ) {
33276      storeLastErrno(pFile, lrc1Errno);
33277      rc = lrc1;
33278      goto afp_end_lock;
33279    } else if( IS_LOCK_ERROR(lrc2) ){
33280      rc = lrc2;
33281      goto afp_end_lock;
33282    } else if( lrc1 != SQLITE_OK ) {
33283      rc = lrc1;
33284    } else {
33285      pFile->eFileLock = SHARED_LOCK;
33286      pInode->nLock++;
33287      pInode->nShared = 1;
33288    }
33289  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
33290    /* We are trying for an exclusive lock but another thread in this
33291     ** same process is still holding a shared lock. */
33292    rc = SQLITE_BUSY;
33293  }else{
33294    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
33295    ** assumed that there is a SHARED or greater lock on the file
33296    ** already.
33297    */
33298    int failed = 0;
33299    assert( 0!=pFile->eFileLock );
33300    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
33301        /* Acquire a RESERVED lock */
33302        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
33303      if( !failed ){
33304        context->reserved = 1;
33305      }
33306    }
33307    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
33308      /* Acquire an EXCLUSIVE lock */
33309
33310      /* Remove the shared lock before trying the range.  we'll need to
33311      ** reestablish the shared lock if we can't get the  afpUnlock
33312      */
33313      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
33314                         pInode->sharedByte, 1, 0)) ){
33315        int failed2 = SQLITE_OK;
33316        /* now attemmpt to get the exclusive lock range */
33317        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
33318                               SHARED_SIZE, 1);
33319        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
33320                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
33321          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
33322          ** a critical I/O error
33323          */
33324          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
33325               SQLITE_IOERR_LOCK;
33326          goto afp_end_lock;
33327        }
33328      }else{
33329        rc = failed;
33330      }
33331    }
33332    if( failed ){
33333      rc = failed;
33334    }
33335  }
33336
33337  if( rc==SQLITE_OK ){
33338    pFile->eFileLock = eFileLock;
33339    pInode->eFileLock = eFileLock;
33340  }else if( eFileLock==EXCLUSIVE_LOCK ){
33341    pFile->eFileLock = PENDING_LOCK;
33342    pInode->eFileLock = PENDING_LOCK;
33343  }
33344
33345afp_end_lock:
33346  unixLeaveMutex();
33347  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
33348         rc==SQLITE_OK ? "ok" : "failed"));
33349  return rc;
33350}
33351
33352/*
33353** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
33354** must be either NO_LOCK or SHARED_LOCK.
33355**
33356** If the locking level of the file descriptor is already at or below
33357** the requested locking level, this routine is a no-op.
33358*/
33359static int afpUnlock(sqlite3_file *id, int eFileLock) {
33360  int rc = SQLITE_OK;
33361  unixFile *pFile = (unixFile*)id;
33362  unixInodeInfo *pInode;
33363  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
33364  int skipShared = 0;
33365#ifdef SQLITE_TEST
33366  int h = pFile->h;
33367#endif
33368
33369  assert( pFile );
33370  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
33371           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
33372           osGetpid(0)));
33373
33374  assert( eFileLock<=SHARED_LOCK );
33375  if( pFile->eFileLock<=eFileLock ){
33376    return SQLITE_OK;
33377  }
33378  unixEnterMutex();
33379  pInode = pFile->pInode;
33380  assert( pInode->nShared!=0 );
33381  if( pFile->eFileLock>SHARED_LOCK ){
33382    assert( pInode->eFileLock==pFile->eFileLock );
33383    SimulateIOErrorBenign(1);
33384    SimulateIOError( h=(-1) )
33385    SimulateIOErrorBenign(0);
33386
33387#ifdef SQLITE_DEBUG
33388    /* When reducing a lock such that other processes can start
33389    ** reading the database file again, make sure that the
33390    ** transaction counter was updated if any part of the database
33391    ** file changed.  If the transaction counter is not updated,
33392    ** other connections to the same file might not realize that
33393    ** the file has changed and hence might not know to flush their
33394    ** cache.  The use of a stale cache can lead to database corruption.
33395    */
33396    assert( pFile->inNormalWrite==0
33397           || pFile->dbUpdate==0
33398           || pFile->transCntrChng==1 );
33399    pFile->inNormalWrite = 0;
33400#endif
33401
33402    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
33403      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
33404      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
33405        /* only re-establish the shared lock if necessary */
33406        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
33407        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
33408      } else {
33409        skipShared = 1;
33410      }
33411    }
33412    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
33413      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
33414    }
33415    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
33416      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
33417      if( !rc ){
33418        context->reserved = 0;
33419      }
33420    }
33421    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
33422      pInode->eFileLock = SHARED_LOCK;
33423    }
33424  }
33425  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
33426
33427    /* Decrement the shared lock counter.  Release the lock using an
33428    ** OS call only when all threads in this same process have released
33429    ** the lock.
33430    */
33431    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
33432    pInode->nShared--;
33433    if( pInode->nShared==0 ){
33434      SimulateIOErrorBenign(1);
33435      SimulateIOError( h=(-1) )
33436      SimulateIOErrorBenign(0);
33437      if( !skipShared ){
33438        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
33439      }
33440      if( !rc ){
33441        pInode->eFileLock = NO_LOCK;
33442        pFile->eFileLock = NO_LOCK;
33443      }
33444    }
33445    if( rc==SQLITE_OK ){
33446      pInode->nLock--;
33447      assert( pInode->nLock>=0 );
33448      if( pInode->nLock==0 ){
33449        closePendingFds(pFile);
33450      }
33451    }
33452  }
33453
33454  unixLeaveMutex();
33455  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
33456  return rc;
33457}
33458
33459/*
33460** Close a file & cleanup AFP specific locking context
33461*/
33462static int afpClose(sqlite3_file *id) {
33463  int rc = SQLITE_OK;
33464  unixFile *pFile = (unixFile*)id;
33465  assert( id!=0 );
33466  afpUnlock(id, NO_LOCK);
33467  unixEnterMutex();
33468  if( pFile->pInode && pFile->pInode->nLock ){
33469    /* If there are outstanding locks, do not actually close the file just
33470    ** yet because that would clear those locks.  Instead, add the file
33471    ** descriptor to pInode->aPending.  It will be automatically closed when
33472    ** the last lock is cleared.
33473    */
33474    setPendingFd(pFile);
33475  }
33476  releaseInodeInfo(pFile);
33477  sqlite3_free(pFile->lockingContext);
33478  rc = closeUnixFile(id);
33479  unixLeaveMutex();
33480  return rc;
33481}
33482
33483#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
33484/*
33485** The code above is the AFP lock implementation.  The code is specific
33486** to MacOSX and does not work on other unix platforms.  No alternative
33487** is available.  If you don't compile for a mac, then the "unix-afp"
33488** VFS is not available.
33489**
33490********************* End of the AFP lock implementation **********************
33491******************************************************************************/
33492
33493/******************************************************************************
33494*************************** Begin NFS Locking ********************************/
33495
33496#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
33497/*
33498 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
33499 ** must be either NO_LOCK or SHARED_LOCK.
33500 **
33501 ** If the locking level of the file descriptor is already at or below
33502 ** the requested locking level, this routine is a no-op.
33503 */
33504static int nfsUnlock(sqlite3_file *id, int eFileLock){
33505  return posixUnlock(id, eFileLock, 1);
33506}
33507
33508#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
33509/*
33510** The code above is the NFS lock implementation.  The code is specific
33511** to MacOSX and does not work on other unix platforms.  No alternative
33512** is available.
33513**
33514********************* End of the NFS lock implementation **********************
33515******************************************************************************/
33516
33517/******************************************************************************
33518**************** Non-locking sqlite3_file methods *****************************
33519**
33520** The next division contains implementations for all methods of the
33521** sqlite3_file object other than the locking methods.  The locking
33522** methods were defined in divisions above (one locking method per
33523** division).  Those methods that are common to all locking modes
33524** are gather together into this division.
33525*/
33526
33527/*
33528** Seek to the offset passed as the second argument, then read cnt
33529** bytes into pBuf. Return the number of bytes actually read.
33530**
33531** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
33532** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
33533** one system to another.  Since SQLite does not define USE_PREAD
33534** in any form by default, we will not attempt to define _XOPEN_SOURCE.
33535** See tickets #2741 and #2681.
33536**
33537** To avoid stomping the errno value on a failed read the lastErrno value
33538** is set before returning.
33539*/
33540static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
33541  int got;
33542  int prior = 0;
33543#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
33544  i64 newOffset;
33545#endif
33546  TIMER_START;
33547  assert( cnt==(cnt&0x1ffff) );
33548  assert( id->h>2 );
33549  do{
33550#if defined(USE_PREAD)
33551    got = osPread(id->h, pBuf, cnt, offset);
33552    SimulateIOError( got = -1 );
33553#elif defined(USE_PREAD64)
33554    got = osPread64(id->h, pBuf, cnt, offset);
33555    SimulateIOError( got = -1 );
33556#else
33557    newOffset = lseek(id->h, offset, SEEK_SET);
33558    SimulateIOError( newOffset = -1 );
33559    if( newOffset<0 ){
33560      storeLastErrno((unixFile*)id, errno);
33561      return -1;
33562    }
33563    got = osRead(id->h, pBuf, cnt);
33564#endif
33565    if( got==cnt ) break;
33566    if( got<0 ){
33567      if( errno==EINTR ){ got = 1; continue; }
33568      prior = 0;
33569      storeLastErrno((unixFile*)id,  errno);
33570      break;
33571    }else if( got>0 ){
33572      cnt -= got;
33573      offset += got;
33574      prior += got;
33575      pBuf = (void*)(got + (char*)pBuf);
33576    }
33577  }while( got>0 );
33578  TIMER_END;
33579  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
33580            id->h, got+prior, offset-prior, TIMER_ELAPSED));
33581  return got+prior;
33582}
33583
33584/*
33585** Read data from a file into a buffer.  Return SQLITE_OK if all
33586** bytes were read successfully and SQLITE_IOERR if anything goes
33587** wrong.
33588*/
33589static int unixRead(
33590  sqlite3_file *id,
33591  void *pBuf,
33592  int amt,
33593  sqlite3_int64 offset
33594){
33595  unixFile *pFile = (unixFile *)id;
33596  int got;
33597  assert( id );
33598  assert( offset>=0 );
33599  assert( amt>0 );
33600
33601  /* If this is a database file (not a journal, master-journal or temp
33602  ** file), the bytes in the locking range should never be read or written. */
33603#if 0
33604  assert( pFile->pUnused==0
33605       || offset>=PENDING_BYTE+512
33606       || offset+amt<=PENDING_BYTE
33607  );
33608#endif
33609
33610#if SQLITE_MAX_MMAP_SIZE>0
33611  /* Deal with as much of this read request as possible by transfering
33612  ** data from the memory mapping using memcpy().  */
33613  if( offset<pFile->mmapSize ){
33614    if( offset+amt <= pFile->mmapSize ){
33615      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
33616      return SQLITE_OK;
33617    }else{
33618      int nCopy = pFile->mmapSize - offset;
33619      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
33620      pBuf = &((u8 *)pBuf)[nCopy];
33621      amt -= nCopy;
33622      offset += nCopy;
33623    }
33624  }
33625#endif
33626
33627  got = seekAndRead(pFile, offset, pBuf, amt);
33628  if( got==amt ){
33629    return SQLITE_OK;
33630  }else if( got<0 ){
33631    /* lastErrno set by seekAndRead */
33632    return SQLITE_IOERR_READ;
33633  }else{
33634    storeLastErrno(pFile, 0);   /* not a system error */
33635    /* Unread parts of the buffer must be zero-filled */
33636    memset(&((char*)pBuf)[got], 0, amt-got);
33637    return SQLITE_IOERR_SHORT_READ;
33638  }
33639}
33640
33641/*
33642** Attempt to seek the file-descriptor passed as the first argument to
33643** absolute offset iOff, then attempt to write nBuf bytes of data from
33644** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
33645** return the actual number of bytes written (which may be less than
33646** nBuf).
33647*/
33648static int seekAndWriteFd(
33649  int fd,                         /* File descriptor to write to */
33650  i64 iOff,                       /* File offset to begin writing at */
33651  const void *pBuf,               /* Copy data from this buffer to the file */
33652  int nBuf,                       /* Size of buffer pBuf in bytes */
33653  int *piErrno                    /* OUT: Error number if error occurs */
33654){
33655  int rc = 0;                     /* Value returned by system call */
33656
33657  assert( nBuf==(nBuf&0x1ffff) );
33658  assert( fd>2 );
33659  assert( piErrno!=0 );
33660  nBuf &= 0x1ffff;
33661  TIMER_START;
33662
33663#if defined(USE_PREAD)
33664  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
33665#elif defined(USE_PREAD64)
33666  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
33667#else
33668  do{
33669    i64 iSeek = lseek(fd, iOff, SEEK_SET);
33670    SimulateIOError( iSeek = -1 );
33671    if( iSeek<0 ){
33672      rc = -1;
33673      break;
33674    }
33675    rc = osWrite(fd, pBuf, nBuf);
33676  }while( rc<0 && errno==EINTR );
33677#endif
33678
33679  TIMER_END;
33680  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
33681
33682  if( rc<0 ) *piErrno = errno;
33683  return rc;
33684}
33685
33686
33687/*
33688** Seek to the offset in id->offset then read cnt bytes into pBuf.
33689** Return the number of bytes actually read.  Update the offset.
33690**
33691** To avoid stomping the errno value on a failed write the lastErrno value
33692** is set before returning.
33693*/
33694static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
33695  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
33696}
33697
33698
33699/*
33700** Write data from a buffer into a file.  Return SQLITE_OK on success
33701** or some other error code on failure.
33702*/
33703static int unixWrite(
33704  sqlite3_file *id,
33705  const void *pBuf,
33706  int amt,
33707  sqlite3_int64 offset
33708){
33709  unixFile *pFile = (unixFile*)id;
33710  int wrote = 0;
33711  assert( id );
33712  assert( amt>0 );
33713
33714  /* If this is a database file (not a journal, master-journal or temp
33715  ** file), the bytes in the locking range should never be read or written. */
33716#if 0
33717  assert( pFile->pUnused==0
33718       || offset>=PENDING_BYTE+512
33719       || offset+amt<=PENDING_BYTE
33720  );
33721#endif
33722
33723#ifdef SQLITE_DEBUG
33724  /* If we are doing a normal write to a database file (as opposed to
33725  ** doing a hot-journal rollback or a write to some file other than a
33726  ** normal database file) then record the fact that the database
33727  ** has changed.  If the transaction counter is modified, record that
33728  ** fact too.
33729  */
33730  if( pFile->inNormalWrite ){
33731    pFile->dbUpdate = 1;  /* The database has been modified */
33732    if( offset<=24 && offset+amt>=27 ){
33733      int rc;
33734      char oldCntr[4];
33735      SimulateIOErrorBenign(1);
33736      rc = seekAndRead(pFile, 24, oldCntr, 4);
33737      SimulateIOErrorBenign(0);
33738      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
33739        pFile->transCntrChng = 1;  /* The transaction counter has changed */
33740      }
33741    }
33742  }
33743#endif
33744
33745#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
33746  /* Deal with as much of this write request as possible by transfering
33747  ** data from the memory mapping using memcpy().  */
33748  if( offset<pFile->mmapSize ){
33749    if( offset+amt <= pFile->mmapSize ){
33750      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
33751      return SQLITE_OK;
33752    }else{
33753      int nCopy = pFile->mmapSize - offset;
33754      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
33755      pBuf = &((u8 *)pBuf)[nCopy];
33756      amt -= nCopy;
33757      offset += nCopy;
33758    }
33759  }
33760#endif
33761
33762  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
33763    amt -= wrote;
33764    offset += wrote;
33765    pBuf = &((char*)pBuf)[wrote];
33766  }
33767  SimulateIOError(( wrote=(-1), amt=1 ));
33768  SimulateDiskfullError(( wrote=0, amt=1 ));
33769
33770  if( amt>wrote ){
33771    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
33772      /* lastErrno set by seekAndWrite */
33773      return SQLITE_IOERR_WRITE;
33774    }else{
33775      storeLastErrno(pFile, 0); /* not a system error */
33776      return SQLITE_FULL;
33777    }
33778  }
33779
33780  return SQLITE_OK;
33781}
33782
33783#ifdef SQLITE_TEST
33784/*
33785** Count the number of fullsyncs and normal syncs.  This is used to test
33786** that syncs and fullsyncs are occurring at the right times.
33787*/
33788SQLITE_API int sqlite3_sync_count = 0;
33789SQLITE_API int sqlite3_fullsync_count = 0;
33790#endif
33791
33792/*
33793** We do not trust systems to provide a working fdatasync().  Some do.
33794** Others do no.  To be safe, we will stick with the (slightly slower)
33795** fsync(). If you know that your system does support fdatasync() correctly,
33796** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
33797*/
33798#if !defined(fdatasync) && !HAVE_FDATASYNC
33799# define fdatasync fsync
33800#endif
33801
33802/*
33803** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
33804** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
33805** only available on Mac OS X.  But that could change.
33806*/
33807#ifdef F_FULLFSYNC
33808# define HAVE_FULLFSYNC 1
33809#else
33810# define HAVE_FULLFSYNC 0
33811#endif
33812
33813
33814/*
33815** The fsync() system call does not work as advertised on many
33816** unix systems.  The following procedure is an attempt to make
33817** it work better.
33818**
33819** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
33820** for testing when we want to run through the test suite quickly.
33821** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
33822** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
33823** or power failure will likely corrupt the database file.
33824**
33825** SQLite sets the dataOnly flag if the size of the file is unchanged.
33826** The idea behind dataOnly is that it should only write the file content
33827** to disk, not the inode.  We only set dataOnly if the file size is
33828** unchanged since the file size is part of the inode.  However,
33829** Ted Ts'o tells us that fdatasync() will also write the inode if the
33830** file size has changed.  The only real difference between fdatasync()
33831** and fsync(), Ted tells us, is that fdatasync() will not flush the
33832** inode if the mtime or owner or other inode attributes have changed.
33833** We only care about the file size, not the other file attributes, so
33834** as far as SQLite is concerned, an fdatasync() is always adequate.
33835** So, we always use fdatasync() if it is available, regardless of
33836** the value of the dataOnly flag.
33837*/
33838static int full_fsync(int fd, int fullSync, int dataOnly){
33839  int rc;
33840
33841  /* The following "ifdef/elif/else/" block has the same structure as
33842  ** the one below. It is replicated here solely to avoid cluttering
33843  ** up the real code with the UNUSED_PARAMETER() macros.
33844  */
33845#ifdef SQLITE_NO_SYNC
33846  UNUSED_PARAMETER(fd);
33847  UNUSED_PARAMETER(fullSync);
33848  UNUSED_PARAMETER(dataOnly);
33849#elif HAVE_FULLFSYNC
33850  UNUSED_PARAMETER(dataOnly);
33851#else
33852  UNUSED_PARAMETER(fullSync);
33853  UNUSED_PARAMETER(dataOnly);
33854#endif
33855
33856  /* Record the number of times that we do a normal fsync() and
33857  ** FULLSYNC.  This is used during testing to verify that this procedure
33858  ** gets called with the correct arguments.
33859  */
33860#ifdef SQLITE_TEST
33861  if( fullSync ) sqlite3_fullsync_count++;
33862  sqlite3_sync_count++;
33863#endif
33864
33865  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33866  ** no-op.  But go ahead and call fstat() to validate the file
33867  ** descriptor as we need a method to provoke a failure during
33868  ** coverate testing.
33869  */
33870#ifdef SQLITE_NO_SYNC
33871  {
33872    struct stat buf;
33873    rc = osFstat(fd, &buf);
33874  }
33875#elif HAVE_FULLFSYNC
33876  if( fullSync ){
33877    rc = osFcntl(fd, F_FULLFSYNC, 0);
33878  }else{
33879    rc = 1;
33880  }
33881  /* If the FULLFSYNC failed, fall back to attempting an fsync().
33882  ** It shouldn't be possible for fullfsync to fail on the local
33883  ** file system (on OSX), so failure indicates that FULLFSYNC
33884  ** isn't supported for this file system. So, attempt an fsync
33885  ** and (for now) ignore the overhead of a superfluous fcntl call.
33886  ** It'd be better to detect fullfsync support once and avoid
33887  ** the fcntl call every time sync is called.
33888  */
33889  if( rc ) rc = fsync(fd);
33890
33891#elif defined(__APPLE__)
33892  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
33893  ** so currently we default to the macro that redefines fdatasync to fsync
33894  */
33895  rc = fsync(fd);
33896#else
33897  rc = fdatasync(fd);
33898#if OS_VXWORKS
33899  if( rc==-1 && errno==ENOTSUP ){
33900    rc = fsync(fd);
33901  }
33902#endif /* OS_VXWORKS */
33903#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
33904
33905  if( OS_VXWORKS && rc!= -1 ){
33906    rc = 0;
33907  }
33908  return rc;
33909}
33910
33911/*
33912** Open a file descriptor to the directory containing file zFilename.
33913** If successful, *pFd is set to the opened file descriptor and
33914** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
33915** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
33916** value.
33917**
33918** The directory file descriptor is used for only one thing - to
33919** fsync() a directory to make sure file creation and deletion events
33920** are flushed to disk.  Such fsyncs are not needed on newer
33921** journaling filesystems, but are required on older filesystems.
33922**
33923** This routine can be overridden using the xSetSysCall interface.
33924** The ability to override this routine was added in support of the
33925** chromium sandbox.  Opening a directory is a security risk (we are
33926** told) so making it overrideable allows the chromium sandbox to
33927** replace this routine with a harmless no-op.  To make this routine
33928** a no-op, replace it with a stub that returns SQLITE_OK but leaves
33929** *pFd set to a negative number.
33930**
33931** If SQLITE_OK is returned, the caller is responsible for closing
33932** the file descriptor *pFd using close().
33933*/
33934static int openDirectory(const char *zFilename, int *pFd){
33935  int ii;
33936  int fd = -1;
33937  char zDirname[MAX_PATHNAME+1];
33938
33939  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
33940  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
33941  if( ii>0 ){
33942    zDirname[ii] = '\0';
33943  }else{
33944    if( zDirname[0]!='/' ) zDirname[0] = '.';
33945    zDirname[1] = 0;
33946  }
33947  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
33948  if( fd>=0 ){
33949    OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
33950  }
33951  *pFd = fd;
33952  if( fd>=0 ) return SQLITE_OK;
33953  return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
33954}
33955
33956/*
33957** Make sure all writes to a particular file are committed to disk.
33958**
33959** If dataOnly==0 then both the file itself and its metadata (file
33960** size, access time, etc) are synced.  If dataOnly!=0 then only the
33961** file data is synced.
33962**
33963** Under Unix, also make sure that the directory entry for the file
33964** has been created by fsync-ing the directory that contains the file.
33965** If we do not do this and we encounter a power failure, the directory
33966** entry for the journal might not exist after we reboot.  The next
33967** SQLite to access the file will not know that the journal exists (because
33968** the directory entry for the journal was never created) and the transaction
33969** will not roll back - possibly leading to database corruption.
33970*/
33971static int unixSync(sqlite3_file *id, int flags){
33972  int rc;
33973  unixFile *pFile = (unixFile*)id;
33974
33975  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
33976  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
33977
33978  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33979  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33980      || (flags&0x0F)==SQLITE_SYNC_FULL
33981  );
33982
33983  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33984  ** line is to test that doing so does not cause any problems.
33985  */
33986  SimulateDiskfullError( return SQLITE_FULL );
33987
33988  assert( pFile );
33989  OSTRACE(("SYNC    %-3d\n", pFile->h));
33990  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
33991  SimulateIOError( rc=1 );
33992  if( rc ){
33993    storeLastErrno(pFile, errno);
33994    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
33995  }
33996
33997  /* Also fsync the directory containing the file if the DIRSYNC flag
33998  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
33999  ** are unable to fsync a directory, so ignore errors on the fsync.
34000  */
34001  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
34002    int dirfd;
34003    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
34004            HAVE_FULLFSYNC, isFullsync));
34005    rc = osOpenDirectory(pFile->zPath, &dirfd);
34006    if( rc==SQLITE_OK ){
34007      full_fsync(dirfd, 0, 0);
34008      robust_close(pFile, dirfd, __LINE__);
34009    }else{
34010      assert( rc==SQLITE_CANTOPEN );
34011      rc = SQLITE_OK;
34012    }
34013    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
34014  }
34015  return rc;
34016}
34017
34018/*
34019** Truncate an open file to a specified size
34020*/
34021static int unixTruncate(sqlite3_file *id, i64 nByte){
34022  unixFile *pFile = (unixFile *)id;
34023  int rc;
34024  assert( pFile );
34025  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
34026
34027  /* If the user has configured a chunk-size for this file, truncate the
34028  ** file so that it consists of an integer number of chunks (i.e. the
34029  ** actual file size after the operation may be larger than the requested
34030  ** size).
34031  */
34032  if( pFile->szChunk>0 ){
34033    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
34034  }
34035
34036  rc = robust_ftruncate(pFile->h, nByte);
34037  if( rc ){
34038    storeLastErrno(pFile, errno);
34039    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
34040  }else{
34041#ifdef SQLITE_DEBUG
34042    /* If we are doing a normal write to a database file (as opposed to
34043    ** doing a hot-journal rollback or a write to some file other than a
34044    ** normal database file) and we truncate the file to zero length,
34045    ** that effectively updates the change counter.  This might happen
34046    ** when restoring a database using the backup API from a zero-length
34047    ** source.
34048    */
34049    if( pFile->inNormalWrite && nByte==0 ){
34050      pFile->transCntrChng = 1;
34051    }
34052#endif
34053
34054#if SQLITE_MAX_MMAP_SIZE>0
34055    /* If the file was just truncated to a size smaller than the currently
34056    ** mapped region, reduce the effective mapping size as well. SQLite will
34057    ** use read() and write() to access data beyond this point from now on.
34058    */
34059    if( nByte<pFile->mmapSize ){
34060      pFile->mmapSize = nByte;
34061    }
34062#endif
34063
34064    return SQLITE_OK;
34065  }
34066}
34067
34068/*
34069** Determine the current size of a file in bytes
34070*/
34071static int unixFileSize(sqlite3_file *id, i64 *pSize){
34072  int rc;
34073  struct stat buf;
34074  assert( id );
34075  rc = osFstat(((unixFile*)id)->h, &buf);
34076  SimulateIOError( rc=1 );
34077  if( rc!=0 ){
34078    storeLastErrno((unixFile*)id, errno);
34079    return SQLITE_IOERR_FSTAT;
34080  }
34081  *pSize = buf.st_size;
34082
34083  /* When opening a zero-size database, the findInodeInfo() procedure
34084  ** writes a single byte into that file in order to work around a bug
34085  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
34086  ** layers, we need to report this file size as zero even though it is
34087  ** really 1.   Ticket #3260.
34088  */
34089  if( *pSize==1 ) *pSize = 0;
34090
34091
34092  return SQLITE_OK;
34093}
34094
34095#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34096/*
34097** Handler for proxy-locking file-control verbs.  Defined below in the
34098** proxying locking division.
34099*/
34100static int proxyFileControl(sqlite3_file*,int,void*);
34101#endif
34102
34103/*
34104** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
34105** file-control operation.  Enlarge the database to nBytes in size
34106** (rounded up to the next chunk-size).  If the database is already
34107** nBytes or larger, this routine is a no-op.
34108*/
34109static int fcntlSizeHint(unixFile *pFile, i64 nByte){
34110  if( pFile->szChunk>0 ){
34111    i64 nSize;                    /* Required file size */
34112    struct stat buf;              /* Used to hold return values of fstat() */
34113
34114    if( osFstat(pFile->h, &buf) ){
34115      return SQLITE_IOERR_FSTAT;
34116    }
34117
34118    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
34119    if( nSize>(i64)buf.st_size ){
34120
34121#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
34122      /* The code below is handling the return value of osFallocate()
34123      ** correctly. posix_fallocate() is defined to "returns zero on success,
34124      ** or an error number on  failure". See the manpage for details. */
34125      int err;
34126      do{
34127        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
34128      }while( err==EINTR );
34129      if( err ) return SQLITE_IOERR_WRITE;
34130#else
34131      /* If the OS does not have posix_fallocate(), fake it. Write a
34132      ** single byte to the last byte in each block that falls entirely
34133      ** within the extended region. Then, if required, a single byte
34134      ** at offset (nSize-1), to set the size of the file correctly.
34135      ** This is a similar technique to that used by glibc on systems
34136      ** that do not have a real fallocate() call.
34137      */
34138      int nBlk = buf.st_blksize;  /* File-system block size */
34139      int nWrite = 0;             /* Number of bytes written by seekAndWrite */
34140      i64 iWrite;                 /* Next offset to write to */
34141
34142      iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
34143      assert( iWrite>=buf.st_size );
34144      assert( ((iWrite+1)%nBlk)==0 );
34145      for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
34146        if( iWrite>=nSize ) iWrite = nSize - 1;
34147        nWrite = seekAndWrite(pFile, iWrite, "", 1);
34148        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
34149      }
34150#endif
34151    }
34152  }
34153
34154#if SQLITE_MAX_MMAP_SIZE>0
34155  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
34156    int rc;
34157    if( pFile->szChunk<=0 ){
34158      if( robust_ftruncate(pFile->h, nByte) ){
34159        storeLastErrno(pFile, errno);
34160        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
34161      }
34162    }
34163
34164    rc = unixMapfile(pFile, nByte);
34165    return rc;
34166  }
34167#endif
34168
34169  return SQLITE_OK;
34170}
34171
34172/*
34173** If *pArg is initially negative then this is a query.  Set *pArg to
34174** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
34175**
34176** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
34177*/
34178static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
34179  if( *pArg<0 ){
34180    *pArg = (pFile->ctrlFlags & mask)!=0;
34181  }else if( (*pArg)==0 ){
34182    pFile->ctrlFlags &= ~mask;
34183  }else{
34184    pFile->ctrlFlags |= mask;
34185  }
34186}
34187
34188/* Forward declaration */
34189static int unixGetTempname(int nBuf, char *zBuf);
34190
34191/*
34192** Information and control of an open file handle.
34193*/
34194static int unixFileControl(sqlite3_file *id, int op, void *pArg){
34195  unixFile *pFile = (unixFile*)id;
34196  switch( op ){
34197    case SQLITE_FCNTL_LOCKSTATE: {
34198      *(int*)pArg = pFile->eFileLock;
34199      return SQLITE_OK;
34200    }
34201    case SQLITE_FCNTL_LAST_ERRNO: {
34202      *(int*)pArg = pFile->lastErrno;
34203      return SQLITE_OK;
34204    }
34205    case SQLITE_FCNTL_CHUNK_SIZE: {
34206      pFile->szChunk = *(int *)pArg;
34207      return SQLITE_OK;
34208    }
34209    case SQLITE_FCNTL_SIZE_HINT: {
34210      int rc;
34211      SimulateIOErrorBenign(1);
34212      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
34213      SimulateIOErrorBenign(0);
34214      return rc;
34215    }
34216    case SQLITE_FCNTL_PERSIST_WAL: {
34217      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
34218      return SQLITE_OK;
34219    }
34220    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
34221      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
34222      return SQLITE_OK;
34223    }
34224    case SQLITE_FCNTL_VFSNAME: {
34225      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
34226      return SQLITE_OK;
34227    }
34228    case SQLITE_FCNTL_TEMPFILENAME: {
34229      char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
34230      if( zTFile ){
34231        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
34232        *(char**)pArg = zTFile;
34233      }
34234      return SQLITE_OK;
34235    }
34236    case SQLITE_FCNTL_HAS_MOVED: {
34237      *(int*)pArg = fileHasMoved(pFile);
34238      return SQLITE_OK;
34239    }
34240#if SQLITE_MAX_MMAP_SIZE>0
34241    case SQLITE_FCNTL_MMAP_SIZE: {
34242      i64 newLimit = *(i64*)pArg;
34243      int rc = SQLITE_OK;
34244      if( newLimit>sqlite3GlobalConfig.mxMmap ){
34245        newLimit = sqlite3GlobalConfig.mxMmap;
34246      }
34247      *(i64*)pArg = pFile->mmapSizeMax;
34248      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
34249        pFile->mmapSizeMax = newLimit;
34250        if( pFile->mmapSize>0 ){
34251          unixUnmapfile(pFile);
34252          rc = unixMapfile(pFile, -1);
34253        }
34254      }
34255      return rc;
34256    }
34257#endif
34258#ifdef SQLITE_DEBUG
34259    /* The pager calls this method to signal that it has done
34260    ** a rollback and that the database is therefore unchanged and
34261    ** it hence it is OK for the transaction change counter to be
34262    ** unchanged.
34263    */
34264    case SQLITE_FCNTL_DB_UNCHANGED: {
34265      ((unixFile*)id)->dbUpdate = 0;
34266      return SQLITE_OK;
34267    }
34268#endif
34269#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34270    case SQLITE_FCNTL_SET_LOCKPROXYFILE:
34271    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
34272      return proxyFileControl(id,op,pArg);
34273    }
34274#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
34275  }
34276  return SQLITE_NOTFOUND;
34277}
34278
34279/*
34280** Return the sector size in bytes of the underlying block device for
34281** the specified file. This is almost always 512 bytes, but may be
34282** larger for some devices.
34283**
34284** SQLite code assumes this function cannot fail. It also assumes that
34285** if two files are created in the same file-system directory (i.e.
34286** a database and its journal file) that the sector size will be the
34287** same for both.
34288*/
34289#ifndef __QNXNTO__
34290static int unixSectorSize(sqlite3_file *NotUsed){
34291  UNUSED_PARAMETER(NotUsed);
34292  return SQLITE_DEFAULT_SECTOR_SIZE;
34293}
34294#endif
34295
34296/*
34297** The following version of unixSectorSize() is optimized for QNX.
34298*/
34299#ifdef __QNXNTO__
34300#include <sys/dcmd_blk.h>
34301#include <sys/statvfs.h>
34302static int unixSectorSize(sqlite3_file *id){
34303  unixFile *pFile = (unixFile*)id;
34304  if( pFile->sectorSize == 0 ){
34305    struct statvfs fsInfo;
34306
34307    /* Set defaults for non-supported filesystems */
34308    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
34309    pFile->deviceCharacteristics = 0;
34310    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
34311      return pFile->sectorSize;
34312    }
34313
34314    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
34315      pFile->sectorSize = fsInfo.f_bsize;
34316      pFile->deviceCharacteristics =
34317        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
34318        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
34319                                      ** the write succeeds */
34320        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
34321                                      ** so it is ordered */
34322        0;
34323    }else if( strstr(fsInfo.f_basetype, "etfs") ){
34324      pFile->sectorSize = fsInfo.f_bsize;
34325      pFile->deviceCharacteristics =
34326        /* etfs cluster size writes are atomic */
34327        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
34328        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
34329                                      ** the write succeeds */
34330        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
34331                                      ** so it is ordered */
34332        0;
34333    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
34334      pFile->sectorSize = fsInfo.f_bsize;
34335      pFile->deviceCharacteristics =
34336        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
34337        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
34338                                      ** the write succeeds */
34339        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
34340                                      ** so it is ordered */
34341        0;
34342    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
34343      pFile->sectorSize = fsInfo.f_bsize;
34344      pFile->deviceCharacteristics =
34345        /* full bitset of atomics from max sector size and smaller */
34346        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
34347        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
34348                                      ** so it is ordered */
34349        0;
34350    }else if( strstr(fsInfo.f_basetype, "dos") ){
34351      pFile->sectorSize = fsInfo.f_bsize;
34352      pFile->deviceCharacteristics =
34353        /* full bitset of atomics from max sector size and smaller */
34354        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
34355        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
34356                                      ** so it is ordered */
34357        0;
34358    }else{
34359      pFile->deviceCharacteristics =
34360        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
34361        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
34362                                      ** the write succeeds */
34363        0;
34364    }
34365  }
34366  /* Last chance verification.  If the sector size isn't a multiple of 512
34367  ** then it isn't valid.*/
34368  if( pFile->sectorSize % 512 != 0 ){
34369    pFile->deviceCharacteristics = 0;
34370    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
34371  }
34372  return pFile->sectorSize;
34373}
34374#endif /* __QNXNTO__ */
34375
34376/*
34377** Return the device characteristics for the file.
34378**
34379** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
34380** However, that choice is controversial since technically the underlying
34381** file system does not always provide powersafe overwrites.  (In other
34382** words, after a power-loss event, parts of the file that were never
34383** written might end up being altered.)  However, non-PSOW behavior is very,
34384** very rare.  And asserting PSOW makes a large reduction in the amount
34385** of required I/O for journaling, since a lot of padding is eliminated.
34386**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
34387** available to turn it off and URI query parameter available to turn it off.
34388*/
34389static int unixDeviceCharacteristics(sqlite3_file *id){
34390  unixFile *p = (unixFile*)id;
34391  int rc = 0;
34392#ifdef __QNXNTO__
34393  if( p->sectorSize==0 ) unixSectorSize(id);
34394  rc = p->deviceCharacteristics;
34395#endif
34396  if( p->ctrlFlags & UNIXFILE_PSOW ){
34397    rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
34398  }
34399  return rc;
34400}
34401
34402#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
34403
34404/*
34405** Return the system page size.
34406**
34407** This function should not be called directly by other code in this file.
34408** Instead, it should be called via macro osGetpagesize().
34409*/
34410static int unixGetpagesize(void){
34411#if OS_VXWORKS
34412  return 1024;
34413#elif defined(_BSD_SOURCE)
34414  return getpagesize();
34415#else
34416  return (int)sysconf(_SC_PAGESIZE);
34417#endif
34418}
34419
34420#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
34421
34422#ifndef SQLITE_OMIT_WAL
34423
34424/*
34425** Object used to represent an shared memory buffer.
34426**
34427** When multiple threads all reference the same wal-index, each thread
34428** has its own unixShm object, but they all point to a single instance
34429** of this unixShmNode object.  In other words, each wal-index is opened
34430** only once per process.
34431**
34432** Each unixShmNode object is connected to a single unixInodeInfo object.
34433** We could coalesce this object into unixInodeInfo, but that would mean
34434** every open file that does not use shared memory (in other words, most
34435** open files) would have to carry around this extra information.  So
34436** the unixInodeInfo object contains a pointer to this unixShmNode object
34437** and the unixShmNode object is created only when needed.
34438**
34439** unixMutexHeld() must be true when creating or destroying
34440** this object or while reading or writing the following fields:
34441**
34442**      nRef
34443**
34444** The following fields are read-only after the object is created:
34445**
34446**      fid
34447**      zFilename
34448**
34449** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
34450** unixMutexHeld() is true when reading or writing any other field
34451** in this structure.
34452*/
34453struct unixShmNode {
34454  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
34455  sqlite3_mutex *mutex;      /* Mutex to access this object */
34456  char *zFilename;           /* Name of the mmapped file */
34457  int h;                     /* Open file descriptor */
34458  int szRegion;              /* Size of shared-memory regions */
34459  u16 nRegion;               /* Size of array apRegion */
34460  u8 isReadonly;             /* True if read-only */
34461  char **apRegion;           /* Array of mapped shared-memory regions */
34462  int nRef;                  /* Number of unixShm objects pointing to this */
34463  unixShm *pFirst;           /* All unixShm objects pointing to this */
34464#ifdef SQLITE_DEBUG
34465  u8 exclMask;               /* Mask of exclusive locks held */
34466  u8 sharedMask;             /* Mask of shared locks held */
34467  u8 nextShmId;              /* Next available unixShm.id value */
34468#endif
34469};
34470
34471/*
34472** Structure used internally by this VFS to record the state of an
34473** open shared memory connection.
34474**
34475** The following fields are initialized when this object is created and
34476** are read-only thereafter:
34477**
34478**    unixShm.pFile
34479**    unixShm.id
34480**
34481** All other fields are read/write.  The unixShm.pFile->mutex must be held
34482** while accessing any read/write fields.
34483*/
34484struct unixShm {
34485  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
34486  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
34487  u8 hasMutex;               /* True if holding the unixShmNode mutex */
34488  u8 id;                     /* Id of this connection within its unixShmNode */
34489  u16 sharedMask;            /* Mask of shared locks held */
34490  u16 exclMask;              /* Mask of exclusive locks held */
34491};
34492
34493/*
34494** Constants used for locking
34495*/
34496#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
34497#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
34498
34499/*
34500** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
34501**
34502** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
34503** otherwise.
34504*/
34505static int unixShmSystemLock(
34506  unixFile *pFile,       /* Open connection to the WAL file */
34507  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
34508  int ofst,              /* First byte of the locking range */
34509  int n                  /* Number of bytes to lock */
34510){
34511  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
34512  struct flock f;        /* The posix advisory locking structure */
34513  int rc = SQLITE_OK;    /* Result code form fcntl() */
34514
34515  /* Access to the unixShmNode object is serialized by the caller */
34516  pShmNode = pFile->pInode->pShmNode;
34517  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
34518
34519  /* Shared locks never span more than one byte */
34520  assert( n==1 || lockType!=F_RDLCK );
34521
34522  /* Locks are within range */
34523  assert( n>=1 && n<=SQLITE_SHM_NLOCK );
34524
34525  if( pShmNode->h>=0 ){
34526    /* Initialize the locking parameters */
34527    memset(&f, 0, sizeof(f));
34528    f.l_type = lockType;
34529    f.l_whence = SEEK_SET;
34530    f.l_start = ofst;
34531    f.l_len = n;
34532
34533    rc = osFcntl(pShmNode->h, F_SETLK, &f);
34534    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
34535  }
34536
34537  /* Update the global lock state and do debug tracing */
34538#ifdef SQLITE_DEBUG
34539  { u16 mask;
34540  OSTRACE(("SHM-LOCK "));
34541  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
34542  if( rc==SQLITE_OK ){
34543    if( lockType==F_UNLCK ){
34544      OSTRACE(("unlock %d ok", ofst));
34545      pShmNode->exclMask &= ~mask;
34546      pShmNode->sharedMask &= ~mask;
34547    }else if( lockType==F_RDLCK ){
34548      OSTRACE(("read-lock %d ok", ofst));
34549      pShmNode->exclMask &= ~mask;
34550      pShmNode->sharedMask |= mask;
34551    }else{
34552      assert( lockType==F_WRLCK );
34553      OSTRACE(("write-lock %d ok", ofst));
34554      pShmNode->exclMask |= mask;
34555      pShmNode->sharedMask &= ~mask;
34556    }
34557  }else{
34558    if( lockType==F_UNLCK ){
34559      OSTRACE(("unlock %d failed", ofst));
34560    }else if( lockType==F_RDLCK ){
34561      OSTRACE(("read-lock failed"));
34562    }else{
34563      assert( lockType==F_WRLCK );
34564      OSTRACE(("write-lock %d failed", ofst));
34565    }
34566  }
34567  OSTRACE((" - afterwards %03x,%03x\n",
34568           pShmNode->sharedMask, pShmNode->exclMask));
34569  }
34570#endif
34571
34572  return rc;
34573}
34574
34575/*
34576** Return the minimum number of 32KB shm regions that should be mapped at
34577** a time, assuming that each mapping must be an integer multiple of the
34578** current system page-size.
34579**
34580** Usually, this is 1. The exception seems to be systems that are configured
34581** to use 64KB pages - in this case each mapping must cover at least two
34582** shm regions.
34583*/
34584static int unixShmRegionPerMap(void){
34585  int shmsz = 32*1024;            /* SHM region size */
34586  int pgsz = osGetpagesize();   /* System page size */
34587  assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
34588  if( pgsz<shmsz ) return 1;
34589  return pgsz/shmsz;
34590}
34591
34592/*
34593** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
34594**
34595** This is not a VFS shared-memory method; it is a utility function called
34596** by VFS shared-memory methods.
34597*/
34598static void unixShmPurge(unixFile *pFd){
34599  unixShmNode *p = pFd->pInode->pShmNode;
34600  assert( unixMutexHeld() );
34601  if( p && ALWAYS(p->nRef==0) ){
34602    int nShmPerMap = unixShmRegionPerMap();
34603    int i;
34604    assert( p->pInode==pFd->pInode );
34605    sqlite3_mutex_free(p->mutex);
34606    for(i=0; i<p->nRegion; i+=nShmPerMap){
34607      if( p->h>=0 ){
34608        osMunmap(p->apRegion[i], p->szRegion);
34609      }else{
34610        sqlite3_free(p->apRegion[i]);
34611      }
34612    }
34613    sqlite3_free(p->apRegion);
34614    if( p->h>=0 ){
34615      robust_close(pFd, p->h, __LINE__);
34616      p->h = -1;
34617    }
34618    p->pInode->pShmNode = 0;
34619    sqlite3_free(p);
34620  }
34621}
34622
34623/*
34624** Open a shared-memory area associated with open database file pDbFd.
34625** This particular implementation uses mmapped files.
34626**
34627** The file used to implement shared-memory is in the same directory
34628** as the open database file and has the same name as the open database
34629** file with the "-shm" suffix added.  For example, if the database file
34630** is "/home/user1/config.db" then the file that is created and mmapped
34631** for shared memory will be called "/home/user1/config.db-shm".
34632**
34633** Another approach to is to use files in /dev/shm or /dev/tmp or an
34634** some other tmpfs mount. But if a file in a different directory
34635** from the database file is used, then differing access permissions
34636** or a chroot() might cause two different processes on the same
34637** database to end up using different files for shared memory -
34638** meaning that their memory would not really be shared - resulting
34639** in database corruption.  Nevertheless, this tmpfs file usage
34640** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
34641** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
34642** option results in an incompatible build of SQLite;  builds of SQLite
34643** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
34644** same database file at the same time, database corruption will likely
34645** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
34646** "unsupported" and may go away in a future SQLite release.
34647**
34648** When opening a new shared-memory file, if no other instances of that
34649** file are currently open, in this process or in other processes, then
34650** the file must be truncated to zero length or have its header cleared.
34651**
34652** If the original database file (pDbFd) is using the "unix-excl" VFS
34653** that means that an exclusive lock is held on the database file and
34654** that no other processes are able to read or write the database.  In
34655** that case, we do not really need shared memory.  No shared memory
34656** file is created.  The shared memory will be simulated with heap memory.
34657*/
34658static int unixOpenSharedMemory(unixFile *pDbFd){
34659  struct unixShm *p = 0;          /* The connection to be opened */
34660  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
34661  int rc;                         /* Result code */
34662  unixInodeInfo *pInode;          /* The inode of fd */
34663  char *zShmFilename;             /* Name of the file used for SHM */
34664  int nShmFilename;               /* Size of the SHM filename in bytes */
34665
34666  /* Allocate space for the new unixShm object. */
34667  p = sqlite3_malloc64( sizeof(*p) );
34668  if( p==0 ) return SQLITE_NOMEM_BKPT;
34669  memset(p, 0, sizeof(*p));
34670  assert( pDbFd->pShm==0 );
34671
34672  /* Check to see if a unixShmNode object already exists. Reuse an existing
34673  ** one if present. Create a new one if necessary.
34674  */
34675  unixEnterMutex();
34676  pInode = pDbFd->pInode;
34677  pShmNode = pInode->pShmNode;
34678  if( pShmNode==0 ){
34679    struct stat sStat;                 /* fstat() info for database file */
34680#ifndef SQLITE_SHM_DIRECTORY
34681    const char *zBasePath = pDbFd->zPath;
34682#endif
34683
34684    /* Call fstat() to figure out the permissions on the database file. If
34685    ** a new *-shm file is created, an attempt will be made to create it
34686    ** with the same permissions.
34687    */
34688    if( osFstat(pDbFd->h, &sStat) ){
34689      rc = SQLITE_IOERR_FSTAT;
34690      goto shm_open_err;
34691    }
34692
34693#ifdef SQLITE_SHM_DIRECTORY
34694    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
34695#else
34696    nShmFilename = 6 + (int)strlen(zBasePath);
34697#endif
34698    pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
34699    if( pShmNode==0 ){
34700      rc = SQLITE_NOMEM_BKPT;
34701      goto shm_open_err;
34702    }
34703    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
34704    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
34705#ifdef SQLITE_SHM_DIRECTORY
34706    sqlite3_snprintf(nShmFilename, zShmFilename,
34707                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
34708                     (u32)sStat.st_ino, (u32)sStat.st_dev);
34709#else
34710    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
34711    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
34712#endif
34713    pShmNode->h = -1;
34714    pDbFd->pInode->pShmNode = pShmNode;
34715    pShmNode->pInode = pDbFd->pInode;
34716    if( sqlite3GlobalConfig.bCoreMutex ){
34717      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
34718      if( pShmNode->mutex==0 ){
34719        rc = SQLITE_NOMEM_BKPT;
34720        goto shm_open_err;
34721      }
34722    }
34723
34724    if( pInode->bProcessLock==0 ){
34725      int openFlags = O_RDWR | O_CREAT;
34726      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
34727        openFlags = O_RDONLY;
34728        pShmNode->isReadonly = 1;
34729      }
34730      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
34731      if( pShmNode->h<0 ){
34732        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
34733        goto shm_open_err;
34734      }
34735
34736      /* If this process is running as root, make sure that the SHM file
34737      ** is owned by the same user that owns the original database.  Otherwise,
34738      ** the original owner will not be able to connect.
34739      */
34740      robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
34741
34742      /* Check to see if another process is holding the dead-man switch.
34743      ** If not, truncate the file to zero length.
34744      */
34745      rc = SQLITE_OK;
34746      if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
34747        if( robust_ftruncate(pShmNode->h, 0) ){
34748          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
34749        }
34750      }
34751      if( rc==SQLITE_OK ){
34752        rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
34753      }
34754      if( rc ) goto shm_open_err;
34755    }
34756  }
34757
34758  /* Make the new connection a child of the unixShmNode */
34759  p->pShmNode = pShmNode;
34760#ifdef SQLITE_DEBUG
34761  p->id = pShmNode->nextShmId++;
34762#endif
34763  pShmNode->nRef++;
34764  pDbFd->pShm = p;
34765  unixLeaveMutex();
34766
34767  /* The reference count on pShmNode has already been incremented under
34768  ** the cover of the unixEnterMutex() mutex and the pointer from the
34769  ** new (struct unixShm) object to the pShmNode has been set. All that is
34770  ** left to do is to link the new object into the linked list starting
34771  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
34772  ** mutex.
34773  */
34774  sqlite3_mutex_enter(pShmNode->mutex);
34775  p->pNext = pShmNode->pFirst;
34776  pShmNode->pFirst = p;
34777  sqlite3_mutex_leave(pShmNode->mutex);
34778  return SQLITE_OK;
34779
34780  /* Jump here on any error */
34781shm_open_err:
34782  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
34783  sqlite3_free(p);
34784  unixLeaveMutex();
34785  return rc;
34786}
34787
34788/*
34789** This function is called to obtain a pointer to region iRegion of the
34790** shared-memory associated with the database file fd. Shared-memory regions
34791** are numbered starting from zero. Each shared-memory region is szRegion
34792** bytes in size.
34793**
34794** If an error occurs, an error code is returned and *pp is set to NULL.
34795**
34796** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
34797** region has not been allocated (by any client, including one running in a
34798** separate process), then *pp is set to NULL and SQLITE_OK returned. If
34799** bExtend is non-zero and the requested shared-memory region has not yet
34800** been allocated, it is allocated by this function.
34801**
34802** If the shared-memory region has already been allocated or is allocated by
34803** this call as described above, then it is mapped into this processes
34804** address space (if it is not already), *pp is set to point to the mapped
34805** memory and SQLITE_OK returned.
34806*/
34807static int unixShmMap(
34808  sqlite3_file *fd,               /* Handle open on database file */
34809  int iRegion,                    /* Region to retrieve */
34810  int szRegion,                   /* Size of regions */
34811  int bExtend,                    /* True to extend file if necessary */
34812  void volatile **pp              /* OUT: Mapped memory */
34813){
34814  unixFile *pDbFd = (unixFile*)fd;
34815  unixShm *p;
34816  unixShmNode *pShmNode;
34817  int rc = SQLITE_OK;
34818  int nShmPerMap = unixShmRegionPerMap();
34819  int nReqRegion;
34820
34821  /* If the shared-memory file has not yet been opened, open it now. */
34822  if( pDbFd->pShm==0 ){
34823    rc = unixOpenSharedMemory(pDbFd);
34824    if( rc!=SQLITE_OK ) return rc;
34825  }
34826
34827  p = pDbFd->pShm;
34828  pShmNode = p->pShmNode;
34829  sqlite3_mutex_enter(pShmNode->mutex);
34830  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34831  assert( pShmNode->pInode==pDbFd->pInode );
34832  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
34833  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
34834
34835  /* Minimum number of regions required to be mapped. */
34836  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
34837
34838  if( pShmNode->nRegion<nReqRegion ){
34839    char **apNew;                      /* New apRegion[] array */
34840    int nByte = nReqRegion*szRegion;   /* Minimum required file size */
34841    struct stat sStat;                 /* Used by fstat() */
34842
34843    pShmNode->szRegion = szRegion;
34844
34845    if( pShmNode->h>=0 ){
34846      /* The requested region is not mapped into this processes address space.
34847      ** Check to see if it has been allocated (i.e. if the wal-index file is
34848      ** large enough to contain the requested region).
34849      */
34850      if( osFstat(pShmNode->h, &sStat) ){
34851        rc = SQLITE_IOERR_SHMSIZE;
34852        goto shmpage_out;
34853      }
34854
34855      if( sStat.st_size<nByte ){
34856        /* The requested memory region does not exist. If bExtend is set to
34857        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
34858        */
34859        if( !bExtend ){
34860          goto shmpage_out;
34861        }
34862
34863        /* Alternatively, if bExtend is true, extend the file. Do this by
34864        ** writing a single byte to the end of each (OS) page being
34865        ** allocated or extended. Technically, we need only write to the
34866        ** last page in order to extend the file. But writing to all new
34867        ** pages forces the OS to allocate them immediately, which reduces
34868        ** the chances of SIGBUS while accessing the mapped region later on.
34869        */
34870        else{
34871          static const int pgsz = 4096;
34872          int iPg;
34873
34874          /* Write to the last byte of each newly allocated or extended page */
34875          assert( (nByte % pgsz)==0 );
34876          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
34877            int x = 0;
34878            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
34879              const char *zFile = pShmNode->zFilename;
34880              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
34881              goto shmpage_out;
34882            }
34883          }
34884        }
34885      }
34886    }
34887
34888    /* Map the requested memory region into this processes address space. */
34889    apNew = (char **)sqlite3_realloc(
34890        pShmNode->apRegion, nReqRegion*sizeof(char *)
34891    );
34892    if( !apNew ){
34893      rc = SQLITE_IOERR_NOMEM_BKPT;
34894      goto shmpage_out;
34895    }
34896    pShmNode->apRegion = apNew;
34897    while( pShmNode->nRegion<nReqRegion ){
34898      int nMap = szRegion*nShmPerMap;
34899      int i;
34900      void *pMem;
34901      if( pShmNode->h>=0 ){
34902        pMem = osMmap(0, nMap,
34903            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
34904            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
34905        );
34906        if( pMem==MAP_FAILED ){
34907          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
34908          goto shmpage_out;
34909        }
34910      }else{
34911        pMem = sqlite3_malloc64(szRegion);
34912        if( pMem==0 ){
34913          rc = SQLITE_NOMEM_BKPT;
34914          goto shmpage_out;
34915        }
34916        memset(pMem, 0, szRegion);
34917      }
34918
34919      for(i=0; i<nShmPerMap; i++){
34920        pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
34921      }
34922      pShmNode->nRegion += nShmPerMap;
34923    }
34924  }
34925
34926shmpage_out:
34927  if( pShmNode->nRegion>iRegion ){
34928    *pp = pShmNode->apRegion[iRegion];
34929  }else{
34930    *pp = 0;
34931  }
34932  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
34933  sqlite3_mutex_leave(pShmNode->mutex);
34934  return rc;
34935}
34936
34937/*
34938** Change the lock state for a shared-memory segment.
34939**
34940** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
34941** different here than in posix.  In xShmLock(), one can go from unlocked
34942** to shared and back or from unlocked to exclusive and back.  But one may
34943** not go from shared to exclusive or from exclusive to shared.
34944*/
34945static int unixShmLock(
34946  sqlite3_file *fd,          /* Database file holding the shared memory */
34947  int ofst,                  /* First lock to acquire or release */
34948  int n,                     /* Number of locks to acquire or release */
34949  int flags                  /* What to do with the lock */
34950){
34951  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
34952  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
34953  unixShm *pX;                          /* For looping over all siblings */
34954  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
34955  int rc = SQLITE_OK;                   /* Result code */
34956  u16 mask;                             /* Mask of locks to take or release */
34957
34958  assert( pShmNode==pDbFd->pInode->pShmNode );
34959  assert( pShmNode->pInode==pDbFd->pInode );
34960  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34961  assert( n>=1 );
34962  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34963       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34964       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34965       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34966  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34967  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
34968  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
34969
34970  mask = (1<<(ofst+n)) - (1<<ofst);
34971  assert( n>1 || mask==(1<<ofst) );
34972  sqlite3_mutex_enter(pShmNode->mutex);
34973  if( flags & SQLITE_SHM_UNLOCK ){
34974    u16 allMask = 0; /* Mask of locks held by siblings */
34975
34976    /* See if any siblings hold this same lock */
34977    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34978      if( pX==p ) continue;
34979      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34980      allMask |= pX->sharedMask;
34981    }
34982
34983    /* Unlock the system-level locks */
34984    if( (mask & allMask)==0 ){
34985      rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
34986    }else{
34987      rc = SQLITE_OK;
34988    }
34989
34990    /* Undo the local locks */
34991    if( rc==SQLITE_OK ){
34992      p->exclMask &= ~mask;
34993      p->sharedMask &= ~mask;
34994    }
34995  }else if( flags & SQLITE_SHM_SHARED ){
34996    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
34997
34998    /* Find out which shared locks are already held by sibling connections.
34999    ** If any sibling already holds an exclusive lock, go ahead and return
35000    ** SQLITE_BUSY.
35001    */
35002    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35003      if( (pX->exclMask & mask)!=0 ){
35004        rc = SQLITE_BUSY;
35005        break;
35006      }
35007      allShared |= pX->sharedMask;
35008    }
35009
35010    /* Get shared locks at the system level, if necessary */
35011    if( rc==SQLITE_OK ){
35012      if( (allShared & mask)==0 ){
35013        rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
35014      }else{
35015        rc = SQLITE_OK;
35016      }
35017    }
35018
35019    /* Get the local shared locks */
35020    if( rc==SQLITE_OK ){
35021      p->sharedMask |= mask;
35022    }
35023  }else{
35024    /* Make sure no sibling connections hold locks that will block this
35025    ** lock.  If any do, return SQLITE_BUSY right away.
35026    */
35027    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35028      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
35029        rc = SQLITE_BUSY;
35030        break;
35031      }
35032    }
35033
35034    /* Get the exclusive locks at the system level.  Then if successful
35035    ** also mark the local connection as being locked.
35036    */
35037    if( rc==SQLITE_OK ){
35038      rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
35039      if( rc==SQLITE_OK ){
35040        assert( (p->sharedMask & mask)==0 );
35041        p->exclMask |= mask;
35042      }
35043    }
35044  }
35045  sqlite3_mutex_leave(pShmNode->mutex);
35046  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
35047           p->id, osGetpid(0), p->sharedMask, p->exclMask));
35048  return rc;
35049}
35050
35051/*
35052** Implement a memory barrier or memory fence on shared memory.
35053**
35054** All loads and stores begun before the barrier must complete before
35055** any load or store begun after the barrier.
35056*/
35057static void unixShmBarrier(
35058  sqlite3_file *fd                /* Database file holding the shared memory */
35059){
35060  UNUSED_PARAMETER(fd);
35061  sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
35062  unixEnterMutex();               /* Also mutex, for redundancy */
35063  unixLeaveMutex();
35064}
35065
35066/*
35067** Close a connection to shared-memory.  Delete the underlying
35068** storage if deleteFlag is true.
35069**
35070** If there is no shared memory associated with the connection then this
35071** routine is a harmless no-op.
35072*/
35073static int unixShmUnmap(
35074  sqlite3_file *fd,               /* The underlying database file */
35075  int deleteFlag                  /* Delete shared-memory if true */
35076){
35077  unixShm *p;                     /* The connection to be closed */
35078  unixShmNode *pShmNode;          /* The underlying shared-memory file */
35079  unixShm **pp;                   /* For looping over sibling connections */
35080  unixFile *pDbFd;                /* The underlying database file */
35081
35082  pDbFd = (unixFile*)fd;
35083  p = pDbFd->pShm;
35084  if( p==0 ) return SQLITE_OK;
35085  pShmNode = p->pShmNode;
35086
35087  assert( pShmNode==pDbFd->pInode->pShmNode );
35088  assert( pShmNode->pInode==pDbFd->pInode );
35089
35090  /* Remove connection p from the set of connections associated
35091  ** with pShmNode */
35092  sqlite3_mutex_enter(pShmNode->mutex);
35093  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
35094  *pp = p->pNext;
35095
35096  /* Free the connection p */
35097  sqlite3_free(p);
35098  pDbFd->pShm = 0;
35099  sqlite3_mutex_leave(pShmNode->mutex);
35100
35101  /* If pShmNode->nRef has reached 0, then close the underlying
35102  ** shared-memory file, too */
35103  unixEnterMutex();
35104  assert( pShmNode->nRef>0 );
35105  pShmNode->nRef--;
35106  if( pShmNode->nRef==0 ){
35107    if( deleteFlag && pShmNode->h>=0 ){
35108      osUnlink(pShmNode->zFilename);
35109    }
35110    unixShmPurge(pDbFd);
35111  }
35112  unixLeaveMutex();
35113
35114  return SQLITE_OK;
35115}
35116
35117
35118#else
35119# define unixShmMap     0
35120# define unixShmLock    0
35121# define unixShmBarrier 0
35122# define unixShmUnmap   0
35123#endif /* #ifndef SQLITE_OMIT_WAL */
35124
35125#if SQLITE_MAX_MMAP_SIZE>0
35126/*
35127** If it is currently memory mapped, unmap file pFd.
35128*/
35129static void unixUnmapfile(unixFile *pFd){
35130  assert( pFd->nFetchOut==0 );
35131  if( pFd->pMapRegion ){
35132    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
35133    pFd->pMapRegion = 0;
35134    pFd->mmapSize = 0;
35135    pFd->mmapSizeActual = 0;
35136  }
35137}
35138
35139/*
35140** Attempt to set the size of the memory mapping maintained by file
35141** descriptor pFd to nNew bytes. Any existing mapping is discarded.
35142**
35143** If successful, this function sets the following variables:
35144**
35145**       unixFile.pMapRegion
35146**       unixFile.mmapSize
35147**       unixFile.mmapSizeActual
35148**
35149** If unsuccessful, an error message is logged via sqlite3_log() and
35150** the three variables above are zeroed. In this case SQLite should
35151** continue accessing the database using the xRead() and xWrite()
35152** methods.
35153*/
35154static void unixRemapfile(
35155  unixFile *pFd,                  /* File descriptor object */
35156  i64 nNew                        /* Required mapping size */
35157){
35158  const char *zErr = "mmap";
35159  int h = pFd->h;                      /* File descriptor open on db file */
35160  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
35161  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
35162  u8 *pNew = 0;                        /* Location of new mapping */
35163  int flags = PROT_READ;               /* Flags to pass to mmap() */
35164
35165  assert( pFd->nFetchOut==0 );
35166  assert( nNew>pFd->mmapSize );
35167  assert( nNew<=pFd->mmapSizeMax );
35168  assert( nNew>0 );
35169  assert( pFd->mmapSizeActual>=pFd->mmapSize );
35170  assert( MAP_FAILED!=0 );
35171
35172#ifdef SQLITE_MMAP_READWRITE
35173  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
35174#endif
35175
35176  if( pOrig ){
35177#if HAVE_MREMAP
35178    i64 nReuse = pFd->mmapSize;
35179#else
35180    const int szSyspage = osGetpagesize();
35181    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
35182#endif
35183    u8 *pReq = &pOrig[nReuse];
35184
35185    /* Unmap any pages of the existing mapping that cannot be reused. */
35186    if( nReuse!=nOrig ){
35187      osMunmap(pReq, nOrig-nReuse);
35188    }
35189
35190#if HAVE_MREMAP
35191    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
35192    zErr = "mremap";
35193#else
35194    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
35195    if( pNew!=MAP_FAILED ){
35196      if( pNew!=pReq ){
35197        osMunmap(pNew, nNew - nReuse);
35198        pNew = 0;
35199      }else{
35200        pNew = pOrig;
35201      }
35202    }
35203#endif
35204
35205    /* The attempt to extend the existing mapping failed. Free it. */
35206    if( pNew==MAP_FAILED || pNew==0 ){
35207      osMunmap(pOrig, nReuse);
35208    }
35209  }
35210
35211  /* If pNew is still NULL, try to create an entirely new mapping. */
35212  if( pNew==0 ){
35213    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
35214  }
35215
35216  if( pNew==MAP_FAILED ){
35217    pNew = 0;
35218    nNew = 0;
35219    unixLogError(SQLITE_OK, zErr, pFd->zPath);
35220
35221    /* If the mmap() above failed, assume that all subsequent mmap() calls
35222    ** will probably fail too. Fall back to using xRead/xWrite exclusively
35223    ** in this case.  */
35224    pFd->mmapSizeMax = 0;
35225  }
35226  pFd->pMapRegion = (void *)pNew;
35227  pFd->mmapSize = pFd->mmapSizeActual = nNew;
35228}
35229
35230/*
35231** Memory map or remap the file opened by file-descriptor pFd (if the file
35232** is already mapped, the existing mapping is replaced by the new). Or, if
35233** there already exists a mapping for this file, and there are still
35234** outstanding xFetch() references to it, this function is a no-op.
35235**
35236** If parameter nByte is non-negative, then it is the requested size of
35237** the mapping to create. Otherwise, if nByte is less than zero, then the
35238** requested size is the size of the file on disk. The actual size of the
35239** created mapping is either the requested size or the value configured
35240** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
35241**
35242** SQLITE_OK is returned if no error occurs (even if the mapping is not
35243** recreated as a result of outstanding references) or an SQLite error
35244** code otherwise.
35245*/
35246static int unixMapfile(unixFile *pFd, i64 nMap){
35247  assert( nMap>=0 || pFd->nFetchOut==0 );
35248  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
35249  if( pFd->nFetchOut>0 ) return SQLITE_OK;
35250
35251  if( nMap<0 ){
35252    struct stat statbuf;          /* Low-level file information */
35253    if( osFstat(pFd->h, &statbuf) ){
35254      return SQLITE_IOERR_FSTAT;
35255    }
35256    nMap = statbuf.st_size;
35257  }
35258  if( nMap>pFd->mmapSizeMax ){
35259    nMap = pFd->mmapSizeMax;
35260  }
35261
35262  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
35263  if( nMap!=pFd->mmapSize ){
35264    unixRemapfile(pFd, nMap);
35265  }
35266
35267  return SQLITE_OK;
35268}
35269#endif /* SQLITE_MAX_MMAP_SIZE>0 */
35270
35271/*
35272** If possible, return a pointer to a mapping of file fd starting at offset
35273** iOff. The mapping must be valid for at least nAmt bytes.
35274**
35275** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
35276** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
35277** Finally, if an error does occur, return an SQLite error code. The final
35278** value of *pp is undefined in this case.
35279**
35280** If this function does return a pointer, the caller must eventually
35281** release the reference by calling unixUnfetch().
35282*/
35283static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
35284#if SQLITE_MAX_MMAP_SIZE>0
35285  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
35286#endif
35287  *pp = 0;
35288
35289#if SQLITE_MAX_MMAP_SIZE>0
35290  if( pFd->mmapSizeMax>0 ){
35291    if( pFd->pMapRegion==0 ){
35292      int rc = unixMapfile(pFd, -1);
35293      if( rc!=SQLITE_OK ) return rc;
35294    }
35295    if( pFd->mmapSize >= iOff+nAmt ){
35296      *pp = &((u8 *)pFd->pMapRegion)[iOff];
35297      pFd->nFetchOut++;
35298    }
35299  }
35300#endif
35301  return SQLITE_OK;
35302}
35303
35304/*
35305** If the third argument is non-NULL, then this function releases a
35306** reference obtained by an earlier call to unixFetch(). The second
35307** argument passed to this function must be the same as the corresponding
35308** argument that was passed to the unixFetch() invocation.
35309**
35310** Or, if the third argument is NULL, then this function is being called
35311** to inform the VFS layer that, according to POSIX, any existing mapping
35312** may now be invalid and should be unmapped.
35313*/
35314static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
35315#if SQLITE_MAX_MMAP_SIZE>0
35316  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
35317  UNUSED_PARAMETER(iOff);
35318
35319  /* If p==0 (unmap the entire file) then there must be no outstanding
35320  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
35321  ** then there must be at least one outstanding.  */
35322  assert( (p==0)==(pFd->nFetchOut==0) );
35323
35324  /* If p!=0, it must match the iOff value. */
35325  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
35326
35327  if( p ){
35328    pFd->nFetchOut--;
35329  }else{
35330    unixUnmapfile(pFd);
35331  }
35332
35333  assert( pFd->nFetchOut>=0 );
35334#else
35335  UNUSED_PARAMETER(fd);
35336  UNUSED_PARAMETER(p);
35337  UNUSED_PARAMETER(iOff);
35338#endif
35339  return SQLITE_OK;
35340}
35341
35342/*
35343** Here ends the implementation of all sqlite3_file methods.
35344**
35345********************** End sqlite3_file Methods *******************************
35346******************************************************************************/
35347
35348/*
35349** This division contains definitions of sqlite3_io_methods objects that
35350** implement various file locking strategies.  It also contains definitions
35351** of "finder" functions.  A finder-function is used to locate the appropriate
35352** sqlite3_io_methods object for a particular database file.  The pAppData
35353** field of the sqlite3_vfs VFS objects are initialized to be pointers to
35354** the correct finder-function for that VFS.
35355**
35356** Most finder functions return a pointer to a fixed sqlite3_io_methods
35357** object.  The only interesting finder-function is autolockIoFinder, which
35358** looks at the filesystem type and tries to guess the best locking
35359** strategy from that.
35360**
35361** For finder-function F, two objects are created:
35362**
35363**    (1) The real finder-function named "FImpt()".
35364**
35365**    (2) A constant pointer to this function named just "F".
35366**
35367**
35368** A pointer to the F pointer is used as the pAppData value for VFS
35369** objects.  We have to do this instead of letting pAppData point
35370** directly at the finder-function since C90 rules prevent a void*
35371** from be cast into a function pointer.
35372**
35373**
35374** Each instance of this macro generates two objects:
35375**
35376**   *  A constant sqlite3_io_methods object call METHOD that has locking
35377**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
35378**
35379**   *  An I/O method finder function called FINDER that returns a pointer
35380**      to the METHOD object in the previous bullet.
35381*/
35382#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
35383static const sqlite3_io_methods METHOD = {                                   \
35384   VERSION,                    /* iVersion */                                \
35385   CLOSE,                      /* xClose */                                  \
35386   unixRead,                   /* xRead */                                   \
35387   unixWrite,                  /* xWrite */                                  \
35388   unixTruncate,               /* xTruncate */                               \
35389   unixSync,                   /* xSync */                                   \
35390   unixFileSize,               /* xFileSize */                               \
35391   LOCK,                       /* xLock */                                   \
35392   UNLOCK,                     /* xUnlock */                                 \
35393   CKLOCK,                     /* xCheckReservedLock */                      \
35394   unixFileControl,            /* xFileControl */                            \
35395   unixSectorSize,             /* xSectorSize */                             \
35396   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
35397   SHMMAP,                     /* xShmMap */                                 \
35398   unixShmLock,                /* xShmLock */                                \
35399   unixShmBarrier,             /* xShmBarrier */                             \
35400   unixShmUnmap,               /* xShmUnmap */                               \
35401   unixFetch,                  /* xFetch */                                  \
35402   unixUnfetch,                /* xUnfetch */                                \
35403};                                                                           \
35404static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
35405  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
35406  return &METHOD;                                                            \
35407}                                                                            \
35408static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
35409    = FINDER##Impl;
35410
35411/*
35412** Here are all of the sqlite3_io_methods objects for each of the
35413** locking strategies.  Functions that return pointers to these methods
35414** are also created.
35415*/
35416IOMETHODS(
35417  posixIoFinder,            /* Finder function name */
35418  posixIoMethods,           /* sqlite3_io_methods object name */
35419  3,                        /* shared memory and mmap are enabled */
35420  unixClose,                /* xClose method */
35421  unixLock,                 /* xLock method */
35422  unixUnlock,               /* xUnlock method */
35423  unixCheckReservedLock,    /* xCheckReservedLock method */
35424  unixShmMap                /* xShmMap method */
35425)
35426IOMETHODS(
35427  nolockIoFinder,           /* Finder function name */
35428  nolockIoMethods,          /* sqlite3_io_methods object name */
35429  3,                        /* shared memory is disabled */
35430  nolockClose,              /* xClose method */
35431  nolockLock,               /* xLock method */
35432  nolockUnlock,             /* xUnlock method */
35433  nolockCheckReservedLock,  /* xCheckReservedLock method */
35434  0                         /* xShmMap method */
35435)
35436IOMETHODS(
35437  dotlockIoFinder,          /* Finder function name */
35438  dotlockIoMethods,         /* sqlite3_io_methods object name */
35439  1,                        /* shared memory is disabled */
35440  dotlockClose,             /* xClose method */
35441  dotlockLock,              /* xLock method */
35442  dotlockUnlock,            /* xUnlock method */
35443  dotlockCheckReservedLock, /* xCheckReservedLock method */
35444  0                         /* xShmMap method */
35445)
35446
35447#if SQLITE_ENABLE_LOCKING_STYLE
35448IOMETHODS(
35449  flockIoFinder,            /* Finder function name */
35450  flockIoMethods,           /* sqlite3_io_methods object name */
35451  1,                        /* shared memory is disabled */
35452  flockClose,               /* xClose method */
35453  flockLock,                /* xLock method */
35454  flockUnlock,              /* xUnlock method */
35455  flockCheckReservedLock,   /* xCheckReservedLock method */
35456  0                         /* xShmMap method */
35457)
35458#endif
35459
35460#if OS_VXWORKS
35461IOMETHODS(
35462  semIoFinder,              /* Finder function name */
35463  semIoMethods,             /* sqlite3_io_methods object name */
35464  1,                        /* shared memory is disabled */
35465  semXClose,                /* xClose method */
35466  semXLock,                 /* xLock method */
35467  semXUnlock,               /* xUnlock method */
35468  semXCheckReservedLock,    /* xCheckReservedLock method */
35469  0                         /* xShmMap method */
35470)
35471#endif
35472
35473#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35474IOMETHODS(
35475  afpIoFinder,              /* Finder function name */
35476  afpIoMethods,             /* sqlite3_io_methods object name */
35477  1,                        /* shared memory is disabled */
35478  afpClose,                 /* xClose method */
35479  afpLock,                  /* xLock method */
35480  afpUnlock,                /* xUnlock method */
35481  afpCheckReservedLock,     /* xCheckReservedLock method */
35482  0                         /* xShmMap method */
35483)
35484#endif
35485
35486/*
35487** The proxy locking method is a "super-method" in the sense that it
35488** opens secondary file descriptors for the conch and lock files and
35489** it uses proxy, dot-file, AFP, and flock() locking methods on those
35490** secondary files.  For this reason, the division that implements
35491** proxy locking is located much further down in the file.  But we need
35492** to go ahead and define the sqlite3_io_methods and finder function
35493** for proxy locking here.  So we forward declare the I/O methods.
35494*/
35495#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35496static int proxyClose(sqlite3_file*);
35497static int proxyLock(sqlite3_file*, int);
35498static int proxyUnlock(sqlite3_file*, int);
35499static int proxyCheckReservedLock(sqlite3_file*, int*);
35500IOMETHODS(
35501  proxyIoFinder,            /* Finder function name */
35502  proxyIoMethods,           /* sqlite3_io_methods object name */
35503  1,                        /* shared memory is disabled */
35504  proxyClose,               /* xClose method */
35505  proxyLock,                /* xLock method */
35506  proxyUnlock,              /* xUnlock method */
35507  proxyCheckReservedLock,   /* xCheckReservedLock method */
35508  0                         /* xShmMap method */
35509)
35510#endif
35511
35512/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
35513#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35514IOMETHODS(
35515  nfsIoFinder,               /* Finder function name */
35516  nfsIoMethods,              /* sqlite3_io_methods object name */
35517  1,                         /* shared memory is disabled */
35518  unixClose,                 /* xClose method */
35519  unixLock,                  /* xLock method */
35520  nfsUnlock,                 /* xUnlock method */
35521  unixCheckReservedLock,     /* xCheckReservedLock method */
35522  0                          /* xShmMap method */
35523)
35524#endif
35525
35526#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35527/*
35528** This "finder" function attempts to determine the best locking strategy
35529** for the database file "filePath".  It then returns the sqlite3_io_methods
35530** object that implements that strategy.
35531**
35532** This is for MacOSX only.
35533*/
35534static const sqlite3_io_methods *autolockIoFinderImpl(
35535  const char *filePath,    /* name of the database file */
35536  unixFile *pNew           /* open file object for the database file */
35537){
35538  static const struct Mapping {
35539    const char *zFilesystem;              /* Filesystem type name */
35540    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
35541  } aMap[] = {
35542    { "hfs",    &posixIoMethods },
35543    { "ufs",    &posixIoMethods },
35544    { "afpfs",  &afpIoMethods },
35545    { "smbfs",  &afpIoMethods },
35546    { "webdav", &nolockIoMethods },
35547    { 0, 0 }
35548  };
35549  int i;
35550  struct statfs fsInfo;
35551  struct flock lockInfo;
35552
35553  if( !filePath ){
35554    /* If filePath==NULL that means we are dealing with a transient file
35555    ** that does not need to be locked. */
35556    return &nolockIoMethods;
35557  }
35558  if( statfs(filePath, &fsInfo) != -1 ){
35559    if( fsInfo.f_flags & MNT_RDONLY ){
35560      return &nolockIoMethods;
35561    }
35562    for(i=0; aMap[i].zFilesystem; i++){
35563      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
35564        return aMap[i].pMethods;
35565      }
35566    }
35567  }
35568
35569  /* Default case. Handles, amongst others, "nfs".
35570  ** Test byte-range lock using fcntl(). If the call succeeds,
35571  ** assume that the file-system supports POSIX style locks.
35572  */
35573  lockInfo.l_len = 1;
35574  lockInfo.l_start = 0;
35575  lockInfo.l_whence = SEEK_SET;
35576  lockInfo.l_type = F_RDLCK;
35577  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
35578    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
35579      return &nfsIoMethods;
35580    } else {
35581      return &posixIoMethods;
35582    }
35583  }else{
35584    return &dotlockIoMethods;
35585  }
35586}
35587static const sqlite3_io_methods
35588  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
35589
35590#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
35591
35592#if OS_VXWORKS
35593/*
35594** This "finder" function for VxWorks checks to see if posix advisory
35595** locking works.  If it does, then that is what is used.  If it does not
35596** work, then fallback to named semaphore locking.
35597*/
35598static const sqlite3_io_methods *vxworksIoFinderImpl(
35599  const char *filePath,    /* name of the database file */
35600  unixFile *pNew           /* the open file object */
35601){
35602  struct flock lockInfo;
35603
35604  if( !filePath ){
35605    /* If filePath==NULL that means we are dealing with a transient file
35606    ** that does not need to be locked. */
35607    return &nolockIoMethods;
35608  }
35609
35610  /* Test if fcntl() is supported and use POSIX style locks.
35611  ** Otherwise fall back to the named semaphore method.
35612  */
35613  lockInfo.l_len = 1;
35614  lockInfo.l_start = 0;
35615  lockInfo.l_whence = SEEK_SET;
35616  lockInfo.l_type = F_RDLCK;
35617  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
35618    return &posixIoMethods;
35619  }else{
35620    return &semIoMethods;
35621  }
35622}
35623static const sqlite3_io_methods
35624  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
35625
35626#endif /* OS_VXWORKS */
35627
35628/*
35629** An abstract type for a pointer to an IO method finder function:
35630*/
35631typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
35632
35633
35634/****************************************************************************
35635**************************** sqlite3_vfs methods ****************************
35636**
35637** This division contains the implementation of methods on the
35638** sqlite3_vfs object.
35639*/
35640
35641/*
35642** Initialize the contents of the unixFile structure pointed to by pId.
35643*/
35644static int fillInUnixFile(
35645  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
35646  int h,                  /* Open file descriptor of file being opened */
35647  sqlite3_file *pId,      /* Write to the unixFile structure here */
35648  const char *zFilename,  /* Name of the file being opened */
35649  int ctrlFlags           /* Zero or more UNIXFILE_* values */
35650){
35651  const sqlite3_io_methods *pLockingStyle;
35652  unixFile *pNew = (unixFile *)pId;
35653  int rc = SQLITE_OK;
35654
35655  assert( pNew->pInode==NULL );
35656
35657  /* Usually the path zFilename should not be a relative pathname. The
35658  ** exception is when opening the proxy "conch" file in builds that
35659  ** include the special Apple locking styles.
35660  */
35661#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35662  assert( zFilename==0 || zFilename[0]=='/'
35663    || pVfs->pAppData==(void*)&autolockIoFinder );
35664#else
35665  assert( zFilename==0 || zFilename[0]=='/' );
35666#endif
35667
35668  /* No locking occurs in temporary files */
35669  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
35670
35671  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
35672  pNew->h = h;
35673  pNew->pVfs = pVfs;
35674  pNew->zPath = zFilename;
35675  pNew->ctrlFlags = (u8)ctrlFlags;
35676#if SQLITE_MAX_MMAP_SIZE>0
35677  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
35678#endif
35679  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
35680                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
35681    pNew->ctrlFlags |= UNIXFILE_PSOW;
35682  }
35683  if( strcmp(pVfs->zName,"unix-excl")==0 ){
35684    pNew->ctrlFlags |= UNIXFILE_EXCL;
35685  }
35686
35687#if OS_VXWORKS
35688  pNew->pId = vxworksFindFileId(zFilename);
35689  if( pNew->pId==0 ){
35690    ctrlFlags |= UNIXFILE_NOLOCK;
35691    rc = SQLITE_NOMEM_BKPT;
35692  }
35693#endif
35694
35695  if( ctrlFlags & UNIXFILE_NOLOCK ){
35696    pLockingStyle = &nolockIoMethods;
35697  }else{
35698    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
35699#if SQLITE_ENABLE_LOCKING_STYLE
35700    /* Cache zFilename in the locking context (AFP and dotlock override) for
35701    ** proxyLock activation is possible (remote proxy is based on db name)
35702    ** zFilename remains valid until file is closed, to support */
35703    pNew->lockingContext = (void*)zFilename;
35704#endif
35705  }
35706
35707  if( pLockingStyle == &posixIoMethods
35708#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35709    || pLockingStyle == &nfsIoMethods
35710#endif
35711  ){
35712    unixEnterMutex();
35713    rc = findInodeInfo(pNew, &pNew->pInode);
35714    if( rc!=SQLITE_OK ){
35715      /* If an error occurred in findInodeInfo(), close the file descriptor
35716      ** immediately, before releasing the mutex. findInodeInfo() may fail
35717      ** in two scenarios:
35718      **
35719      **   (a) A call to fstat() failed.
35720      **   (b) A malloc failed.
35721      **
35722      ** Scenario (b) may only occur if the process is holding no other
35723      ** file descriptors open on the same file. If there were other file
35724      ** descriptors on this file, then no malloc would be required by
35725      ** findInodeInfo(). If this is the case, it is quite safe to close
35726      ** handle h - as it is guaranteed that no posix locks will be released
35727      ** by doing so.
35728      **
35729      ** If scenario (a) caused the error then things are not so safe. The
35730      ** implicit assumption here is that if fstat() fails, things are in
35731      ** such bad shape that dropping a lock or two doesn't matter much.
35732      */
35733      robust_close(pNew, h, __LINE__);
35734      h = -1;
35735    }
35736    unixLeaveMutex();
35737  }
35738
35739#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
35740  else if( pLockingStyle == &afpIoMethods ){
35741    /* AFP locking uses the file path so it needs to be included in
35742    ** the afpLockingContext.
35743    */
35744    afpLockingContext *pCtx;
35745    pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
35746    if( pCtx==0 ){
35747      rc = SQLITE_NOMEM_BKPT;
35748    }else{
35749      /* NB: zFilename exists and remains valid until the file is closed
35750      ** according to requirement F11141.  So we do not need to make a
35751      ** copy of the filename. */
35752      pCtx->dbPath = zFilename;
35753      pCtx->reserved = 0;
35754      srandomdev();
35755      unixEnterMutex();
35756      rc = findInodeInfo(pNew, &pNew->pInode);
35757      if( rc!=SQLITE_OK ){
35758        sqlite3_free(pNew->lockingContext);
35759        robust_close(pNew, h, __LINE__);
35760        h = -1;
35761      }
35762      unixLeaveMutex();
35763    }
35764  }
35765#endif
35766
35767  else if( pLockingStyle == &dotlockIoMethods ){
35768    /* Dotfile locking uses the file path so it needs to be included in
35769    ** the dotlockLockingContext
35770    */
35771    char *zLockFile;
35772    int nFilename;
35773    assert( zFilename!=0 );
35774    nFilename = (int)strlen(zFilename) + 6;
35775    zLockFile = (char *)sqlite3_malloc64(nFilename);
35776    if( zLockFile==0 ){
35777      rc = SQLITE_NOMEM_BKPT;
35778    }else{
35779      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
35780    }
35781    pNew->lockingContext = zLockFile;
35782  }
35783
35784#if OS_VXWORKS
35785  else if( pLockingStyle == &semIoMethods ){
35786    /* Named semaphore locking uses the file path so it needs to be
35787    ** included in the semLockingContext
35788    */
35789    unixEnterMutex();
35790    rc = findInodeInfo(pNew, &pNew->pInode);
35791    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
35792      char *zSemName = pNew->pInode->aSemName;
35793      int n;
35794      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
35795                       pNew->pId->zCanonicalName);
35796      for( n=1; zSemName[n]; n++ )
35797        if( zSemName[n]=='/' ) zSemName[n] = '_';
35798      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
35799      if( pNew->pInode->pSem == SEM_FAILED ){
35800        rc = SQLITE_NOMEM_BKPT;
35801        pNew->pInode->aSemName[0] = '\0';
35802      }
35803    }
35804    unixLeaveMutex();
35805  }
35806#endif
35807
35808  storeLastErrno(pNew, 0);
35809#if OS_VXWORKS
35810  if( rc!=SQLITE_OK ){
35811    if( h>=0 ) robust_close(pNew, h, __LINE__);
35812    h = -1;
35813    osUnlink(zFilename);
35814    pNew->ctrlFlags |= UNIXFILE_DELETE;
35815  }
35816#endif
35817  if( rc!=SQLITE_OK ){
35818    if( h>=0 ) robust_close(pNew, h, __LINE__);
35819  }else{
35820    pNew->pMethod = pLockingStyle;
35821    OpenCounter(+1);
35822    verifyDbFile(pNew);
35823  }
35824  return rc;
35825}
35826
35827/*
35828** Return the name of a directory in which to put temporary files.
35829** If no suitable temporary file directory can be found, return NULL.
35830*/
35831static const char *unixTempFileDir(void){
35832  static const char *azDirs[] = {
35833     0,
35834     0,
35835     "/var/tmp",
35836     "/usr/tmp",
35837     "/tmp",
35838     "."
35839  };
35840  unsigned int i = 0;
35841  struct stat buf;
35842  const char *zDir = sqlite3_temp_directory;
35843
35844  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
35845  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
35846  while(1){
35847    if( zDir!=0
35848     && osStat(zDir, &buf)==0
35849     && S_ISDIR(buf.st_mode)
35850     && osAccess(zDir, 03)==0
35851    ){
35852      return zDir;
35853    }
35854    if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
35855    zDir = azDirs[i++];
35856  }
35857  return 0;
35858}
35859
35860/*
35861** Create a temporary file name in zBuf.  zBuf must be allocated
35862** by the calling process and must be big enough to hold at least
35863** pVfs->mxPathname bytes.
35864*/
35865static int unixGetTempname(int nBuf, char *zBuf){
35866  const char *zDir;
35867  int iLimit = 0;
35868
35869  /* It's odd to simulate an io-error here, but really this is just
35870  ** using the io-error infrastructure to test that SQLite handles this
35871  ** function failing.
35872  */
35873  zBuf[0] = 0;
35874  SimulateIOError( return SQLITE_IOERR );
35875
35876  zDir = unixTempFileDir();
35877  if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
35878  do{
35879    u64 r;
35880    sqlite3_randomness(sizeof(r), &r);
35881    assert( nBuf>2 );
35882    zBuf[nBuf-2] = 0;
35883    sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
35884                     zDir, r, 0);
35885    if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
35886  }while( osAccess(zBuf,0)==0 );
35887  return SQLITE_OK;
35888}
35889
35890#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
35891/*
35892** Routine to transform a unixFile into a proxy-locking unixFile.
35893** Implementation in the proxy-lock division, but used by unixOpen()
35894** if SQLITE_PREFER_PROXY_LOCKING is defined.
35895*/
35896static int proxyTransformUnixFile(unixFile*, const char*);
35897#endif
35898
35899/*
35900** Search for an unused file descriptor that was opened on the database
35901** file (not a journal or master-journal file) identified by pathname
35902** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
35903** argument to this function.
35904**
35905** Such a file descriptor may exist if a database connection was closed
35906** but the associated file descriptor could not be closed because some
35907** other file descriptor open on the same file is holding a file-lock.
35908** Refer to comments in the unixClose() function and the lengthy comment
35909** describing "Posix Advisory Locking" at the start of this file for
35910** further details. Also, ticket #4018.
35911**
35912** If a suitable file descriptor is found, then it is returned. If no
35913** such file descriptor is located, -1 is returned.
35914*/
35915static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
35916  UnixUnusedFd *pUnused = 0;
35917
35918  /* Do not search for an unused file descriptor on vxworks. Not because
35919  ** vxworks would not benefit from the change (it might, we're not sure),
35920  ** but because no way to test it is currently available. It is better
35921  ** not to risk breaking vxworks support for the sake of such an obscure
35922  ** feature.  */
35923#if !OS_VXWORKS
35924  struct stat sStat;                   /* Results of stat() call */
35925
35926  /* A stat() call may fail for various reasons. If this happens, it is
35927  ** almost certain that an open() call on the same path will also fail.
35928  ** For this reason, if an error occurs in the stat() call here, it is
35929  ** ignored and -1 is returned. The caller will try to open a new file
35930  ** descriptor on the same path, fail, and return an error to SQLite.
35931  **
35932  ** Even if a subsequent open() call does succeed, the consequences of
35933  ** not searching for a reusable file descriptor are not dire.  */
35934  if( 0==osStat(zPath, &sStat) ){
35935    unixInodeInfo *pInode;
35936
35937    unixEnterMutex();
35938    pInode = inodeList;
35939    while( pInode && (pInode->fileId.dev!=sStat.st_dev
35940                     || pInode->fileId.ino!=(u64)sStat.st_ino) ){
35941       pInode = pInode->pNext;
35942    }
35943    if( pInode ){
35944      UnixUnusedFd **pp;
35945      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
35946      pUnused = *pp;
35947      if( pUnused ){
35948        *pp = pUnused->pNext;
35949      }
35950    }
35951    unixLeaveMutex();
35952  }
35953#endif    /* if !OS_VXWORKS */
35954  return pUnused;
35955}
35956
35957/*
35958** Find the mode, uid and gid of file zFile.
35959*/
35960static int getFileMode(
35961  const char *zFile,              /* File name */
35962  mode_t *pMode,                  /* OUT: Permissions of zFile */
35963  uid_t *pUid,                    /* OUT: uid of zFile. */
35964  gid_t *pGid                     /* OUT: gid of zFile. */
35965){
35966  struct stat sStat;              /* Output of stat() on database file */
35967  int rc = SQLITE_OK;
35968  if( 0==osStat(zFile, &sStat) ){
35969    *pMode = sStat.st_mode & 0777;
35970    *pUid = sStat.st_uid;
35971    *pGid = sStat.st_gid;
35972  }else{
35973    rc = SQLITE_IOERR_FSTAT;
35974  }
35975  return rc;
35976}
35977
35978/*
35979** This function is called by unixOpen() to determine the unix permissions
35980** to create new files with. If no error occurs, then SQLITE_OK is returned
35981** and a value suitable for passing as the third argument to open(2) is
35982** written to *pMode. If an IO error occurs, an SQLite error code is
35983** returned and the value of *pMode is not modified.
35984**
35985** In most cases, this routine sets *pMode to 0, which will become
35986** an indication to robust_open() to create the file using
35987** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
35988** But if the file being opened is a WAL or regular journal file, then
35989** this function queries the file-system for the permissions on the
35990** corresponding database file and sets *pMode to this value. Whenever
35991** possible, WAL and journal files are created using the same permissions
35992** as the associated database file.
35993**
35994** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
35995** original filename is unavailable.  But 8_3_NAMES is only used for
35996** FAT filesystems and permissions do not matter there, so just use
35997** the default permissions.
35998*/
35999static int findCreateFileMode(
36000  const char *zPath,              /* Path of file (possibly) being created */
36001  int flags,                      /* Flags passed as 4th argument to xOpen() */
36002  mode_t *pMode,                  /* OUT: Permissions to open file with */
36003  uid_t *pUid,                    /* OUT: uid to set on the file */
36004  gid_t *pGid                     /* OUT: gid to set on the file */
36005){
36006  int rc = SQLITE_OK;             /* Return Code */
36007  *pMode = 0;
36008  *pUid = 0;
36009  *pGid = 0;
36010  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
36011    char zDb[MAX_PATHNAME+1];     /* Database file path */
36012    int nDb;                      /* Number of valid bytes in zDb */
36013
36014    /* zPath is a path to a WAL or journal file. The following block derives
36015    ** the path to the associated database file from zPath. This block handles
36016    ** the following naming conventions:
36017    **
36018    **   "<path to db>-journal"
36019    **   "<path to db>-wal"
36020    **   "<path to db>-journalNN"
36021    **   "<path to db>-walNN"
36022    **
36023    ** where NN is a decimal number. The NN naming schemes are
36024    ** used by the test_multiplex.c module.
36025    */
36026    nDb = sqlite3Strlen30(zPath) - 1;
36027    while( zPath[nDb]!='-' ){
36028#ifndef SQLITE_ENABLE_8_3_NAMES
36029      /* In the normal case (8+3 filenames disabled) the journal filename
36030      ** is guaranteed to contain a '-' character. */
36031      assert( nDb>0 );
36032      assert( sqlite3Isalnum(zPath[nDb]) );
36033#else
36034      /* If 8+3 names are possible, then the journal file might not contain
36035      ** a '-' character.  So check for that case and return early. */
36036      if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
36037#endif
36038      nDb--;
36039    }
36040    memcpy(zDb, zPath, nDb);
36041    zDb[nDb] = '\0';
36042
36043    rc = getFileMode(zDb, pMode, pUid, pGid);
36044  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
36045    *pMode = 0600;
36046  }else if( flags & SQLITE_OPEN_URI ){
36047    /* If this is a main database file and the file was opened using a URI
36048    ** filename, check for the "modeof" parameter. If present, interpret
36049    ** its value as a filename and try to copy the mode, uid and gid from
36050    ** that file.  */
36051    const char *z = sqlite3_uri_parameter(zPath, "modeof");
36052    if( z ){
36053      rc = getFileMode(z, pMode, pUid, pGid);
36054    }
36055  }
36056  return rc;
36057}
36058
36059/*
36060** Open the file zPath.
36061**
36062** Previously, the SQLite OS layer used three functions in place of this
36063** one:
36064**
36065**     sqlite3OsOpenReadWrite();
36066**     sqlite3OsOpenReadOnly();
36067**     sqlite3OsOpenExclusive();
36068**
36069** These calls correspond to the following combinations of flags:
36070**
36071**     ReadWrite() ->     (READWRITE | CREATE)
36072**     ReadOnly()  ->     (READONLY)
36073**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
36074**
36075** The old OpenExclusive() accepted a boolean argument - "delFlag". If
36076** true, the file was configured to be automatically deleted when the
36077** file handle closed. To achieve the same effect using this new
36078** interface, add the DELETEONCLOSE flag to those specified above for
36079** OpenExclusive().
36080*/
36081static int unixOpen(
36082  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
36083  const char *zPath,           /* Pathname of file to be opened */
36084  sqlite3_file *pFile,         /* The file descriptor to be filled in */
36085  int flags,                   /* Input flags to control the opening */
36086  int *pOutFlags               /* Output flags returned to SQLite core */
36087){
36088  unixFile *p = (unixFile *)pFile;
36089  int fd = -1;                   /* File descriptor returned by open() */
36090  int openFlags = 0;             /* Flags to pass to open() */
36091  int eType = flags&0xFFFFFF00;  /* Type of file to open */
36092  int noLock;                    /* True to omit locking primitives */
36093  int rc = SQLITE_OK;            /* Function Return Code */
36094  int ctrlFlags = 0;             /* UNIXFILE_* flags */
36095
36096  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
36097  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
36098  int isCreate     = (flags & SQLITE_OPEN_CREATE);
36099  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
36100  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
36101#if SQLITE_ENABLE_LOCKING_STYLE
36102  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
36103#endif
36104#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
36105  struct statfs fsInfo;
36106#endif
36107
36108  /* If creating a master or main-file journal, this function will open
36109  ** a file-descriptor on the directory too. The first time unixSync()
36110  ** is called the directory file descriptor will be fsync()ed and close()d.
36111  */
36112  int syncDir = (isCreate && (
36113        eType==SQLITE_OPEN_MASTER_JOURNAL
36114     || eType==SQLITE_OPEN_MAIN_JOURNAL
36115     || eType==SQLITE_OPEN_WAL
36116  ));
36117
36118  /* If argument zPath is a NULL pointer, this function is required to open
36119  ** a temporary file. Use this buffer to store the file name in.
36120  */
36121  char zTmpname[MAX_PATHNAME+2];
36122  const char *zName = zPath;
36123
36124  /* Check the following statements are true:
36125  **
36126  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
36127  **   (b) if CREATE is set, then READWRITE must also be set, and
36128  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
36129  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
36130  */
36131  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
36132  assert(isCreate==0 || isReadWrite);
36133  assert(isExclusive==0 || isCreate);
36134  assert(isDelete==0 || isCreate);
36135
36136  /* The main DB, main journal, WAL file and master journal are never
36137  ** automatically deleted. Nor are they ever temporary files.  */
36138  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
36139  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
36140  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
36141  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
36142
36143  /* Assert that the upper layer has set one of the "file-type" flags. */
36144  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
36145       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
36146       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
36147       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
36148  );
36149
36150  /* Detect a pid change and reset the PRNG.  There is a race condition
36151  ** here such that two or more threads all trying to open databases at
36152  ** the same instant might all reset the PRNG.  But multiple resets
36153  ** are harmless.
36154  */
36155  if( randomnessPid!=osGetpid(0) ){
36156    randomnessPid = osGetpid(0);
36157    sqlite3_randomness(0,0);
36158  }
36159
36160  memset(p, 0, sizeof(unixFile));
36161
36162  if( eType==SQLITE_OPEN_MAIN_DB ){
36163    UnixUnusedFd *pUnused;
36164    pUnused = findReusableFd(zName, flags);
36165    if( pUnused ){
36166      fd = pUnused->fd;
36167    }else{
36168      pUnused = sqlite3_malloc64(sizeof(*pUnused));
36169      if( !pUnused ){
36170        return SQLITE_NOMEM_BKPT;
36171      }
36172    }
36173    p->pUnused = pUnused;
36174
36175    /* Database filenames are double-zero terminated if they are not
36176    ** URIs with parameters.  Hence, they can always be passed into
36177    ** sqlite3_uri_parameter(). */
36178    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
36179
36180  }else if( !zName ){
36181    /* If zName is NULL, the upper layer is requesting a temp file. */
36182    assert(isDelete && !syncDir);
36183    rc = unixGetTempname(pVfs->mxPathname, zTmpname);
36184    if( rc!=SQLITE_OK ){
36185      return rc;
36186    }
36187    zName = zTmpname;
36188
36189    /* Generated temporary filenames are always double-zero terminated
36190    ** for use by sqlite3_uri_parameter(). */
36191    assert( zName[strlen(zName)+1]==0 );
36192  }
36193
36194  /* Determine the value of the flags parameter passed to POSIX function
36195  ** open(). These must be calculated even if open() is not called, as
36196  ** they may be stored as part of the file handle and used by the
36197  ** 'conch file' locking functions later on.  */
36198  if( isReadonly )  openFlags |= O_RDONLY;
36199  if( isReadWrite ) openFlags |= O_RDWR;
36200  if( isCreate )    openFlags |= O_CREAT;
36201  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
36202  openFlags |= (O_LARGEFILE|O_BINARY);
36203
36204  if( fd<0 ){
36205    mode_t openMode;              /* Permissions to create file with */
36206    uid_t uid;                    /* Userid for the file */
36207    gid_t gid;                    /* Groupid for the file */
36208    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
36209    if( rc!=SQLITE_OK ){
36210      assert( !p->pUnused );
36211      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
36212      return rc;
36213    }
36214    fd = robust_open(zName, openFlags, openMode);
36215    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
36216    assert( !isExclusive || (openFlags & O_CREAT)!=0 );
36217    if( fd<0 && errno!=EISDIR && isReadWrite ){
36218      /* Failed to open the file for read/write access. Try read-only. */
36219      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
36220      openFlags &= ~(O_RDWR|O_CREAT);
36221      flags |= SQLITE_OPEN_READONLY;
36222      openFlags |= O_RDONLY;
36223      isReadonly = 1;
36224      fd = robust_open(zName, openFlags, openMode);
36225    }
36226    if( fd<0 ){
36227      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
36228      goto open_finished;
36229    }
36230
36231    /* If this process is running as root and if creating a new rollback
36232    ** journal or WAL file, set the ownership of the journal or WAL to be
36233    ** the same as the original database.
36234    */
36235    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
36236      robustFchown(fd, uid, gid);
36237    }
36238  }
36239  assert( fd>=0 );
36240  if( pOutFlags ){
36241    *pOutFlags = flags;
36242  }
36243
36244  if( p->pUnused ){
36245    p->pUnused->fd = fd;
36246    p->pUnused->flags = flags;
36247  }
36248
36249  if( isDelete ){
36250#if OS_VXWORKS
36251    zPath = zName;
36252#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
36253    zPath = sqlite3_mprintf("%s", zName);
36254    if( zPath==0 ){
36255      robust_close(p, fd, __LINE__);
36256      return SQLITE_NOMEM_BKPT;
36257    }
36258#else
36259    osUnlink(zName);
36260#endif
36261  }
36262#if SQLITE_ENABLE_LOCKING_STYLE
36263  else{
36264    p->openFlags = openFlags;
36265  }
36266#endif
36267
36268#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
36269  if( fstatfs(fd, &fsInfo) == -1 ){
36270    storeLastErrno(p, errno);
36271    robust_close(p, fd, __LINE__);
36272    return SQLITE_IOERR_ACCESS;
36273  }
36274  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
36275    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
36276  }
36277  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
36278    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
36279  }
36280#endif
36281
36282  /* Set up appropriate ctrlFlags */
36283  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
36284  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
36285  noLock = eType!=SQLITE_OPEN_MAIN_DB;
36286  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
36287  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
36288  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
36289
36290#if SQLITE_ENABLE_LOCKING_STYLE
36291#if SQLITE_PREFER_PROXY_LOCKING
36292  isAutoProxy = 1;
36293#endif
36294  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
36295    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
36296    int useProxy = 0;
36297
36298    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
36299    ** never use proxy, NULL means use proxy for non-local files only.  */
36300    if( envforce!=NULL ){
36301      useProxy = atoi(envforce)>0;
36302    }else{
36303      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
36304    }
36305    if( useProxy ){
36306      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
36307      if( rc==SQLITE_OK ){
36308        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
36309        if( rc!=SQLITE_OK ){
36310          /* Use unixClose to clean up the resources added in fillInUnixFile
36311          ** and clear all the structure's references.  Specifically,
36312          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
36313          */
36314          unixClose(pFile);
36315          return rc;
36316        }
36317      }
36318      goto open_finished;
36319    }
36320  }
36321#endif
36322
36323  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
36324
36325open_finished:
36326  if( rc!=SQLITE_OK ){
36327    sqlite3_free(p->pUnused);
36328  }
36329  return rc;
36330}
36331
36332
36333/*
36334** Delete the file at zPath. If the dirSync argument is true, fsync()
36335** the directory after deleting the file.
36336*/
36337static int unixDelete(
36338  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
36339  const char *zPath,        /* Name of file to be deleted */
36340  int dirSync               /* If true, fsync() directory after deleting file */
36341){
36342  int rc = SQLITE_OK;
36343  UNUSED_PARAMETER(NotUsed);
36344  SimulateIOError(return SQLITE_IOERR_DELETE);
36345  if( osUnlink(zPath)==(-1) ){
36346    if( errno==ENOENT
36347#if OS_VXWORKS
36348        || osAccess(zPath,0)!=0
36349#endif
36350    ){
36351      rc = SQLITE_IOERR_DELETE_NOENT;
36352    }else{
36353      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
36354    }
36355    return rc;
36356  }
36357#ifndef SQLITE_DISABLE_DIRSYNC
36358  if( (dirSync & 1)!=0 ){
36359    int fd;
36360    rc = osOpenDirectory(zPath, &fd);
36361    if( rc==SQLITE_OK ){
36362      if( full_fsync(fd,0,0) ){
36363        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
36364      }
36365      robust_close(0, fd, __LINE__);
36366    }else{
36367      assert( rc==SQLITE_CANTOPEN );
36368      rc = SQLITE_OK;
36369    }
36370  }
36371#endif
36372  return rc;
36373}
36374
36375/*
36376** Test the existence of or access permissions of file zPath. The
36377** test performed depends on the value of flags:
36378**
36379**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
36380**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
36381**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
36382**
36383** Otherwise return 0.
36384*/
36385static int unixAccess(
36386  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
36387  const char *zPath,      /* Path of the file to examine */
36388  int flags,              /* What do we want to learn about the zPath file? */
36389  int *pResOut            /* Write result boolean here */
36390){
36391  UNUSED_PARAMETER(NotUsed);
36392  SimulateIOError( return SQLITE_IOERR_ACCESS; );
36393  assert( pResOut!=0 );
36394
36395  /* The spec says there are three possible values for flags.  But only
36396  ** two of them are actually used */
36397  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
36398
36399  if( flags==SQLITE_ACCESS_EXISTS ){
36400    struct stat buf;
36401    *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
36402  }else{
36403    *pResOut = osAccess(zPath, W_OK|R_OK)==0;
36404  }
36405  return SQLITE_OK;
36406}
36407
36408/*
36409**
36410*/
36411static int mkFullPathname(
36412  const char *zPath,              /* Input path */
36413  char *zOut,                     /* Output buffer */
36414  int nOut                        /* Allocated size of buffer zOut */
36415){
36416  int nPath = sqlite3Strlen30(zPath);
36417  int iOff = 0;
36418  if( zPath[0]!='/' ){
36419    if( osGetcwd(zOut, nOut-2)==0 ){
36420      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
36421    }
36422    iOff = sqlite3Strlen30(zOut);
36423    zOut[iOff++] = '/';
36424  }
36425  if( (iOff+nPath+1)>nOut ){
36426    /* SQLite assumes that xFullPathname() nul-terminates the output buffer
36427    ** even if it returns an error.  */
36428    zOut[iOff] = '\0';
36429    return SQLITE_CANTOPEN_BKPT;
36430  }
36431  sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
36432  return SQLITE_OK;
36433}
36434
36435/*
36436** Turn a relative pathname into a full pathname. The relative path
36437** is stored as a nul-terminated string in the buffer pointed to by
36438** zPath.
36439**
36440** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
36441** (in this case, MAX_PATHNAME bytes). The full-path is written to
36442** this buffer before returning.
36443*/
36444static int unixFullPathname(
36445  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
36446  const char *zPath,            /* Possibly relative input path */
36447  int nOut,                     /* Size of output buffer in bytes */
36448  char *zOut                    /* Output buffer */
36449){
36450#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
36451  return mkFullPathname(zPath, zOut, nOut);
36452#else
36453  int rc = SQLITE_OK;
36454  int nByte;
36455  int nLink = 1;                /* Number of symbolic links followed so far */
36456  const char *zIn = zPath;      /* Input path for each iteration of loop */
36457  char *zDel = 0;
36458
36459  assert( pVfs->mxPathname==MAX_PATHNAME );
36460  UNUSED_PARAMETER(pVfs);
36461
36462  /* It's odd to simulate an io-error here, but really this is just
36463  ** using the io-error infrastructure to test that SQLite handles this
36464  ** function failing. This function could fail if, for example, the
36465  ** current working directory has been unlinked.
36466  */
36467  SimulateIOError( return SQLITE_ERROR );
36468
36469  do {
36470
36471    /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
36472    ** link, or false otherwise.  */
36473    int bLink = 0;
36474    struct stat buf;
36475    if( osLstat(zIn, &buf)!=0 ){
36476      if( errno!=ENOENT ){
36477        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
36478      }
36479    }else{
36480      bLink = S_ISLNK(buf.st_mode);
36481    }
36482
36483    if( bLink ){
36484      if( zDel==0 ){
36485        zDel = sqlite3_malloc(nOut);
36486        if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
36487      }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
36488        rc = SQLITE_CANTOPEN_BKPT;
36489      }
36490
36491      if( rc==SQLITE_OK ){
36492        nByte = osReadlink(zIn, zDel, nOut-1);
36493        if( nByte<0 ){
36494          rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
36495        }else{
36496          if( zDel[0]!='/' ){
36497            int n;
36498            for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
36499            if( nByte+n+1>nOut ){
36500              rc = SQLITE_CANTOPEN_BKPT;
36501            }else{
36502              memmove(&zDel[n], zDel, nByte+1);
36503              memcpy(zDel, zIn, n);
36504              nByte += n;
36505            }
36506          }
36507          zDel[nByte] = '\0';
36508        }
36509      }
36510
36511      zIn = zDel;
36512    }
36513
36514    assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
36515    if( rc==SQLITE_OK && zIn!=zOut ){
36516      rc = mkFullPathname(zIn, zOut, nOut);
36517    }
36518    if( bLink==0 ) break;
36519    zIn = zOut;
36520  }while( rc==SQLITE_OK );
36521
36522  sqlite3_free(zDel);
36523  return rc;
36524#endif   /* HAVE_READLINK && HAVE_LSTAT */
36525}
36526
36527
36528#ifndef SQLITE_OMIT_LOAD_EXTENSION
36529/*
36530** Interfaces for opening a shared library, finding entry points
36531** within the shared library, and closing the shared library.
36532*/
36533#include <dlfcn.h>
36534static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
36535  UNUSED_PARAMETER(NotUsed);
36536  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
36537}
36538
36539/*
36540** SQLite calls this function immediately after a call to unixDlSym() or
36541** unixDlOpen() fails (returns a null pointer). If a more detailed error
36542** message is available, it is written to zBufOut. If no error message
36543** is available, zBufOut is left unmodified and SQLite uses a default
36544** error message.
36545*/
36546static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
36547  const char *zErr;
36548  UNUSED_PARAMETER(NotUsed);
36549  unixEnterMutex();
36550  zErr = dlerror();
36551  if( zErr ){
36552    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
36553  }
36554  unixLeaveMutex();
36555}
36556static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
36557  /*
36558  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
36559  ** cast into a pointer to a function.  And yet the library dlsym() routine
36560  ** returns a void* which is really a pointer to a function.  So how do we
36561  ** use dlsym() with -pedantic-errors?
36562  **
36563  ** Variable x below is defined to be a pointer to a function taking
36564  ** parameters void* and const char* and returning a pointer to a function.
36565  ** We initialize x by assigning it a pointer to the dlsym() function.
36566  ** (That assignment requires a cast.)  Then we call the function that
36567  ** x points to.
36568  **
36569  ** This work-around is unlikely to work correctly on any system where
36570  ** you really cannot cast a function pointer into void*.  But then, on the
36571  ** other hand, dlsym() will not work on such a system either, so we have
36572  ** not really lost anything.
36573  */
36574  void (*(*x)(void*,const char*))(void);
36575  UNUSED_PARAMETER(NotUsed);
36576  x = (void(*(*)(void*,const char*))(void))dlsym;
36577  return (*x)(p, zSym);
36578}
36579static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
36580  UNUSED_PARAMETER(NotUsed);
36581  dlclose(pHandle);
36582}
36583#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
36584  #define unixDlOpen  0
36585  #define unixDlError 0
36586  #define unixDlSym   0
36587  #define unixDlClose 0
36588#endif
36589
36590/*
36591** Write nBuf bytes of random data to the supplied buffer zBuf.
36592*/
36593static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
36594  UNUSED_PARAMETER(NotUsed);
36595  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
36596
36597  /* We have to initialize zBuf to prevent valgrind from reporting
36598  ** errors.  The reports issued by valgrind are incorrect - we would
36599  ** prefer that the randomness be increased by making use of the
36600  ** uninitialized space in zBuf - but valgrind errors tend to worry
36601  ** some users.  Rather than argue, it seems easier just to initialize
36602  ** the whole array and silence valgrind, even if that means less randomness
36603  ** in the random seed.
36604  **
36605  ** When testing, initializing zBuf[] to zero is all we do.  That means
36606  ** that we always use the same random number sequence.  This makes the
36607  ** tests repeatable.
36608  */
36609  memset(zBuf, 0, nBuf);
36610  randomnessPid = osGetpid(0);
36611#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
36612  {
36613    int fd, got;
36614    fd = robust_open("/dev/urandom", O_RDONLY, 0);
36615    if( fd<0 ){
36616      time_t t;
36617      time(&t);
36618      memcpy(zBuf, &t, sizeof(t));
36619      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
36620      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
36621      nBuf = sizeof(t) + sizeof(randomnessPid);
36622    }else{
36623      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
36624      robust_close(0, fd, __LINE__);
36625    }
36626  }
36627#endif
36628  return nBuf;
36629}
36630
36631
36632/*
36633** Sleep for a little while.  Return the amount of time slept.
36634** The argument is the number of microseconds we want to sleep.
36635** The return value is the number of microseconds of sleep actually
36636** requested from the underlying operating system, a number which
36637** might be greater than or equal to the argument, but not less
36638** than the argument.
36639*/
36640static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
36641#if OS_VXWORKS
36642  struct timespec sp;
36643
36644  sp.tv_sec = microseconds / 1000000;
36645  sp.tv_nsec = (microseconds % 1000000) * 1000;
36646  nanosleep(&sp, NULL);
36647  UNUSED_PARAMETER(NotUsed);
36648  return microseconds;
36649#elif defined(HAVE_USLEEP) && HAVE_USLEEP
36650  usleep(microseconds);
36651  UNUSED_PARAMETER(NotUsed);
36652  return microseconds;
36653#else
36654  int seconds = (microseconds+999999)/1000000;
36655  sleep(seconds);
36656  UNUSED_PARAMETER(NotUsed);
36657  return seconds*1000000;
36658#endif
36659}
36660
36661/*
36662** The following variable, if set to a non-zero value, is interpreted as
36663** the number of seconds since 1970 and is used to set the result of
36664** sqlite3OsCurrentTime() during testing.
36665*/
36666#ifdef SQLITE_TEST
36667SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
36668#endif
36669
36670/*
36671** Find the current time (in Universal Coordinated Time).  Write into *piNow
36672** the current time and date as a Julian Day number times 86_400_000.  In
36673** other words, write into *piNow the number of milliseconds since the Julian
36674** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36675** proleptic Gregorian calendar.
36676**
36677** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
36678** cannot be found.
36679*/
36680static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
36681  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
36682  int rc = SQLITE_OK;
36683#if defined(NO_GETTOD)
36684  time_t t;
36685  time(&t);
36686  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
36687#elif OS_VXWORKS
36688  struct timespec sNow;
36689  clock_gettime(CLOCK_REALTIME, &sNow);
36690  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
36691#else
36692  struct timeval sNow;
36693  (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
36694  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
36695#endif
36696
36697#ifdef SQLITE_TEST
36698  if( sqlite3_current_time ){
36699    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
36700  }
36701#endif
36702  UNUSED_PARAMETER(NotUsed);
36703  return rc;
36704}
36705
36706#ifndef SQLITE_OMIT_DEPRECATED
36707/*
36708** Find the current time (in Universal Coordinated Time).  Write the
36709** current time and date as a Julian Day number into *prNow and
36710** return 0.  Return 1 if the time and date cannot be found.
36711*/
36712static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
36713  sqlite3_int64 i = 0;
36714  int rc;
36715  UNUSED_PARAMETER(NotUsed);
36716  rc = unixCurrentTimeInt64(0, &i);
36717  *prNow = i/86400000.0;
36718  return rc;
36719}
36720#else
36721# define unixCurrentTime 0
36722#endif
36723
36724/*
36725** The xGetLastError() method is designed to return a better
36726** low-level error message when operating-system problems come up
36727** during SQLite operation.  Only the integer return code is currently
36728** used.
36729*/
36730static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
36731  UNUSED_PARAMETER(NotUsed);
36732  UNUSED_PARAMETER(NotUsed2);
36733  UNUSED_PARAMETER(NotUsed3);
36734  return errno;
36735}
36736
36737
36738/*
36739************************ End of sqlite3_vfs methods ***************************
36740******************************************************************************/
36741
36742/******************************************************************************
36743************************** Begin Proxy Locking ********************************
36744**
36745** Proxy locking is a "uber-locking-method" in this sense:  It uses the
36746** other locking methods on secondary lock files.  Proxy locking is a
36747** meta-layer over top of the primitive locking implemented above.  For
36748** this reason, the division that implements of proxy locking is deferred
36749** until late in the file (here) after all of the other I/O methods have
36750** been defined - so that the primitive locking methods are available
36751** as services to help with the implementation of proxy locking.
36752**
36753****
36754**
36755** The default locking schemes in SQLite use byte-range locks on the
36756** database file to coordinate safe, concurrent access by multiple readers
36757** and writers [http://sqlite.org/lockingv3.html].  The five file locking
36758** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
36759** as POSIX read & write locks over fixed set of locations (via fsctl),
36760** on AFP and SMB only exclusive byte-range locks are available via fsctl
36761** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
36762** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
36763** address in the shared range is taken for a SHARED lock, the entire
36764** shared range is taken for an EXCLUSIVE lock):
36765**
36766**      PENDING_BYTE        0x40000000
36767**      RESERVED_BYTE       0x40000001
36768**      SHARED_RANGE        0x40000002 -> 0x40000200
36769**
36770** This works well on the local file system, but shows a nearly 100x
36771** slowdown in read performance on AFP because the AFP client disables
36772** the read cache when byte-range locks are present.  Enabling the read
36773** cache exposes a cache coherency problem that is present on all OS X
36774** supported network file systems.  NFS and AFP both observe the
36775** close-to-open semantics for ensuring cache coherency
36776** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
36777** address the requirements for concurrent database access by multiple
36778** readers and writers
36779** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
36780**
36781** To address the performance and cache coherency issues, proxy file locking
36782** changes the way database access is controlled by limiting access to a
36783** single host at a time and moving file locks off of the database file
36784** and onto a proxy file on the local file system.
36785**
36786**
36787** Using proxy locks
36788** -----------------
36789**
36790** C APIs
36791**
36792**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
36793**                       <proxy_path> | ":auto:");
36794**  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
36795**                       &<proxy_path>);
36796**
36797**
36798** SQL pragmas
36799**
36800**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
36801**  PRAGMA [database.]lock_proxy_file
36802**
36803** Specifying ":auto:" means that if there is a conch file with a matching
36804** host ID in it, the proxy path in the conch file will be used, otherwise
36805** a proxy path based on the user's temp dir
36806** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
36807** actual proxy file name is generated from the name and path of the
36808** database file.  For example:
36809**
36810**       For database path "/Users/me/foo.db"
36811**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
36812**
36813** Once a lock proxy is configured for a database connection, it can not
36814** be removed, however it may be switched to a different proxy path via
36815** the above APIs (assuming the conch file is not being held by another
36816** connection or process).
36817**
36818**
36819** How proxy locking works
36820** -----------------------
36821**
36822** Proxy file locking relies primarily on two new supporting files:
36823**
36824**   *  conch file to limit access to the database file to a single host
36825**      at a time
36826**
36827**   *  proxy file to act as a proxy for the advisory locks normally
36828**      taken on the database
36829**
36830** The conch file - to use a proxy file, sqlite must first "hold the conch"
36831** by taking an sqlite-style shared lock on the conch file, reading the
36832** contents and comparing the host's unique host ID (see below) and lock
36833** proxy path against the values stored in the conch.  The conch file is
36834** stored in the same directory as the database file and the file name
36835** is patterned after the database file name as ".<databasename>-conch".
36836** If the conch file does not exist, or its contents do not match the
36837** host ID and/or proxy path, then the lock is escalated to an exclusive
36838** lock and the conch file contents is updated with the host ID and proxy
36839** path and the lock is downgraded to a shared lock again.  If the conch
36840** is held by another process (with a shared lock), the exclusive lock
36841** will fail and SQLITE_BUSY is returned.
36842**
36843** The proxy file - a single-byte file used for all advisory file locks
36844** normally taken on the database file.   This allows for safe sharing
36845** of the database file for multiple readers and writers on the same
36846** host (the conch ensures that they all use the same local lock file).
36847**
36848** Requesting the lock proxy does not immediately take the conch, it is
36849** only taken when the first request to lock database file is made.
36850** This matches the semantics of the traditional locking behavior, where
36851** opening a connection to a database file does not take a lock on it.
36852** The shared lock and an open file descriptor are maintained until
36853** the connection to the database is closed.
36854**
36855** The proxy file and the lock file are never deleted so they only need
36856** to be created the first time they are used.
36857**
36858** Configuration options
36859** ---------------------
36860**
36861**  SQLITE_PREFER_PROXY_LOCKING
36862**
36863**       Database files accessed on non-local file systems are
36864**       automatically configured for proxy locking, lock files are
36865**       named automatically using the same logic as
36866**       PRAGMA lock_proxy_file=":auto:"
36867**
36868**  SQLITE_PROXY_DEBUG
36869**
36870**       Enables the logging of error messages during host id file
36871**       retrieval and creation
36872**
36873**  LOCKPROXYDIR
36874**
36875**       Overrides the default directory used for lock proxy files that
36876**       are named automatically via the ":auto:" setting
36877**
36878**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
36879**
36880**       Permissions to use when creating a directory for storing the
36881**       lock proxy files, only used when LOCKPROXYDIR is not set.
36882**
36883**
36884** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
36885** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
36886** force proxy locking to be used for every database file opened, and 0
36887** will force automatic proxy locking to be disabled for all database
36888** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
36889** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
36890*/
36891
36892/*
36893** Proxy locking is only available on MacOSX
36894*/
36895#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
36896
36897/*
36898** The proxyLockingContext has the path and file structures for the remote
36899** and local proxy files in it
36900*/
36901typedef struct proxyLockingContext proxyLockingContext;
36902struct proxyLockingContext {
36903  unixFile *conchFile;         /* Open conch file */
36904  char *conchFilePath;         /* Name of the conch file */
36905  unixFile *lockProxy;         /* Open proxy lock file */
36906  char *lockProxyPath;         /* Name of the proxy lock file */
36907  char *dbPath;                /* Name of the open file */
36908  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
36909  int nFails;                  /* Number of conch taking failures */
36910  void *oldLockingContext;     /* Original lockingcontext to restore on close */
36911  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
36912};
36913
36914/*
36915** The proxy lock file path for the database at dbPath is written into lPath,
36916** which must point to valid, writable memory large enough for a maxLen length
36917** file path.
36918*/
36919static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
36920  int len;
36921  int dbLen;
36922  int i;
36923
36924#ifdef LOCKPROXYDIR
36925  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
36926#else
36927# ifdef _CS_DARWIN_USER_TEMP_DIR
36928  {
36929    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
36930      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
36931               lPath, errno, osGetpid(0)));
36932      return SQLITE_IOERR_LOCK;
36933    }
36934    len = strlcat(lPath, "sqliteplocks", maxLen);
36935  }
36936# else
36937  len = strlcpy(lPath, "/tmp/", maxLen);
36938# endif
36939#endif
36940
36941  if( lPath[len-1]!='/' ){
36942    len = strlcat(lPath, "/", maxLen);
36943  }
36944
36945  /* transform the db path to a unique cache name */
36946  dbLen = (int)strlen(dbPath);
36947  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
36948    char c = dbPath[i];
36949    lPath[i+len] = (c=='/')?'_':c;
36950  }
36951  lPath[i+len]='\0';
36952  strlcat(lPath, ":auto:", maxLen);
36953  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
36954  return SQLITE_OK;
36955}
36956
36957/*
36958 ** Creates the lock file and any missing directories in lockPath
36959 */
36960static int proxyCreateLockPath(const char *lockPath){
36961  int i, len;
36962  char buf[MAXPATHLEN];
36963  int start = 0;
36964
36965  assert(lockPath!=NULL);
36966  /* try to create all the intermediate directories */
36967  len = (int)strlen(lockPath);
36968  buf[0] = lockPath[0];
36969  for( i=1; i<len; i++ ){
36970    if( lockPath[i] == '/' && (i - start > 0) ){
36971      /* only mkdir if leaf dir != "." or "/" or ".." */
36972      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
36973         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
36974        buf[i]='\0';
36975        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
36976          int err=errno;
36977          if( err!=EEXIST ) {
36978            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
36979                     "'%s' proxy lock path=%s pid=%d\n",
36980                     buf, strerror(err), lockPath, osGetpid(0)));
36981            return err;
36982          }
36983        }
36984      }
36985      start=i+1;
36986    }
36987    buf[i] = lockPath[i];
36988  }
36989  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
36990  return 0;
36991}
36992
36993/*
36994** Create a new VFS file descriptor (stored in memory obtained from
36995** sqlite3_malloc) and open the file named "path" in the file descriptor.
36996**
36997** The caller is responsible not only for closing the file descriptor
36998** but also for freeing the memory associated with the file descriptor.
36999*/
37000static int proxyCreateUnixFile(
37001    const char *path,        /* path for the new unixFile */
37002    unixFile **ppFile,       /* unixFile created and returned by ref */
37003    int islockfile           /* if non zero missing dirs will be created */
37004) {
37005  int fd = -1;
37006  unixFile *pNew;
37007  int rc = SQLITE_OK;
37008  int openFlags = O_RDWR | O_CREAT;
37009  sqlite3_vfs dummyVfs;
37010  int terrno = 0;
37011  UnixUnusedFd *pUnused = NULL;
37012
37013  /* 1. first try to open/create the file
37014  ** 2. if that fails, and this is a lock file (not-conch), try creating
37015  ** the parent directories and then try again.
37016  ** 3. if that fails, try to open the file read-only
37017  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
37018  */
37019  pUnused = findReusableFd(path, openFlags);
37020  if( pUnused ){
37021    fd = pUnused->fd;
37022  }else{
37023    pUnused = sqlite3_malloc64(sizeof(*pUnused));
37024    if( !pUnused ){
37025      return SQLITE_NOMEM_BKPT;
37026    }
37027  }
37028  if( fd<0 ){
37029    fd = robust_open(path, openFlags, 0);
37030    terrno = errno;
37031    if( fd<0 && errno==ENOENT && islockfile ){
37032      if( proxyCreateLockPath(path) == SQLITE_OK ){
37033        fd = robust_open(path, openFlags, 0);
37034      }
37035    }
37036  }
37037  if( fd<0 ){
37038    openFlags = O_RDONLY;
37039    fd = robust_open(path, openFlags, 0);
37040    terrno = errno;
37041  }
37042  if( fd<0 ){
37043    if( islockfile ){
37044      return SQLITE_BUSY;
37045    }
37046    switch (terrno) {
37047      case EACCES:
37048        return SQLITE_PERM;
37049      case EIO:
37050        return SQLITE_IOERR_LOCK; /* even though it is the conch */
37051      default:
37052        return SQLITE_CANTOPEN_BKPT;
37053    }
37054  }
37055
37056  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
37057  if( pNew==NULL ){
37058    rc = SQLITE_NOMEM_BKPT;
37059    goto end_create_proxy;
37060  }
37061  memset(pNew, 0, sizeof(unixFile));
37062  pNew->openFlags = openFlags;
37063  memset(&dummyVfs, 0, sizeof(dummyVfs));
37064  dummyVfs.pAppData = (void*)&autolockIoFinder;
37065  dummyVfs.zName = "dummy";
37066  pUnused->fd = fd;
37067  pUnused->flags = openFlags;
37068  pNew->pUnused = pUnused;
37069
37070  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
37071  if( rc==SQLITE_OK ){
37072    *ppFile = pNew;
37073    return SQLITE_OK;
37074  }
37075end_create_proxy:
37076  robust_close(pNew, fd, __LINE__);
37077  sqlite3_free(pNew);
37078  sqlite3_free(pUnused);
37079  return rc;
37080}
37081
37082#ifdef SQLITE_TEST
37083/* simulate multiple hosts by creating unique hostid file paths */
37084SQLITE_API int sqlite3_hostid_num = 0;
37085#endif
37086
37087#define PROXY_HOSTIDLEN    16  /* conch file host id length */
37088
37089#ifdef HAVE_GETHOSTUUID
37090/* Not always defined in the headers as it ought to be */
37091extern int gethostuuid(uuid_t id, const struct timespec *wait);
37092#endif
37093
37094/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
37095** bytes of writable memory.
37096*/
37097static int proxyGetHostID(unsigned char *pHostID, int *pError){
37098  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
37099  memset(pHostID, 0, PROXY_HOSTIDLEN);
37100#ifdef HAVE_GETHOSTUUID
37101  {
37102    struct timespec timeout = {1, 0}; /* 1 sec timeout */
37103    if( gethostuuid(pHostID, &timeout) ){
37104      int err = errno;
37105      if( pError ){
37106        *pError = err;
37107      }
37108      return SQLITE_IOERR;
37109    }
37110  }
37111#else
37112  UNUSED_PARAMETER(pError);
37113#endif
37114#ifdef SQLITE_TEST
37115  /* simulate multiple hosts by creating unique hostid file paths */
37116  if( sqlite3_hostid_num != 0){
37117    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
37118  }
37119#endif
37120
37121  return SQLITE_OK;
37122}
37123
37124/* The conch file contains the header, host id and lock file path
37125 */
37126#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
37127#define PROXY_HEADERLEN    1   /* conch file header length */
37128#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
37129#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
37130
37131/*
37132** Takes an open conch file, copies the contents to a new path and then moves
37133** it back.  The newly created file's file descriptor is assigned to the
37134** conch file structure and finally the original conch file descriptor is
37135** closed.  Returns zero if successful.
37136*/
37137static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
37138  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37139  unixFile *conchFile = pCtx->conchFile;
37140  char tPath[MAXPATHLEN];
37141  char buf[PROXY_MAXCONCHLEN];
37142  char *cPath = pCtx->conchFilePath;
37143  size_t readLen = 0;
37144  size_t pathLen = 0;
37145  char errmsg[64] = "";
37146  int fd = -1;
37147  int rc = -1;
37148  UNUSED_PARAMETER(myHostID);
37149
37150  /* create a new path by replace the trailing '-conch' with '-break' */
37151  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
37152  if( pathLen>MAXPATHLEN || pathLen<6 ||
37153     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
37154    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
37155    goto end_breaklock;
37156  }
37157  /* read the conch content */
37158  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
37159  if( readLen<PROXY_PATHINDEX ){
37160    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
37161    goto end_breaklock;
37162  }
37163  /* write it out to the temporary break file */
37164  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
37165  if( fd<0 ){
37166    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
37167    goto end_breaklock;
37168  }
37169  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
37170    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
37171    goto end_breaklock;
37172  }
37173  if( rename(tPath, cPath) ){
37174    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
37175    goto end_breaklock;
37176  }
37177  rc = 0;
37178  fprintf(stderr, "broke stale lock on %s\n", cPath);
37179  robust_close(pFile, conchFile->h, __LINE__);
37180  conchFile->h = fd;
37181  conchFile->openFlags = O_RDWR | O_CREAT;
37182
37183end_breaklock:
37184  if( rc ){
37185    if( fd>=0 ){
37186      osUnlink(tPath);
37187      robust_close(pFile, fd, __LINE__);
37188    }
37189    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
37190  }
37191  return rc;
37192}
37193
37194/* Take the requested lock on the conch file and break a stale lock if the
37195** host id matches.
37196*/
37197static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
37198  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37199  unixFile *conchFile = pCtx->conchFile;
37200  int rc = SQLITE_OK;
37201  int nTries = 0;
37202  struct timespec conchModTime;
37203
37204  memset(&conchModTime, 0, sizeof(conchModTime));
37205  do {
37206    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
37207    nTries ++;
37208    if( rc==SQLITE_BUSY ){
37209      /* If the lock failed (busy):
37210       * 1st try: get the mod time of the conch, wait 0.5s and try again.
37211       * 2nd try: fail if the mod time changed or host id is different, wait
37212       *           10 sec and try again
37213       * 3rd try: break the lock unless the mod time has changed.
37214       */
37215      struct stat buf;
37216      if( osFstat(conchFile->h, &buf) ){
37217        storeLastErrno(pFile, errno);
37218        return SQLITE_IOERR_LOCK;
37219      }
37220
37221      if( nTries==1 ){
37222        conchModTime = buf.st_mtimespec;
37223        usleep(500000); /* wait 0.5 sec and try the lock again*/
37224        continue;
37225      }
37226
37227      assert( nTries>1 );
37228      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
37229         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
37230        return SQLITE_BUSY;
37231      }
37232
37233      if( nTries==2 ){
37234        char tBuf[PROXY_MAXCONCHLEN];
37235        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
37236        if( len<0 ){
37237          storeLastErrno(pFile, errno);
37238          return SQLITE_IOERR_LOCK;
37239        }
37240        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
37241          /* don't break the lock if the host id doesn't match */
37242          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
37243            return SQLITE_BUSY;
37244          }
37245        }else{
37246          /* don't break the lock on short read or a version mismatch */
37247          return SQLITE_BUSY;
37248        }
37249        usleep(10000000); /* wait 10 sec and try the lock again */
37250        continue;
37251      }
37252
37253      assert( nTries==3 );
37254      if( 0==proxyBreakConchLock(pFile, myHostID) ){
37255        rc = SQLITE_OK;
37256        if( lockType==EXCLUSIVE_LOCK ){
37257          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
37258        }
37259        if( !rc ){
37260          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
37261        }
37262      }
37263    }
37264  } while( rc==SQLITE_BUSY && nTries<3 );
37265
37266  return rc;
37267}
37268
37269/* Takes the conch by taking a shared lock and read the contents conch, if
37270** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
37271** lockPath means that the lockPath in the conch file will be used if the
37272** host IDs match, or a new lock path will be generated automatically
37273** and written to the conch file.
37274*/
37275static int proxyTakeConch(unixFile *pFile){
37276  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37277
37278  if( pCtx->conchHeld!=0 ){
37279    return SQLITE_OK;
37280  }else{
37281    unixFile *conchFile = pCtx->conchFile;
37282    uuid_t myHostID;
37283    int pError = 0;
37284    char readBuf[PROXY_MAXCONCHLEN];
37285    char lockPath[MAXPATHLEN];
37286    char *tempLockPath = NULL;
37287    int rc = SQLITE_OK;
37288    int createConch = 0;
37289    int hostIdMatch = 0;
37290    int readLen = 0;
37291    int tryOldLockPath = 0;
37292    int forceNewLockPath = 0;
37293
37294    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
37295             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
37296             osGetpid(0)));
37297
37298    rc = proxyGetHostID(myHostID, &pError);
37299    if( (rc&0xff)==SQLITE_IOERR ){
37300      storeLastErrno(pFile, pError);
37301      goto end_takeconch;
37302    }
37303    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
37304    if( rc!=SQLITE_OK ){
37305      goto end_takeconch;
37306    }
37307    /* read the existing conch file */
37308    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
37309    if( readLen<0 ){
37310      /* I/O error: lastErrno set by seekAndRead */
37311      storeLastErrno(pFile, conchFile->lastErrno);
37312      rc = SQLITE_IOERR_READ;
37313      goto end_takeconch;
37314    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
37315             readBuf[0]!=(char)PROXY_CONCHVERSION ){
37316      /* a short read or version format mismatch means we need to create a new
37317      ** conch file.
37318      */
37319      createConch = 1;
37320    }
37321    /* if the host id matches and the lock path already exists in the conch
37322    ** we'll try to use the path there, if we can't open that path, we'll
37323    ** retry with a new auto-generated path
37324    */
37325    do { /* in case we need to try again for an :auto: named lock file */
37326
37327      if( !createConch && !forceNewLockPath ){
37328        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
37329                                  PROXY_HOSTIDLEN);
37330        /* if the conch has data compare the contents */
37331        if( !pCtx->lockProxyPath ){
37332          /* for auto-named local lock file, just check the host ID and we'll
37333           ** use the local lock file path that's already in there
37334           */
37335          if( hostIdMatch ){
37336            size_t pathLen = (readLen - PROXY_PATHINDEX);
37337
37338            if( pathLen>=MAXPATHLEN ){
37339              pathLen=MAXPATHLEN-1;
37340            }
37341            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
37342            lockPath[pathLen] = 0;
37343            tempLockPath = lockPath;
37344            tryOldLockPath = 1;
37345            /* create a copy of the lock path if the conch is taken */
37346            goto end_takeconch;
37347          }
37348        }else if( hostIdMatch
37349               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
37350                           readLen-PROXY_PATHINDEX)
37351        ){
37352          /* conch host and lock path match */
37353          goto end_takeconch;
37354        }
37355      }
37356
37357      /* if the conch isn't writable and doesn't match, we can't take it */
37358      if( (conchFile->openFlags&O_RDWR) == 0 ){
37359        rc = SQLITE_BUSY;
37360        goto end_takeconch;
37361      }
37362
37363      /* either the conch didn't match or we need to create a new one */
37364      if( !pCtx->lockProxyPath ){
37365        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
37366        tempLockPath = lockPath;
37367        /* create a copy of the lock path _only_ if the conch is taken */
37368      }
37369
37370      /* update conch with host and path (this will fail if other process
37371      ** has a shared lock already), if the host id matches, use the big
37372      ** stick.
37373      */
37374      futimes(conchFile->h, NULL);
37375      if( hostIdMatch && !createConch ){
37376        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
37377          /* We are trying for an exclusive lock but another thread in this
37378           ** same process is still holding a shared lock. */
37379          rc = SQLITE_BUSY;
37380        } else {
37381          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
37382        }
37383      }else{
37384        rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
37385      }
37386      if( rc==SQLITE_OK ){
37387        char writeBuffer[PROXY_MAXCONCHLEN];
37388        int writeSize = 0;
37389
37390        writeBuffer[0] = (char)PROXY_CONCHVERSION;
37391        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
37392        if( pCtx->lockProxyPath!=NULL ){
37393          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
37394                  MAXPATHLEN);
37395        }else{
37396          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
37397        }
37398        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
37399        robust_ftruncate(conchFile->h, writeSize);
37400        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
37401        full_fsync(conchFile->h,0,0);
37402        /* If we created a new conch file (not just updated the contents of a
37403         ** valid conch file), try to match the permissions of the database
37404         */
37405        if( rc==SQLITE_OK && createConch ){
37406          struct stat buf;
37407          int err = osFstat(pFile->h, &buf);
37408          if( err==0 ){
37409            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
37410                                        S_IROTH|S_IWOTH);
37411            /* try to match the database file R/W permissions, ignore failure */
37412#ifndef SQLITE_PROXY_DEBUG
37413            osFchmod(conchFile->h, cmode);
37414#else
37415            do{
37416              rc = osFchmod(conchFile->h, cmode);
37417            }while( rc==(-1) && errno==EINTR );
37418            if( rc!=0 ){
37419              int code = errno;
37420              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
37421                      cmode, code, strerror(code));
37422            } else {
37423              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
37424            }
37425          }else{
37426            int code = errno;
37427            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
37428                    err, code, strerror(code));
37429#endif
37430          }
37431        }
37432      }
37433      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
37434
37435    end_takeconch:
37436      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
37437      if( rc==SQLITE_OK && pFile->openFlags ){
37438        int fd;
37439        if( pFile->h>=0 ){
37440          robust_close(pFile, pFile->h, __LINE__);
37441        }
37442        pFile->h = -1;
37443        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
37444        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
37445        if( fd>=0 ){
37446          pFile->h = fd;
37447        }else{
37448          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
37449           during locking */
37450        }
37451      }
37452      if( rc==SQLITE_OK && !pCtx->lockProxy ){
37453        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
37454        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
37455        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
37456          /* we couldn't create the proxy lock file with the old lock file path
37457           ** so try again via auto-naming
37458           */
37459          forceNewLockPath = 1;
37460          tryOldLockPath = 0;
37461          continue; /* go back to the do {} while start point, try again */
37462        }
37463      }
37464      if( rc==SQLITE_OK ){
37465        /* Need to make a copy of path if we extracted the value
37466         ** from the conch file or the path was allocated on the stack
37467         */
37468        if( tempLockPath ){
37469          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
37470          if( !pCtx->lockProxyPath ){
37471            rc = SQLITE_NOMEM_BKPT;
37472          }
37473        }
37474      }
37475      if( rc==SQLITE_OK ){
37476        pCtx->conchHeld = 1;
37477
37478        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
37479          afpLockingContext *afpCtx;
37480          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
37481          afpCtx->dbPath = pCtx->lockProxyPath;
37482        }
37483      } else {
37484        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
37485      }
37486      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
37487               rc==SQLITE_OK?"ok":"failed"));
37488      return rc;
37489    } while (1); /* in case we need to retry the :auto: lock file -
37490                 ** we should never get here except via the 'continue' call. */
37491  }
37492}
37493
37494/*
37495** If pFile holds a lock on a conch file, then release that lock.
37496*/
37497static int proxyReleaseConch(unixFile *pFile){
37498  int rc = SQLITE_OK;         /* Subroutine return code */
37499  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
37500  unixFile *conchFile;        /* Name of the conch file */
37501
37502  pCtx = (proxyLockingContext *)pFile->lockingContext;
37503  conchFile = pCtx->conchFile;
37504  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
37505           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
37506           osGetpid(0)));
37507  if( pCtx->conchHeld>0 ){
37508    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
37509  }
37510  pCtx->conchHeld = 0;
37511  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
37512           (rc==SQLITE_OK ? "ok" : "failed")));
37513  return rc;
37514}
37515
37516/*
37517** Given the name of a database file, compute the name of its conch file.
37518** Store the conch filename in memory obtained from sqlite3_malloc64().
37519** Make *pConchPath point to the new name.  Return SQLITE_OK on success
37520** or SQLITE_NOMEM if unable to obtain memory.
37521**
37522** The caller is responsible for ensuring that the allocated memory
37523** space is eventually freed.
37524**
37525** *pConchPath is set to NULL if a memory allocation error occurs.
37526*/
37527static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
37528  int i;                        /* Loop counter */
37529  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
37530  char *conchPath;              /* buffer in which to construct conch name */
37531
37532  /* Allocate space for the conch filename and initialize the name to
37533  ** the name of the original database file. */
37534  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
37535  if( conchPath==0 ){
37536    return SQLITE_NOMEM_BKPT;
37537  }
37538  memcpy(conchPath, dbPath, len+1);
37539
37540  /* now insert a "." before the last / character */
37541  for( i=(len-1); i>=0; i-- ){
37542    if( conchPath[i]=='/' ){
37543      i++;
37544      break;
37545    }
37546  }
37547  conchPath[i]='.';
37548  while ( i<len ){
37549    conchPath[i+1]=dbPath[i];
37550    i++;
37551  }
37552
37553  /* append the "-conch" suffix to the file */
37554  memcpy(&conchPath[i+1], "-conch", 7);
37555  assert( (int)strlen(conchPath) == len+7 );
37556
37557  return SQLITE_OK;
37558}
37559
37560
37561/* Takes a fully configured proxy locking-style unix file and switches
37562** the local lock file path
37563*/
37564static int switchLockProxyPath(unixFile *pFile, const char *path) {
37565  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
37566  char *oldPath = pCtx->lockProxyPath;
37567  int rc = SQLITE_OK;
37568
37569  if( pFile->eFileLock!=NO_LOCK ){
37570    return SQLITE_BUSY;
37571  }
37572
37573  /* nothing to do if the path is NULL, :auto: or matches the existing path */
37574  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
37575    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
37576    return SQLITE_OK;
37577  }else{
37578    unixFile *lockProxy = pCtx->lockProxy;
37579    pCtx->lockProxy=NULL;
37580    pCtx->conchHeld = 0;
37581    if( lockProxy!=NULL ){
37582      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
37583      if( rc ) return rc;
37584      sqlite3_free(lockProxy);
37585    }
37586    sqlite3_free(oldPath);
37587    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
37588  }
37589
37590  return rc;
37591}
37592
37593/*
37594** pFile is a file that has been opened by a prior xOpen call.  dbPath
37595** is a string buffer at least MAXPATHLEN+1 characters in size.
37596**
37597** This routine find the filename associated with pFile and writes it
37598** int dbPath.
37599*/
37600static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
37601#if defined(__APPLE__)
37602  if( pFile->pMethod == &afpIoMethods ){
37603    /* afp style keeps a reference to the db path in the filePath field
37604    ** of the struct */
37605    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
37606    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
37607            MAXPATHLEN);
37608  } else
37609#endif
37610  if( pFile->pMethod == &dotlockIoMethods ){
37611    /* dot lock style uses the locking context to store the dot lock
37612    ** file path */
37613    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
37614    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
37615  }else{
37616    /* all other styles use the locking context to store the db file path */
37617    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
37618    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
37619  }
37620  return SQLITE_OK;
37621}
37622
37623/*
37624** Takes an already filled in unix file and alters it so all file locking
37625** will be performed on the local proxy lock file.  The following fields
37626** are preserved in the locking context so that they can be restored and
37627** the unix structure properly cleaned up at close time:
37628**  ->lockingContext
37629**  ->pMethod
37630*/
37631static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
37632  proxyLockingContext *pCtx;
37633  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
37634  char *lockPath=NULL;
37635  int rc = SQLITE_OK;
37636
37637  if( pFile->eFileLock!=NO_LOCK ){
37638    return SQLITE_BUSY;
37639  }
37640  proxyGetDbPathForUnixFile(pFile, dbPath);
37641  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
37642    lockPath=NULL;
37643  }else{
37644    lockPath=(char *)path;
37645  }
37646
37647  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
37648           (lockPath ? lockPath : ":auto:"), osGetpid(0)));
37649
37650  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
37651  if( pCtx==0 ){
37652    return SQLITE_NOMEM_BKPT;
37653  }
37654  memset(pCtx, 0, sizeof(*pCtx));
37655
37656  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
37657  if( rc==SQLITE_OK ){
37658    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
37659    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
37660      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
37661      ** (c) the file system is read-only, then enable no-locking access.
37662      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
37663      ** that openFlags will have only one of O_RDONLY or O_RDWR.
37664      */
37665      struct statfs fsInfo;
37666      struct stat conchInfo;
37667      int goLockless = 0;
37668
37669      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
37670        int err = errno;
37671        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
37672          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
37673        }
37674      }
37675      if( goLockless ){
37676        pCtx->conchHeld = -1; /* read only FS/ lockless */
37677        rc = SQLITE_OK;
37678      }
37679    }
37680  }
37681  if( rc==SQLITE_OK && lockPath ){
37682    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
37683  }
37684
37685  if( rc==SQLITE_OK ){
37686    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
37687    if( pCtx->dbPath==NULL ){
37688      rc = SQLITE_NOMEM_BKPT;
37689    }
37690  }
37691  if( rc==SQLITE_OK ){
37692    /* all memory is allocated, proxys are created and assigned,
37693    ** switch the locking context and pMethod then return.
37694    */
37695    pCtx->oldLockingContext = pFile->lockingContext;
37696    pFile->lockingContext = pCtx;
37697    pCtx->pOldMethod = pFile->pMethod;
37698    pFile->pMethod = &proxyIoMethods;
37699  }else{
37700    if( pCtx->conchFile ){
37701      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
37702      sqlite3_free(pCtx->conchFile);
37703    }
37704    sqlite3DbFree(0, pCtx->lockProxyPath);
37705    sqlite3_free(pCtx->conchFilePath);
37706    sqlite3_free(pCtx);
37707  }
37708  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
37709           (rc==SQLITE_OK ? "ok" : "failed")));
37710  return rc;
37711}
37712
37713
37714/*
37715** This routine handles sqlite3_file_control() calls that are specific
37716** to proxy locking.
37717*/
37718static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
37719  switch( op ){
37720    case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
37721      unixFile *pFile = (unixFile*)id;
37722      if( pFile->pMethod == &proxyIoMethods ){
37723        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
37724        proxyTakeConch(pFile);
37725        if( pCtx->lockProxyPath ){
37726          *(const char **)pArg = pCtx->lockProxyPath;
37727        }else{
37728          *(const char **)pArg = ":auto: (not held)";
37729        }
37730      } else {
37731        *(const char **)pArg = NULL;
37732      }
37733      return SQLITE_OK;
37734    }
37735    case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
37736      unixFile *pFile = (unixFile*)id;
37737      int rc = SQLITE_OK;
37738      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
37739      if( pArg==NULL || (const char *)pArg==0 ){
37740        if( isProxyStyle ){
37741          /* turn off proxy locking - not supported.  If support is added for
37742          ** switching proxy locking mode off then it will need to fail if
37743          ** the journal mode is WAL mode.
37744          */
37745          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
37746        }else{
37747          /* turn off proxy locking - already off - NOOP */
37748          rc = SQLITE_OK;
37749        }
37750      }else{
37751        const char *proxyPath = (const char *)pArg;
37752        if( isProxyStyle ){
37753          proxyLockingContext *pCtx =
37754            (proxyLockingContext*)pFile->lockingContext;
37755          if( !strcmp(pArg, ":auto:")
37756           || (pCtx->lockProxyPath &&
37757               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
37758          ){
37759            rc = SQLITE_OK;
37760          }else{
37761            rc = switchLockProxyPath(pFile, proxyPath);
37762          }
37763        }else{
37764          /* turn on proxy file locking */
37765          rc = proxyTransformUnixFile(pFile, proxyPath);
37766        }
37767      }
37768      return rc;
37769    }
37770    default: {
37771      assert( 0 );  /* The call assures that only valid opcodes are sent */
37772    }
37773  }
37774  /*NOTREACHED*/
37775  return SQLITE_ERROR;
37776}
37777
37778/*
37779** Within this division (the proxying locking implementation) the procedures
37780** above this point are all utilities.  The lock-related methods of the
37781** proxy-locking sqlite3_io_method object follow.
37782*/
37783
37784
37785/*
37786** This routine checks if there is a RESERVED lock held on the specified
37787** file by this or any other process. If such a lock is held, set *pResOut
37788** to a non-zero value otherwise *pResOut is set to zero.  The return value
37789** is set to SQLITE_OK unless an I/O error occurs during lock checking.
37790*/
37791static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
37792  unixFile *pFile = (unixFile*)id;
37793  int rc = proxyTakeConch(pFile);
37794  if( rc==SQLITE_OK ){
37795    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37796    if( pCtx->conchHeld>0 ){
37797      unixFile *proxy = pCtx->lockProxy;
37798      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
37799    }else{ /* conchHeld < 0 is lockless */
37800      pResOut=0;
37801    }
37802  }
37803  return rc;
37804}
37805
37806/*
37807** Lock the file with the lock specified by parameter eFileLock - one
37808** of the following:
37809**
37810**     (1) SHARED_LOCK
37811**     (2) RESERVED_LOCK
37812**     (3) PENDING_LOCK
37813**     (4) EXCLUSIVE_LOCK
37814**
37815** Sometimes when requesting one lock state, additional lock states
37816** are inserted in between.  The locking might fail on one of the later
37817** transitions leaving the lock state different from what it started but
37818** still short of its goal.  The following chart shows the allowed
37819** transitions and the inserted intermediate states:
37820**
37821**    UNLOCKED -> SHARED
37822**    SHARED -> RESERVED
37823**    SHARED -> (PENDING) -> EXCLUSIVE
37824**    RESERVED -> (PENDING) -> EXCLUSIVE
37825**    PENDING -> EXCLUSIVE
37826**
37827** This routine will only increase a lock.  Use the sqlite3OsUnlock()
37828** routine to lower a locking level.
37829*/
37830static int proxyLock(sqlite3_file *id, int eFileLock) {
37831  unixFile *pFile = (unixFile*)id;
37832  int rc = proxyTakeConch(pFile);
37833  if( rc==SQLITE_OK ){
37834    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37835    if( pCtx->conchHeld>0 ){
37836      unixFile *proxy = pCtx->lockProxy;
37837      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
37838      pFile->eFileLock = proxy->eFileLock;
37839    }else{
37840      /* conchHeld < 0 is lockless */
37841    }
37842  }
37843  return rc;
37844}
37845
37846
37847/*
37848** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
37849** must be either NO_LOCK or SHARED_LOCK.
37850**
37851** If the locking level of the file descriptor is already at or below
37852** the requested locking level, this routine is a no-op.
37853*/
37854static int proxyUnlock(sqlite3_file *id, int eFileLock) {
37855  unixFile *pFile = (unixFile*)id;
37856  int rc = proxyTakeConch(pFile);
37857  if( rc==SQLITE_OK ){
37858    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37859    if( pCtx->conchHeld>0 ){
37860      unixFile *proxy = pCtx->lockProxy;
37861      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
37862      pFile->eFileLock = proxy->eFileLock;
37863    }else{
37864      /* conchHeld < 0 is lockless */
37865    }
37866  }
37867  return rc;
37868}
37869
37870/*
37871** Close a file that uses proxy locks.
37872*/
37873static int proxyClose(sqlite3_file *id) {
37874  if( ALWAYS(id) ){
37875    unixFile *pFile = (unixFile*)id;
37876    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
37877    unixFile *lockProxy = pCtx->lockProxy;
37878    unixFile *conchFile = pCtx->conchFile;
37879    int rc = SQLITE_OK;
37880
37881    if( lockProxy ){
37882      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
37883      if( rc ) return rc;
37884      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
37885      if( rc ) return rc;
37886      sqlite3_free(lockProxy);
37887      pCtx->lockProxy = 0;
37888    }
37889    if( conchFile ){
37890      if( pCtx->conchHeld ){
37891        rc = proxyReleaseConch(pFile);
37892        if( rc ) return rc;
37893      }
37894      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
37895      if( rc ) return rc;
37896      sqlite3_free(conchFile);
37897    }
37898    sqlite3DbFree(0, pCtx->lockProxyPath);
37899    sqlite3_free(pCtx->conchFilePath);
37900    sqlite3DbFree(0, pCtx->dbPath);
37901    /* restore the original locking context and pMethod then close it */
37902    pFile->lockingContext = pCtx->oldLockingContext;
37903    pFile->pMethod = pCtx->pOldMethod;
37904    sqlite3_free(pCtx);
37905    return pFile->pMethod->xClose(id);
37906  }
37907  return SQLITE_OK;
37908}
37909
37910
37911
37912#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
37913/*
37914** The proxy locking style is intended for use with AFP filesystems.
37915** And since AFP is only supported on MacOSX, the proxy locking is also
37916** restricted to MacOSX.
37917**
37918**
37919******************* End of the proxy lock implementation **********************
37920******************************************************************************/
37921
37922/*
37923** Initialize the operating system interface.
37924**
37925** This routine registers all VFS implementations for unix-like operating
37926** systems.  This routine, and the sqlite3_os_end() routine that follows,
37927** should be the only routines in this file that are visible from other
37928** files.
37929**
37930** This routine is called once during SQLite initialization and by a
37931** single thread.  The memory allocation and mutex subsystems have not
37932** necessarily been initialized when this routine is called, and so they
37933** should not be used.
37934*/
37935SQLITE_API int sqlite3_os_init(void){
37936  /*
37937  ** The following macro defines an initializer for an sqlite3_vfs object.
37938  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
37939  ** to the "finder" function.  (pAppData is a pointer to a pointer because
37940  ** silly C90 rules prohibit a void* from being cast to a function pointer
37941  ** and so we have to go through the intermediate pointer to avoid problems
37942  ** when compiling with -pedantic-errors on GCC.)
37943  **
37944  ** The FINDER parameter to this macro is the name of the pointer to the
37945  ** finder-function.  The finder-function returns a pointer to the
37946  ** sqlite_io_methods object that implements the desired locking
37947  ** behaviors.  See the division above that contains the IOMETHODS
37948  ** macro for addition information on finder-functions.
37949  **
37950  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
37951  ** object.  But the "autolockIoFinder" available on MacOSX does a little
37952  ** more than that; it looks at the filesystem type that hosts the
37953  ** database file and tries to choose an locking method appropriate for
37954  ** that filesystem time.
37955  */
37956  #define UNIXVFS(VFSNAME, FINDER) {                        \
37957    3,                    /* iVersion */                    \
37958    sizeof(unixFile),     /* szOsFile */                    \
37959    MAX_PATHNAME,         /* mxPathname */                  \
37960    0,                    /* pNext */                       \
37961    VFSNAME,              /* zName */                       \
37962    (void*)&FINDER,       /* pAppData */                    \
37963    unixOpen,             /* xOpen */                       \
37964    unixDelete,           /* xDelete */                     \
37965    unixAccess,           /* xAccess */                     \
37966    unixFullPathname,     /* xFullPathname */               \
37967    unixDlOpen,           /* xDlOpen */                     \
37968    unixDlError,          /* xDlError */                    \
37969    unixDlSym,            /* xDlSym */                      \
37970    unixDlClose,          /* xDlClose */                    \
37971    unixRandomness,       /* xRandomness */                 \
37972    unixSleep,            /* xSleep */                      \
37973    unixCurrentTime,      /* xCurrentTime */                \
37974    unixGetLastError,     /* xGetLastError */               \
37975    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
37976    unixSetSystemCall,    /* xSetSystemCall */              \
37977    unixGetSystemCall,    /* xGetSystemCall */              \
37978    unixNextSystemCall,   /* xNextSystemCall */             \
37979  }
37980
37981  /*
37982  ** All default VFSes for unix are contained in the following array.
37983  **
37984  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
37985  ** by the SQLite core when the VFS is registered.  So the following
37986  ** array cannot be const.
37987  */
37988  static sqlite3_vfs aVfs[] = {
37989#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
37990    UNIXVFS("unix",          autolockIoFinder ),
37991#elif OS_VXWORKS
37992    UNIXVFS("unix",          vxworksIoFinder ),
37993#else
37994    UNIXVFS("unix",          posixIoFinder ),
37995#endif
37996    UNIXVFS("unix-none",     nolockIoFinder ),
37997    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
37998    UNIXVFS("unix-excl",     posixIoFinder ),
37999#if OS_VXWORKS
38000    UNIXVFS("unix-namedsem", semIoFinder ),
38001#endif
38002#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
38003    UNIXVFS("unix-posix",    posixIoFinder ),
38004#endif
38005#if SQLITE_ENABLE_LOCKING_STYLE
38006    UNIXVFS("unix-flock",    flockIoFinder ),
38007#endif
38008#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
38009    UNIXVFS("unix-afp",      afpIoFinder ),
38010    UNIXVFS("unix-nfs",      nfsIoFinder ),
38011    UNIXVFS("unix-proxy",    proxyIoFinder ),
38012#endif
38013  };
38014  unsigned int i;          /* Loop counter */
38015
38016  /* Double-check that the aSyscall[] array has been constructed
38017  ** correctly.  See ticket [bb3a86e890c8e96ab] */
38018  assert( ArraySize(aSyscall)==28 );
38019
38020  /* Register all VFSes defined in the aVfs[] array */
38021  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
38022    sqlite3_vfs_register(&aVfs[i], i==0);
38023  }
38024  return SQLITE_OK;
38025}
38026
38027/*
38028** Shutdown the operating system interface.
38029**
38030** Some operating systems might need to do some cleanup in this routine,
38031** to release dynamically allocated objects.  But not on unix.
38032** This routine is a no-op for unix.
38033*/
38034SQLITE_API int sqlite3_os_end(void){
38035  return SQLITE_OK;
38036}
38037
38038#endif /* SQLITE_OS_UNIX */
38039
38040/************** End of os_unix.c *********************************************/
38041/************** Begin file os_win.c ******************************************/
38042/*
38043** 2004 May 22
38044**
38045** The author disclaims copyright to this source code.  In place of
38046** a legal notice, here is a blessing:
38047**
38048**    May you do good and not evil.
38049**    May you find forgiveness for yourself and forgive others.
38050**    May you share freely, never taking more than you give.
38051**
38052******************************************************************************
38053**
38054** This file contains code that is specific to Windows.
38055*/
38056/* #include "sqliteInt.h" */
38057#if SQLITE_OS_WIN               /* This file is used for Windows only */
38058
38059/*
38060** Include code that is common to all os_*.c files
38061*/
38062/************** Include os_common.h in the middle of os_win.c ****************/
38063/************** Begin file os_common.h ***************************************/
38064/*
38065** 2004 May 22
38066**
38067** The author disclaims copyright to this source code.  In place of
38068** a legal notice, here is a blessing:
38069**
38070**    May you do good and not evil.
38071**    May you find forgiveness for yourself and forgive others.
38072**    May you share freely, never taking more than you give.
38073**
38074******************************************************************************
38075**
38076** This file contains macros and a little bit of code that is common to
38077** all of the platform-specific files (os_*.c) and is #included into those
38078** files.
38079**
38080** This file should be #included by the os_*.c files only.  It is not a
38081** general purpose header file.
38082*/
38083#ifndef _OS_COMMON_H_
38084#define _OS_COMMON_H_
38085
38086/*
38087** At least two bugs have slipped in because we changed the MEMORY_DEBUG
38088** macro to SQLITE_DEBUG and some older makefiles have not yet made the
38089** switch.  The following code should catch this problem at compile-time.
38090*/
38091#ifdef MEMORY_DEBUG
38092# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
38093#endif
38094
38095/*
38096** Macros for performance tracing.  Normally turned off.  Only works
38097** on i486 hardware.
38098*/
38099#ifdef SQLITE_PERFORMANCE_TRACE
38100
38101/*
38102** hwtime.h contains inline assembler code for implementing
38103** high-performance timing routines.
38104*/
38105/************** Include hwtime.h in the middle of os_common.h ****************/
38106/************** Begin file hwtime.h ******************************************/
38107/*
38108** 2008 May 27
38109**
38110** The author disclaims copyright to this source code.  In place of
38111** a legal notice, here is a blessing:
38112**
38113**    May you do good and not evil.
38114**    May you find forgiveness for yourself and forgive others.
38115**    May you share freely, never taking more than you give.
38116**
38117******************************************************************************
38118**
38119** This file contains inline asm code for retrieving "high-performance"
38120** counters for x86 class CPUs.
38121*/
38122#ifndef SQLITE_HWTIME_H
38123#define SQLITE_HWTIME_H
38124
38125/*
38126** The following routine only works on pentium-class (or newer) processors.
38127** It uses the RDTSC opcode to read the cycle count value out of the
38128** processor and returns that value.  This can be used for high-res
38129** profiling.
38130*/
38131#if (defined(__GNUC__) || defined(_MSC_VER)) && \
38132      (defined(i386) || defined(__i386__) || defined(_M_IX86))
38133
38134  #if defined(__GNUC__)
38135
38136  __inline__ sqlite_uint64 sqlite3Hwtime(void){
38137     unsigned int lo, hi;
38138     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
38139     return (sqlite_uint64)hi << 32 | lo;
38140  }
38141
38142  #elif defined(_MSC_VER)
38143
38144  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
38145     __asm {
38146        rdtsc
38147        ret       ; return value at EDX:EAX
38148     }
38149  }
38150
38151  #endif
38152
38153#elif (defined(__GNUC__) && defined(__x86_64__))
38154
38155  __inline__ sqlite_uint64 sqlite3Hwtime(void){
38156      unsigned long val;
38157      __asm__ __volatile__ ("rdtsc" : "=A" (val));
38158      return val;
38159  }
38160
38161#elif (defined(__GNUC__) && defined(__ppc__))
38162
38163  __inline__ sqlite_uint64 sqlite3Hwtime(void){
38164      unsigned long long retval;
38165      unsigned long junk;
38166      __asm__ __volatile__ ("\n\
38167          1:      mftbu   %1\n\
38168                  mftb    %L0\n\
38169                  mftbu   %0\n\
38170                  cmpw    %0,%1\n\
38171                  bne     1b"
38172                  : "=r" (retval), "=r" (junk));
38173      return retval;
38174  }
38175
38176#else
38177
38178  #error Need implementation of sqlite3Hwtime() for your platform.
38179
38180  /*
38181  ** To compile without implementing sqlite3Hwtime() for your platform,
38182  ** you can remove the above #error and use the following
38183  ** stub function.  You will lose timing support for many
38184  ** of the debugging and testing utilities, but it should at
38185  ** least compile and run.
38186  */
38187SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
38188
38189#endif
38190
38191#endif /* !defined(SQLITE_HWTIME_H) */
38192
38193/************** End of hwtime.h **********************************************/
38194/************** Continuing where we left off in os_common.h ******************/
38195
38196static sqlite_uint64 g_start;
38197static sqlite_uint64 g_elapsed;
38198#define TIMER_START       g_start=sqlite3Hwtime()
38199#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
38200#define TIMER_ELAPSED     g_elapsed
38201#else
38202#define TIMER_START
38203#define TIMER_END
38204#define TIMER_ELAPSED     ((sqlite_uint64)0)
38205#endif
38206
38207/*
38208** If we compile with the SQLITE_TEST macro set, then the following block
38209** of code will give us the ability to simulate a disk I/O error.  This
38210** is used for testing the I/O recovery logic.
38211*/
38212#if defined(SQLITE_TEST)
38213SQLITE_API extern int sqlite3_io_error_hit;
38214SQLITE_API extern int sqlite3_io_error_hardhit;
38215SQLITE_API extern int sqlite3_io_error_pending;
38216SQLITE_API extern int sqlite3_io_error_persist;
38217SQLITE_API extern int sqlite3_io_error_benign;
38218SQLITE_API extern int sqlite3_diskfull_pending;
38219SQLITE_API extern int sqlite3_diskfull;
38220#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
38221#define SimulateIOError(CODE)  \
38222  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
38223       || sqlite3_io_error_pending-- == 1 )  \
38224              { local_ioerr(); CODE; }
38225static void local_ioerr(){
38226  IOTRACE(("IOERR\n"));
38227  sqlite3_io_error_hit++;
38228  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
38229}
38230#define SimulateDiskfullError(CODE) \
38231   if( sqlite3_diskfull_pending ){ \
38232     if( sqlite3_diskfull_pending == 1 ){ \
38233       local_ioerr(); \
38234       sqlite3_diskfull = 1; \
38235       sqlite3_io_error_hit = 1; \
38236       CODE; \
38237     }else{ \
38238       sqlite3_diskfull_pending--; \
38239     } \
38240   }
38241#else
38242#define SimulateIOErrorBenign(X)
38243#define SimulateIOError(A)
38244#define SimulateDiskfullError(A)
38245#endif /* defined(SQLITE_TEST) */
38246
38247/*
38248** When testing, keep a count of the number of open files.
38249*/
38250#if defined(SQLITE_TEST)
38251SQLITE_API extern int sqlite3_open_file_count;
38252#define OpenCounter(X)  sqlite3_open_file_count+=(X)
38253#else
38254#define OpenCounter(X)
38255#endif /* defined(SQLITE_TEST) */
38256
38257#endif /* !defined(_OS_COMMON_H_) */
38258
38259/************** End of os_common.h *******************************************/
38260/************** Continuing where we left off in os_win.c *********************/
38261
38262/*
38263** Include the header file for the Windows VFS.
38264*/
38265/* #include "os_win.h" */
38266
38267/*
38268** Compiling and using WAL mode requires several APIs that are only
38269** available in Windows platforms based on the NT kernel.
38270*/
38271#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
38272#  error "WAL mode requires support from the Windows NT kernel, compile\
38273 with SQLITE_OMIT_WAL."
38274#endif
38275
38276#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
38277#  error "Memory mapped files require support from the Windows NT kernel,\
38278 compile with SQLITE_MAX_MMAP_SIZE=0."
38279#endif
38280
38281/*
38282** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
38283** based on the sub-platform)?
38284*/
38285#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
38286#  define SQLITE_WIN32_HAS_ANSI
38287#endif
38288
38289/*
38290** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
38291** based on the sub-platform)?
38292*/
38293#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
38294    !defined(SQLITE_WIN32_NO_WIDE)
38295#  define SQLITE_WIN32_HAS_WIDE
38296#endif
38297
38298/*
38299** Make sure at least one set of Win32 APIs is available.
38300*/
38301#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
38302#  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
38303 must be defined."
38304#endif
38305
38306/*
38307** Define the required Windows SDK version constants if they are not
38308** already available.
38309*/
38310#ifndef NTDDI_WIN8
38311#  define NTDDI_WIN8                        0x06020000
38312#endif
38313
38314#ifndef NTDDI_WINBLUE
38315#  define NTDDI_WINBLUE                     0x06030000
38316#endif
38317
38318#ifndef NTDDI_WINTHRESHOLD
38319#  define NTDDI_WINTHRESHOLD                0x06040000
38320#endif
38321
38322/*
38323** Check to see if the GetVersionEx[AW] functions are deprecated on the
38324** target system.  GetVersionEx was first deprecated in Win8.1.
38325*/
38326#ifndef SQLITE_WIN32_GETVERSIONEX
38327#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
38328#    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
38329#  else
38330#    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
38331#  endif
38332#endif
38333
38334/*
38335** Check to see if the CreateFileMappingA function is supported on the
38336** target system.  It is unavailable when using "mincore.lib" on Win10.
38337** When compiling for Windows 10, always assume "mincore.lib" is in use.
38338*/
38339#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
38340#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
38341#    define SQLITE_WIN32_CREATEFILEMAPPINGA   0
38342#  else
38343#    define SQLITE_WIN32_CREATEFILEMAPPINGA   1
38344#  endif
38345#endif
38346
38347/*
38348** This constant should already be defined (in the "WinDef.h" SDK file).
38349*/
38350#ifndef MAX_PATH
38351#  define MAX_PATH                      (260)
38352#endif
38353
38354/*
38355** Maximum pathname length (in chars) for Win32.  This should normally be
38356** MAX_PATH.
38357*/
38358#ifndef SQLITE_WIN32_MAX_PATH_CHARS
38359#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
38360#endif
38361
38362/*
38363** This constant should already be defined (in the "WinNT.h" SDK file).
38364*/
38365#ifndef UNICODE_STRING_MAX_CHARS
38366#  define UNICODE_STRING_MAX_CHARS      (32767)
38367#endif
38368
38369/*
38370** Maximum pathname length (in chars) for WinNT.  This should normally be
38371** UNICODE_STRING_MAX_CHARS.
38372*/
38373#ifndef SQLITE_WINNT_MAX_PATH_CHARS
38374#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
38375#endif
38376
38377/*
38378** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
38379** characters, so we allocate 4 bytes per character assuming worst-case of
38380** 4-bytes-per-character for UTF8.
38381*/
38382#ifndef SQLITE_WIN32_MAX_PATH_BYTES
38383#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
38384#endif
38385
38386/*
38387** Maximum pathname length (in bytes) for WinNT.  This should normally be
38388** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
38389*/
38390#ifndef SQLITE_WINNT_MAX_PATH_BYTES
38391#  define SQLITE_WINNT_MAX_PATH_BYTES   \
38392                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
38393#endif
38394
38395/*
38396** Maximum error message length (in chars) for WinRT.
38397*/
38398#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
38399#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
38400#endif
38401
38402/*
38403** Returns non-zero if the character should be treated as a directory
38404** separator.
38405*/
38406#ifndef winIsDirSep
38407#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
38408#endif
38409
38410/*
38411** This macro is used when a local variable is set to a value that is
38412** [sometimes] not used by the code (e.g. via conditional compilation).
38413*/
38414#ifndef UNUSED_VARIABLE_VALUE
38415#  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
38416#endif
38417
38418/*
38419** Returns the character that should be used as the directory separator.
38420*/
38421#ifndef winGetDirSep
38422#  define winGetDirSep()                '\\'
38423#endif
38424
38425/*
38426** Do we need to manually define the Win32 file mapping APIs for use with WAL
38427** mode or memory mapped files (e.g. these APIs are available in the Windows
38428** CE SDK; however, they are not present in the header file)?
38429*/
38430#if SQLITE_WIN32_FILEMAPPING_API && \
38431        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38432/*
38433** Two of the file mapping APIs are different under WinRT.  Figure out which
38434** set we need.
38435*/
38436#if SQLITE_OS_WINRT
38437WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
38438        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
38439
38440WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
38441#else
38442#if defined(SQLITE_WIN32_HAS_ANSI)
38443WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
38444        DWORD, DWORD, DWORD, LPCSTR);
38445#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
38446
38447#if defined(SQLITE_WIN32_HAS_WIDE)
38448WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
38449        DWORD, DWORD, DWORD, LPCWSTR);
38450#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
38451
38452WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
38453#endif /* SQLITE_OS_WINRT */
38454
38455/*
38456** These file mapping APIs are common to both Win32 and WinRT.
38457*/
38458
38459WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
38460WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
38461#endif /* SQLITE_WIN32_FILEMAPPING_API */
38462
38463/*
38464** Some Microsoft compilers lack this definition.
38465*/
38466#ifndef INVALID_FILE_ATTRIBUTES
38467# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
38468#endif
38469
38470#ifndef FILE_FLAG_MASK
38471# define FILE_FLAG_MASK          (0xFF3C0000)
38472#endif
38473
38474#ifndef FILE_ATTRIBUTE_MASK
38475# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
38476#endif
38477
38478#ifndef SQLITE_OMIT_WAL
38479/* Forward references to structures used for WAL */
38480typedef struct winShm winShm;           /* A connection to shared-memory */
38481typedef struct winShmNode winShmNode;   /* A region of shared-memory */
38482#endif
38483
38484/*
38485** WinCE lacks native support for file locking so we have to fake it
38486** with some code of our own.
38487*/
38488#if SQLITE_OS_WINCE
38489typedef struct winceLock {
38490  int nReaders;       /* Number of reader locks obtained */
38491  BOOL bPending;      /* Indicates a pending lock has been obtained */
38492  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
38493  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
38494} winceLock;
38495#endif
38496
38497/*
38498** The winFile structure is a subclass of sqlite3_file* specific to the win32
38499** portability layer.
38500*/
38501typedef struct winFile winFile;
38502struct winFile {
38503  const sqlite3_io_methods *pMethod; /*** Must be first ***/
38504  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
38505  HANDLE h;               /* Handle for accessing the file */
38506  u8 locktype;            /* Type of lock currently held on this file */
38507  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
38508  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
38509  DWORD lastErrno;        /* The Windows errno from the last I/O error */
38510#ifndef SQLITE_OMIT_WAL
38511  winShm *pShm;           /* Instance of shared memory on this file */
38512#endif
38513  const char *zPath;      /* Full pathname of this file */
38514  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
38515#if SQLITE_OS_WINCE
38516  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
38517  HANDLE hMutex;          /* Mutex used to control access to shared lock */
38518  HANDLE hShared;         /* Shared memory segment used for locking */
38519  winceLock local;        /* Locks obtained by this instance of winFile */
38520  winceLock *shared;      /* Global shared lock memory for the file  */
38521#endif
38522#if SQLITE_MAX_MMAP_SIZE>0
38523  int nFetchOut;                /* Number of outstanding xFetch references */
38524  HANDLE hMap;                  /* Handle for accessing memory mapping */
38525  void *pMapRegion;             /* Area memory mapped */
38526  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
38527  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
38528  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
38529#endif
38530};
38531
38532/*
38533** The winVfsAppData structure is used for the pAppData member for all of the
38534** Win32 VFS variants.
38535*/
38536typedef struct winVfsAppData winVfsAppData;
38537struct winVfsAppData {
38538  const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
38539  void *pAppData;                    /* The extra pAppData, if any. */
38540  BOOL bNoLock;                      /* Non-zero if locking is disabled. */
38541};
38542
38543/*
38544** Allowed values for winFile.ctrlFlags
38545*/
38546#define WINFILE_RDONLY          0x02   /* Connection is read only */
38547#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
38548#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
38549
38550/*
38551 * The size of the buffer used by sqlite3_win32_write_debug().
38552 */
38553#ifndef SQLITE_WIN32_DBG_BUF_SIZE
38554#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
38555#endif
38556
38557/*
38558 * The value used with sqlite3_win32_set_directory() to specify that
38559 * the data directory should be changed.
38560 */
38561#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
38562#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
38563#endif
38564
38565/*
38566 * The value used with sqlite3_win32_set_directory() to specify that
38567 * the temporary directory should be changed.
38568 */
38569#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
38570#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
38571#endif
38572
38573/*
38574 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
38575 * various Win32 API heap functions instead of our own.
38576 */
38577#ifdef SQLITE_WIN32_MALLOC
38578
38579/*
38580 * If this is non-zero, an isolated heap will be created by the native Win32
38581 * allocator subsystem; otherwise, the default process heap will be used.  This
38582 * setting has no effect when compiling for WinRT.  By default, this is enabled
38583 * and an isolated heap will be created to store all allocated data.
38584 *
38585 ******************************************************************************
38586 * WARNING: It is important to note that when this setting is non-zero and the
38587 *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
38588 *          function), all data that was allocated using the isolated heap will
38589 *          be freed immediately and any attempt to access any of that freed
38590 *          data will almost certainly result in an immediate access violation.
38591 ******************************************************************************
38592 */
38593#ifndef SQLITE_WIN32_HEAP_CREATE
38594#  define SQLITE_WIN32_HEAP_CREATE        (TRUE)
38595#endif
38596
38597/*
38598 * This is the maximum possible initial size of the Win32-specific heap, in
38599 * bytes.
38600 */
38601#ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
38602#  define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
38603#endif
38604
38605/*
38606 * This is the extra space for the initial size of the Win32-specific heap,
38607 * in bytes.  This value may be zero.
38608 */
38609#ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
38610#  define SQLITE_WIN32_HEAP_INIT_EXTRA  (4194304)
38611#endif
38612
38613/*
38614 * Calculate the maximum legal cache size, in pages, based on the maximum
38615 * possible initial heap size and the default page size, setting aside the
38616 * needed extra space.
38617 */
38618#ifndef SQLITE_WIN32_MAX_CACHE_SIZE
38619#  define SQLITE_WIN32_MAX_CACHE_SIZE   (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
38620                                          (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
38621                                         (SQLITE_DEFAULT_PAGE_SIZE))
38622#endif
38623
38624/*
38625 * This is cache size used in the calculation of the initial size of the
38626 * Win32-specific heap.  It cannot be negative.
38627 */
38628#ifndef SQLITE_WIN32_CACHE_SIZE
38629#  if SQLITE_DEFAULT_CACHE_SIZE>=0
38630#    define SQLITE_WIN32_CACHE_SIZE     (SQLITE_DEFAULT_CACHE_SIZE)
38631#  else
38632#    define SQLITE_WIN32_CACHE_SIZE     (-(SQLITE_DEFAULT_CACHE_SIZE))
38633#  endif
38634#endif
38635
38636/*
38637 * Make sure that the calculated cache size, in pages, cannot cause the
38638 * initial size of the Win32-specific heap to exceed the maximum amount
38639 * of memory that can be specified in the call to HeapCreate.
38640 */
38641#if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
38642#  undef SQLITE_WIN32_CACHE_SIZE
38643#  define SQLITE_WIN32_CACHE_SIZE       (2000)
38644#endif
38645
38646/*
38647 * The initial size of the Win32-specific heap.  This value may be zero.
38648 */
38649#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
38650#  define SQLITE_WIN32_HEAP_INIT_SIZE   ((SQLITE_WIN32_CACHE_SIZE) * \
38651                                         (SQLITE_DEFAULT_PAGE_SIZE) + \
38652                                         (SQLITE_WIN32_HEAP_INIT_EXTRA))
38653#endif
38654
38655/*
38656 * The maximum size of the Win32-specific heap.  This value may be zero.
38657 */
38658#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
38659#  define SQLITE_WIN32_HEAP_MAX_SIZE    (0)
38660#endif
38661
38662/*
38663 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
38664 * zero for the default behavior.
38665 */
38666#ifndef SQLITE_WIN32_HEAP_FLAGS
38667#  define SQLITE_WIN32_HEAP_FLAGS       (0)
38668#endif
38669
38670
38671/*
38672** The winMemData structure stores information required by the Win32-specific
38673** sqlite3_mem_methods implementation.
38674*/
38675typedef struct winMemData winMemData;
38676struct winMemData {
38677#ifndef NDEBUG
38678  u32 magic1;   /* Magic number to detect structure corruption. */
38679#endif
38680  HANDLE hHeap; /* The handle to our heap. */
38681  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
38682#ifndef NDEBUG
38683  u32 magic2;   /* Magic number to detect structure corruption. */
38684#endif
38685};
38686
38687#ifndef NDEBUG
38688#define WINMEM_MAGIC1     0x42b2830b
38689#define WINMEM_MAGIC2     0xbd4d7cf4
38690#endif
38691
38692static struct winMemData win_mem_data = {
38693#ifndef NDEBUG
38694  WINMEM_MAGIC1,
38695#endif
38696  NULL, FALSE
38697#ifndef NDEBUG
38698  ,WINMEM_MAGIC2
38699#endif
38700};
38701
38702#ifndef NDEBUG
38703#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
38704#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
38705#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
38706#else
38707#define winMemAssertMagic()
38708#endif
38709
38710#define winMemGetDataPtr()  &win_mem_data
38711#define winMemGetHeap()     win_mem_data.hHeap
38712#define winMemGetOwned()    win_mem_data.bOwned
38713
38714static void *winMemMalloc(int nBytes);
38715static void winMemFree(void *pPrior);
38716static void *winMemRealloc(void *pPrior, int nBytes);
38717static int winMemSize(void *p);
38718static int winMemRoundup(int n);
38719static int winMemInit(void *pAppData);
38720static void winMemShutdown(void *pAppData);
38721
38722SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
38723#endif /* SQLITE_WIN32_MALLOC */
38724
38725/*
38726** The following variable is (normally) set once and never changes
38727** thereafter.  It records whether the operating system is Win9x
38728** or WinNT.
38729**
38730** 0:   Operating system unknown.
38731** 1:   Operating system is Win9x.
38732** 2:   Operating system is WinNT.
38733**
38734** In order to facilitate testing on a WinNT system, the test fixture
38735** can manually set this value to 1 to emulate Win98 behavior.
38736*/
38737#ifdef SQLITE_TEST
38738SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
38739#else
38740static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
38741#endif
38742
38743#ifndef SYSCALL
38744#  define SYSCALL sqlite3_syscall_ptr
38745#endif
38746
38747/*
38748** This function is not available on Windows CE or WinRT.
38749 */
38750
38751#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
38752#  define osAreFileApisANSI()       1
38753#endif
38754
38755/*
38756** Many system calls are accessed through pointer-to-functions so that
38757** they may be overridden at runtime to facilitate fault injection during
38758** testing and sandboxing.  The following array holds the names and pointers
38759** to all overrideable system calls.
38760*/
38761static struct win_syscall {
38762  const char *zName;            /* Name of the system call */
38763  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
38764  sqlite3_syscall_ptr pDefault; /* Default value */
38765} aSyscall[] = {
38766#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38767  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
38768#else
38769  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
38770#endif
38771
38772#ifndef osAreFileApisANSI
38773#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
38774#endif
38775
38776#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
38777  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
38778#else
38779  { "CharLowerW",              (SYSCALL)0,                       0 },
38780#endif
38781
38782#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
38783
38784#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
38785  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
38786#else
38787  { "CharUpperW",              (SYSCALL)0,                       0 },
38788#endif
38789
38790#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
38791
38792  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
38793
38794#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
38795
38796#if defined(SQLITE_WIN32_HAS_ANSI)
38797  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
38798#else
38799  { "CreateFileA",             (SYSCALL)0,                       0 },
38800#endif
38801
38802#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
38803        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
38804
38805#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38806  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
38807#else
38808  { "CreateFileW",             (SYSCALL)0,                       0 },
38809#endif
38810
38811#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
38812        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
38813
38814#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
38815        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
38816        SQLITE_WIN32_CREATEFILEMAPPINGA
38817  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
38818#else
38819  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
38820#endif
38821
38822#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
38823        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
38824
38825#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
38826        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
38827  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
38828#else
38829  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
38830#endif
38831
38832#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
38833        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
38834
38835#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38836  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
38837#else
38838  { "CreateMutexW",            (SYSCALL)0,                       0 },
38839#endif
38840
38841#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
38842        LPCWSTR))aSyscall[8].pCurrent)
38843
38844#if defined(SQLITE_WIN32_HAS_ANSI)
38845  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
38846#else
38847  { "DeleteFileA",             (SYSCALL)0,                       0 },
38848#endif
38849
38850#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
38851
38852#if defined(SQLITE_WIN32_HAS_WIDE)
38853  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
38854#else
38855  { "DeleteFileW",             (SYSCALL)0,                       0 },
38856#endif
38857
38858#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
38859
38860#if SQLITE_OS_WINCE
38861  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
38862#else
38863  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
38864#endif
38865
38866#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
38867        LPFILETIME))aSyscall[11].pCurrent)
38868
38869#if SQLITE_OS_WINCE
38870  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
38871#else
38872  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
38873#endif
38874
38875#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
38876        LPSYSTEMTIME))aSyscall[12].pCurrent)
38877
38878  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
38879
38880#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
38881
38882#if defined(SQLITE_WIN32_HAS_ANSI)
38883  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
38884#else
38885  { "FormatMessageA",          (SYSCALL)0,                       0 },
38886#endif
38887
38888#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
38889        DWORD,va_list*))aSyscall[14].pCurrent)
38890
38891#if defined(SQLITE_WIN32_HAS_WIDE)
38892  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
38893#else
38894  { "FormatMessageW",          (SYSCALL)0,                       0 },
38895#endif
38896
38897#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
38898        DWORD,va_list*))aSyscall[15].pCurrent)
38899
38900#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
38901  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
38902#else
38903  { "FreeLibrary",             (SYSCALL)0,                       0 },
38904#endif
38905
38906#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
38907
38908  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
38909
38910#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
38911
38912#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
38913  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
38914#else
38915  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
38916#endif
38917
38918#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
38919        LPDWORD))aSyscall[18].pCurrent)
38920
38921#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38922  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
38923#else
38924  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
38925#endif
38926
38927#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
38928        LPDWORD))aSyscall[19].pCurrent)
38929
38930#if defined(SQLITE_WIN32_HAS_ANSI)
38931  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
38932#else
38933  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
38934#endif
38935
38936#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
38937
38938#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38939  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
38940#else
38941  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
38942#endif
38943
38944#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
38945
38946#if defined(SQLITE_WIN32_HAS_WIDE)
38947  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
38948#else
38949  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
38950#endif
38951
38952#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
38953        LPVOID))aSyscall[22].pCurrent)
38954
38955#if !SQLITE_OS_WINRT
38956  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
38957#else
38958  { "GetFileSize",             (SYSCALL)0,                       0 },
38959#endif
38960
38961#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
38962
38963#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
38964  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
38965#else
38966  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
38967#endif
38968
38969#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
38970        LPSTR*))aSyscall[24].pCurrent)
38971
38972#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
38973  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
38974#else
38975  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
38976#endif
38977
38978#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
38979        LPWSTR*))aSyscall[25].pCurrent)
38980
38981  { "GetLastError",            (SYSCALL)GetLastError,            0 },
38982
38983#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
38984
38985#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
38986#if SQLITE_OS_WINCE
38987  /* The GetProcAddressA() routine is only available on Windows CE. */
38988  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
38989#else
38990  /* All other Windows platforms expect GetProcAddress() to take
38991  ** an ANSI string regardless of the _UNICODE setting */
38992  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
38993#endif
38994#else
38995  { "GetProcAddressA",         (SYSCALL)0,                       0 },
38996#endif
38997
38998#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
38999        LPCSTR))aSyscall[27].pCurrent)
39000
39001#if !SQLITE_OS_WINRT
39002  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
39003#else
39004  { "GetSystemInfo",           (SYSCALL)0,                       0 },
39005#endif
39006
39007#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
39008
39009  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
39010
39011#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
39012
39013#if !SQLITE_OS_WINCE
39014  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
39015#else
39016  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
39017#endif
39018
39019#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
39020        LPFILETIME))aSyscall[30].pCurrent)
39021
39022#if defined(SQLITE_WIN32_HAS_ANSI)
39023  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
39024#else
39025  { "GetTempPathA",            (SYSCALL)0,                       0 },
39026#endif
39027
39028#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
39029
39030#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
39031  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
39032#else
39033  { "GetTempPathW",            (SYSCALL)0,                       0 },
39034#endif
39035
39036#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
39037
39038#if !SQLITE_OS_WINRT
39039  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
39040#else
39041  { "GetTickCount",            (SYSCALL)0,                       0 },
39042#endif
39043
39044#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
39045
39046#if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
39047  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
39048#else
39049  { "GetVersionExA",           (SYSCALL)0,                       0 },
39050#endif
39051
39052#define osGetVersionExA ((BOOL(WINAPI*)( \
39053        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
39054
39055#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
39056        SQLITE_WIN32_GETVERSIONEX
39057  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
39058#else
39059  { "GetVersionExW",           (SYSCALL)0,                       0 },
39060#endif
39061
39062#define osGetVersionExW ((BOOL(WINAPI*)( \
39063        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
39064
39065  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
39066
39067#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
39068        SIZE_T))aSyscall[36].pCurrent)
39069
39070#if !SQLITE_OS_WINRT
39071  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
39072#else
39073  { "HeapCreate",              (SYSCALL)0,                       0 },
39074#endif
39075
39076#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
39077        SIZE_T))aSyscall[37].pCurrent)
39078
39079#if !SQLITE_OS_WINRT
39080  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
39081#else
39082  { "HeapDestroy",             (SYSCALL)0,                       0 },
39083#endif
39084
39085#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
39086
39087  { "HeapFree",                (SYSCALL)HeapFree,                0 },
39088
39089#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
39090
39091  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
39092
39093#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
39094        SIZE_T))aSyscall[40].pCurrent)
39095
39096  { "HeapSize",                (SYSCALL)HeapSize,                0 },
39097
39098#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
39099        LPCVOID))aSyscall[41].pCurrent)
39100
39101#if !SQLITE_OS_WINRT
39102  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
39103#else
39104  { "HeapValidate",            (SYSCALL)0,                       0 },
39105#endif
39106
39107#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
39108        LPCVOID))aSyscall[42].pCurrent)
39109
39110#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
39111  { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
39112#else
39113  { "HeapCompact",             (SYSCALL)0,                       0 },
39114#endif
39115
39116#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
39117
39118#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
39119  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
39120#else
39121  { "LoadLibraryA",            (SYSCALL)0,                       0 },
39122#endif
39123
39124#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
39125
39126#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
39127        !defined(SQLITE_OMIT_LOAD_EXTENSION)
39128  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
39129#else
39130  { "LoadLibraryW",            (SYSCALL)0,                       0 },
39131#endif
39132
39133#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
39134
39135#if !SQLITE_OS_WINRT
39136  { "LocalFree",               (SYSCALL)LocalFree,               0 },
39137#else
39138  { "LocalFree",               (SYSCALL)0,                       0 },
39139#endif
39140
39141#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
39142
39143#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
39144  { "LockFile",                (SYSCALL)LockFile,                0 },
39145#else
39146  { "LockFile",                (SYSCALL)0,                       0 },
39147#endif
39148
39149#ifndef osLockFile
39150#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
39151        DWORD))aSyscall[47].pCurrent)
39152#endif
39153
39154#if !SQLITE_OS_WINCE
39155  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
39156#else
39157  { "LockFileEx",              (SYSCALL)0,                       0 },
39158#endif
39159
39160#ifndef osLockFileEx
39161#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
39162        LPOVERLAPPED))aSyscall[48].pCurrent)
39163#endif
39164
39165#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
39166        (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
39167  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
39168#else
39169  { "MapViewOfFile",           (SYSCALL)0,                       0 },
39170#endif
39171
39172#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
39173        SIZE_T))aSyscall[49].pCurrent)
39174
39175  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
39176
39177#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
39178        int))aSyscall[50].pCurrent)
39179
39180  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
39181
39182#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
39183        LARGE_INTEGER*))aSyscall[51].pCurrent)
39184
39185  { "ReadFile",                (SYSCALL)ReadFile,                0 },
39186
39187#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
39188        LPOVERLAPPED))aSyscall[52].pCurrent)
39189
39190  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
39191
39192#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
39193
39194#if !SQLITE_OS_WINRT
39195  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
39196#else
39197  { "SetFilePointer",          (SYSCALL)0,                       0 },
39198#endif
39199
39200#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
39201        DWORD))aSyscall[54].pCurrent)
39202
39203#if !SQLITE_OS_WINRT
39204  { "Sleep",                   (SYSCALL)Sleep,                   0 },
39205#else
39206  { "Sleep",                   (SYSCALL)0,                       0 },
39207#endif
39208
39209#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
39210
39211  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
39212
39213#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
39214        LPFILETIME))aSyscall[56].pCurrent)
39215
39216#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
39217  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
39218#else
39219  { "UnlockFile",              (SYSCALL)0,                       0 },
39220#endif
39221
39222#ifndef osUnlockFile
39223#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
39224        DWORD))aSyscall[57].pCurrent)
39225#endif
39226
39227#if !SQLITE_OS_WINCE
39228  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
39229#else
39230  { "UnlockFileEx",            (SYSCALL)0,                       0 },
39231#endif
39232
39233#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
39234        LPOVERLAPPED))aSyscall[58].pCurrent)
39235
39236#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
39237  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
39238#else
39239  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
39240#endif
39241
39242#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
39243
39244  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
39245
39246#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
39247        LPCSTR,LPBOOL))aSyscall[60].pCurrent)
39248
39249  { "WriteFile",               (SYSCALL)WriteFile,               0 },
39250
39251#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
39252        LPOVERLAPPED))aSyscall[61].pCurrent)
39253
39254#if SQLITE_OS_WINRT
39255  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
39256#else
39257  { "CreateEventExW",          (SYSCALL)0,                       0 },
39258#endif
39259
39260#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
39261        DWORD,DWORD))aSyscall[62].pCurrent)
39262
39263#if !SQLITE_OS_WINRT
39264  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
39265#else
39266  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
39267#endif
39268
39269#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
39270        DWORD))aSyscall[63].pCurrent)
39271
39272#if !SQLITE_OS_WINCE
39273  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
39274#else
39275  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
39276#endif
39277
39278#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
39279        BOOL))aSyscall[64].pCurrent)
39280
39281#if SQLITE_OS_WINRT
39282  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
39283#else
39284  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
39285#endif
39286
39287#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
39288        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
39289
39290#if SQLITE_OS_WINRT
39291  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
39292#else
39293  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
39294#endif
39295
39296#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
39297        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
39298
39299#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
39300  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
39301#else
39302  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
39303#endif
39304
39305#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
39306        SIZE_T))aSyscall[67].pCurrent)
39307
39308#if SQLITE_OS_WINRT
39309  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
39310#else
39311  { "CreateFile2",             (SYSCALL)0,                       0 },
39312#endif
39313
39314#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
39315        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
39316
39317#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
39318  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
39319#else
39320  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
39321#endif
39322
39323#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
39324        DWORD))aSyscall[69].pCurrent)
39325
39326#if SQLITE_OS_WINRT
39327  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
39328#else
39329  { "GetTickCount64",          (SYSCALL)0,                       0 },
39330#endif
39331
39332#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
39333
39334#if SQLITE_OS_WINRT
39335  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
39336#else
39337  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
39338#endif
39339
39340#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
39341        LPSYSTEM_INFO))aSyscall[71].pCurrent)
39342
39343#if defined(SQLITE_WIN32_HAS_ANSI)
39344  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
39345#else
39346  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
39347#endif
39348
39349#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
39350
39351#if defined(SQLITE_WIN32_HAS_WIDE)
39352  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
39353#else
39354  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
39355#endif
39356
39357#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
39358
39359  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
39360
39361#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
39362
39363#if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
39364  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
39365#else
39366  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
39367#endif
39368
39369#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
39370        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
39371
39372/*
39373** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
39374**       is really just a macro that uses a compiler intrinsic (e.g. x64).
39375**       So do not try to make this is into a redefinable interface.
39376*/
39377#if defined(InterlockedCompareExchange)
39378  { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
39379
39380#define osInterlockedCompareExchange InterlockedCompareExchange
39381#else
39382  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
39383
39384#define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
39385        SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
39386#endif /* defined(InterlockedCompareExchange) */
39387
39388#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
39389  { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
39390#else
39391  { "UuidCreate",               (SYSCALL)0,                      0 },
39392#endif
39393
39394#define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
39395
39396#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
39397  { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
39398#else
39399  { "UuidCreateSequential",     (SYSCALL)0,                      0 },
39400#endif
39401
39402#define osUuidCreateSequential \
39403        ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
39404
39405#if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
39406  { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
39407#else
39408  { "FlushViewOfFile",          (SYSCALL)0,                      0 },
39409#endif
39410
39411#define osFlushViewOfFile \
39412        ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
39413
39414}; /* End of the overrideable system calls */
39415
39416/*
39417** This is the xSetSystemCall() method of sqlite3_vfs for all of the
39418** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
39419** system call pointer, or SQLITE_NOTFOUND if there is no configurable
39420** system call named zName.
39421*/
39422static int winSetSystemCall(
39423  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
39424  const char *zName,            /* Name of system call to override */
39425  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
39426){
39427  unsigned int i;
39428  int rc = SQLITE_NOTFOUND;
39429
39430  UNUSED_PARAMETER(pNotUsed);
39431  if( zName==0 ){
39432    /* If no zName is given, restore all system calls to their default
39433    ** settings and return NULL
39434    */
39435    rc = SQLITE_OK;
39436    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
39437      if( aSyscall[i].pDefault ){
39438        aSyscall[i].pCurrent = aSyscall[i].pDefault;
39439      }
39440    }
39441  }else{
39442    /* If zName is specified, operate on only the one system call
39443    ** specified.
39444    */
39445    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
39446      if( strcmp(zName, aSyscall[i].zName)==0 ){
39447        if( aSyscall[i].pDefault==0 ){
39448          aSyscall[i].pDefault = aSyscall[i].pCurrent;
39449        }
39450        rc = SQLITE_OK;
39451        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
39452        aSyscall[i].pCurrent = pNewFunc;
39453        break;
39454      }
39455    }
39456  }
39457  return rc;
39458}
39459
39460/*
39461** Return the value of a system call.  Return NULL if zName is not a
39462** recognized system call name.  NULL is also returned if the system call
39463** is currently undefined.
39464*/
39465static sqlite3_syscall_ptr winGetSystemCall(
39466  sqlite3_vfs *pNotUsed,
39467  const char *zName
39468){
39469  unsigned int i;
39470
39471  UNUSED_PARAMETER(pNotUsed);
39472  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
39473    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
39474  }
39475  return 0;
39476}
39477
39478/*
39479** Return the name of the first system call after zName.  If zName==NULL
39480** then return the name of the first system call.  Return NULL if zName
39481** is the last system call or if zName is not the name of a valid
39482** system call.
39483*/
39484static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
39485  int i = -1;
39486
39487  UNUSED_PARAMETER(p);
39488  if( zName ){
39489    for(i=0; i<ArraySize(aSyscall)-1; i++){
39490      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
39491    }
39492  }
39493  for(i++; i<ArraySize(aSyscall); i++){
39494    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
39495  }
39496  return 0;
39497}
39498
39499#ifdef SQLITE_WIN32_MALLOC
39500/*
39501** If a Win32 native heap has been configured, this function will attempt to
39502** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
39503** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
39504** "pnLargest" argument, if non-zero, will be used to return the size of the
39505** largest committed free block in the heap, in bytes.
39506*/
39507SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
39508  int rc = SQLITE_OK;
39509  UINT nLargest = 0;
39510  HANDLE hHeap;
39511
39512  winMemAssertMagic();
39513  hHeap = winMemGetHeap();
39514  assert( hHeap!=0 );
39515  assert( hHeap!=INVALID_HANDLE_VALUE );
39516#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39517  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39518#endif
39519#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
39520  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
39521    DWORD lastErrno = osGetLastError();
39522    if( lastErrno==NO_ERROR ){
39523      sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
39524                  (void*)hHeap);
39525      rc = SQLITE_NOMEM_BKPT;
39526    }else{
39527      sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
39528                  osGetLastError(), (void*)hHeap);
39529      rc = SQLITE_ERROR;
39530    }
39531  }
39532#else
39533  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
39534              (void*)hHeap);
39535  rc = SQLITE_NOTFOUND;
39536#endif
39537  if( pnLargest ) *pnLargest = nLargest;
39538  return rc;
39539}
39540
39541/*
39542** If a Win32 native heap has been configured, this function will attempt to
39543** destroy and recreate it.  If the Win32 native heap is not isolated and/or
39544** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
39545** be returned and no changes will be made to the Win32 native heap.
39546*/
39547SQLITE_API int sqlite3_win32_reset_heap(){
39548  int rc;
39549  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
39550  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
39551  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
39552  MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
39553  sqlite3_mutex_enter(pMaster);
39554  sqlite3_mutex_enter(pMem);
39555  winMemAssertMagic();
39556  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
39557    /*
39558    ** At this point, there should be no outstanding memory allocations on
39559    ** the heap.  Also, since both the master and memsys locks are currently
39560    ** being held by us, no other function (i.e. from another thread) should
39561    ** be able to even access the heap.  Attempt to destroy and recreate our
39562    ** isolated Win32 native heap now.
39563    */
39564    assert( winMemGetHeap()!=NULL );
39565    assert( winMemGetOwned() );
39566    assert( sqlite3_memory_used()==0 );
39567    winMemShutdown(winMemGetDataPtr());
39568    assert( winMemGetHeap()==NULL );
39569    assert( !winMemGetOwned() );
39570    assert( sqlite3_memory_used()==0 );
39571    rc = winMemInit(winMemGetDataPtr());
39572    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
39573    assert( rc!=SQLITE_OK || winMemGetOwned() );
39574    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
39575  }else{
39576    /*
39577    ** The Win32 native heap cannot be modified because it may be in use.
39578    */
39579    rc = SQLITE_BUSY;
39580  }
39581  sqlite3_mutex_leave(pMem);
39582  sqlite3_mutex_leave(pMaster);
39583  return rc;
39584}
39585#endif /* SQLITE_WIN32_MALLOC */
39586
39587/*
39588** This function outputs the specified (ANSI) string to the Win32 debugger
39589** (if available).
39590*/
39591
39592SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
39593  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
39594  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
39595  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
39596  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
39597#ifdef SQLITE_ENABLE_API_ARMOR
39598  if( !zBuf ){
39599    (void)SQLITE_MISUSE_BKPT;
39600    return;
39601  }
39602#endif
39603#if defined(SQLITE_WIN32_HAS_ANSI)
39604  if( nMin>0 ){
39605    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39606    memcpy(zDbgBuf, zBuf, nMin);
39607    osOutputDebugStringA(zDbgBuf);
39608  }else{
39609    osOutputDebugStringA(zBuf);
39610  }
39611#elif defined(SQLITE_WIN32_HAS_WIDE)
39612  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39613  if ( osMultiByteToWideChar(
39614          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
39615          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
39616    return;
39617  }
39618  osOutputDebugStringW((LPCWSTR)zDbgBuf);
39619#else
39620  if( nMin>0 ){
39621    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
39622    memcpy(zDbgBuf, zBuf, nMin);
39623    fprintf(stderr, "%s", zDbgBuf);
39624  }else{
39625    fprintf(stderr, "%s", zBuf);
39626  }
39627#endif
39628}
39629
39630/*
39631** The following routine suspends the current thread for at least ms
39632** milliseconds.  This is equivalent to the Win32 Sleep() interface.
39633*/
39634#if SQLITE_OS_WINRT
39635static HANDLE sleepObj = NULL;
39636#endif
39637
39638SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
39639#if SQLITE_OS_WINRT
39640  if ( sleepObj==NULL ){
39641    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
39642                                SYNCHRONIZE);
39643  }
39644  assert( sleepObj!=NULL );
39645  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
39646#else
39647  osSleep(milliseconds);
39648#endif
39649}
39650
39651#if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
39652        SQLITE_THREADSAFE>0
39653SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
39654  DWORD rc;
39655  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
39656                                       TRUE))==WAIT_IO_COMPLETION ){}
39657  return rc;
39658}
39659#endif
39660
39661/*
39662** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
39663** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
39664**
39665** Here is an interesting observation:  Win95, Win98, and WinME lack
39666** the LockFileEx() API.  But we can still statically link against that
39667** API as long as we don't call it when running Win95/98/ME.  A call to
39668** this routine is used to determine if the host is Win95/98/ME or
39669** WinNT/2K/XP so that we will know whether or not we can safely call
39670** the LockFileEx() API.
39671*/
39672
39673#if !SQLITE_WIN32_GETVERSIONEX
39674# define osIsNT()  (1)
39675#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
39676# define osIsNT()  (1)
39677#elif !defined(SQLITE_WIN32_HAS_WIDE)
39678# define osIsNT()  (0)
39679#else
39680# define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
39681#endif
39682
39683/*
39684** This function determines if the machine is running a version of Windows
39685** based on the NT kernel.
39686*/
39687SQLITE_API int sqlite3_win32_is_nt(void){
39688#if SQLITE_OS_WINRT
39689  /*
39690  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
39691  **       kernel.
39692  */
39693  return 1;
39694#elif SQLITE_WIN32_GETVERSIONEX
39695  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
39696#if defined(SQLITE_WIN32_HAS_ANSI)
39697    OSVERSIONINFOA sInfo;
39698    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
39699    osGetVersionExA(&sInfo);
39700    osInterlockedCompareExchange(&sqlite3_os_type,
39701        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
39702#elif defined(SQLITE_WIN32_HAS_WIDE)
39703    OSVERSIONINFOW sInfo;
39704    sInfo.dwOSVersionInfoSize = sizeof(sInfo);
39705    osGetVersionExW(&sInfo);
39706    osInterlockedCompareExchange(&sqlite3_os_type,
39707        (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
39708#endif
39709  }
39710  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
39711#elif SQLITE_TEST
39712  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
39713#else
39714  /*
39715  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
39716  **       deprecated are always assumed to be based on the NT kernel.
39717  */
39718  return 1;
39719#endif
39720}
39721
39722#ifdef SQLITE_WIN32_MALLOC
39723/*
39724** Allocate nBytes of memory.
39725*/
39726static void *winMemMalloc(int nBytes){
39727  HANDLE hHeap;
39728  void *p;
39729
39730  winMemAssertMagic();
39731  hHeap = winMemGetHeap();
39732  assert( hHeap!=0 );
39733  assert( hHeap!=INVALID_HANDLE_VALUE );
39734#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39735  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39736#endif
39737  assert( nBytes>=0 );
39738  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
39739  if( !p ){
39740    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
39741                nBytes, osGetLastError(), (void*)hHeap);
39742  }
39743  return p;
39744}
39745
39746/*
39747** Free memory.
39748*/
39749static void winMemFree(void *pPrior){
39750  HANDLE hHeap;
39751
39752  winMemAssertMagic();
39753  hHeap = winMemGetHeap();
39754  assert( hHeap!=0 );
39755  assert( hHeap!=INVALID_HANDLE_VALUE );
39756#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39757  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
39758#endif
39759  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
39760  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
39761    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
39762                pPrior, osGetLastError(), (void*)hHeap);
39763  }
39764}
39765
39766/*
39767** Change the size of an existing memory allocation
39768*/
39769static void *winMemRealloc(void *pPrior, int nBytes){
39770  HANDLE hHeap;
39771  void *p;
39772
39773  winMemAssertMagic();
39774  hHeap = winMemGetHeap();
39775  assert( hHeap!=0 );
39776  assert( hHeap!=INVALID_HANDLE_VALUE );
39777#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39778  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
39779#endif
39780  assert( nBytes>=0 );
39781  if( !pPrior ){
39782    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
39783  }else{
39784    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
39785  }
39786  if( !p ){
39787    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
39788                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
39789                (void*)hHeap);
39790  }
39791  return p;
39792}
39793
39794/*
39795** Return the size of an outstanding allocation, in bytes.
39796*/
39797static int winMemSize(void *p){
39798  HANDLE hHeap;
39799  SIZE_T n;
39800
39801  winMemAssertMagic();
39802  hHeap = winMemGetHeap();
39803  assert( hHeap!=0 );
39804  assert( hHeap!=INVALID_HANDLE_VALUE );
39805#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39806  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
39807#endif
39808  if( !p ) return 0;
39809  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
39810  if( n==(SIZE_T)-1 ){
39811    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
39812                p, osGetLastError(), (void*)hHeap);
39813    return 0;
39814  }
39815  return (int)n;
39816}
39817
39818/*
39819** Round up a request size to the next valid allocation size.
39820*/
39821static int winMemRoundup(int n){
39822  return n;
39823}
39824
39825/*
39826** Initialize this module.
39827*/
39828static int winMemInit(void *pAppData){
39829  winMemData *pWinMemData = (winMemData *)pAppData;
39830
39831  if( !pWinMemData ) return SQLITE_ERROR;
39832  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
39833  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
39834
39835#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
39836  if( !pWinMemData->hHeap ){
39837    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
39838    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
39839    if( dwMaximumSize==0 ){
39840      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
39841    }else if( dwInitialSize>dwMaximumSize ){
39842      dwInitialSize = dwMaximumSize;
39843    }
39844    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
39845                                      dwInitialSize, dwMaximumSize);
39846    if( !pWinMemData->hHeap ){
39847      sqlite3_log(SQLITE_NOMEM,
39848          "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
39849          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
39850          dwMaximumSize);
39851      return SQLITE_NOMEM_BKPT;
39852    }
39853    pWinMemData->bOwned = TRUE;
39854    assert( pWinMemData->bOwned );
39855  }
39856#else
39857  pWinMemData->hHeap = osGetProcessHeap();
39858  if( !pWinMemData->hHeap ){
39859    sqlite3_log(SQLITE_NOMEM,
39860        "failed to GetProcessHeap (%lu)", osGetLastError());
39861    return SQLITE_NOMEM_BKPT;
39862  }
39863  pWinMemData->bOwned = FALSE;
39864  assert( !pWinMemData->bOwned );
39865#endif
39866  assert( pWinMemData->hHeap!=0 );
39867  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
39868#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39869  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39870#endif
39871  return SQLITE_OK;
39872}
39873
39874/*
39875** Deinitialize this module.
39876*/
39877static void winMemShutdown(void *pAppData){
39878  winMemData *pWinMemData = (winMemData *)pAppData;
39879
39880  if( !pWinMemData ) return;
39881  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
39882  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
39883
39884  if( pWinMemData->hHeap ){
39885    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
39886#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
39887    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
39888#endif
39889    if( pWinMemData->bOwned ){
39890      if( !osHeapDestroy(pWinMemData->hHeap) ){
39891        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
39892                    osGetLastError(), (void*)pWinMemData->hHeap);
39893      }
39894      pWinMemData->bOwned = FALSE;
39895    }
39896    pWinMemData->hHeap = NULL;
39897  }
39898}
39899
39900/*
39901** Populate the low-level memory allocation function pointers in
39902** sqlite3GlobalConfig.m with pointers to the routines in this file. The
39903** arguments specify the block of memory to manage.
39904**
39905** This routine is only called by sqlite3_config(), and therefore
39906** is not required to be threadsafe (it is not).
39907*/
39908SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
39909  static const sqlite3_mem_methods winMemMethods = {
39910    winMemMalloc,
39911    winMemFree,
39912    winMemRealloc,
39913    winMemSize,
39914    winMemRoundup,
39915    winMemInit,
39916    winMemShutdown,
39917    &win_mem_data
39918  };
39919  return &winMemMethods;
39920}
39921
39922SQLITE_PRIVATE void sqlite3MemSetDefault(void){
39923  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
39924}
39925#endif /* SQLITE_WIN32_MALLOC */
39926
39927/*
39928** Convert a UTF-8 string to Microsoft Unicode.
39929**
39930** Space to hold the returned string is obtained from sqlite3_malloc().
39931*/
39932static LPWSTR winUtf8ToUnicode(const char *zText){
39933  int nChar;
39934  LPWSTR zWideText;
39935
39936  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
39937  if( nChar==0 ){
39938    return 0;
39939  }
39940  zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
39941  if( zWideText==0 ){
39942    return 0;
39943  }
39944  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
39945                                nChar);
39946  if( nChar==0 ){
39947    sqlite3_free(zWideText);
39948    zWideText = 0;
39949  }
39950  return zWideText;
39951}
39952
39953/*
39954** Convert a Microsoft Unicode string to UTF-8.
39955**
39956** Space to hold the returned string is obtained from sqlite3_malloc().
39957*/
39958static char *winUnicodeToUtf8(LPCWSTR zWideText){
39959  int nByte;
39960  char *zText;
39961
39962  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
39963  if( nByte == 0 ){
39964    return 0;
39965  }
39966  zText = sqlite3MallocZero( nByte );
39967  if( zText==0 ){
39968    return 0;
39969  }
39970  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
39971                                0, 0);
39972  if( nByte == 0 ){
39973    sqlite3_free(zText);
39974    zText = 0;
39975  }
39976  return zText;
39977}
39978
39979/*
39980** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
39981** code page.
39982**
39983** Space to hold the returned string is obtained from sqlite3_malloc().
39984*/
39985static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
39986  int nByte;
39987  LPWSTR zMbcsText;
39988  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
39989
39990  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
39991                                0)*sizeof(WCHAR);
39992  if( nByte==0 ){
39993    return 0;
39994  }
39995  zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
39996  if( zMbcsText==0 ){
39997    return 0;
39998  }
39999  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
40000                                nByte);
40001  if( nByte==0 ){
40002    sqlite3_free(zMbcsText);
40003    zMbcsText = 0;
40004  }
40005  return zMbcsText;
40006}
40007
40008/*
40009** Convert a Microsoft Unicode string to a multi-byte character string,
40010** using the ANSI or OEM code page.
40011**
40012** Space to hold the returned string is obtained from sqlite3_malloc().
40013*/
40014static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
40015  int nByte;
40016  char *zText;
40017  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
40018
40019  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
40020  if( nByte == 0 ){
40021    return 0;
40022  }
40023  zText = sqlite3MallocZero( nByte );
40024  if( zText==0 ){
40025    return 0;
40026  }
40027  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
40028                                nByte, 0, 0);
40029  if( nByte == 0 ){
40030    sqlite3_free(zText);
40031    zText = 0;
40032  }
40033  return zText;
40034}
40035
40036/*
40037** Convert a multi-byte character string to UTF-8.
40038**
40039** Space to hold the returned string is obtained from sqlite3_malloc().
40040*/
40041static char *winMbcsToUtf8(const char *zText, int useAnsi){
40042  char *zTextUtf8;
40043  LPWSTR zTmpWide;
40044
40045  zTmpWide = winMbcsToUnicode(zText, useAnsi);
40046  if( zTmpWide==0 ){
40047    return 0;
40048  }
40049  zTextUtf8 = winUnicodeToUtf8(zTmpWide);
40050  sqlite3_free(zTmpWide);
40051  return zTextUtf8;
40052}
40053
40054/*
40055** Convert a UTF-8 string to a multi-byte character string.
40056**
40057** Space to hold the returned string is obtained from sqlite3_malloc().
40058*/
40059static char *winUtf8ToMbcs(const char *zText, int useAnsi){
40060  char *zTextMbcs;
40061  LPWSTR zTmpWide;
40062
40063  zTmpWide = winUtf8ToUnicode(zText);
40064  if( zTmpWide==0 ){
40065    return 0;
40066  }
40067  zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
40068  sqlite3_free(zTmpWide);
40069  return zTextMbcs;
40070}
40071
40072/*
40073** This is a public wrapper for the winUtf8ToUnicode() function.
40074*/
40075SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
40076#ifdef SQLITE_ENABLE_API_ARMOR
40077  if( !zText ){
40078    (void)SQLITE_MISUSE_BKPT;
40079    return 0;
40080  }
40081#endif
40082#ifndef SQLITE_OMIT_AUTOINIT
40083  if( sqlite3_initialize() ) return 0;
40084#endif
40085  return winUtf8ToUnicode(zText);
40086}
40087
40088/*
40089** This is a public wrapper for the winUnicodeToUtf8() function.
40090*/
40091SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
40092#ifdef SQLITE_ENABLE_API_ARMOR
40093  if( !zWideText ){
40094    (void)SQLITE_MISUSE_BKPT;
40095    return 0;
40096  }
40097#endif
40098#ifndef SQLITE_OMIT_AUTOINIT
40099  if( sqlite3_initialize() ) return 0;
40100#endif
40101  return winUnicodeToUtf8(zWideText);
40102}
40103
40104/*
40105** This is a public wrapper for the winMbcsToUtf8() function.
40106*/
40107SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
40108#ifdef SQLITE_ENABLE_API_ARMOR
40109  if( !zText ){
40110    (void)SQLITE_MISUSE_BKPT;
40111    return 0;
40112  }
40113#endif
40114#ifndef SQLITE_OMIT_AUTOINIT
40115  if( sqlite3_initialize() ) return 0;
40116#endif
40117  return winMbcsToUtf8(zText, osAreFileApisANSI());
40118}
40119
40120/*
40121** This is a public wrapper for the winMbcsToUtf8() function.
40122*/
40123SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
40124#ifdef SQLITE_ENABLE_API_ARMOR
40125  if( !zText ){
40126    (void)SQLITE_MISUSE_BKPT;
40127    return 0;
40128  }
40129#endif
40130#ifndef SQLITE_OMIT_AUTOINIT
40131  if( sqlite3_initialize() ) return 0;
40132#endif
40133  return winMbcsToUtf8(zText, useAnsi);
40134}
40135
40136/*
40137** This is a public wrapper for the winUtf8ToMbcs() function.
40138*/
40139SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
40140#ifdef SQLITE_ENABLE_API_ARMOR
40141  if( !zText ){
40142    (void)SQLITE_MISUSE_BKPT;
40143    return 0;
40144  }
40145#endif
40146#ifndef SQLITE_OMIT_AUTOINIT
40147  if( sqlite3_initialize() ) return 0;
40148#endif
40149  return winUtf8ToMbcs(zText, osAreFileApisANSI());
40150}
40151
40152/*
40153** This is a public wrapper for the winUtf8ToMbcs() function.
40154*/
40155SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
40156#ifdef SQLITE_ENABLE_API_ARMOR
40157  if( !zText ){
40158    (void)SQLITE_MISUSE_BKPT;
40159    return 0;
40160  }
40161#endif
40162#ifndef SQLITE_OMIT_AUTOINIT
40163  if( sqlite3_initialize() ) return 0;
40164#endif
40165  return winUtf8ToMbcs(zText, useAnsi);
40166}
40167
40168/*
40169** This function sets the data directory or the temporary directory based on
40170** the provided arguments.  The type argument must be 1 in order to set the
40171** data directory or 2 in order to set the temporary directory.  The zValue
40172** argument is the name of the directory to use.  The return value will be
40173** SQLITE_OK if successful.
40174*/
40175SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
40176  char **ppDirectory = 0;
40177#ifndef SQLITE_OMIT_AUTOINIT
40178  int rc = sqlite3_initialize();
40179  if( rc ) return rc;
40180#endif
40181  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
40182    ppDirectory = &sqlite3_data_directory;
40183  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
40184    ppDirectory = &sqlite3_temp_directory;
40185  }
40186  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
40187          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
40188  );
40189  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
40190  if( ppDirectory ){
40191    char *zValueUtf8 = 0;
40192    if( zValue && zValue[0] ){
40193      zValueUtf8 = winUnicodeToUtf8(zValue);
40194      if ( zValueUtf8==0 ){
40195        return SQLITE_NOMEM_BKPT;
40196      }
40197    }
40198    sqlite3_free(*ppDirectory);
40199    *ppDirectory = zValueUtf8;
40200    return SQLITE_OK;
40201  }
40202  return SQLITE_ERROR;
40203}
40204
40205/*
40206** The return value of winGetLastErrorMsg
40207** is zero if the error message fits in the buffer, or non-zero
40208** otherwise (if the message was truncated).
40209*/
40210static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
40211  /* FormatMessage returns 0 on failure.  Otherwise it
40212  ** returns the number of TCHARs written to the output
40213  ** buffer, excluding the terminating null char.
40214  */
40215  DWORD dwLen = 0;
40216  char *zOut = 0;
40217
40218  if( osIsNT() ){
40219#if SQLITE_OS_WINRT
40220    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
40221    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
40222                             FORMAT_MESSAGE_IGNORE_INSERTS,
40223                             NULL,
40224                             lastErrno,
40225                             0,
40226                             zTempWide,
40227                             SQLITE_WIN32_MAX_ERRMSG_CHARS,
40228                             0);
40229#else
40230    LPWSTR zTempWide = NULL;
40231    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
40232                             FORMAT_MESSAGE_FROM_SYSTEM |
40233                             FORMAT_MESSAGE_IGNORE_INSERTS,
40234                             NULL,
40235                             lastErrno,
40236                             0,
40237                             (LPWSTR) &zTempWide,
40238                             0,
40239                             0);
40240#endif
40241    if( dwLen > 0 ){
40242      /* allocate a buffer and convert to UTF8 */
40243      sqlite3BeginBenignMalloc();
40244      zOut = winUnicodeToUtf8(zTempWide);
40245      sqlite3EndBenignMalloc();
40246#if !SQLITE_OS_WINRT
40247      /* free the system buffer allocated by FormatMessage */
40248      osLocalFree(zTempWide);
40249#endif
40250    }
40251  }
40252#ifdef SQLITE_WIN32_HAS_ANSI
40253  else{
40254    char *zTemp = NULL;
40255    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
40256                             FORMAT_MESSAGE_FROM_SYSTEM |
40257                             FORMAT_MESSAGE_IGNORE_INSERTS,
40258                             NULL,
40259                             lastErrno,
40260                             0,
40261                             (LPSTR) &zTemp,
40262                             0,
40263                             0);
40264    if( dwLen > 0 ){
40265      /* allocate a buffer and convert to UTF8 */
40266      sqlite3BeginBenignMalloc();
40267      zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
40268      sqlite3EndBenignMalloc();
40269      /* free the system buffer allocated by FormatMessage */
40270      osLocalFree(zTemp);
40271    }
40272  }
40273#endif
40274  if( 0 == dwLen ){
40275    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
40276  }else{
40277    /* copy a maximum of nBuf chars to output buffer */
40278    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
40279    /* free the UTF8 buffer */
40280    sqlite3_free(zOut);
40281  }
40282  return 0;
40283}
40284
40285/*
40286**
40287** This function - winLogErrorAtLine() - is only ever called via the macro
40288** winLogError().
40289**
40290** This routine is invoked after an error occurs in an OS function.
40291** It logs a message using sqlite3_log() containing the current value of
40292** error code and, if possible, the human-readable equivalent from
40293** FormatMessage.
40294**
40295** The first argument passed to the macro should be the error code that
40296** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
40297** The two subsequent arguments should be the name of the OS function that
40298** failed and the associated file-system path, if any.
40299*/
40300#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
40301static int winLogErrorAtLine(
40302  int errcode,                    /* SQLite error code */
40303  DWORD lastErrno,                /* Win32 last error */
40304  const char *zFunc,              /* Name of OS function that failed */
40305  const char *zPath,              /* File path associated with error */
40306  int iLine                       /* Source line number where error occurred */
40307){
40308  char zMsg[500];                 /* Human readable error text */
40309  int i;                          /* Loop counter */
40310
40311  zMsg[0] = 0;
40312  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
40313  assert( errcode!=SQLITE_OK );
40314  if( zPath==0 ) zPath = "";
40315  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
40316  zMsg[i] = 0;
40317  sqlite3_log(errcode,
40318      "os_win.c:%d: (%lu) %s(%s) - %s",
40319      iLine, lastErrno, zFunc, zPath, zMsg
40320  );
40321
40322  return errcode;
40323}
40324
40325/*
40326** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
40327** will be retried following a locking error - probably caused by
40328** antivirus software.  Also the initial delay before the first retry.
40329** The delay increases linearly with each retry.
40330*/
40331#ifndef SQLITE_WIN32_IOERR_RETRY
40332# define SQLITE_WIN32_IOERR_RETRY 10
40333#endif
40334#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
40335# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
40336#endif
40337static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
40338static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
40339
40340/*
40341** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
40342** error code obtained via GetLastError() is eligible to be retried.  It
40343** must accept the error code DWORD as its only argument and should return
40344** non-zero if the error code is transient in nature and the operation
40345** responsible for generating the original error might succeed upon being
40346** retried.  The argument to this macro should be a variable.
40347**
40348** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
40349** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
40350** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
40351** may be used to include additional error codes in the set that should
40352** result in the failing I/O operation being retried by the caller.  If
40353** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
40354** identical to those of the "winIoerrCanRetry1" macro.
40355*/
40356#if !defined(winIoerrCanRetry1)
40357#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
40358                              ((a)==ERROR_SHARING_VIOLATION)    || \
40359                              ((a)==ERROR_LOCK_VIOLATION)       || \
40360                              ((a)==ERROR_DEV_NOT_EXIST)        || \
40361                              ((a)==ERROR_NETNAME_DELETED)      || \
40362                              ((a)==ERROR_SEM_TIMEOUT)          || \
40363                              ((a)==ERROR_NETWORK_UNREACHABLE))
40364#endif
40365
40366/*
40367** If a ReadFile() or WriteFile() error occurs, invoke this routine
40368** to see if it should be retried.  Return TRUE to retry.  Return FALSE
40369** to give up with an error.
40370*/
40371static int winRetryIoerr(int *pnRetry, DWORD *pError){
40372  DWORD e = osGetLastError();
40373  if( *pnRetry>=winIoerrRetry ){
40374    if( pError ){
40375      *pError = e;
40376    }
40377    return 0;
40378  }
40379  if( winIoerrCanRetry1(e) ){
40380    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
40381    ++*pnRetry;
40382    return 1;
40383  }
40384#if defined(winIoerrCanRetry2)
40385  else if( winIoerrCanRetry2(e) ){
40386    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
40387    ++*pnRetry;
40388    return 1;
40389  }
40390#endif
40391  if( pError ){
40392    *pError = e;
40393  }
40394  return 0;
40395}
40396
40397/*
40398** Log a I/O error retry episode.
40399*/
40400static void winLogIoerr(int nRetry, int lineno){
40401  if( nRetry ){
40402    sqlite3_log(SQLITE_NOTICE,
40403      "delayed %dms for lock/sharing conflict at line %d",
40404      winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
40405    );
40406  }
40407}
40408
40409/*
40410** This #if does not rely on the SQLITE_OS_WINCE define because the
40411** corresponding section in "date.c" cannot use it.
40412*/
40413#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
40414    (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
40415/*
40416** The MSVC CRT on Windows CE may not have a localtime() function.
40417** So define a substitute.
40418*/
40419/* #  include <time.h> */
40420struct tm *__cdecl localtime(const time_t *t)
40421{
40422  static struct tm y;
40423  FILETIME uTm, lTm;
40424  SYSTEMTIME pTm;
40425  sqlite3_int64 t64;
40426  t64 = *t;
40427  t64 = (t64 + 11644473600)*10000000;
40428  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
40429  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
40430  osFileTimeToLocalFileTime(&uTm,&lTm);
40431  osFileTimeToSystemTime(&lTm,&pTm);
40432  y.tm_year = pTm.wYear - 1900;
40433  y.tm_mon = pTm.wMonth - 1;
40434  y.tm_wday = pTm.wDayOfWeek;
40435  y.tm_mday = pTm.wDay;
40436  y.tm_hour = pTm.wHour;
40437  y.tm_min = pTm.wMinute;
40438  y.tm_sec = pTm.wSecond;
40439  return &y;
40440}
40441#endif
40442
40443#if SQLITE_OS_WINCE
40444/*************************************************************************
40445** This section contains code for WinCE only.
40446*/
40447#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
40448
40449/*
40450** Acquire a lock on the handle h
40451*/
40452static void winceMutexAcquire(HANDLE h){
40453   DWORD dwErr;
40454   do {
40455     dwErr = osWaitForSingleObject(h, INFINITE);
40456   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
40457}
40458/*
40459** Release a lock acquired by winceMutexAcquire()
40460*/
40461#define winceMutexRelease(h) ReleaseMutex(h)
40462
40463/*
40464** Create the mutex and shared memory used for locking in the file
40465** descriptor pFile
40466*/
40467static int winceCreateLock(const char *zFilename, winFile *pFile){
40468  LPWSTR zTok;
40469  LPWSTR zName;
40470  DWORD lastErrno;
40471  BOOL bLogged = FALSE;
40472  BOOL bInit = TRUE;
40473
40474  zName = winUtf8ToUnicode(zFilename);
40475  if( zName==0 ){
40476    /* out of memory */
40477    return SQLITE_IOERR_NOMEM_BKPT;
40478  }
40479
40480  /* Initialize the local lockdata */
40481  memset(&pFile->local, 0, sizeof(pFile->local));
40482
40483  /* Replace the backslashes from the filename and lowercase it
40484  ** to derive a mutex name. */
40485  zTok = osCharLowerW(zName);
40486  for (;*zTok;zTok++){
40487    if (*zTok == '\\') *zTok = '_';
40488  }
40489
40490  /* Create/open the named mutex */
40491  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
40492  if (!pFile->hMutex){
40493    pFile->lastErrno = osGetLastError();
40494    sqlite3_free(zName);
40495    return winLogError(SQLITE_IOERR, pFile->lastErrno,
40496                       "winceCreateLock1", zFilename);
40497  }
40498
40499  /* Acquire the mutex before continuing */
40500  winceMutexAcquire(pFile->hMutex);
40501
40502  /* Since the names of named mutexes, semaphores, file mappings etc are
40503  ** case-sensitive, take advantage of that by uppercasing the mutex name
40504  ** and using that as the shared filemapping name.
40505  */
40506  osCharUpperW(zName);
40507  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
40508                                        PAGE_READWRITE, 0, sizeof(winceLock),
40509                                        zName);
40510
40511  /* Set a flag that indicates we're the first to create the memory so it
40512  ** must be zero-initialized */
40513  lastErrno = osGetLastError();
40514  if (lastErrno == ERROR_ALREADY_EXISTS){
40515    bInit = FALSE;
40516  }
40517
40518  sqlite3_free(zName);
40519
40520  /* If we succeeded in making the shared memory handle, map it. */
40521  if( pFile->hShared ){
40522    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
40523             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
40524    /* If mapping failed, close the shared memory handle and erase it */
40525    if( !pFile->shared ){
40526      pFile->lastErrno = osGetLastError();
40527      winLogError(SQLITE_IOERR, pFile->lastErrno,
40528                  "winceCreateLock2", zFilename);
40529      bLogged = TRUE;
40530      osCloseHandle(pFile->hShared);
40531      pFile->hShared = NULL;
40532    }
40533  }
40534
40535  /* If shared memory could not be created, then close the mutex and fail */
40536  if( pFile->hShared==NULL ){
40537    if( !bLogged ){
40538      pFile->lastErrno = lastErrno;
40539      winLogError(SQLITE_IOERR, pFile->lastErrno,
40540                  "winceCreateLock3", zFilename);
40541      bLogged = TRUE;
40542    }
40543    winceMutexRelease(pFile->hMutex);
40544    osCloseHandle(pFile->hMutex);
40545    pFile->hMutex = NULL;
40546    return SQLITE_IOERR;
40547  }
40548
40549  /* Initialize the shared memory if we're supposed to */
40550  if( bInit ){
40551    memset(pFile->shared, 0, sizeof(winceLock));
40552  }
40553
40554  winceMutexRelease(pFile->hMutex);
40555  return SQLITE_OK;
40556}
40557
40558/*
40559** Destroy the part of winFile that deals with wince locks
40560*/
40561static void winceDestroyLock(winFile *pFile){
40562  if (pFile->hMutex){
40563    /* Acquire the mutex */
40564    winceMutexAcquire(pFile->hMutex);
40565
40566    /* The following blocks should probably assert in debug mode, but they
40567       are to cleanup in case any locks remained open */
40568    if (pFile->local.nReaders){
40569      pFile->shared->nReaders --;
40570    }
40571    if (pFile->local.bReserved){
40572      pFile->shared->bReserved = FALSE;
40573    }
40574    if (pFile->local.bPending){
40575      pFile->shared->bPending = FALSE;
40576    }
40577    if (pFile->local.bExclusive){
40578      pFile->shared->bExclusive = FALSE;
40579    }
40580
40581    /* De-reference and close our copy of the shared memory handle */
40582    osUnmapViewOfFile(pFile->shared);
40583    osCloseHandle(pFile->hShared);
40584
40585    /* Done with the mutex */
40586    winceMutexRelease(pFile->hMutex);
40587    osCloseHandle(pFile->hMutex);
40588    pFile->hMutex = NULL;
40589  }
40590}
40591
40592/*
40593** An implementation of the LockFile() API of Windows for CE
40594*/
40595static BOOL winceLockFile(
40596  LPHANDLE phFile,
40597  DWORD dwFileOffsetLow,
40598  DWORD dwFileOffsetHigh,
40599  DWORD nNumberOfBytesToLockLow,
40600  DWORD nNumberOfBytesToLockHigh
40601){
40602  winFile *pFile = HANDLE_TO_WINFILE(phFile);
40603  BOOL bReturn = FALSE;
40604
40605  UNUSED_PARAMETER(dwFileOffsetHigh);
40606  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
40607
40608  if (!pFile->hMutex) return TRUE;
40609  winceMutexAcquire(pFile->hMutex);
40610
40611  /* Wanting an exclusive lock? */
40612  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
40613       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
40614    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
40615       pFile->shared->bExclusive = TRUE;
40616       pFile->local.bExclusive = TRUE;
40617       bReturn = TRUE;
40618    }
40619  }
40620
40621  /* Want a read-only lock? */
40622  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
40623           nNumberOfBytesToLockLow == 1){
40624    if (pFile->shared->bExclusive == 0){
40625      pFile->local.nReaders ++;
40626      if (pFile->local.nReaders == 1){
40627        pFile->shared->nReaders ++;
40628      }
40629      bReturn = TRUE;
40630    }
40631  }
40632
40633  /* Want a pending lock? */
40634  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
40635           && nNumberOfBytesToLockLow == 1){
40636    /* If no pending lock has been acquired, then acquire it */
40637    if (pFile->shared->bPending == 0) {
40638      pFile->shared->bPending = TRUE;
40639      pFile->local.bPending = TRUE;
40640      bReturn = TRUE;
40641    }
40642  }
40643
40644  /* Want a reserved lock? */
40645  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
40646           && nNumberOfBytesToLockLow == 1){
40647    if (pFile->shared->bReserved == 0) {
40648      pFile->shared->bReserved = TRUE;
40649      pFile->local.bReserved = TRUE;
40650      bReturn = TRUE;
40651    }
40652  }
40653
40654  winceMutexRelease(pFile->hMutex);
40655  return bReturn;
40656}
40657
40658/*
40659** An implementation of the UnlockFile API of Windows for CE
40660*/
40661static BOOL winceUnlockFile(
40662  LPHANDLE phFile,
40663  DWORD dwFileOffsetLow,
40664  DWORD dwFileOffsetHigh,
40665  DWORD nNumberOfBytesToUnlockLow,
40666  DWORD nNumberOfBytesToUnlockHigh
40667){
40668  winFile *pFile = HANDLE_TO_WINFILE(phFile);
40669  BOOL bReturn = FALSE;
40670
40671  UNUSED_PARAMETER(dwFileOffsetHigh);
40672  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
40673
40674  if (!pFile->hMutex) return TRUE;
40675  winceMutexAcquire(pFile->hMutex);
40676
40677  /* Releasing a reader lock or an exclusive lock */
40678  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
40679    /* Did we have an exclusive lock? */
40680    if (pFile->local.bExclusive){
40681      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
40682      pFile->local.bExclusive = FALSE;
40683      pFile->shared->bExclusive = FALSE;
40684      bReturn = TRUE;
40685    }
40686
40687    /* Did we just have a reader lock? */
40688    else if (pFile->local.nReaders){
40689      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
40690             || nNumberOfBytesToUnlockLow == 1);
40691      pFile->local.nReaders --;
40692      if (pFile->local.nReaders == 0)
40693      {
40694        pFile->shared->nReaders --;
40695      }
40696      bReturn = TRUE;
40697    }
40698  }
40699
40700  /* Releasing a pending lock */
40701  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
40702           && nNumberOfBytesToUnlockLow == 1){
40703    if (pFile->local.bPending){
40704      pFile->local.bPending = FALSE;
40705      pFile->shared->bPending = FALSE;
40706      bReturn = TRUE;
40707    }
40708  }
40709  /* Releasing a reserved lock */
40710  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
40711           && nNumberOfBytesToUnlockLow == 1){
40712    if (pFile->local.bReserved) {
40713      pFile->local.bReserved = FALSE;
40714      pFile->shared->bReserved = FALSE;
40715      bReturn = TRUE;
40716    }
40717  }
40718
40719  winceMutexRelease(pFile->hMutex);
40720  return bReturn;
40721}
40722/*
40723** End of the special code for wince
40724*****************************************************************************/
40725#endif /* SQLITE_OS_WINCE */
40726
40727/*
40728** Lock a file region.
40729*/
40730static BOOL winLockFile(
40731  LPHANDLE phFile,
40732  DWORD flags,
40733  DWORD offsetLow,
40734  DWORD offsetHigh,
40735  DWORD numBytesLow,
40736  DWORD numBytesHigh
40737){
40738#if SQLITE_OS_WINCE
40739  /*
40740  ** NOTE: Windows CE is handled differently here due its lack of the Win32
40741  **       API LockFile.
40742  */
40743  return winceLockFile(phFile, offsetLow, offsetHigh,
40744                       numBytesLow, numBytesHigh);
40745#else
40746  if( osIsNT() ){
40747    OVERLAPPED ovlp;
40748    memset(&ovlp, 0, sizeof(OVERLAPPED));
40749    ovlp.Offset = offsetLow;
40750    ovlp.OffsetHigh = offsetHigh;
40751    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
40752  }else{
40753    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
40754                      numBytesHigh);
40755  }
40756#endif
40757}
40758
40759/*
40760** Unlock a file region.
40761 */
40762static BOOL winUnlockFile(
40763  LPHANDLE phFile,
40764  DWORD offsetLow,
40765  DWORD offsetHigh,
40766  DWORD numBytesLow,
40767  DWORD numBytesHigh
40768){
40769#if SQLITE_OS_WINCE
40770  /*
40771  ** NOTE: Windows CE is handled differently here due its lack of the Win32
40772  **       API UnlockFile.
40773  */
40774  return winceUnlockFile(phFile, offsetLow, offsetHigh,
40775                         numBytesLow, numBytesHigh);
40776#else
40777  if( osIsNT() ){
40778    OVERLAPPED ovlp;
40779    memset(&ovlp, 0, sizeof(OVERLAPPED));
40780    ovlp.Offset = offsetLow;
40781    ovlp.OffsetHigh = offsetHigh;
40782    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
40783  }else{
40784    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
40785                        numBytesHigh);
40786  }
40787#endif
40788}
40789
40790/*****************************************************************************
40791** The next group of routines implement the I/O methods specified
40792** by the sqlite3_io_methods object.
40793******************************************************************************/
40794
40795/*
40796** Some Microsoft compilers lack this definition.
40797*/
40798#ifndef INVALID_SET_FILE_POINTER
40799# define INVALID_SET_FILE_POINTER ((DWORD)-1)
40800#endif
40801
40802/*
40803** Move the current position of the file handle passed as the first
40804** argument to offset iOffset within the file. If successful, return 0.
40805** Otherwise, set pFile->lastErrno and return non-zero.
40806*/
40807static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
40808#if !SQLITE_OS_WINRT
40809  LONG upperBits;                 /* Most sig. 32 bits of new offset */
40810  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
40811  DWORD dwRet;                    /* Value returned by SetFilePointer() */
40812  DWORD lastErrno;                /* Value returned by GetLastError() */
40813
40814  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
40815
40816  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
40817  lowerBits = (LONG)(iOffset & 0xffffffff);
40818
40819  /* API oddity: If successful, SetFilePointer() returns a dword
40820  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
40821  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
40822  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
40823  ** whether an error has actually occurred, it is also necessary to call
40824  ** GetLastError().
40825  */
40826  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
40827
40828  if( (dwRet==INVALID_SET_FILE_POINTER
40829      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
40830    pFile->lastErrno = lastErrno;
40831    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
40832                "winSeekFile", pFile->zPath);
40833    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
40834    return 1;
40835  }
40836
40837  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
40838  return 0;
40839#else
40840  /*
40841  ** Same as above, except that this implementation works for WinRT.
40842  */
40843
40844  LARGE_INTEGER x;                /* The new offset */
40845  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
40846
40847  x.QuadPart = iOffset;
40848  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
40849
40850  if(!bRet){
40851    pFile->lastErrno = osGetLastError();
40852    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
40853                "winSeekFile", pFile->zPath);
40854    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
40855    return 1;
40856  }
40857
40858  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
40859  return 0;
40860#endif
40861}
40862
40863#if SQLITE_MAX_MMAP_SIZE>0
40864/* Forward references to VFS helper methods used for memory mapped files */
40865static int winMapfile(winFile*, sqlite3_int64);
40866static int winUnmapfile(winFile*);
40867#endif
40868
40869/*
40870** Close a file.
40871**
40872** It is reported that an attempt to close a handle might sometimes
40873** fail.  This is a very unreasonable result, but Windows is notorious
40874** for being unreasonable so I do not doubt that it might happen.  If
40875** the close fails, we pause for 100 milliseconds and try again.  As
40876** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
40877** giving up and returning an error.
40878*/
40879#define MX_CLOSE_ATTEMPT 3
40880static int winClose(sqlite3_file *id){
40881  int rc, cnt = 0;
40882  winFile *pFile = (winFile*)id;
40883
40884  assert( id!=0 );
40885#ifndef SQLITE_OMIT_WAL
40886  assert( pFile->pShm==0 );
40887#endif
40888  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
40889  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
40890           osGetCurrentProcessId(), pFile, pFile->h));
40891
40892#if SQLITE_MAX_MMAP_SIZE>0
40893  winUnmapfile(pFile);
40894#endif
40895
40896  do{
40897    rc = osCloseHandle(pFile->h);
40898    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
40899  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
40900#if SQLITE_OS_WINCE
40901#define WINCE_DELETION_ATTEMPTS 3
40902  {
40903    winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
40904    if( pAppData==NULL || !pAppData->bNoLock ){
40905      winceDestroyLock(pFile);
40906    }
40907  }
40908  if( pFile->zDeleteOnClose ){
40909    int cnt = 0;
40910    while(
40911           osDeleteFileW(pFile->zDeleteOnClose)==0
40912        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
40913        && cnt++ < WINCE_DELETION_ATTEMPTS
40914    ){
40915       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
40916    }
40917    sqlite3_free(pFile->zDeleteOnClose);
40918  }
40919#endif
40920  if( rc ){
40921    pFile->h = NULL;
40922  }
40923  OpenCounter(-1);
40924  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
40925           osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
40926  return rc ? SQLITE_OK
40927            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
40928                          "winClose", pFile->zPath);
40929}
40930
40931/*
40932** Read data from a file into a buffer.  Return SQLITE_OK if all
40933** bytes were read successfully and SQLITE_IOERR if anything goes
40934** wrong.
40935*/
40936static int winRead(
40937  sqlite3_file *id,          /* File to read from */
40938  void *pBuf,                /* Write content into this buffer */
40939  int amt,                   /* Number of bytes to read */
40940  sqlite3_int64 offset       /* Begin reading at this offset */
40941){
40942#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40943  OVERLAPPED overlapped;          /* The offset for ReadFile. */
40944#endif
40945  winFile *pFile = (winFile*)id;  /* file handle */
40946  DWORD nRead;                    /* Number of bytes actually read from file */
40947  int nRetry = 0;                 /* Number of retrys */
40948
40949  assert( id!=0 );
40950  assert( amt>0 );
40951  assert( offset>=0 );
40952  SimulateIOError(return SQLITE_IOERR_READ);
40953  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
40954           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
40955           pFile->h, pBuf, amt, offset, pFile->locktype));
40956
40957#if SQLITE_MAX_MMAP_SIZE>0
40958  /* Deal with as much of this read request as possible by transfering
40959  ** data from the memory mapping using memcpy().  */
40960  if( offset<pFile->mmapSize ){
40961    if( offset+amt <= pFile->mmapSize ){
40962      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
40963      OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40964               osGetCurrentProcessId(), pFile, pFile->h));
40965      return SQLITE_OK;
40966    }else{
40967      int nCopy = (int)(pFile->mmapSize - offset);
40968      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
40969      pBuf = &((u8 *)pBuf)[nCopy];
40970      amt -= nCopy;
40971      offset += nCopy;
40972    }
40973  }
40974#endif
40975
40976#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
40977  if( winSeekFile(pFile, offset) ){
40978    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
40979             osGetCurrentProcessId(), pFile, pFile->h));
40980    return SQLITE_FULL;
40981  }
40982  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
40983#else
40984  memset(&overlapped, 0, sizeof(OVERLAPPED));
40985  overlapped.Offset = (LONG)(offset & 0xffffffff);
40986  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
40987  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
40988         osGetLastError()!=ERROR_HANDLE_EOF ){
40989#endif
40990    DWORD lastErrno;
40991    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
40992    pFile->lastErrno = lastErrno;
40993    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
40994             osGetCurrentProcessId(), pFile, pFile->h));
40995    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
40996                       "winRead", pFile->zPath);
40997  }
40998  winLogIoerr(nRetry, __LINE__);
40999  if( nRead<(DWORD)amt ){
41000    /* Unread parts of the buffer must be zero-filled */
41001    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
41002    OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
41003             osGetCurrentProcessId(), pFile, pFile->h));
41004    return SQLITE_IOERR_SHORT_READ;
41005  }
41006
41007  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41008           osGetCurrentProcessId(), pFile, pFile->h));
41009  return SQLITE_OK;
41010}
41011
41012/*
41013** Write data from a buffer into a file.  Return SQLITE_OK on success
41014** or some other error code on failure.
41015*/
41016static int winWrite(
41017  sqlite3_file *id,               /* File to write into */
41018  const void *pBuf,               /* The bytes to be written */
41019  int amt,                        /* Number of bytes to write */
41020  sqlite3_int64 offset            /* Offset into the file to begin writing at */
41021){
41022  int rc = 0;                     /* True if error has occurred, else false */
41023  winFile *pFile = (winFile*)id;  /* File handle */
41024  int nRetry = 0;                 /* Number of retries */
41025
41026  assert( amt>0 );
41027  assert( pFile );
41028  SimulateIOError(return SQLITE_IOERR_WRITE);
41029  SimulateDiskfullError(return SQLITE_FULL);
41030
41031  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
41032           "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
41033           pFile->h, pBuf, amt, offset, pFile->locktype));
41034
41035#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
41036  /* Deal with as much of this write request as possible by transfering
41037  ** data from the memory mapping using memcpy().  */
41038  if( offset<pFile->mmapSize ){
41039    if( offset+amt <= pFile->mmapSize ){
41040      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
41041      OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41042               osGetCurrentProcessId(), pFile, pFile->h));
41043      return SQLITE_OK;
41044    }else{
41045      int nCopy = (int)(pFile->mmapSize - offset);
41046      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
41047      pBuf = &((u8 *)pBuf)[nCopy];
41048      amt -= nCopy;
41049      offset += nCopy;
41050    }
41051  }
41052#endif
41053
41054#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
41055  rc = winSeekFile(pFile, offset);
41056  if( rc==0 ){
41057#else
41058  {
41059#endif
41060#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
41061    OVERLAPPED overlapped;        /* The offset for WriteFile. */
41062#endif
41063    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
41064    int nRem = amt;               /* Number of bytes yet to be written */
41065    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
41066    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
41067
41068#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
41069    memset(&overlapped, 0, sizeof(OVERLAPPED));
41070    overlapped.Offset = (LONG)(offset & 0xffffffff);
41071    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
41072#endif
41073
41074    while( nRem>0 ){
41075#if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
41076      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
41077#else
41078      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
41079#endif
41080        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
41081        break;
41082      }
41083      assert( nWrite==0 || nWrite<=(DWORD)nRem );
41084      if( nWrite==0 || nWrite>(DWORD)nRem ){
41085        lastErrno = osGetLastError();
41086        break;
41087      }
41088#if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
41089      offset += nWrite;
41090      overlapped.Offset = (LONG)(offset & 0xffffffff);
41091      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
41092#endif
41093      aRem += nWrite;
41094      nRem -= nWrite;
41095    }
41096    if( nRem>0 ){
41097      pFile->lastErrno = lastErrno;
41098      rc = 1;
41099    }
41100  }
41101
41102  if( rc ){
41103    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
41104       || ( pFile->lastErrno==ERROR_DISK_FULL )){
41105      OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
41106               osGetCurrentProcessId(), pFile, pFile->h));
41107      return winLogError(SQLITE_FULL, pFile->lastErrno,
41108                         "winWrite1", pFile->zPath);
41109    }
41110    OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
41111             osGetCurrentProcessId(), pFile, pFile->h));
41112    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
41113                       "winWrite2", pFile->zPath);
41114  }else{
41115    winLogIoerr(nRetry, __LINE__);
41116  }
41117  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41118           osGetCurrentProcessId(), pFile, pFile->h));
41119  return SQLITE_OK;
41120}
41121
41122/*
41123** Truncate an open file to a specified size
41124*/
41125static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
41126  winFile *pFile = (winFile*)id;  /* File handle object */
41127  int rc = SQLITE_OK;             /* Return code for this function */
41128  DWORD lastErrno;
41129
41130  assert( pFile );
41131  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
41132  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
41133           osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
41134
41135  /* If the user has configured a chunk-size for this file, truncate the
41136  ** file so that it consists of an integer number of chunks (i.e. the
41137  ** actual file size after the operation may be larger than the requested
41138  ** size).
41139  */
41140  if( pFile->szChunk>0 ){
41141    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
41142  }
41143
41144  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
41145  if( winSeekFile(pFile, nByte) ){
41146    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
41147                     "winTruncate1", pFile->zPath);
41148  }else if( 0==osSetEndOfFile(pFile->h) &&
41149            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
41150    pFile->lastErrno = lastErrno;
41151    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
41152                     "winTruncate2", pFile->zPath);
41153  }
41154
41155#if SQLITE_MAX_MMAP_SIZE>0
41156  /* If the file was truncated to a size smaller than the currently
41157  ** mapped region, reduce the effective mapping size as well. SQLite will
41158  ** use read() and write() to access data beyond this point from now on.
41159  */
41160  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
41161    pFile->mmapSize = nByte;
41162  }
41163#endif
41164
41165  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
41166           osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
41167  return rc;
41168}
41169
41170#ifdef SQLITE_TEST
41171/*
41172** Count the number of fullsyncs and normal syncs.  This is used to test
41173** that syncs and fullsyncs are occuring at the right times.
41174*/
41175SQLITE_API int sqlite3_sync_count = 0;
41176SQLITE_API int sqlite3_fullsync_count = 0;
41177#endif
41178
41179/*
41180** Make sure all writes to a particular file are committed to disk.
41181*/
41182static int winSync(sqlite3_file *id, int flags){
41183#ifndef SQLITE_NO_SYNC
41184  /*
41185  ** Used only when SQLITE_NO_SYNC is not defined.
41186   */
41187  BOOL rc;
41188#endif
41189#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
41190    defined(SQLITE_HAVE_OS_TRACE)
41191  /*
41192  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
41193  ** OSTRACE() macros.
41194   */
41195  winFile *pFile = (winFile*)id;
41196#else
41197  UNUSED_PARAMETER(id);
41198#endif
41199
41200  assert( pFile );
41201  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
41202  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
41203      || (flags&0x0F)==SQLITE_SYNC_FULL
41204  );
41205
41206  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
41207  ** line is to test that doing so does not cause any problems.
41208  */
41209  SimulateDiskfullError( return SQLITE_FULL );
41210
41211  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
41212           osGetCurrentProcessId(), pFile, pFile->h, flags,
41213           pFile->locktype));
41214
41215#ifndef SQLITE_TEST
41216  UNUSED_PARAMETER(flags);
41217#else
41218  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
41219    sqlite3_fullsync_count++;
41220  }
41221  sqlite3_sync_count++;
41222#endif
41223
41224  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
41225  ** no-op
41226  */
41227#ifdef SQLITE_NO_SYNC
41228  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41229           osGetCurrentProcessId(), pFile, pFile->h));
41230  return SQLITE_OK;
41231#else
41232#if SQLITE_MAX_MMAP_SIZE>0
41233  if( pFile->pMapRegion ){
41234    if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
41235      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
41236               "rc=SQLITE_OK\n", osGetCurrentProcessId(),
41237               pFile, pFile->pMapRegion));
41238    }else{
41239      pFile->lastErrno = osGetLastError();
41240      OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
41241               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
41242               pFile, pFile->pMapRegion));
41243      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41244                         "winSync1", pFile->zPath);
41245    }
41246  }
41247#endif
41248  rc = osFlushFileBuffers(pFile->h);
41249  SimulateIOError( rc=FALSE );
41250  if( rc ){
41251    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
41252             osGetCurrentProcessId(), pFile, pFile->h));
41253    return SQLITE_OK;
41254  }else{
41255    pFile->lastErrno = osGetLastError();
41256    OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
41257             osGetCurrentProcessId(), pFile, pFile->h));
41258    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
41259                       "winSync2", pFile->zPath);
41260  }
41261#endif
41262}
41263
41264/*
41265** Determine the current size of a file in bytes
41266*/
41267static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
41268  winFile *pFile = (winFile*)id;
41269  int rc = SQLITE_OK;
41270
41271  assert( id!=0 );
41272  assert( pSize!=0 );
41273  SimulateIOError(return SQLITE_IOERR_FSTAT);
41274  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
41275
41276#if SQLITE_OS_WINRT
41277  {
41278    FILE_STANDARD_INFO info;
41279    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
41280                                     &info, sizeof(info)) ){
41281      *pSize = info.EndOfFile.QuadPart;
41282    }else{
41283      pFile->lastErrno = osGetLastError();
41284      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
41285                       "winFileSize", pFile->zPath);
41286    }
41287  }
41288#else
41289  {
41290    DWORD upperBits;
41291    DWORD lowerBits;
41292    DWORD lastErrno;
41293
41294    lowerBits = osGetFileSize(pFile->h, &upperBits);
41295    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
41296    if(   (lowerBits == INVALID_FILE_SIZE)
41297       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
41298      pFile->lastErrno = lastErrno;
41299      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
41300                       "winFileSize", pFile->zPath);
41301    }
41302  }
41303#endif
41304  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
41305           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
41306  return rc;
41307}
41308
41309/*
41310** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
41311*/
41312#ifndef LOCKFILE_FAIL_IMMEDIATELY
41313# define LOCKFILE_FAIL_IMMEDIATELY 1
41314#endif
41315
41316#ifndef LOCKFILE_EXCLUSIVE_LOCK
41317# define LOCKFILE_EXCLUSIVE_LOCK 2
41318#endif
41319
41320/*
41321** Historically, SQLite has used both the LockFile and LockFileEx functions.
41322** When the LockFile function was used, it was always expected to fail
41323** immediately if the lock could not be obtained.  Also, it always expected to
41324** obtain an exclusive lock.  These flags are used with the LockFileEx function
41325** and reflect those expectations; therefore, they should not be changed.
41326*/
41327#ifndef SQLITE_LOCKFILE_FLAGS
41328# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
41329                                  LOCKFILE_EXCLUSIVE_LOCK)
41330#endif
41331
41332/*
41333** Currently, SQLite never calls the LockFileEx function without wanting the
41334** call to fail immediately if the lock cannot be obtained.
41335*/
41336#ifndef SQLITE_LOCKFILEEX_FLAGS
41337# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
41338#endif
41339
41340/*
41341** Acquire a reader lock.
41342** Different API routines are called depending on whether or not this
41343** is Win9x or WinNT.
41344*/
41345static int winGetReadLock(winFile *pFile){
41346  int res;
41347  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
41348  if( osIsNT() ){
41349#if SQLITE_OS_WINCE
41350    /*
41351    ** NOTE: Windows CE is handled differently here due its lack of the Win32
41352    **       API LockFileEx.
41353    */
41354    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
41355#else
41356    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
41357                      SHARED_SIZE, 0);
41358#endif
41359  }
41360#ifdef SQLITE_WIN32_HAS_ANSI
41361  else{
41362    int lk;
41363    sqlite3_randomness(sizeof(lk), &lk);
41364    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
41365    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
41366                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
41367  }
41368#endif
41369  if( res == 0 ){
41370    pFile->lastErrno = osGetLastError();
41371    /* No need to log a failure to lock */
41372  }
41373  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
41374  return res;
41375}
41376
41377/*
41378** Undo a readlock
41379*/
41380static int winUnlockReadLock(winFile *pFile){
41381  int res;
41382  DWORD lastErrno;
41383  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
41384  if( osIsNT() ){
41385    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
41386  }
41387#ifdef SQLITE_WIN32_HAS_ANSI
41388  else{
41389    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
41390  }
41391#endif
41392  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
41393    pFile->lastErrno = lastErrno;
41394    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
41395                "winUnlockReadLock", pFile->zPath);
41396  }
41397  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
41398  return res;
41399}
41400
41401/*
41402** Lock the file with the lock specified by parameter locktype - one
41403** of the following:
41404**
41405**     (1) SHARED_LOCK
41406**     (2) RESERVED_LOCK
41407**     (3) PENDING_LOCK
41408**     (4) EXCLUSIVE_LOCK
41409**
41410** Sometimes when requesting one lock state, additional lock states
41411** are inserted in between.  The locking might fail on one of the later
41412** transitions leaving the lock state different from what it started but
41413** still short of its goal.  The following chart shows the allowed
41414** transitions and the inserted intermediate states:
41415**
41416**    UNLOCKED -> SHARED
41417**    SHARED -> RESERVED
41418**    SHARED -> (PENDING) -> EXCLUSIVE
41419**    RESERVED -> (PENDING) -> EXCLUSIVE
41420**    PENDING -> EXCLUSIVE
41421**
41422** This routine will only increase a lock.  The winUnlock() routine
41423** erases all locks at once and returns us immediately to locking level 0.
41424** It is not possible to lower the locking level one step at a time.  You
41425** must go straight to locking level 0.
41426*/
41427static int winLock(sqlite3_file *id, int locktype){
41428  int rc = SQLITE_OK;    /* Return code from subroutines */
41429  int res = 1;           /* Result of a Windows lock call */
41430  int newLocktype;       /* Set pFile->locktype to this value before exiting */
41431  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
41432  winFile *pFile = (winFile*)id;
41433  DWORD lastErrno = NO_ERROR;
41434
41435  assert( id!=0 );
41436  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
41437           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
41438
41439  /* If there is already a lock of this type or more restrictive on the
41440  ** OsFile, do nothing. Don't use the end_lock: exit path, as
41441  ** sqlite3OsEnterMutex() hasn't been called yet.
41442  */
41443  if( pFile->locktype>=locktype ){
41444    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
41445    return SQLITE_OK;
41446  }
41447
41448  /* Do not allow any kind of write-lock on a read-only database
41449  */
41450  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
41451    return SQLITE_IOERR_LOCK;
41452  }
41453
41454  /* Make sure the locking sequence is correct
41455  */
41456  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
41457  assert( locktype!=PENDING_LOCK );
41458  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
41459
41460  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
41461  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
41462  ** the PENDING_LOCK byte is temporary.
41463  */
41464  newLocktype = pFile->locktype;
41465  if( pFile->locktype==NO_LOCK
41466   || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
41467  ){
41468    int cnt = 3;
41469    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
41470                                         PENDING_BYTE, 0, 1, 0))==0 ){
41471      /* Try 3 times to get the pending lock.  This is needed to work
41472      ** around problems caused by indexing and/or anti-virus software on
41473      ** Windows systems.
41474      ** If you are using this code as a model for alternative VFSes, do not
41475      ** copy this retry logic.  It is a hack intended for Windows only.
41476      */
41477      lastErrno = osGetLastError();
41478      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
41479               pFile->h, cnt, res));
41480      if( lastErrno==ERROR_INVALID_HANDLE ){
41481        pFile->lastErrno = lastErrno;
41482        rc = SQLITE_IOERR_LOCK;
41483        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
41484                 pFile->h, cnt, sqlite3ErrName(rc)));
41485        return rc;
41486      }
41487      if( cnt ) sqlite3_win32_sleep(1);
41488    }
41489    gotPendingLock = res;
41490    if( !res ){
41491      lastErrno = osGetLastError();
41492    }
41493  }
41494
41495  /* Acquire a shared lock
41496  */
41497  if( locktype==SHARED_LOCK && res ){
41498    assert( pFile->locktype==NO_LOCK );
41499    res = winGetReadLock(pFile);
41500    if( res ){
41501      newLocktype = SHARED_LOCK;
41502    }else{
41503      lastErrno = osGetLastError();
41504    }
41505  }
41506
41507  /* Acquire a RESERVED lock
41508  */
41509  if( locktype==RESERVED_LOCK && res ){
41510    assert( pFile->locktype==SHARED_LOCK );
41511    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
41512    if( res ){
41513      newLocktype = RESERVED_LOCK;
41514    }else{
41515      lastErrno = osGetLastError();
41516    }
41517  }
41518
41519  /* Acquire a PENDING lock
41520  */
41521  if( locktype==EXCLUSIVE_LOCK && res ){
41522    newLocktype = PENDING_LOCK;
41523    gotPendingLock = 0;
41524  }
41525
41526  /* Acquire an EXCLUSIVE lock
41527  */
41528  if( locktype==EXCLUSIVE_LOCK && res ){
41529    assert( pFile->locktype>=SHARED_LOCK );
41530    res = winUnlockReadLock(pFile);
41531    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
41532                      SHARED_SIZE, 0);
41533    if( res ){
41534      newLocktype = EXCLUSIVE_LOCK;
41535    }else{
41536      lastErrno = osGetLastError();
41537      winGetReadLock(pFile);
41538    }
41539  }
41540
41541  /* If we are holding a PENDING lock that ought to be released, then
41542  ** release it now.
41543  */
41544  if( gotPendingLock && locktype==SHARED_LOCK ){
41545    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
41546  }
41547
41548  /* Update the state of the lock has held in the file descriptor then
41549  ** return the appropriate result code.
41550  */
41551  if( res ){
41552    rc = SQLITE_OK;
41553  }else{
41554    pFile->lastErrno = lastErrno;
41555    rc = SQLITE_BUSY;
41556    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
41557             pFile->h, locktype, newLocktype));
41558  }
41559  pFile->locktype = (u8)newLocktype;
41560  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
41561           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
41562  return rc;
41563}
41564
41565/*
41566** This routine checks if there is a RESERVED lock held on the specified
41567** file by this or any other process. If such a lock is held, return
41568** non-zero, otherwise zero.
41569*/
41570static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
41571  int res;
41572  winFile *pFile = (winFile*)id;
41573
41574  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
41575  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
41576
41577  assert( id!=0 );
41578  if( pFile->locktype>=RESERVED_LOCK ){
41579    res = 1;
41580    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
41581  }else{
41582    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
41583    if( res ){
41584      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
41585    }
41586    res = !res;
41587    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
41588  }
41589  *pResOut = res;
41590  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
41591           pFile->h, pResOut, *pResOut));
41592  return SQLITE_OK;
41593}
41594
41595/*
41596** Lower the locking level on file descriptor id to locktype.  locktype
41597** must be either NO_LOCK or SHARED_LOCK.
41598**
41599** If the locking level of the file descriptor is already at or below
41600** the requested locking level, this routine is a no-op.
41601**
41602** It is not possible for this routine to fail if the second argument
41603** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
41604** might return SQLITE_IOERR;
41605*/
41606static int winUnlock(sqlite3_file *id, int locktype){
41607  int type;
41608  winFile *pFile = (winFile*)id;
41609  int rc = SQLITE_OK;
41610  assert( pFile!=0 );
41611  assert( locktype<=SHARED_LOCK );
41612  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
41613           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
41614  type = pFile->locktype;
41615  if( type>=EXCLUSIVE_LOCK ){
41616    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
41617    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
41618      /* This should never happen.  We should always be able to
41619      ** reacquire the read lock */
41620      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
41621                       "winUnlock", pFile->zPath);
41622    }
41623  }
41624  if( type>=RESERVED_LOCK ){
41625    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
41626  }
41627  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
41628    winUnlockReadLock(pFile);
41629  }
41630  if( type>=PENDING_LOCK ){
41631    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
41632  }
41633  pFile->locktype = (u8)locktype;
41634  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
41635           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
41636  return rc;
41637}
41638
41639/******************************************************************************
41640****************************** No-op Locking **********************************
41641**
41642** Of the various locking implementations available, this is by far the
41643** simplest:  locking is ignored.  No attempt is made to lock the database
41644** file for reading or writing.
41645**
41646** This locking mode is appropriate for use on read-only databases
41647** (ex: databases that are burned into CD-ROM, for example.)  It can
41648** also be used if the application employs some external mechanism to
41649** prevent simultaneous access of the same database by two or more
41650** database connections.  But there is a serious risk of database
41651** corruption if this locking mode is used in situations where multiple
41652** database connections are accessing the same database file at the same
41653** time and one or more of those connections are writing.
41654*/
41655
41656static int winNolockLock(sqlite3_file *id, int locktype){
41657  UNUSED_PARAMETER(id);
41658  UNUSED_PARAMETER(locktype);
41659  return SQLITE_OK;
41660}
41661
41662static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
41663  UNUSED_PARAMETER(id);
41664  UNUSED_PARAMETER(pResOut);
41665  return SQLITE_OK;
41666}
41667
41668static int winNolockUnlock(sqlite3_file *id, int locktype){
41669  UNUSED_PARAMETER(id);
41670  UNUSED_PARAMETER(locktype);
41671  return SQLITE_OK;
41672}
41673
41674/******************* End of the no-op lock implementation *********************
41675******************************************************************************/
41676
41677/*
41678** If *pArg is initially negative then this is a query.  Set *pArg to
41679** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
41680**
41681** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
41682*/
41683static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
41684  if( *pArg<0 ){
41685    *pArg = (pFile->ctrlFlags & mask)!=0;
41686  }else if( (*pArg)==0 ){
41687    pFile->ctrlFlags &= ~mask;
41688  }else{
41689    pFile->ctrlFlags |= mask;
41690  }
41691}
41692
41693/* Forward references to VFS helper methods used for temporary files */
41694static int winGetTempname(sqlite3_vfs *, char **);
41695static int winIsDir(const void *);
41696static BOOL winIsDriveLetterAndColon(const char *);
41697
41698/*
41699** Control and query of the open file handle.
41700*/
41701static int winFileControl(sqlite3_file *id, int op, void *pArg){
41702  winFile *pFile = (winFile*)id;
41703  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
41704  switch( op ){
41705    case SQLITE_FCNTL_LOCKSTATE: {
41706      *(int*)pArg = pFile->locktype;
41707      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41708      return SQLITE_OK;
41709    }
41710    case SQLITE_FCNTL_LAST_ERRNO: {
41711      *(int*)pArg = (int)pFile->lastErrno;
41712      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41713      return SQLITE_OK;
41714    }
41715    case SQLITE_FCNTL_CHUNK_SIZE: {
41716      pFile->szChunk = *(int *)pArg;
41717      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41718      return SQLITE_OK;
41719    }
41720    case SQLITE_FCNTL_SIZE_HINT: {
41721      if( pFile->szChunk>0 ){
41722        sqlite3_int64 oldSz;
41723        int rc = winFileSize(id, &oldSz);
41724        if( rc==SQLITE_OK ){
41725          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
41726          if( newSz>oldSz ){
41727            SimulateIOErrorBenign(1);
41728            rc = winTruncate(id, newSz);
41729            SimulateIOErrorBenign(0);
41730          }
41731        }
41732        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41733        return rc;
41734      }
41735      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41736      return SQLITE_OK;
41737    }
41738    case SQLITE_FCNTL_PERSIST_WAL: {
41739      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
41740      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41741      return SQLITE_OK;
41742    }
41743    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
41744      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
41745      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41746      return SQLITE_OK;
41747    }
41748    case SQLITE_FCNTL_VFSNAME: {
41749      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
41750      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41751      return SQLITE_OK;
41752    }
41753    case SQLITE_FCNTL_WIN32_AV_RETRY: {
41754      int *a = (int*)pArg;
41755      if( a[0]>0 ){
41756        winIoerrRetry = a[0];
41757      }else{
41758        a[0] = winIoerrRetry;
41759      }
41760      if( a[1]>0 ){
41761        winIoerrRetryDelay = a[1];
41762      }else{
41763        a[1] = winIoerrRetryDelay;
41764      }
41765      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41766      return SQLITE_OK;
41767    }
41768    case SQLITE_FCNTL_WIN32_GET_HANDLE: {
41769      LPHANDLE phFile = (LPHANDLE)pArg;
41770      *phFile = pFile->h;
41771      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
41772      return SQLITE_OK;
41773    }
41774#ifdef SQLITE_TEST
41775    case SQLITE_FCNTL_WIN32_SET_HANDLE: {
41776      LPHANDLE phFile = (LPHANDLE)pArg;
41777      HANDLE hOldFile = pFile->h;
41778      pFile->h = *phFile;
41779      *phFile = hOldFile;
41780      OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
41781               hOldFile, pFile->h));
41782      return SQLITE_OK;
41783    }
41784#endif
41785    case SQLITE_FCNTL_TEMPFILENAME: {
41786      char *zTFile = 0;
41787      int rc = winGetTempname(pFile->pVfs, &zTFile);
41788      if( rc==SQLITE_OK ){
41789        *(char**)pArg = zTFile;
41790      }
41791      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41792      return rc;
41793    }
41794#if SQLITE_MAX_MMAP_SIZE>0
41795    case SQLITE_FCNTL_MMAP_SIZE: {
41796      i64 newLimit = *(i64*)pArg;
41797      int rc = SQLITE_OK;
41798      if( newLimit>sqlite3GlobalConfig.mxMmap ){
41799        newLimit = sqlite3GlobalConfig.mxMmap;
41800      }
41801      *(i64*)pArg = pFile->mmapSizeMax;
41802      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
41803        pFile->mmapSizeMax = newLimit;
41804        if( pFile->mmapSize>0 ){
41805          winUnmapfile(pFile);
41806          rc = winMapfile(pFile, -1);
41807        }
41808      }
41809      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
41810      return rc;
41811    }
41812#endif
41813  }
41814  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
41815  return SQLITE_NOTFOUND;
41816}
41817
41818/*
41819** Return the sector size in bytes of the underlying block device for
41820** the specified file. This is almost always 512 bytes, but may be
41821** larger for some devices.
41822**
41823** SQLite code assumes this function cannot fail. It also assumes that
41824** if two files are created in the same file-system directory (i.e.
41825** a database and its journal file) that the sector size will be the
41826** same for both.
41827*/
41828static int winSectorSize(sqlite3_file *id){
41829  (void)id;
41830  return SQLITE_DEFAULT_SECTOR_SIZE;
41831}
41832
41833/*
41834** Return a vector of device characteristics.
41835*/
41836static int winDeviceCharacteristics(sqlite3_file *id){
41837  winFile *p = (winFile*)id;
41838  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
41839         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
41840}
41841
41842/*
41843** Windows will only let you create file view mappings
41844** on allocation size granularity boundaries.
41845** During sqlite3_os_init() we do a GetSystemInfo()
41846** to get the granularity size.
41847*/
41848static SYSTEM_INFO winSysInfo;
41849
41850#ifndef SQLITE_OMIT_WAL
41851
41852/*
41853** Helper functions to obtain and relinquish the global mutex. The
41854** global mutex is used to protect the winLockInfo objects used by
41855** this file, all of which may be shared by multiple threads.
41856**
41857** Function winShmMutexHeld() is used to assert() that the global mutex
41858** is held when required. This function is only used as part of assert()
41859** statements. e.g.
41860**
41861**   winShmEnterMutex()
41862**     assert( winShmMutexHeld() );
41863**   winShmLeaveMutex()
41864*/
41865static void winShmEnterMutex(void){
41866  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41867}
41868static void winShmLeaveMutex(void){
41869  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41870}
41871#ifndef NDEBUG
41872static int winShmMutexHeld(void) {
41873  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
41874}
41875#endif
41876
41877/*
41878** Object used to represent a single file opened and mmapped to provide
41879** shared memory.  When multiple threads all reference the same
41880** log-summary, each thread has its own winFile object, but they all
41881** point to a single instance of this object.  In other words, each
41882** log-summary is opened only once per process.
41883**
41884** winShmMutexHeld() must be true when creating or destroying
41885** this object or while reading or writing the following fields:
41886**
41887**      nRef
41888**      pNext
41889**
41890** The following fields are read-only after the object is created:
41891**
41892**      fid
41893**      zFilename
41894**
41895** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
41896** winShmMutexHeld() is true when reading or writing any other field
41897** in this structure.
41898**
41899*/
41900struct winShmNode {
41901  sqlite3_mutex *mutex;      /* Mutex to access this object */
41902  char *zFilename;           /* Name of the file */
41903  winFile hFile;             /* File handle from winOpen */
41904
41905  int szRegion;              /* Size of shared-memory regions */
41906  int nRegion;               /* Size of array apRegion */
41907  struct ShmRegion {
41908    HANDLE hMap;             /* File handle from CreateFileMapping */
41909    void *pMap;
41910  } *aRegion;
41911  DWORD lastErrno;           /* The Windows errno from the last I/O error */
41912
41913  int nRef;                  /* Number of winShm objects pointing to this */
41914  winShm *pFirst;            /* All winShm objects pointing to this */
41915  winShmNode *pNext;         /* Next in list of all winShmNode objects */
41916#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41917  u8 nextShmId;              /* Next available winShm.id value */
41918#endif
41919};
41920
41921/*
41922** A global array of all winShmNode objects.
41923**
41924** The winShmMutexHeld() must be true while reading or writing this list.
41925*/
41926static winShmNode *winShmNodeList = 0;
41927
41928/*
41929** Structure used internally by this VFS to record the state of an
41930** open shared memory connection.
41931**
41932** The following fields are initialized when this object is created and
41933** are read-only thereafter:
41934**
41935**    winShm.pShmNode
41936**    winShm.id
41937**
41938** All other fields are read/write.  The winShm.pShmNode->mutex must be held
41939** while accessing any read/write fields.
41940*/
41941struct winShm {
41942  winShmNode *pShmNode;      /* The underlying winShmNode object */
41943  winShm *pNext;             /* Next winShm with the same winShmNode */
41944  u8 hasMutex;               /* True if holding the winShmNode mutex */
41945  u16 sharedMask;            /* Mask of shared locks held */
41946  u16 exclMask;              /* Mask of exclusive locks held */
41947#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41948  u8 id;                     /* Id of this connection with its winShmNode */
41949#endif
41950};
41951
41952/*
41953** Constants used for locking
41954*/
41955#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
41956#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
41957
41958/*
41959** Apply advisory locks for all n bytes beginning at ofst.
41960*/
41961#define WINSHM_UNLCK  1
41962#define WINSHM_RDLCK  2
41963#define WINSHM_WRLCK  3
41964static int winShmSystemLock(
41965  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
41966  int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
41967  int ofst,             /* Offset to first byte to be locked/unlocked */
41968  int nByte             /* Number of bytes to lock or unlock */
41969){
41970  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
41971
41972  /* Access to the winShmNode object is serialized by the caller */
41973  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
41974
41975  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
41976           pFile->hFile.h, lockType, ofst, nByte));
41977
41978  /* Release/Acquire the system-level lock */
41979  if( lockType==WINSHM_UNLCK ){
41980    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
41981  }else{
41982    /* Initialize the locking parameters */
41983    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
41984    if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
41985    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
41986  }
41987
41988  if( rc!= 0 ){
41989    rc = SQLITE_OK;
41990  }else{
41991    pFile->lastErrno =  osGetLastError();
41992    rc = SQLITE_BUSY;
41993  }
41994
41995  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
41996           pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
41997           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
41998
41999  return rc;
42000}
42001
42002/* Forward references to VFS methods */
42003static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
42004static int winDelete(sqlite3_vfs *,const char*,int);
42005
42006/*
42007** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
42008**
42009** This is not a VFS shared-memory method; it is a utility function called
42010** by VFS shared-memory methods.
42011*/
42012static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
42013  winShmNode **pp;
42014  winShmNode *p;
42015  assert( winShmMutexHeld() );
42016  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
42017           osGetCurrentProcessId(), deleteFlag));
42018  pp = &winShmNodeList;
42019  while( (p = *pp)!=0 ){
42020    if( p->nRef==0 ){
42021      int i;
42022      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
42023      for(i=0; i<p->nRegion; i++){
42024        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
42025        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
42026                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
42027        UNUSED_VARIABLE_VALUE(bRc);
42028        bRc = osCloseHandle(p->aRegion[i].hMap);
42029        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
42030                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
42031        UNUSED_VARIABLE_VALUE(bRc);
42032      }
42033      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
42034        SimulateIOErrorBenign(1);
42035        winClose((sqlite3_file *)&p->hFile);
42036        SimulateIOErrorBenign(0);
42037      }
42038      if( deleteFlag ){
42039        SimulateIOErrorBenign(1);
42040        sqlite3BeginBenignMalloc();
42041        winDelete(pVfs, p->zFilename, 0);
42042        sqlite3EndBenignMalloc();
42043        SimulateIOErrorBenign(0);
42044      }
42045      *pp = p->pNext;
42046      sqlite3_free(p->aRegion);
42047      sqlite3_free(p);
42048    }else{
42049      pp = &p->pNext;
42050    }
42051  }
42052}
42053
42054/*
42055** Open the shared-memory area associated with database file pDbFd.
42056**
42057** When opening a new shared-memory file, if no other instances of that
42058** file are currently open, in this process or in other processes, then
42059** the file must be truncated to zero length or have its header cleared.
42060*/
42061static int winOpenSharedMemory(winFile *pDbFd){
42062  struct winShm *p;                  /* The connection to be opened */
42063  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
42064  int rc;                            /* Result code */
42065  struct winShmNode *pNew;           /* Newly allocated winShmNode */
42066  int nName;                         /* Size of zName in bytes */
42067
42068  assert( pDbFd->pShm==0 );    /* Not previously opened */
42069
42070  /* Allocate space for the new sqlite3_shm object.  Also speculatively
42071  ** allocate space for a new winShmNode and filename.
42072  */
42073  p = sqlite3MallocZero( sizeof(*p) );
42074  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
42075  nName = sqlite3Strlen30(pDbFd->zPath);
42076  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
42077  if( pNew==0 ){
42078    sqlite3_free(p);
42079    return SQLITE_IOERR_NOMEM_BKPT;
42080  }
42081  pNew->zFilename = (char*)&pNew[1];
42082  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
42083  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
42084
42085  /* Look to see if there is an existing winShmNode that can be used.
42086  ** If no matching winShmNode currently exists, create a new one.
42087  */
42088  winShmEnterMutex();
42089  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
42090    /* TBD need to come up with better match here.  Perhaps
42091    ** use FILE_ID_BOTH_DIR_INFO Structure.
42092    */
42093    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
42094  }
42095  if( pShmNode ){
42096    sqlite3_free(pNew);
42097  }else{
42098    pShmNode = pNew;
42099    pNew = 0;
42100    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
42101    pShmNode->pNext = winShmNodeList;
42102    winShmNodeList = pShmNode;
42103
42104    if( sqlite3GlobalConfig.bCoreMutex ){
42105      pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
42106      if( pShmNode->mutex==0 ){
42107        rc = SQLITE_IOERR_NOMEM_BKPT;
42108        goto shm_open_err;
42109      }
42110    }
42111
42112    rc = winOpen(pDbFd->pVfs,
42113                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
42114                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
42115                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
42116                 0);
42117    if( SQLITE_OK!=rc ){
42118      goto shm_open_err;
42119    }
42120
42121    /* Check to see if another process is holding the dead-man switch.
42122    ** If not, truncate the file to zero length.
42123    */
42124    if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
42125      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
42126      if( rc!=SQLITE_OK ){
42127        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
42128                         "winOpenShm", pDbFd->zPath);
42129      }
42130    }
42131    if( rc==SQLITE_OK ){
42132      winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
42133      rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
42134    }
42135    if( rc ) goto shm_open_err;
42136  }
42137
42138  /* Make the new connection a child of the winShmNode */
42139  p->pShmNode = pShmNode;
42140#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
42141  p->id = pShmNode->nextShmId++;
42142#endif
42143  pShmNode->nRef++;
42144  pDbFd->pShm = p;
42145  winShmLeaveMutex();
42146
42147  /* The reference count on pShmNode has already been incremented under
42148  ** the cover of the winShmEnterMutex() mutex and the pointer from the
42149  ** new (struct winShm) object to the pShmNode has been set. All that is
42150  ** left to do is to link the new object into the linked list starting
42151  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
42152  ** mutex.
42153  */
42154  sqlite3_mutex_enter(pShmNode->mutex);
42155  p->pNext = pShmNode->pFirst;
42156  pShmNode->pFirst = p;
42157  sqlite3_mutex_leave(pShmNode->mutex);
42158  return SQLITE_OK;
42159
42160  /* Jump here on any error */
42161shm_open_err:
42162  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
42163  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
42164  sqlite3_free(p);
42165  sqlite3_free(pNew);
42166  winShmLeaveMutex();
42167  return rc;
42168}
42169
42170/*
42171** Close a connection to shared-memory.  Delete the underlying
42172** storage if deleteFlag is true.
42173*/
42174static int winShmUnmap(
42175  sqlite3_file *fd,          /* Database holding shared memory */
42176  int deleteFlag             /* Delete after closing if true */
42177){
42178  winFile *pDbFd;       /* Database holding shared-memory */
42179  winShm *p;            /* The connection to be closed */
42180  winShmNode *pShmNode; /* The underlying shared-memory file */
42181  winShm **pp;          /* For looping over sibling connections */
42182
42183  pDbFd = (winFile*)fd;
42184  p = pDbFd->pShm;
42185  if( p==0 ) return SQLITE_OK;
42186  pShmNode = p->pShmNode;
42187
42188  /* Remove connection p from the set of connections associated
42189  ** with pShmNode */
42190  sqlite3_mutex_enter(pShmNode->mutex);
42191  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
42192  *pp = p->pNext;
42193
42194  /* Free the connection p */
42195  sqlite3_free(p);
42196  pDbFd->pShm = 0;
42197  sqlite3_mutex_leave(pShmNode->mutex);
42198
42199  /* If pShmNode->nRef has reached 0, then close the underlying
42200  ** shared-memory file, too */
42201  winShmEnterMutex();
42202  assert( pShmNode->nRef>0 );
42203  pShmNode->nRef--;
42204  if( pShmNode->nRef==0 ){
42205    winShmPurge(pDbFd->pVfs, deleteFlag);
42206  }
42207  winShmLeaveMutex();
42208
42209  return SQLITE_OK;
42210}
42211
42212/*
42213** Change the lock state for a shared-memory segment.
42214*/
42215static int winShmLock(
42216  sqlite3_file *fd,          /* Database file holding the shared memory */
42217  int ofst,                  /* First lock to acquire or release */
42218  int n,                     /* Number of locks to acquire or release */
42219  int flags                  /* What to do with the lock */
42220){
42221  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
42222  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
42223  winShm *pX;                           /* For looping over all siblings */
42224  winShmNode *pShmNode = p->pShmNode;
42225  int rc = SQLITE_OK;                   /* Result code */
42226  u16 mask;                             /* Mask of locks to take or release */
42227
42228  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
42229  assert( n>=1 );
42230  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
42231       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
42232       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
42233       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
42234  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
42235
42236  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
42237  assert( n>1 || mask==(1<<ofst) );
42238  sqlite3_mutex_enter(pShmNode->mutex);
42239  if( flags & SQLITE_SHM_UNLOCK ){
42240    u16 allMask = 0; /* Mask of locks held by siblings */
42241
42242    /* See if any siblings hold this same lock */
42243    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
42244      if( pX==p ) continue;
42245      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
42246      allMask |= pX->sharedMask;
42247    }
42248
42249    /* Unlock the system-level locks */
42250    if( (mask & allMask)==0 ){
42251      rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
42252    }else{
42253      rc = SQLITE_OK;
42254    }
42255
42256    /* Undo the local locks */
42257    if( rc==SQLITE_OK ){
42258      p->exclMask &= ~mask;
42259      p->sharedMask &= ~mask;
42260    }
42261  }else if( flags & SQLITE_SHM_SHARED ){
42262    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
42263
42264    /* Find out which shared locks are already held by sibling connections.
42265    ** If any sibling already holds an exclusive lock, go ahead and return
42266    ** SQLITE_BUSY.
42267    */
42268    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
42269      if( (pX->exclMask & mask)!=0 ){
42270        rc = SQLITE_BUSY;
42271        break;
42272      }
42273      allShared |= pX->sharedMask;
42274    }
42275
42276    /* Get shared locks at the system level, if necessary */
42277    if( rc==SQLITE_OK ){
42278      if( (allShared & mask)==0 ){
42279        rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
42280      }else{
42281        rc = SQLITE_OK;
42282      }
42283    }
42284
42285    /* Get the local shared locks */
42286    if( rc==SQLITE_OK ){
42287      p->sharedMask |= mask;
42288    }
42289  }else{
42290    /* Make sure no sibling connections hold locks that will block this
42291    ** lock.  If any do, return SQLITE_BUSY right away.
42292    */
42293    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
42294      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
42295        rc = SQLITE_BUSY;
42296        break;
42297      }
42298    }
42299
42300    /* Get the exclusive locks at the system level.  Then if successful
42301    ** also mark the local connection as being locked.
42302    */
42303    if( rc==SQLITE_OK ){
42304      rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
42305      if( rc==SQLITE_OK ){
42306        assert( (p->sharedMask & mask)==0 );
42307        p->exclMask |= mask;
42308      }
42309    }
42310  }
42311  sqlite3_mutex_leave(pShmNode->mutex);
42312  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
42313           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
42314           sqlite3ErrName(rc)));
42315  return rc;
42316}
42317
42318/*
42319** Implement a memory barrier or memory fence on shared memory.
42320**
42321** All loads and stores begun before the barrier must complete before
42322** any load or store begun after the barrier.
42323*/
42324static void winShmBarrier(
42325  sqlite3_file *fd          /* Database holding the shared memory */
42326){
42327  UNUSED_PARAMETER(fd);
42328  sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
42329  winShmEnterMutex();       /* Also mutex, for redundancy */
42330  winShmLeaveMutex();
42331}
42332
42333/*
42334** This function is called to obtain a pointer to region iRegion of the
42335** shared-memory associated with the database file fd. Shared-memory regions
42336** are numbered starting from zero. Each shared-memory region is szRegion
42337** bytes in size.
42338**
42339** If an error occurs, an error code is returned and *pp is set to NULL.
42340**
42341** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
42342** region has not been allocated (by any client, including one running in a
42343** separate process), then *pp is set to NULL and SQLITE_OK returned. If
42344** isWrite is non-zero and the requested shared-memory region has not yet
42345** been allocated, it is allocated by this function.
42346**
42347** If the shared-memory region has already been allocated or is allocated by
42348** this call as described above, then it is mapped into this processes
42349** address space (if it is not already), *pp is set to point to the mapped
42350** memory and SQLITE_OK returned.
42351*/
42352static int winShmMap(
42353  sqlite3_file *fd,               /* Handle open on database file */
42354  int iRegion,                    /* Region to retrieve */
42355  int szRegion,                   /* Size of regions */
42356  int isWrite,                    /* True to extend file if necessary */
42357  void volatile **pp              /* OUT: Mapped memory */
42358){
42359  winFile *pDbFd = (winFile*)fd;
42360  winShm *pShm = pDbFd->pShm;
42361  winShmNode *pShmNode;
42362  int rc = SQLITE_OK;
42363
42364  if( !pShm ){
42365    rc = winOpenSharedMemory(pDbFd);
42366    if( rc!=SQLITE_OK ) return rc;
42367    pShm = pDbFd->pShm;
42368  }
42369  pShmNode = pShm->pShmNode;
42370
42371  sqlite3_mutex_enter(pShmNode->mutex);
42372  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
42373
42374  if( pShmNode->nRegion<=iRegion ){
42375    struct ShmRegion *apNew;           /* New aRegion[] array */
42376    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
42377    sqlite3_int64 sz;                  /* Current size of wal-index file */
42378
42379    pShmNode->szRegion = szRegion;
42380
42381    /* The requested region is not mapped into this processes address space.
42382    ** Check to see if it has been allocated (i.e. if the wal-index file is
42383    ** large enough to contain the requested region).
42384    */
42385    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
42386    if( rc!=SQLITE_OK ){
42387      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
42388                       "winShmMap1", pDbFd->zPath);
42389      goto shmpage_out;
42390    }
42391
42392    if( sz<nByte ){
42393      /* The requested memory region does not exist. If isWrite is set to
42394      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
42395      **
42396      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
42397      ** the requested memory region.
42398      */
42399      if( !isWrite ) goto shmpage_out;
42400      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
42401      if( rc!=SQLITE_OK ){
42402        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
42403                         "winShmMap2", pDbFd->zPath);
42404        goto shmpage_out;
42405      }
42406    }
42407
42408    /* Map the requested memory region into this processes address space. */
42409    apNew = (struct ShmRegion *)sqlite3_realloc64(
42410        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
42411    );
42412    if( !apNew ){
42413      rc = SQLITE_IOERR_NOMEM_BKPT;
42414      goto shmpage_out;
42415    }
42416    pShmNode->aRegion = apNew;
42417
42418    while( pShmNode->nRegion<=iRegion ){
42419      HANDLE hMap = NULL;         /* file-mapping handle */
42420      void *pMap = 0;             /* Mapped memory region */
42421
42422#if SQLITE_OS_WINRT
42423      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
42424          NULL, PAGE_READWRITE, nByte, NULL
42425      );
42426#elif defined(SQLITE_WIN32_HAS_WIDE)
42427      hMap = osCreateFileMappingW(pShmNode->hFile.h,
42428          NULL, PAGE_READWRITE, 0, nByte, NULL
42429      );
42430#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
42431      hMap = osCreateFileMappingA(pShmNode->hFile.h,
42432          NULL, PAGE_READWRITE, 0, nByte, NULL
42433      );
42434#endif
42435      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
42436               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
42437               hMap ? "ok" : "failed"));
42438      if( hMap ){
42439        int iOffset = pShmNode->nRegion*szRegion;
42440        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
42441#if SQLITE_OS_WINRT
42442        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
42443            iOffset - iOffsetShift, szRegion + iOffsetShift
42444        );
42445#else
42446        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
42447            0, iOffset - iOffsetShift, szRegion + iOffsetShift
42448        );
42449#endif
42450        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
42451                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
42452                 szRegion, pMap ? "ok" : "failed"));
42453      }
42454      if( !pMap ){
42455        pShmNode->lastErrno = osGetLastError();
42456        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
42457                         "winShmMap3", pDbFd->zPath);
42458        if( hMap ) osCloseHandle(hMap);
42459        goto shmpage_out;
42460      }
42461
42462      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
42463      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
42464      pShmNode->nRegion++;
42465    }
42466  }
42467
42468shmpage_out:
42469  if( pShmNode->nRegion>iRegion ){
42470    int iOffset = iRegion*szRegion;
42471    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
42472    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
42473    *pp = (void *)&p[iOffsetShift];
42474  }else{
42475    *pp = 0;
42476  }
42477  sqlite3_mutex_leave(pShmNode->mutex);
42478  return rc;
42479}
42480
42481#else
42482# define winShmMap     0
42483# define winShmLock    0
42484# define winShmBarrier 0
42485# define winShmUnmap   0
42486#endif /* #ifndef SQLITE_OMIT_WAL */
42487
42488/*
42489** Cleans up the mapped region of the specified file, if any.
42490*/
42491#if SQLITE_MAX_MMAP_SIZE>0
42492static int winUnmapfile(winFile *pFile){
42493  assert( pFile!=0 );
42494  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
42495           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
42496           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
42497           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
42498  if( pFile->pMapRegion ){
42499    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
42500      pFile->lastErrno = osGetLastError();
42501      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
42502               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
42503               pFile->pMapRegion));
42504      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
42505                         "winUnmapfile1", pFile->zPath);
42506    }
42507    pFile->pMapRegion = 0;
42508    pFile->mmapSize = 0;
42509    pFile->mmapSizeActual = 0;
42510  }
42511  if( pFile->hMap!=NULL ){
42512    if( !osCloseHandle(pFile->hMap) ){
42513      pFile->lastErrno = osGetLastError();
42514      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
42515               osGetCurrentProcessId(), pFile, pFile->hMap));
42516      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
42517                         "winUnmapfile2", pFile->zPath);
42518    }
42519    pFile->hMap = NULL;
42520  }
42521  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
42522           osGetCurrentProcessId(), pFile));
42523  return SQLITE_OK;
42524}
42525
42526/*
42527** Memory map or remap the file opened by file-descriptor pFd (if the file
42528** is already mapped, the existing mapping is replaced by the new). Or, if
42529** there already exists a mapping for this file, and there are still
42530** outstanding xFetch() references to it, this function is a no-op.
42531**
42532** If parameter nByte is non-negative, then it is the requested size of
42533** the mapping to create. Otherwise, if nByte is less than zero, then the
42534** requested size is the size of the file on disk. The actual size of the
42535** created mapping is either the requested size or the value configured
42536** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
42537**
42538** SQLITE_OK is returned if no error occurs (even if the mapping is not
42539** recreated as a result of outstanding references) or an SQLite error
42540** code otherwise.
42541*/
42542static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
42543  sqlite3_int64 nMap = nByte;
42544  int rc;
42545
42546  assert( nMap>=0 || pFd->nFetchOut==0 );
42547  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
42548           osGetCurrentProcessId(), pFd, nByte));
42549
42550  if( pFd->nFetchOut>0 ) return SQLITE_OK;
42551
42552  if( nMap<0 ){
42553    rc = winFileSize((sqlite3_file*)pFd, &nMap);
42554    if( rc ){
42555      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
42556               osGetCurrentProcessId(), pFd));
42557      return SQLITE_IOERR_FSTAT;
42558    }
42559  }
42560  if( nMap>pFd->mmapSizeMax ){
42561    nMap = pFd->mmapSizeMax;
42562  }
42563  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
42564
42565  if( nMap==0 && pFd->mmapSize>0 ){
42566    winUnmapfile(pFd);
42567  }
42568  if( nMap!=pFd->mmapSize ){
42569    void *pNew = 0;
42570    DWORD protect = PAGE_READONLY;
42571    DWORD flags = FILE_MAP_READ;
42572
42573    winUnmapfile(pFd);
42574#ifdef SQLITE_MMAP_READWRITE
42575    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
42576      protect = PAGE_READWRITE;
42577      flags |= FILE_MAP_WRITE;
42578    }
42579#endif
42580#if SQLITE_OS_WINRT
42581    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
42582#elif defined(SQLITE_WIN32_HAS_WIDE)
42583    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
42584                                (DWORD)((nMap>>32) & 0xffffffff),
42585                                (DWORD)(nMap & 0xffffffff), NULL);
42586#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
42587    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
42588                                (DWORD)((nMap>>32) & 0xffffffff),
42589                                (DWORD)(nMap & 0xffffffff), NULL);
42590#endif
42591    if( pFd->hMap==NULL ){
42592      pFd->lastErrno = osGetLastError();
42593      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
42594                       "winMapfile1", pFd->zPath);
42595      /* Log the error, but continue normal operation using xRead/xWrite */
42596      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
42597               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42598      return SQLITE_OK;
42599    }
42600    assert( (nMap % winSysInfo.dwPageSize)==0 );
42601    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
42602#if SQLITE_OS_WINRT
42603    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
42604#else
42605    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
42606#endif
42607    if( pNew==NULL ){
42608      osCloseHandle(pFd->hMap);
42609      pFd->hMap = NULL;
42610      pFd->lastErrno = osGetLastError();
42611      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
42612                       "winMapfile2", pFd->zPath);
42613      /* Log the error, but continue normal operation using xRead/xWrite */
42614      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
42615               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42616      return SQLITE_OK;
42617    }
42618    pFd->pMapRegion = pNew;
42619    pFd->mmapSize = nMap;
42620    pFd->mmapSizeActual = nMap;
42621  }
42622
42623  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
42624           osGetCurrentProcessId(), pFd));
42625  return SQLITE_OK;
42626}
42627#endif /* SQLITE_MAX_MMAP_SIZE>0 */
42628
42629/*
42630** If possible, return a pointer to a mapping of file fd starting at offset
42631** iOff. The mapping must be valid for at least nAmt bytes.
42632**
42633** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
42634** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
42635** Finally, if an error does occur, return an SQLite error code. The final
42636** value of *pp is undefined in this case.
42637**
42638** If this function does return a pointer, the caller must eventually
42639** release the reference by calling winUnfetch().
42640*/
42641static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
42642#if SQLITE_MAX_MMAP_SIZE>0
42643  winFile *pFd = (winFile*)fd;   /* The underlying database file */
42644#endif
42645  *pp = 0;
42646
42647  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
42648           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
42649
42650#if SQLITE_MAX_MMAP_SIZE>0
42651  if( pFd->mmapSizeMax>0 ){
42652    if( pFd->pMapRegion==0 ){
42653      int rc = winMapfile(pFd, -1);
42654      if( rc!=SQLITE_OK ){
42655        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
42656                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
42657        return rc;
42658      }
42659    }
42660    if( pFd->mmapSize >= iOff+nAmt ){
42661      *pp = &((u8 *)pFd->pMapRegion)[iOff];
42662      pFd->nFetchOut++;
42663    }
42664  }
42665#endif
42666
42667  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
42668           osGetCurrentProcessId(), fd, pp, *pp));
42669  return SQLITE_OK;
42670}
42671
42672/*
42673** If the third argument is non-NULL, then this function releases a
42674** reference obtained by an earlier call to winFetch(). The second
42675** argument passed to this function must be the same as the corresponding
42676** argument that was passed to the winFetch() invocation.
42677**
42678** Or, if the third argument is NULL, then this function is being called
42679** to inform the VFS layer that, according to POSIX, any existing mapping
42680** may now be invalid and should be unmapped.
42681*/
42682static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
42683#if SQLITE_MAX_MMAP_SIZE>0
42684  winFile *pFd = (winFile*)fd;   /* The underlying database file */
42685
42686  /* If p==0 (unmap the entire file) then there must be no outstanding
42687  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
42688  ** then there must be at least one outstanding.  */
42689  assert( (p==0)==(pFd->nFetchOut==0) );
42690
42691  /* If p!=0, it must match the iOff value. */
42692  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
42693
42694  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
42695           osGetCurrentProcessId(), pFd, iOff, p));
42696
42697  if( p ){
42698    pFd->nFetchOut--;
42699  }else{
42700    /* FIXME:  If Windows truly always prevents truncating or deleting a
42701    ** file while a mapping is held, then the following winUnmapfile() call
42702    ** is unnecessary can be omitted - potentially improving
42703    ** performance.  */
42704    winUnmapfile(pFd);
42705  }
42706
42707  assert( pFd->nFetchOut>=0 );
42708#endif
42709
42710  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
42711           osGetCurrentProcessId(), fd));
42712  return SQLITE_OK;
42713}
42714
42715/*
42716** Here ends the implementation of all sqlite3_file methods.
42717**
42718********************** End sqlite3_file Methods *******************************
42719******************************************************************************/
42720
42721/*
42722** This vector defines all the methods that can operate on an
42723** sqlite3_file for win32.
42724*/
42725static const sqlite3_io_methods winIoMethod = {
42726  3,                              /* iVersion */
42727  winClose,                       /* xClose */
42728  winRead,                        /* xRead */
42729  winWrite,                       /* xWrite */
42730  winTruncate,                    /* xTruncate */
42731  winSync,                        /* xSync */
42732  winFileSize,                    /* xFileSize */
42733  winLock,                        /* xLock */
42734  winUnlock,                      /* xUnlock */
42735  winCheckReservedLock,           /* xCheckReservedLock */
42736  winFileControl,                 /* xFileControl */
42737  winSectorSize,                  /* xSectorSize */
42738  winDeviceCharacteristics,       /* xDeviceCharacteristics */
42739  winShmMap,                      /* xShmMap */
42740  winShmLock,                     /* xShmLock */
42741  winShmBarrier,                  /* xShmBarrier */
42742  winShmUnmap,                    /* xShmUnmap */
42743  winFetch,                       /* xFetch */
42744  winUnfetch                      /* xUnfetch */
42745};
42746
42747/*
42748** This vector defines all the methods that can operate on an
42749** sqlite3_file for win32 without performing any locking.
42750*/
42751static const sqlite3_io_methods winIoNolockMethod = {
42752  3,                              /* iVersion */
42753  winClose,                       /* xClose */
42754  winRead,                        /* xRead */
42755  winWrite,                       /* xWrite */
42756  winTruncate,                    /* xTruncate */
42757  winSync,                        /* xSync */
42758  winFileSize,                    /* xFileSize */
42759  winNolockLock,                  /* xLock */
42760  winNolockUnlock,                /* xUnlock */
42761  winNolockCheckReservedLock,     /* xCheckReservedLock */
42762  winFileControl,                 /* xFileControl */
42763  winSectorSize,                  /* xSectorSize */
42764  winDeviceCharacteristics,       /* xDeviceCharacteristics */
42765  winShmMap,                      /* xShmMap */
42766  winShmLock,                     /* xShmLock */
42767  winShmBarrier,                  /* xShmBarrier */
42768  winShmUnmap,                    /* xShmUnmap */
42769  winFetch,                       /* xFetch */
42770  winUnfetch                      /* xUnfetch */
42771};
42772
42773static winVfsAppData winAppData = {
42774  &winIoMethod,       /* pMethod */
42775  0,                  /* pAppData */
42776  0                   /* bNoLock */
42777};
42778
42779static winVfsAppData winNolockAppData = {
42780  &winIoNolockMethod, /* pMethod */
42781  0,                  /* pAppData */
42782  1                   /* bNoLock */
42783};
42784
42785/****************************************************************************
42786**************************** sqlite3_vfs methods ****************************
42787**
42788** This division contains the implementation of methods on the
42789** sqlite3_vfs object.
42790*/
42791
42792#if defined(__CYGWIN__)
42793/*
42794** Convert a filename from whatever the underlying operating system
42795** supports for filenames into UTF-8.  Space to hold the result is
42796** obtained from malloc and must be freed by the calling function.
42797*/
42798static char *winConvertToUtf8Filename(const void *zFilename){
42799  char *zConverted = 0;
42800  if( osIsNT() ){
42801    zConverted = winUnicodeToUtf8(zFilename);
42802  }
42803#ifdef SQLITE_WIN32_HAS_ANSI
42804  else{
42805    zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
42806  }
42807#endif
42808  /* caller will handle out of memory */
42809  return zConverted;
42810}
42811#endif
42812
42813/*
42814** Convert a UTF-8 filename into whatever form the underlying
42815** operating system wants filenames in.  Space to hold the result
42816** is obtained from malloc and must be freed by the calling
42817** function.
42818*/
42819static void *winConvertFromUtf8Filename(const char *zFilename){
42820  void *zConverted = 0;
42821  if( osIsNT() ){
42822    zConverted = winUtf8ToUnicode(zFilename);
42823  }
42824#ifdef SQLITE_WIN32_HAS_ANSI
42825  else{
42826    zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
42827  }
42828#endif
42829  /* caller will handle out of memory */
42830  return zConverted;
42831}
42832
42833/*
42834** This function returns non-zero if the specified UTF-8 string buffer
42835** ends with a directory separator character or one was successfully
42836** added to it.
42837*/
42838static int winMakeEndInDirSep(int nBuf, char *zBuf){
42839  if( zBuf ){
42840    int nLen = sqlite3Strlen30(zBuf);
42841    if( nLen>0 ){
42842      if( winIsDirSep(zBuf[nLen-1]) ){
42843        return 1;
42844      }else if( nLen+1<nBuf ){
42845        zBuf[nLen] = winGetDirSep();
42846        zBuf[nLen+1] = '\0';
42847        return 1;
42848      }
42849    }
42850  }
42851  return 0;
42852}
42853
42854/*
42855** Create a temporary file name and store the resulting pointer into pzBuf.
42856** The pointer returned in pzBuf must be freed via sqlite3_free().
42857*/
42858static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
42859  static char zChars[] =
42860    "abcdefghijklmnopqrstuvwxyz"
42861    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
42862    "0123456789";
42863  size_t i, j;
42864  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
42865  int nMax, nBuf, nDir, nLen;
42866  char *zBuf;
42867
42868  /* It's odd to simulate an io-error here, but really this is just
42869  ** using the io-error infrastructure to test that SQLite handles this
42870  ** function failing.
42871  */
42872  SimulateIOError( return SQLITE_IOERR );
42873
42874  /* Allocate a temporary buffer to store the fully qualified file
42875  ** name for the temporary file.  If this fails, we cannot continue.
42876  */
42877  nMax = pVfs->mxPathname; nBuf = nMax + 2;
42878  zBuf = sqlite3MallocZero( nBuf );
42879  if( !zBuf ){
42880    OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42881    return SQLITE_IOERR_NOMEM_BKPT;
42882  }
42883
42884  /* Figure out the effective temporary directory.  First, check if one
42885  ** has been explicitly set by the application; otherwise, use the one
42886  ** configured by the operating system.
42887  */
42888  nDir = nMax - (nPre + 15);
42889  assert( nDir>0 );
42890  if( sqlite3_temp_directory ){
42891    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
42892    if( nDirLen>0 ){
42893      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
42894        nDirLen++;
42895      }
42896      if( nDirLen>nDir ){
42897        sqlite3_free(zBuf);
42898        OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
42899        return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
42900      }
42901      sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
42902    }
42903  }
42904#if defined(__CYGWIN__)
42905  else{
42906    static const char *azDirs[] = {
42907       0, /* getenv("SQLITE_TMPDIR") */
42908       0, /* getenv("TMPDIR") */
42909       0, /* getenv("TMP") */
42910       0, /* getenv("TEMP") */
42911       0, /* getenv("USERPROFILE") */
42912       "/var/tmp",
42913       "/usr/tmp",
42914       "/tmp",
42915       ".",
42916       0        /* List terminator */
42917    };
42918    unsigned int i;
42919    const char *zDir = 0;
42920
42921    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
42922    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
42923    if( !azDirs[2] ) azDirs[2] = getenv("TMP");
42924    if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
42925    if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
42926    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
42927      void *zConverted;
42928      if( zDir==0 ) continue;
42929      /* If the path starts with a drive letter followed by the colon
42930      ** character, assume it is already a native Win32 path; otherwise,
42931      ** it must be converted to a native Win32 path via the Cygwin API
42932      ** prior to using it.
42933      */
42934      if( winIsDriveLetterAndColon(zDir) ){
42935        zConverted = winConvertFromUtf8Filename(zDir);
42936        if( !zConverted ){
42937          sqlite3_free(zBuf);
42938          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42939          return SQLITE_IOERR_NOMEM_BKPT;
42940        }
42941        if( winIsDir(zConverted) ){
42942          sqlite3_snprintf(nMax, zBuf, "%s", zDir);
42943          sqlite3_free(zConverted);
42944          break;
42945        }
42946        sqlite3_free(zConverted);
42947      }else{
42948        zConverted = sqlite3MallocZero( nMax+1 );
42949        if( !zConverted ){
42950          sqlite3_free(zBuf);
42951          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42952          return SQLITE_IOERR_NOMEM_BKPT;
42953        }
42954        if( cygwin_conv_path(
42955                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
42956                zConverted, nMax+1)<0 ){
42957          sqlite3_free(zConverted);
42958          sqlite3_free(zBuf);
42959          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
42960          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
42961                             "winGetTempname2", zDir);
42962        }
42963        if( winIsDir(zConverted) ){
42964          /* At this point, we know the candidate directory exists and should
42965          ** be used.  However, we may need to convert the string containing
42966          ** its name into UTF-8 (i.e. if it is UTF-16 right now).
42967          */
42968          char *zUtf8 = winConvertToUtf8Filename(zConverted);
42969          if( !zUtf8 ){
42970            sqlite3_free(zConverted);
42971            sqlite3_free(zBuf);
42972            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42973            return SQLITE_IOERR_NOMEM_BKPT;
42974          }
42975          sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
42976          sqlite3_free(zUtf8);
42977          sqlite3_free(zConverted);
42978          break;
42979        }
42980        sqlite3_free(zConverted);
42981      }
42982    }
42983  }
42984#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42985  else if( osIsNT() ){
42986    char *zMulti;
42987    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
42988    if( !zWidePath ){
42989      sqlite3_free(zBuf);
42990      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
42991      return SQLITE_IOERR_NOMEM_BKPT;
42992    }
42993    if( osGetTempPathW(nMax, zWidePath)==0 ){
42994      sqlite3_free(zWidePath);
42995      sqlite3_free(zBuf);
42996      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
42997      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
42998                         "winGetTempname2", 0);
42999    }
43000    zMulti = winUnicodeToUtf8(zWidePath);
43001    if( zMulti ){
43002      sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
43003      sqlite3_free(zMulti);
43004      sqlite3_free(zWidePath);
43005    }else{
43006      sqlite3_free(zWidePath);
43007      sqlite3_free(zBuf);
43008      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
43009      return SQLITE_IOERR_NOMEM_BKPT;
43010    }
43011  }
43012#ifdef SQLITE_WIN32_HAS_ANSI
43013  else{
43014    char *zUtf8;
43015    char *zMbcsPath = sqlite3MallocZero( nMax );
43016    if( !zMbcsPath ){
43017      sqlite3_free(zBuf);
43018      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
43019      return SQLITE_IOERR_NOMEM_BKPT;
43020    }
43021    if( osGetTempPathA(nMax, zMbcsPath)==0 ){
43022      sqlite3_free(zBuf);
43023      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
43024      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
43025                         "winGetTempname3", 0);
43026    }
43027    zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
43028    if( zUtf8 ){
43029      sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
43030      sqlite3_free(zUtf8);
43031    }else{
43032      sqlite3_free(zBuf);
43033      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
43034      return SQLITE_IOERR_NOMEM_BKPT;
43035    }
43036  }
43037#endif /* SQLITE_WIN32_HAS_ANSI */
43038#endif /* !SQLITE_OS_WINRT */
43039
43040  /*
43041  ** Check to make sure the temporary directory ends with an appropriate
43042  ** separator.  If it does not and there is not enough space left to add
43043  ** one, fail.
43044  */
43045  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
43046    sqlite3_free(zBuf);
43047    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
43048    return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
43049  }
43050
43051  /*
43052  ** Check that the output buffer is large enough for the temporary file
43053  ** name in the following format:
43054  **
43055  **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
43056  **
43057  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
43058  ** account for the space used by the 15 character random suffix and the
43059  ** two trailing NUL characters.  The final directory separator character
43060  ** has already added if it was not already present.
43061  */
43062  nLen = sqlite3Strlen30(zBuf);
43063  if( (nLen + nPre + 17) > nBuf ){
43064    sqlite3_free(zBuf);
43065    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
43066    return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
43067  }
43068
43069  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
43070
43071  j = sqlite3Strlen30(zBuf);
43072  sqlite3_randomness(15, &zBuf[j]);
43073  for(i=0; i<15; i++, j++){
43074    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
43075  }
43076  zBuf[j] = 0;
43077  zBuf[j+1] = 0;
43078  *pzBuf = zBuf;
43079
43080  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
43081  return SQLITE_OK;
43082}
43083
43084/*
43085** Return TRUE if the named file is really a directory.  Return false if
43086** it is something other than a directory, or if there is any kind of memory
43087** allocation failure.
43088*/
43089static int winIsDir(const void *zConverted){
43090  DWORD attr;
43091  int rc = 0;
43092  DWORD lastErrno;
43093
43094  if( osIsNT() ){
43095    int cnt = 0;
43096    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
43097    memset(&sAttrData, 0, sizeof(sAttrData));
43098    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
43099                             GetFileExInfoStandard,
43100                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
43101    if( !rc ){
43102      return 0; /* Invalid name? */
43103    }
43104    attr = sAttrData.dwFileAttributes;
43105#if SQLITE_OS_WINCE==0
43106  }else{
43107    attr = osGetFileAttributesA((char*)zConverted);
43108#endif
43109  }
43110  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
43111}
43112
43113/*
43114** Open a file.
43115*/
43116static int winOpen(
43117  sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */
43118  const char *zName,        /* Name of the file (UTF-8) */
43119  sqlite3_file *id,         /* Write the SQLite file handle here */
43120  int flags,                /* Open mode flags */
43121  int *pOutFlags            /* Status return flags */
43122){
43123  HANDLE h;
43124  DWORD lastErrno = 0;
43125  DWORD dwDesiredAccess;
43126  DWORD dwShareMode;
43127  DWORD dwCreationDisposition;
43128  DWORD dwFlagsAndAttributes = 0;
43129#if SQLITE_OS_WINCE
43130  int isTemp = 0;
43131#endif
43132  winVfsAppData *pAppData;
43133  winFile *pFile = (winFile*)id;
43134  void *zConverted;              /* Filename in OS encoding */
43135  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
43136  int cnt = 0;
43137
43138  /* If argument zPath is a NULL pointer, this function is required to open
43139  ** a temporary file. Use this buffer to store the file name in.
43140  */
43141  char *zTmpname = 0; /* For temporary filename, if necessary. */
43142
43143  int rc = SQLITE_OK;            /* Function Return Code */
43144#if !defined(NDEBUG) || SQLITE_OS_WINCE
43145  int eType = flags&0xFFFFFF00;  /* Type of file to open */
43146#endif
43147
43148  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
43149  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
43150  int isCreate     = (flags & SQLITE_OPEN_CREATE);
43151  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
43152  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
43153
43154#ifndef NDEBUG
43155  int isOpenJournal = (isCreate && (
43156        eType==SQLITE_OPEN_MASTER_JOURNAL
43157     || eType==SQLITE_OPEN_MAIN_JOURNAL
43158     || eType==SQLITE_OPEN_WAL
43159  ));
43160#endif
43161
43162  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
43163           zUtf8Name, id, flags, pOutFlags));
43164
43165  /* Check the following statements are true:
43166  **
43167  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
43168  **   (b) if CREATE is set, then READWRITE must also be set, and
43169  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
43170  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
43171  */
43172  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
43173  assert(isCreate==0 || isReadWrite);
43174  assert(isExclusive==0 || isCreate);
43175  assert(isDelete==0 || isCreate);
43176
43177  /* The main DB, main journal, WAL file and master journal are never
43178  ** automatically deleted. Nor are they ever temporary files.  */
43179  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
43180  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
43181  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
43182  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
43183
43184  /* Assert that the upper layer has set one of the "file-type" flags. */
43185  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
43186       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
43187       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
43188       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
43189  );
43190
43191  assert( pFile!=0 );
43192  memset(pFile, 0, sizeof(winFile));
43193  pFile->h = INVALID_HANDLE_VALUE;
43194
43195#if SQLITE_OS_WINRT
43196  if( !zUtf8Name && !sqlite3_temp_directory ){
43197    sqlite3_log(SQLITE_ERROR,
43198        "sqlite3_temp_directory variable should be set for WinRT");
43199  }
43200#endif
43201
43202  /* If the second argument to this function is NULL, generate a
43203  ** temporary file name to use
43204  */
43205  if( !zUtf8Name ){
43206    assert( isDelete && !isOpenJournal );
43207    rc = winGetTempname(pVfs, &zTmpname);
43208    if( rc!=SQLITE_OK ){
43209      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
43210      return rc;
43211    }
43212    zUtf8Name = zTmpname;
43213  }
43214
43215  /* Database filenames are double-zero terminated if they are not
43216  ** URIs with parameters.  Hence, they can always be passed into
43217  ** sqlite3_uri_parameter().
43218  */
43219  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
43220       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
43221
43222  /* Convert the filename to the system encoding. */
43223  zConverted = winConvertFromUtf8Filename(zUtf8Name);
43224  if( zConverted==0 ){
43225    sqlite3_free(zTmpname);
43226    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
43227    return SQLITE_IOERR_NOMEM_BKPT;
43228  }
43229
43230  if( winIsDir(zConverted) ){
43231    sqlite3_free(zConverted);
43232    sqlite3_free(zTmpname);
43233    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
43234    return SQLITE_CANTOPEN_ISDIR;
43235  }
43236
43237  if( isReadWrite ){
43238    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
43239  }else{
43240    dwDesiredAccess = GENERIC_READ;
43241  }
43242
43243  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
43244  ** created. SQLite doesn't use it to indicate "exclusive access"
43245  ** as it is usually understood.
43246  */
43247  if( isExclusive ){
43248    /* Creates a new file, only if it does not already exist. */
43249    /* If the file exists, it fails. */
43250    dwCreationDisposition = CREATE_NEW;
43251  }else if( isCreate ){
43252    /* Open existing file, or create if it doesn't exist */
43253    dwCreationDisposition = OPEN_ALWAYS;
43254  }else{
43255    /* Opens a file, only if it exists. */
43256    dwCreationDisposition = OPEN_EXISTING;
43257  }
43258
43259  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
43260
43261  if( isDelete ){
43262#if SQLITE_OS_WINCE
43263    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
43264    isTemp = 1;
43265#else
43266    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
43267                               | FILE_ATTRIBUTE_HIDDEN
43268                               | FILE_FLAG_DELETE_ON_CLOSE;
43269#endif
43270  }else{
43271    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
43272  }
43273  /* Reports from the internet are that performance is always
43274  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
43275#if SQLITE_OS_WINCE
43276  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
43277#endif
43278
43279  if( osIsNT() ){
43280#if SQLITE_OS_WINRT
43281    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
43282    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
43283    extendedParameters.dwFileAttributes =
43284            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
43285    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
43286    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
43287    extendedParameters.lpSecurityAttributes = NULL;
43288    extendedParameters.hTemplateFile = NULL;
43289    while( (h = osCreateFile2((LPCWSTR)zConverted,
43290                              dwDesiredAccess,
43291                              dwShareMode,
43292                              dwCreationDisposition,
43293                              &extendedParameters))==INVALID_HANDLE_VALUE &&
43294                              winRetryIoerr(&cnt, &lastErrno) ){
43295               /* Noop */
43296    }
43297#else
43298    while( (h = osCreateFileW((LPCWSTR)zConverted,
43299                              dwDesiredAccess,
43300                              dwShareMode, NULL,
43301                              dwCreationDisposition,
43302                              dwFlagsAndAttributes,
43303                              NULL))==INVALID_HANDLE_VALUE &&
43304                              winRetryIoerr(&cnt, &lastErrno) ){
43305               /* Noop */
43306    }
43307#endif
43308  }
43309#ifdef SQLITE_WIN32_HAS_ANSI
43310  else{
43311    while( (h = osCreateFileA((LPCSTR)zConverted,
43312                              dwDesiredAccess,
43313                              dwShareMode, NULL,
43314                              dwCreationDisposition,
43315                              dwFlagsAndAttributes,
43316                              NULL))==INVALID_HANDLE_VALUE &&
43317                              winRetryIoerr(&cnt, &lastErrno) ){
43318               /* Noop */
43319    }
43320  }
43321#endif
43322  winLogIoerr(cnt, __LINE__);
43323
43324  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
43325           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
43326
43327  if( h==INVALID_HANDLE_VALUE ){
43328    pFile->lastErrno = lastErrno;
43329    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
43330    sqlite3_free(zConverted);
43331    sqlite3_free(zTmpname);
43332    if( isReadWrite && !isExclusive ){
43333      return winOpen(pVfs, zName, id,
43334         ((flags|SQLITE_OPEN_READONLY) &
43335                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
43336         pOutFlags);
43337    }else{
43338      return SQLITE_CANTOPEN_BKPT;
43339    }
43340  }
43341
43342  if( pOutFlags ){
43343    if( isReadWrite ){
43344      *pOutFlags = SQLITE_OPEN_READWRITE;
43345    }else{
43346      *pOutFlags = SQLITE_OPEN_READONLY;
43347    }
43348  }
43349
43350  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
43351           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
43352           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
43353
43354  pAppData = (winVfsAppData*)pVfs->pAppData;
43355
43356#if SQLITE_OS_WINCE
43357  {
43358    if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
43359         && ((pAppData==NULL) || !pAppData->bNoLock)
43360         && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
43361    ){
43362      osCloseHandle(h);
43363      sqlite3_free(zConverted);
43364      sqlite3_free(zTmpname);
43365      OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
43366      return rc;
43367    }
43368  }
43369  if( isTemp ){
43370    pFile->zDeleteOnClose = zConverted;
43371  }else
43372#endif
43373  {
43374    sqlite3_free(zConverted);
43375  }
43376
43377  sqlite3_free(zTmpname);
43378  pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
43379  pFile->pVfs = pVfs;
43380  pFile->h = h;
43381  if( isReadonly ){
43382    pFile->ctrlFlags |= WINFILE_RDONLY;
43383  }
43384  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
43385    pFile->ctrlFlags |= WINFILE_PSOW;
43386  }
43387  pFile->lastErrno = NO_ERROR;
43388  pFile->zPath = zName;
43389#if SQLITE_MAX_MMAP_SIZE>0
43390  pFile->hMap = NULL;
43391  pFile->pMapRegion = 0;
43392  pFile->mmapSize = 0;
43393  pFile->mmapSizeActual = 0;
43394  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
43395#endif
43396
43397  OpenCounter(+1);
43398  return rc;
43399}
43400
43401/*
43402** Delete the named file.
43403**
43404** Note that Windows does not allow a file to be deleted if some other
43405** process has it open.  Sometimes a virus scanner or indexing program
43406** will open a journal file shortly after it is created in order to do
43407** whatever it does.  While this other process is holding the
43408** file open, we will be unable to delete it.  To work around this
43409** problem, we delay 100 milliseconds and try to delete again.  Up
43410** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
43411** up and returning an error.
43412*/
43413static int winDelete(
43414  sqlite3_vfs *pVfs,          /* Not used on win32 */
43415  const char *zFilename,      /* Name of file to delete */
43416  int syncDir                 /* Not used on win32 */
43417){
43418  int cnt = 0;
43419  int rc;
43420  DWORD attr;
43421  DWORD lastErrno = 0;
43422  void *zConverted;
43423  UNUSED_PARAMETER(pVfs);
43424  UNUSED_PARAMETER(syncDir);
43425
43426  SimulateIOError(return SQLITE_IOERR_DELETE);
43427  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
43428
43429  zConverted = winConvertFromUtf8Filename(zFilename);
43430  if( zConverted==0 ){
43431    OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
43432    return SQLITE_IOERR_NOMEM_BKPT;
43433  }
43434  if( osIsNT() ){
43435    do {
43436#if SQLITE_OS_WINRT
43437      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
43438      memset(&sAttrData, 0, sizeof(sAttrData));
43439      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
43440                                  &sAttrData) ){
43441        attr = sAttrData.dwFileAttributes;
43442      }else{
43443        lastErrno = osGetLastError();
43444        if( lastErrno==ERROR_FILE_NOT_FOUND
43445         || lastErrno==ERROR_PATH_NOT_FOUND ){
43446          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
43447        }else{
43448          rc = SQLITE_ERROR;
43449        }
43450        break;
43451      }
43452#else
43453      attr = osGetFileAttributesW(zConverted);
43454#endif
43455      if ( attr==INVALID_FILE_ATTRIBUTES ){
43456        lastErrno = osGetLastError();
43457        if( lastErrno==ERROR_FILE_NOT_FOUND
43458         || lastErrno==ERROR_PATH_NOT_FOUND ){
43459          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
43460        }else{
43461          rc = SQLITE_ERROR;
43462        }
43463        break;
43464      }
43465      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
43466        rc = SQLITE_ERROR; /* Files only. */
43467        break;
43468      }
43469      if ( osDeleteFileW(zConverted) ){
43470        rc = SQLITE_OK; /* Deleted OK. */
43471        break;
43472      }
43473      if ( !winRetryIoerr(&cnt, &lastErrno) ){
43474        rc = SQLITE_ERROR; /* No more retries. */
43475        break;
43476      }
43477    } while(1);
43478  }
43479#ifdef SQLITE_WIN32_HAS_ANSI
43480  else{
43481    do {
43482      attr = osGetFileAttributesA(zConverted);
43483      if ( attr==INVALID_FILE_ATTRIBUTES ){
43484        lastErrno = osGetLastError();
43485        if( lastErrno==ERROR_FILE_NOT_FOUND
43486         || lastErrno==ERROR_PATH_NOT_FOUND ){
43487          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
43488        }else{
43489          rc = SQLITE_ERROR;
43490        }
43491        break;
43492      }
43493      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
43494        rc = SQLITE_ERROR; /* Files only. */
43495        break;
43496      }
43497      if ( osDeleteFileA(zConverted) ){
43498        rc = SQLITE_OK; /* Deleted OK. */
43499        break;
43500      }
43501      if ( !winRetryIoerr(&cnt, &lastErrno) ){
43502        rc = SQLITE_ERROR; /* No more retries. */
43503        break;
43504      }
43505    } while(1);
43506  }
43507#endif
43508  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
43509    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
43510  }else{
43511    winLogIoerr(cnt, __LINE__);
43512  }
43513  sqlite3_free(zConverted);
43514  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
43515  return rc;
43516}
43517
43518/*
43519** Check the existence and status of a file.
43520*/
43521static int winAccess(
43522  sqlite3_vfs *pVfs,         /* Not used on win32 */
43523  const char *zFilename,     /* Name of file to check */
43524  int flags,                 /* Type of test to make on this file */
43525  int *pResOut               /* OUT: Result */
43526){
43527  DWORD attr;
43528  int rc = 0;
43529  DWORD lastErrno = 0;
43530  void *zConverted;
43531  UNUSED_PARAMETER(pVfs);
43532
43533  SimulateIOError( return SQLITE_IOERR_ACCESS; );
43534  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
43535           zFilename, flags, pResOut));
43536
43537  zConverted = winConvertFromUtf8Filename(zFilename);
43538  if( zConverted==0 ){
43539    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
43540    return SQLITE_IOERR_NOMEM_BKPT;
43541  }
43542  if( osIsNT() ){
43543    int cnt = 0;
43544    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
43545    memset(&sAttrData, 0, sizeof(sAttrData));
43546    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
43547                             GetFileExInfoStandard,
43548                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
43549    if( rc ){
43550      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
43551      ** as if it does not exist.
43552      */
43553      if(    flags==SQLITE_ACCESS_EXISTS
43554          && sAttrData.nFileSizeHigh==0
43555          && sAttrData.nFileSizeLow==0 ){
43556        attr = INVALID_FILE_ATTRIBUTES;
43557      }else{
43558        attr = sAttrData.dwFileAttributes;
43559      }
43560    }else{
43561      winLogIoerr(cnt, __LINE__);
43562      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
43563        sqlite3_free(zConverted);
43564        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
43565                           zFilename);
43566      }else{
43567        attr = INVALID_FILE_ATTRIBUTES;
43568      }
43569    }
43570  }
43571#ifdef SQLITE_WIN32_HAS_ANSI
43572  else{
43573    attr = osGetFileAttributesA((char*)zConverted);
43574  }
43575#endif
43576  sqlite3_free(zConverted);
43577  switch( flags ){
43578    case SQLITE_ACCESS_READ:
43579    case SQLITE_ACCESS_EXISTS:
43580      rc = attr!=INVALID_FILE_ATTRIBUTES;
43581      break;
43582    case SQLITE_ACCESS_READWRITE:
43583      rc = attr!=INVALID_FILE_ATTRIBUTES &&
43584             (attr & FILE_ATTRIBUTE_READONLY)==0;
43585      break;
43586    default:
43587      assert(!"Invalid flags argument");
43588  }
43589  *pResOut = rc;
43590  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
43591           zFilename, pResOut, *pResOut));
43592  return SQLITE_OK;
43593}
43594
43595/*
43596** Returns non-zero if the specified path name starts with a drive letter
43597** followed by a colon character.
43598*/
43599static BOOL winIsDriveLetterAndColon(
43600  const char *zPathname
43601){
43602  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
43603}
43604
43605/*
43606** Returns non-zero if the specified path name should be used verbatim.  If
43607** non-zero is returned from this function, the calling function must simply
43608** use the provided path name verbatim -OR- resolve it into a full path name
43609** using the GetFullPathName Win32 API function (if available).
43610*/
43611static BOOL winIsVerbatimPathname(
43612  const char *zPathname
43613){
43614  /*
43615  ** If the path name starts with a forward slash or a backslash, it is either
43616  ** a legal UNC name, a volume relative path, or an absolute path name in the
43617  ** "Unix" format on Windows.  There is no easy way to differentiate between
43618  ** the final two cases; therefore, we return the safer return value of TRUE
43619  ** so that callers of this function will simply use it verbatim.
43620  */
43621  if ( winIsDirSep(zPathname[0]) ){
43622    return TRUE;
43623  }
43624
43625  /*
43626  ** If the path name starts with a letter and a colon it is either a volume
43627  ** relative path or an absolute path.  Callers of this function must not
43628  ** attempt to treat it as a relative path name (i.e. they should simply use
43629  ** it verbatim).
43630  */
43631  if ( winIsDriveLetterAndColon(zPathname) ){
43632    return TRUE;
43633  }
43634
43635  /*
43636  ** If we get to this point, the path name should almost certainly be a purely
43637  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
43638  */
43639  return FALSE;
43640}
43641
43642/*
43643** Turn a relative pathname into a full pathname.  Write the full
43644** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
43645** bytes in size.
43646*/
43647static int winFullPathname(
43648  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
43649  const char *zRelative,        /* Possibly relative input path */
43650  int nFull,                    /* Size of output buffer in bytes */
43651  char *zFull                   /* Output buffer */
43652){
43653#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
43654  DWORD nByte;
43655  void *zConverted;
43656  char *zOut;
43657#endif
43658
43659  /* If this path name begins with "/X:", where "X" is any alphabetic
43660  ** character, discard the initial "/" from the pathname.
43661  */
43662  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
43663    zRelative++;
43664  }
43665
43666#if defined(__CYGWIN__)
43667  SimulateIOError( return SQLITE_ERROR );
43668  UNUSED_PARAMETER(nFull);
43669  assert( nFull>=pVfs->mxPathname );
43670  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43671    /*
43672    ** NOTE: We are dealing with a relative path name and the data
43673    **       directory has been set.  Therefore, use it as the basis
43674    **       for converting the relative path name to an absolute
43675    **       one by prepending the data directory and a slash.
43676    */
43677    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
43678    if( !zOut ){
43679      return SQLITE_IOERR_NOMEM_BKPT;
43680    }
43681    if( cygwin_conv_path(
43682            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
43683            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
43684      sqlite3_free(zOut);
43685      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
43686                         "winFullPathname1", zRelative);
43687    }else{
43688      char *zUtf8 = winConvertToUtf8Filename(zOut);
43689      if( !zUtf8 ){
43690        sqlite3_free(zOut);
43691        return SQLITE_IOERR_NOMEM_BKPT;
43692      }
43693      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43694                       sqlite3_data_directory, winGetDirSep(), zUtf8);
43695      sqlite3_free(zUtf8);
43696      sqlite3_free(zOut);
43697    }
43698  }else{
43699    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
43700    if( !zOut ){
43701      return SQLITE_IOERR_NOMEM_BKPT;
43702    }
43703    if( cygwin_conv_path(
43704            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
43705            zRelative, zOut, pVfs->mxPathname+1)<0 ){
43706      sqlite3_free(zOut);
43707      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
43708                         "winFullPathname2", zRelative);
43709    }else{
43710      char *zUtf8 = winConvertToUtf8Filename(zOut);
43711      if( !zUtf8 ){
43712        sqlite3_free(zOut);
43713        return SQLITE_IOERR_NOMEM_BKPT;
43714      }
43715      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
43716      sqlite3_free(zUtf8);
43717      sqlite3_free(zOut);
43718    }
43719  }
43720  return SQLITE_OK;
43721#endif
43722
43723#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
43724  SimulateIOError( return SQLITE_ERROR );
43725  /* WinCE has no concept of a relative pathname, or so I am told. */
43726  /* WinRT has no way to convert a relative path to an absolute one. */
43727  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43728    /*
43729    ** NOTE: We are dealing with a relative path name and the data
43730    **       directory has been set.  Therefore, use it as the basis
43731    **       for converting the relative path name to an absolute
43732    **       one by prepending the data directory and a backslash.
43733    */
43734    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43735                     sqlite3_data_directory, winGetDirSep(), zRelative);
43736  }else{
43737    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
43738  }
43739  return SQLITE_OK;
43740#endif
43741
43742#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
43743  /* It's odd to simulate an io-error here, but really this is just
43744  ** using the io-error infrastructure to test that SQLite handles this
43745  ** function failing. This function could fail if, for example, the
43746  ** current working directory has been unlinked.
43747  */
43748  SimulateIOError( return SQLITE_ERROR );
43749  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
43750    /*
43751    ** NOTE: We are dealing with a relative path name and the data
43752    **       directory has been set.  Therefore, use it as the basis
43753    **       for converting the relative path name to an absolute
43754    **       one by prepending the data directory and a backslash.
43755    */
43756    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
43757                     sqlite3_data_directory, winGetDirSep(), zRelative);
43758    return SQLITE_OK;
43759  }
43760  zConverted = winConvertFromUtf8Filename(zRelative);
43761  if( zConverted==0 ){
43762    return SQLITE_IOERR_NOMEM_BKPT;
43763  }
43764  if( osIsNT() ){
43765    LPWSTR zTemp;
43766    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
43767    if( nByte==0 ){
43768      sqlite3_free(zConverted);
43769      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43770                         "winFullPathname1", zRelative);
43771    }
43772    nByte += 3;
43773    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
43774    if( zTemp==0 ){
43775      sqlite3_free(zConverted);
43776      return SQLITE_IOERR_NOMEM_BKPT;
43777    }
43778    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
43779    if( nByte==0 ){
43780      sqlite3_free(zConverted);
43781      sqlite3_free(zTemp);
43782      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43783                         "winFullPathname2", zRelative);
43784    }
43785    sqlite3_free(zConverted);
43786    zOut = winUnicodeToUtf8(zTemp);
43787    sqlite3_free(zTemp);
43788  }
43789#ifdef SQLITE_WIN32_HAS_ANSI
43790  else{
43791    char *zTemp;
43792    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
43793    if( nByte==0 ){
43794      sqlite3_free(zConverted);
43795      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43796                         "winFullPathname3", zRelative);
43797    }
43798    nByte += 3;
43799    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
43800    if( zTemp==0 ){
43801      sqlite3_free(zConverted);
43802      return SQLITE_IOERR_NOMEM_BKPT;
43803    }
43804    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
43805    if( nByte==0 ){
43806      sqlite3_free(zConverted);
43807      sqlite3_free(zTemp);
43808      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
43809                         "winFullPathname4", zRelative);
43810    }
43811    sqlite3_free(zConverted);
43812    zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
43813    sqlite3_free(zTemp);
43814  }
43815#endif
43816  if( zOut ){
43817    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
43818    sqlite3_free(zOut);
43819    return SQLITE_OK;
43820  }else{
43821    return SQLITE_IOERR_NOMEM_BKPT;
43822  }
43823#endif
43824}
43825
43826#ifndef SQLITE_OMIT_LOAD_EXTENSION
43827/*
43828** Interfaces for opening a shared library, finding entry points
43829** within the shared library, and closing the shared library.
43830*/
43831static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
43832  HANDLE h;
43833#if defined(__CYGWIN__)
43834  int nFull = pVfs->mxPathname+1;
43835  char *zFull = sqlite3MallocZero( nFull );
43836  void *zConverted = 0;
43837  if( zFull==0 ){
43838    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43839    return 0;
43840  }
43841  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
43842    sqlite3_free(zFull);
43843    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43844    return 0;
43845  }
43846  zConverted = winConvertFromUtf8Filename(zFull);
43847  sqlite3_free(zFull);
43848#else
43849  void *zConverted = winConvertFromUtf8Filename(zFilename);
43850  UNUSED_PARAMETER(pVfs);
43851#endif
43852  if( zConverted==0 ){
43853    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
43854    return 0;
43855  }
43856  if( osIsNT() ){
43857#if SQLITE_OS_WINRT
43858    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
43859#else
43860    h = osLoadLibraryW((LPCWSTR)zConverted);
43861#endif
43862  }
43863#ifdef SQLITE_WIN32_HAS_ANSI
43864  else{
43865    h = osLoadLibraryA((char*)zConverted);
43866  }
43867#endif
43868  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
43869  sqlite3_free(zConverted);
43870  return (void*)h;
43871}
43872static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
43873  UNUSED_PARAMETER(pVfs);
43874  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
43875}
43876static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
43877  FARPROC proc;
43878  UNUSED_PARAMETER(pVfs);
43879  proc = osGetProcAddressA((HANDLE)pH, zSym);
43880  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
43881           (void*)pH, zSym, (void*)proc));
43882  return (void(*)(void))proc;
43883}
43884static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
43885  UNUSED_PARAMETER(pVfs);
43886  osFreeLibrary((HANDLE)pHandle);
43887  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
43888}
43889#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
43890  #define winDlOpen  0
43891  #define winDlError 0
43892  #define winDlSym   0
43893  #define winDlClose 0
43894#endif
43895
43896/* State information for the randomness gatherer. */
43897typedef struct EntropyGatherer EntropyGatherer;
43898struct EntropyGatherer {
43899  unsigned char *a;   /* Gather entropy into this buffer */
43900  int na;             /* Size of a[] in bytes */
43901  int i;              /* XOR next input into a[i] */
43902  int nXor;           /* Number of XOR operations done */
43903};
43904
43905#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
43906/* Mix sz bytes of entropy into p. */
43907static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
43908  int j, k;
43909  for(j=0, k=p->i; j<sz; j++){
43910    p->a[k++] ^= x[j];
43911    if( k>=p->na ) k = 0;
43912  }
43913  p->i = k;
43914  p->nXor += sz;
43915}
43916#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
43917
43918/*
43919** Write up to nBuf bytes of randomness into zBuf.
43920*/
43921static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43922#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
43923  UNUSED_PARAMETER(pVfs);
43924  memset(zBuf, 0, nBuf);
43925  return nBuf;
43926#else
43927  EntropyGatherer e;
43928  UNUSED_PARAMETER(pVfs);
43929  memset(zBuf, 0, nBuf);
43930#if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
43931  rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
43932#endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
43933  e.a = (unsigned char*)zBuf;
43934  e.na = nBuf;
43935  e.nXor = 0;
43936  e.i = 0;
43937  {
43938    SYSTEMTIME x;
43939    osGetSystemTime(&x);
43940    xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
43941  }
43942  {
43943    DWORD pid = osGetCurrentProcessId();
43944    xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
43945  }
43946#if SQLITE_OS_WINRT
43947  {
43948    ULONGLONG cnt = osGetTickCount64();
43949    xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
43950  }
43951#else
43952  {
43953    DWORD cnt = osGetTickCount();
43954    xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
43955  }
43956#endif /* SQLITE_OS_WINRT */
43957  {
43958    LARGE_INTEGER i;
43959    osQueryPerformanceCounter(&i);
43960    xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
43961  }
43962#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
43963  {
43964    UUID id;
43965    memset(&id, 0, sizeof(UUID));
43966    osUuidCreate(&id);
43967    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
43968    memset(&id, 0, sizeof(UUID));
43969    osUuidCreateSequential(&id);
43970    xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
43971  }
43972#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
43973  return e.nXor>nBuf ? nBuf : e.nXor;
43974#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
43975}
43976
43977
43978/*
43979** Sleep for a little while.  Return the amount of time slept.
43980*/
43981static int winSleep(sqlite3_vfs *pVfs, int microsec){
43982  sqlite3_win32_sleep((microsec+999)/1000);
43983  UNUSED_PARAMETER(pVfs);
43984  return ((microsec+999)/1000)*1000;
43985}
43986
43987/*
43988** The following variable, if set to a non-zero value, is interpreted as
43989** the number of seconds since 1970 and is used to set the result of
43990** sqlite3OsCurrentTime() during testing.
43991*/
43992#ifdef SQLITE_TEST
43993SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
43994#endif
43995
43996/*
43997** Find the current time (in Universal Coordinated Time).  Write into *piNow
43998** the current time and date as a Julian Day number times 86_400_000.  In
43999** other words, write into *piNow the number of milliseconds since the Julian
44000** epoch of noon in Greenwich on November 24, 4714 B.C according to the
44001** proleptic Gregorian calendar.
44002**
44003** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
44004** cannot be found.
44005*/
44006static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
44007  /* FILETIME structure is a 64-bit value representing the number of
44008     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
44009  */
44010  FILETIME ft;
44011  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
44012#ifdef SQLITE_TEST
44013  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
44014#endif
44015  /* 2^32 - to avoid use of LL and warnings in gcc */
44016  static const sqlite3_int64 max32BitValue =
44017      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
44018      (sqlite3_int64)294967296;
44019
44020#if SQLITE_OS_WINCE
44021  SYSTEMTIME time;
44022  osGetSystemTime(&time);
44023  /* if SystemTimeToFileTime() fails, it returns zero. */
44024  if (!osSystemTimeToFileTime(&time,&ft)){
44025    return SQLITE_ERROR;
44026  }
44027#else
44028  osGetSystemTimeAsFileTime( &ft );
44029#endif
44030
44031  *piNow = winFiletimeEpoch +
44032            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
44033               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
44034
44035#ifdef SQLITE_TEST
44036  if( sqlite3_current_time ){
44037    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
44038  }
44039#endif
44040  UNUSED_PARAMETER(pVfs);
44041  return SQLITE_OK;
44042}
44043
44044/*
44045** Find the current time (in Universal Coordinated Time).  Write the
44046** current time and date as a Julian Day number into *prNow and
44047** return 0.  Return 1 if the time and date cannot be found.
44048*/
44049static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
44050  int rc;
44051  sqlite3_int64 i;
44052  rc = winCurrentTimeInt64(pVfs, &i);
44053  if( !rc ){
44054    *prNow = i/86400000.0;
44055  }
44056  return rc;
44057}
44058
44059/*
44060** The idea is that this function works like a combination of
44061** GetLastError() and FormatMessage() on Windows (or errno and
44062** strerror_r() on Unix). After an error is returned by an OS
44063** function, SQLite calls this function with zBuf pointing to
44064** a buffer of nBuf bytes. The OS layer should populate the
44065** buffer with a nul-terminated UTF-8 encoded error message
44066** describing the last IO error to have occurred within the calling
44067** thread.
44068**
44069** If the error message is too large for the supplied buffer,
44070** it should be truncated. The return value of xGetLastError
44071** is zero if the error message fits in the buffer, or non-zero
44072** otherwise (if the message was truncated). If non-zero is returned,
44073** then it is not necessary to include the nul-terminator character
44074** in the output buffer.
44075**
44076** Not supplying an error message will have no adverse effect
44077** on SQLite. It is fine to have an implementation that never
44078** returns an error message:
44079**
44080**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
44081**     assert(zBuf[0]=='\0');
44082**     return 0;
44083**   }
44084**
44085** However if an error message is supplied, it will be incorporated
44086** by sqlite into the error message available to the user using
44087** sqlite3_errmsg(), possibly making IO errors easier to debug.
44088*/
44089static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
44090  DWORD e = osGetLastError();
44091  UNUSED_PARAMETER(pVfs);
44092  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
44093  return e;
44094}
44095
44096/*
44097** Initialize and deinitialize the operating system interface.
44098*/
44099SQLITE_API int sqlite3_os_init(void){
44100  static sqlite3_vfs winVfs = {
44101    3,                     /* iVersion */
44102    sizeof(winFile),       /* szOsFile */
44103    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
44104    0,                     /* pNext */
44105    "win32",               /* zName */
44106    &winAppData,           /* pAppData */
44107    winOpen,               /* xOpen */
44108    winDelete,             /* xDelete */
44109    winAccess,             /* xAccess */
44110    winFullPathname,       /* xFullPathname */
44111    winDlOpen,             /* xDlOpen */
44112    winDlError,            /* xDlError */
44113    winDlSym,              /* xDlSym */
44114    winDlClose,            /* xDlClose */
44115    winRandomness,         /* xRandomness */
44116    winSleep,              /* xSleep */
44117    winCurrentTime,        /* xCurrentTime */
44118    winGetLastError,       /* xGetLastError */
44119    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
44120    winSetSystemCall,      /* xSetSystemCall */
44121    winGetSystemCall,      /* xGetSystemCall */
44122    winNextSystemCall,     /* xNextSystemCall */
44123  };
44124#if defined(SQLITE_WIN32_HAS_WIDE)
44125  static sqlite3_vfs winLongPathVfs = {
44126    3,                     /* iVersion */
44127    sizeof(winFile),       /* szOsFile */
44128    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
44129    0,                     /* pNext */
44130    "win32-longpath",      /* zName */
44131    &winAppData,           /* pAppData */
44132    winOpen,               /* xOpen */
44133    winDelete,             /* xDelete */
44134    winAccess,             /* xAccess */
44135    winFullPathname,       /* xFullPathname */
44136    winDlOpen,             /* xDlOpen */
44137    winDlError,            /* xDlError */
44138    winDlSym,              /* xDlSym */
44139    winDlClose,            /* xDlClose */
44140    winRandomness,         /* xRandomness */
44141    winSleep,              /* xSleep */
44142    winCurrentTime,        /* xCurrentTime */
44143    winGetLastError,       /* xGetLastError */
44144    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
44145    winSetSystemCall,      /* xSetSystemCall */
44146    winGetSystemCall,      /* xGetSystemCall */
44147    winNextSystemCall,     /* xNextSystemCall */
44148  };
44149#endif
44150  static sqlite3_vfs winNolockVfs = {
44151    3,                     /* iVersion */
44152    sizeof(winFile),       /* szOsFile */
44153    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
44154    0,                     /* pNext */
44155    "win32-none",          /* zName */
44156    &winNolockAppData,     /* pAppData */
44157    winOpen,               /* xOpen */
44158    winDelete,             /* xDelete */
44159    winAccess,             /* xAccess */
44160    winFullPathname,       /* xFullPathname */
44161    winDlOpen,             /* xDlOpen */
44162    winDlError,            /* xDlError */
44163    winDlSym,              /* xDlSym */
44164    winDlClose,            /* xDlClose */
44165    winRandomness,         /* xRandomness */
44166    winSleep,              /* xSleep */
44167    winCurrentTime,        /* xCurrentTime */
44168    winGetLastError,       /* xGetLastError */
44169    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
44170    winSetSystemCall,      /* xSetSystemCall */
44171    winGetSystemCall,      /* xGetSystemCall */
44172    winNextSystemCall,     /* xNextSystemCall */
44173  };
44174#if defined(SQLITE_WIN32_HAS_WIDE)
44175  static sqlite3_vfs winLongPathNolockVfs = {
44176    3,                     /* iVersion */
44177    sizeof(winFile),       /* szOsFile */
44178    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
44179    0,                     /* pNext */
44180    "win32-longpath-none", /* zName */
44181    &winNolockAppData,     /* pAppData */
44182    winOpen,               /* xOpen */
44183    winDelete,             /* xDelete */
44184    winAccess,             /* xAccess */
44185    winFullPathname,       /* xFullPathname */
44186    winDlOpen,             /* xDlOpen */
44187    winDlError,            /* xDlError */
44188    winDlSym,              /* xDlSym */
44189    winDlClose,            /* xDlClose */
44190    winRandomness,         /* xRandomness */
44191    winSleep,              /* xSleep */
44192    winCurrentTime,        /* xCurrentTime */
44193    winGetLastError,       /* xGetLastError */
44194    winCurrentTimeInt64,   /* xCurrentTimeInt64 */
44195    winSetSystemCall,      /* xSetSystemCall */
44196    winGetSystemCall,      /* xGetSystemCall */
44197    winNextSystemCall,     /* xNextSystemCall */
44198  };
44199#endif
44200
44201  /* Double-check that the aSyscall[] array has been constructed
44202  ** correctly.  See ticket [bb3a86e890c8e96ab] */
44203  assert( ArraySize(aSyscall)==80 );
44204
44205  /* get memory map allocation granularity */
44206  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
44207#if SQLITE_OS_WINRT
44208  osGetNativeSystemInfo(&winSysInfo);
44209#else
44210  osGetSystemInfo(&winSysInfo);
44211#endif
44212  assert( winSysInfo.dwAllocationGranularity>0 );
44213  assert( winSysInfo.dwPageSize>0 );
44214
44215  sqlite3_vfs_register(&winVfs, 1);
44216
44217#if defined(SQLITE_WIN32_HAS_WIDE)
44218  sqlite3_vfs_register(&winLongPathVfs, 0);
44219#endif
44220
44221  sqlite3_vfs_register(&winNolockVfs, 0);
44222
44223#if defined(SQLITE_WIN32_HAS_WIDE)
44224  sqlite3_vfs_register(&winLongPathNolockVfs, 0);
44225#endif
44226
44227  return SQLITE_OK;
44228}
44229
44230SQLITE_API int sqlite3_os_end(void){
44231#if SQLITE_OS_WINRT
44232  if( sleepObj!=NULL ){
44233    osCloseHandle(sleepObj);
44234    sleepObj = NULL;
44235  }
44236#endif
44237  return SQLITE_OK;
44238}
44239
44240#endif /* SQLITE_OS_WIN */
44241
44242/************** End of os_win.c **********************************************/
44243/************** Begin file bitvec.c ******************************************/
44244/*
44245** 2008 February 16
44246**
44247** The author disclaims copyright to this source code.  In place of
44248** a legal notice, here is a blessing:
44249**
44250**    May you do good and not evil.
44251**    May you find forgiveness for yourself and forgive others.
44252**    May you share freely, never taking more than you give.
44253**
44254*************************************************************************
44255** This file implements an object that represents a fixed-length
44256** bitmap.  Bits are numbered starting with 1.
44257**
44258** A bitmap is used to record which pages of a database file have been
44259** journalled during a transaction, or which pages have the "dont-write"
44260** property.  Usually only a few pages are meet either condition.
44261** So the bitmap is usually sparse and has low cardinality.
44262** But sometimes (for example when during a DROP of a large table) most
44263** or all of the pages in a database can get journalled.  In those cases,
44264** the bitmap becomes dense with high cardinality.  The algorithm needs
44265** to handle both cases well.
44266**
44267** The size of the bitmap is fixed when the object is created.
44268**
44269** All bits are clear when the bitmap is created.  Individual bits
44270** may be set or cleared one at a time.
44271**
44272** Test operations are about 100 times more common that set operations.
44273** Clear operations are exceedingly rare.  There are usually between
44274** 5 and 500 set operations per Bitvec object, though the number of sets can
44275** sometimes grow into tens of thousands or larger.  The size of the
44276** Bitvec object is the number of pages in the database file at the
44277** start of a transaction, and is thus usually less than a few thousand,
44278** but can be as large as 2 billion for a really big database.
44279*/
44280/* #include "sqliteInt.h" */
44281
44282/* Size of the Bitvec structure in bytes. */
44283#define BITVEC_SZ        512
44284
44285/* Round the union size down to the nearest pointer boundary, since that's how
44286** it will be aligned within the Bitvec struct. */
44287#define BITVEC_USIZE \
44288    (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
44289
44290/* Type of the array "element" for the bitmap representation.
44291** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
44292** Setting this to the "natural word" size of your CPU may improve
44293** performance. */
44294#define BITVEC_TELEM     u8
44295/* Size, in bits, of the bitmap element. */
44296#define BITVEC_SZELEM    8
44297/* Number of elements in a bitmap array. */
44298#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
44299/* Number of bits in the bitmap array. */
44300#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
44301
44302/* Number of u32 values in hash table. */
44303#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
44304/* Maximum number of entries in hash table before
44305** sub-dividing and re-hashing. */
44306#define BITVEC_MXHASH    (BITVEC_NINT/2)
44307/* Hashing function for the aHash representation.
44308** Empirical testing showed that the *37 multiplier
44309** (an arbitrary prime)in the hash function provided
44310** no fewer collisions than the no-op *1. */
44311#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
44312
44313#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
44314
44315
44316/*
44317** A bitmap is an instance of the following structure.
44318**
44319** This bitmap records the existence of zero or more bits
44320** with values between 1 and iSize, inclusive.
44321**
44322** There are three possible representations of the bitmap.
44323** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
44324** bitmap.  The least significant bit is bit 1.
44325**
44326** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
44327** a hash table that will hold up to BITVEC_MXHASH distinct values.
44328**
44329** Otherwise, the value i is redirected into one of BITVEC_NPTR
44330** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
44331** handles up to iDivisor separate values of i.  apSub[0] holds
44332** values between 1 and iDivisor.  apSub[1] holds values between
44333** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
44334** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
44335** to hold deal with values between 1 and iDivisor.
44336*/
44337struct Bitvec {
44338  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
44339  u32 nSet;       /* Number of bits that are set - only valid for aHash
44340                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
44341                  ** this would be 125. */
44342  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
44343                  /* Should >=0 for apSub element. */
44344                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
44345                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
44346  union {
44347    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
44348    u32 aHash[BITVEC_NINT];      /* Hash table representation */
44349    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
44350  } u;
44351};
44352
44353/*
44354** Create a new bitmap object able to handle bits between 0 and iSize,
44355** inclusive.  Return a pointer to the new object.  Return NULL if
44356** malloc fails.
44357*/
44358SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
44359  Bitvec *p;
44360  assert( sizeof(*p)==BITVEC_SZ );
44361  p = sqlite3MallocZero( sizeof(*p) );
44362  if( p ){
44363    p->iSize = iSize;
44364  }
44365  return p;
44366}
44367
44368/*
44369** Check to see if the i-th bit is set.  Return true or false.
44370** If p is NULL (if the bitmap has not been created) or if
44371** i is out of range, then return false.
44372*/
44373SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
44374  assert( p!=0 );
44375  i--;
44376  if( i>=p->iSize ) return 0;
44377  while( p->iDivisor ){
44378    u32 bin = i/p->iDivisor;
44379    i = i%p->iDivisor;
44380    p = p->u.apSub[bin];
44381    if (!p) {
44382      return 0;
44383    }
44384  }
44385  if( p->iSize<=BITVEC_NBIT ){
44386    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
44387  } else{
44388    u32 h = BITVEC_HASH(i++);
44389    while( p->u.aHash[h] ){
44390      if( p->u.aHash[h]==i ) return 1;
44391      h = (h+1) % BITVEC_NINT;
44392    }
44393    return 0;
44394  }
44395}
44396SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
44397  return p!=0 && sqlite3BitvecTestNotNull(p,i);
44398}
44399
44400/*
44401** Set the i-th bit.  Return 0 on success and an error code if
44402** anything goes wrong.
44403**
44404** This routine might cause sub-bitmaps to be allocated.  Failing
44405** to get the memory needed to hold the sub-bitmap is the only
44406** that can go wrong with an insert, assuming p and i are valid.
44407**
44408** The calling function must ensure that p is a valid Bitvec object
44409** and that the value for "i" is within range of the Bitvec object.
44410** Otherwise the behavior is undefined.
44411*/
44412SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
44413  u32 h;
44414  if( p==0 ) return SQLITE_OK;
44415  assert( i>0 );
44416  assert( i<=p->iSize );
44417  i--;
44418  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
44419    u32 bin = i/p->iDivisor;
44420    i = i%p->iDivisor;
44421    if( p->u.apSub[bin]==0 ){
44422      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
44423      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
44424    }
44425    p = p->u.apSub[bin];
44426  }
44427  if( p->iSize<=BITVEC_NBIT ){
44428    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
44429    return SQLITE_OK;
44430  }
44431  h = BITVEC_HASH(i++);
44432  /* if there wasn't a hash collision, and this doesn't */
44433  /* completely fill the hash, then just add it without */
44434  /* worring about sub-dividing and re-hashing. */
44435  if( !p->u.aHash[h] ){
44436    if (p->nSet<(BITVEC_NINT-1)) {
44437      goto bitvec_set_end;
44438    } else {
44439      goto bitvec_set_rehash;
44440    }
44441  }
44442  /* there was a collision, check to see if it's already */
44443  /* in hash, if not, try to find a spot for it */
44444  do {
44445    if( p->u.aHash[h]==i ) return SQLITE_OK;
44446    h++;
44447    if( h>=BITVEC_NINT ) h = 0;
44448  } while( p->u.aHash[h] );
44449  /* we didn't find it in the hash.  h points to the first */
44450  /* available free spot. check to see if this is going to */
44451  /* make our hash too "full".  */
44452bitvec_set_rehash:
44453  if( p->nSet>=BITVEC_MXHASH ){
44454    unsigned int j;
44455    int rc;
44456    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
44457    if( aiValues==0 ){
44458      return SQLITE_NOMEM_BKPT;
44459    }else{
44460      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
44461      memset(p->u.apSub, 0, sizeof(p->u.apSub));
44462      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
44463      rc = sqlite3BitvecSet(p, i);
44464      for(j=0; j<BITVEC_NINT; j++){
44465        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
44466      }
44467      sqlite3StackFree(0, aiValues);
44468      return rc;
44469    }
44470  }
44471bitvec_set_end:
44472  p->nSet++;
44473  p->u.aHash[h] = i;
44474  return SQLITE_OK;
44475}
44476
44477/*
44478** Clear the i-th bit.
44479**
44480** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
44481** that BitvecClear can use to rebuilt its hash table.
44482*/
44483SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
44484  if( p==0 ) return;
44485  assert( i>0 );
44486  i--;
44487  while( p->iDivisor ){
44488    u32 bin = i/p->iDivisor;
44489    i = i%p->iDivisor;
44490    p = p->u.apSub[bin];
44491    if (!p) {
44492      return;
44493    }
44494  }
44495  if( p->iSize<=BITVEC_NBIT ){
44496    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
44497  }else{
44498    unsigned int j;
44499    u32 *aiValues = pBuf;
44500    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
44501    memset(p->u.aHash, 0, sizeof(p->u.aHash));
44502    p->nSet = 0;
44503    for(j=0; j<BITVEC_NINT; j++){
44504      if( aiValues[j] && aiValues[j]!=(i+1) ){
44505        u32 h = BITVEC_HASH(aiValues[j]-1);
44506        p->nSet++;
44507        while( p->u.aHash[h] ){
44508          h++;
44509          if( h>=BITVEC_NINT ) h = 0;
44510        }
44511        p->u.aHash[h] = aiValues[j];
44512      }
44513    }
44514  }
44515}
44516
44517/*
44518** Destroy a bitmap object.  Reclaim all memory used.
44519*/
44520SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
44521  if( p==0 ) return;
44522  if( p->iDivisor ){
44523    unsigned int i;
44524    for(i=0; i<BITVEC_NPTR; i++){
44525      sqlite3BitvecDestroy(p->u.apSub[i]);
44526    }
44527  }
44528  sqlite3_free(p);
44529}
44530
44531/*
44532** Return the value of the iSize parameter specified when Bitvec *p
44533** was created.
44534*/
44535SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
44536  return p->iSize;
44537}
44538
44539#ifndef SQLITE_UNTESTABLE
44540/*
44541** Let V[] be an array of unsigned characters sufficient to hold
44542** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
44543** Then the following macros can be used to set, clear, or test
44544** individual bits within V.
44545*/
44546#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
44547#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
44548#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
44549
44550/*
44551** This routine runs an extensive test of the Bitvec code.
44552**
44553** The input is an array of integers that acts as a program
44554** to test the Bitvec.  The integers are opcodes followed
44555** by 0, 1, or 3 operands, depending on the opcode.  Another
44556** opcode follows immediately after the last operand.
44557**
44558** There are 6 opcodes numbered from 0 through 5.  0 is the
44559** "halt" opcode and causes the test to end.
44560**
44561**    0          Halt and return the number of errors
44562**    1 N S X    Set N bits beginning with S and incrementing by X
44563**    2 N S X    Clear N bits beginning with S and incrementing by X
44564**    3 N        Set N randomly chosen bits
44565**    4 N        Clear N randomly chosen bits
44566**    5 N S X    Set N bits from S increment X in array only, not in bitvec
44567**
44568** The opcodes 1 through 4 perform set and clear operations are performed
44569** on both a Bitvec object and on a linear array of bits obtained from malloc.
44570** Opcode 5 works on the linear array only, not on the Bitvec.
44571** Opcode 5 is used to deliberately induce a fault in order to
44572** confirm that error detection works.
44573**
44574** At the conclusion of the test the linear array is compared
44575** against the Bitvec object.  If there are any differences,
44576** an error is returned.  If they are the same, zero is returned.
44577**
44578** If a memory allocation error occurs, return -1.
44579*/
44580SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
44581  Bitvec *pBitvec = 0;
44582  unsigned char *pV = 0;
44583  int rc = -1;
44584  int i, nx, pc, op;
44585  void *pTmpSpace;
44586
44587  /* Allocate the Bitvec to be tested and a linear array of
44588  ** bits to act as the reference */
44589  pBitvec = sqlite3BitvecCreate( sz );
44590  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
44591  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
44592  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
44593
44594  /* NULL pBitvec tests */
44595  sqlite3BitvecSet(0, 1);
44596  sqlite3BitvecClear(0, 1, pTmpSpace);
44597
44598  /* Run the program */
44599  pc = 0;
44600  while( (op = aOp[pc])!=0 ){
44601    switch( op ){
44602      case 1:
44603      case 2:
44604      case 5: {
44605        nx = 4;
44606        i = aOp[pc+2] - 1;
44607        aOp[pc+2] += aOp[pc+3];
44608        break;
44609      }
44610      case 3:
44611      case 4:
44612      default: {
44613        nx = 2;
44614        sqlite3_randomness(sizeof(i), &i);
44615        break;
44616      }
44617    }
44618    if( (--aOp[pc+1]) > 0 ) nx = 0;
44619    pc += nx;
44620    i = (i & 0x7fffffff)%sz;
44621    if( (op & 1)!=0 ){
44622      SETBIT(pV, (i+1));
44623      if( op!=5 ){
44624        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
44625      }
44626    }else{
44627      CLEARBIT(pV, (i+1));
44628      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
44629    }
44630  }
44631
44632  /* Test to make sure the linear array exactly matches the
44633  ** Bitvec object.  Start with the assumption that they do
44634  ** match (rc==0).  Change rc to non-zero if a discrepancy
44635  ** is found.
44636  */
44637  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
44638          + sqlite3BitvecTest(pBitvec, 0)
44639          + (sqlite3BitvecSize(pBitvec) - sz);
44640  for(i=1; i<=sz; i++){
44641    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
44642      rc = i;
44643      break;
44644    }
44645  }
44646
44647  /* Free allocated structure */
44648bitvec_end:
44649  sqlite3_free(pTmpSpace);
44650  sqlite3_free(pV);
44651  sqlite3BitvecDestroy(pBitvec);
44652  return rc;
44653}
44654#endif /* SQLITE_UNTESTABLE */
44655
44656/************** End of bitvec.c **********************************************/
44657/************** Begin file pcache.c ******************************************/
44658/*
44659** 2008 August 05
44660**
44661** The author disclaims copyright to this source code.  In place of
44662** a legal notice, here is a blessing:
44663**
44664**    May you do good and not evil.
44665**    May you find forgiveness for yourself and forgive others.
44666**    May you share freely, never taking more than you give.
44667**
44668*************************************************************************
44669** This file implements that page cache.
44670*/
44671/* #include "sqliteInt.h" */
44672
44673/*
44674** A complete page cache is an instance of this structure.  Every
44675** entry in the cache holds a single page of the database file.  The
44676** btree layer only operates on the cached copy of the database pages.
44677**
44678** A page cache entry is "clean" if it exactly matches what is currently
44679** on disk.  A page is "dirty" if it has been modified and needs to be
44680** persisted to disk.
44681**
44682** pDirty, pDirtyTail, pSynced:
44683**   All dirty pages are linked into the doubly linked list using
44684**   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
44685**   such that p was added to the list more recently than p->pDirtyNext.
44686**   PCache.pDirty points to the first (newest) element in the list and
44687**   pDirtyTail to the last (oldest).
44688**
44689**   The PCache.pSynced variable is used to optimize searching for a dirty
44690**   page to eject from the cache mid-transaction. It is better to eject
44691**   a page that does not require a journal sync than one that does.
44692**   Therefore, pSynced is maintained to that it *almost* always points
44693**   to either the oldest page in the pDirty/pDirtyTail list that has a
44694**   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
44695**   (so that the right page to eject can be found by following pDirtyPrev
44696**   pointers).
44697*/
44698struct PCache {
44699  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
44700  PgHdr *pSynced;                     /* Last synced page in dirty page list */
44701  int nRefSum;                        /* Sum of ref counts over all pages */
44702  int szCache;                        /* Configured cache size */
44703  int szSpill;                        /* Size before spilling occurs */
44704  int szPage;                         /* Size of every page in this cache */
44705  int szExtra;                        /* Size of extra space for each page */
44706  u8 bPurgeable;                      /* True if pages are on backing store */
44707  u8 eCreate;                         /* eCreate value for for xFetch() */
44708  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
44709  void *pStress;                      /* Argument to xStress */
44710  sqlite3_pcache *pCache;             /* Pluggable cache module */
44711};
44712
44713/********************************** Test and Debug Logic **********************/
44714/*
44715** Debug tracing macros.  Enable by by changing the "0" to "1" and
44716** recompiling.
44717**
44718** When sqlite3PcacheTrace is 1, single line trace messages are issued.
44719** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
44720** is displayed for many operations, resulting in a lot of output.
44721*/
44722#if defined(SQLITE_DEBUG) && 0
44723  int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
44724  int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
44725# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
44726  void pcacheDump(PCache *pCache){
44727    int N;
44728    int i, j;
44729    sqlite3_pcache_page *pLower;
44730    PgHdr *pPg;
44731    unsigned char *a;
44732
44733    if( sqlite3PcacheTrace<2 ) return;
44734    if( pCache->pCache==0 ) return;
44735    N = sqlite3PcachePagecount(pCache);
44736    if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
44737    for(i=1; i<=N; i++){
44738       pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
44739       if( pLower==0 ) continue;
44740       pPg = (PgHdr*)pLower->pExtra;
44741       printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
44742       a = (unsigned char *)pLower->pBuf;
44743       for(j=0; j<12; j++) printf("%02x", a[j]);
44744       printf("\n");
44745       if( pPg->pPage==0 ){
44746         sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
44747       }
44748    }
44749  }
44750  #else
44751# define pcacheTrace(X)
44752# define pcacheDump(X)
44753#endif
44754
44755/*
44756** Check invariants on a PgHdr entry.  Return true if everything is OK.
44757** Return false if any invariant is violated.
44758**
44759** This routine is for use inside of assert() statements only.  For
44760** example:
44761**
44762**          assert( sqlite3PcachePageSanity(pPg) );
44763*/
44764#ifdef SQLITE_DEBUG
44765SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
44766  PCache *pCache;
44767  assert( pPg!=0 );
44768  assert( pPg->pgno>0 || pPg->pPager==0 );    /* Page number is 1 or more */
44769  pCache = pPg->pCache;
44770  assert( pCache!=0 );      /* Every page has an associated PCache */
44771  if( pPg->flags & PGHDR_CLEAN ){
44772    assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
44773    assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */
44774    assert( pCache->pDirtyTail!=pPg );
44775  }
44776  /* WRITEABLE pages must also be DIRTY */
44777  if( pPg->flags & PGHDR_WRITEABLE ){
44778    assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
44779  }
44780  /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
44781  ** for example, when using the sqlite3PagerDontWrite() optimization:
44782  **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
44783  **    (2)  Page X moved to freelist, WRITEABLE is cleared
44784  **    (3)  Page X reused, WRITEABLE is set again
44785  ** If NEED_SYNC had been cleared in step 2, then it would not be reset
44786  ** in step 3, and page might be written into the database without first
44787  ** syncing the rollback journal, which might cause corruption on a power
44788  ** loss.
44789  **
44790  ** Another example is when the database page size is smaller than the
44791  ** disk sector size.  When any page of a sector is journalled, all pages
44792  ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
44793  ** in case they are later modified, since all pages in the same sector
44794  ** must be journalled and synced before any of those pages can be safely
44795  ** written.
44796  */
44797  return 1;
44798}
44799#endif /* SQLITE_DEBUG */
44800
44801
44802/********************************** Linked List Management ********************/
44803
44804/* Allowed values for second argument to pcacheManageDirtyList() */
44805#define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
44806#define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
44807#define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
44808
44809/*
44810** Manage pPage's participation on the dirty list.  Bits of the addRemove
44811** argument determines what operation to do.  The 0x01 bit means first
44812** remove pPage from the dirty list.  The 0x02 means add pPage back to
44813** the dirty list.  Doing both moves pPage to the front of the dirty list.
44814*/
44815static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
44816  PCache *p = pPage->pCache;
44817
44818  pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
44819                addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
44820                pPage->pgno));
44821  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
44822    assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
44823    assert( pPage->pDirtyPrev || pPage==p->pDirty );
44824
44825    /* Update the PCache1.pSynced variable if necessary. */
44826    if( p->pSynced==pPage ){
44827      p->pSynced = pPage->pDirtyPrev;
44828    }
44829
44830    if( pPage->pDirtyNext ){
44831      pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
44832    }else{
44833      assert( pPage==p->pDirtyTail );
44834      p->pDirtyTail = pPage->pDirtyPrev;
44835    }
44836    if( pPage->pDirtyPrev ){
44837      pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
44838    }else{
44839      /* If there are now no dirty pages in the cache, set eCreate to 2.
44840      ** This is an optimization that allows sqlite3PcacheFetch() to skip
44841      ** searching for a dirty page to eject from the cache when it might
44842      ** otherwise have to.  */
44843      assert( pPage==p->pDirty );
44844      p->pDirty = pPage->pDirtyNext;
44845      assert( p->bPurgeable || p->eCreate==2 );
44846      if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
44847        assert( p->bPurgeable==0 || p->eCreate==1 );
44848        p->eCreate = 2;
44849      }
44850    }
44851    pPage->pDirtyNext = 0;
44852    pPage->pDirtyPrev = 0;
44853  }
44854  if( addRemove & PCACHE_DIRTYLIST_ADD ){
44855    assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
44856
44857    pPage->pDirtyNext = p->pDirty;
44858    if( pPage->pDirtyNext ){
44859      assert( pPage->pDirtyNext->pDirtyPrev==0 );
44860      pPage->pDirtyNext->pDirtyPrev = pPage;
44861    }else{
44862      p->pDirtyTail = pPage;
44863      if( p->bPurgeable ){
44864        assert( p->eCreate==2 );
44865        p->eCreate = 1;
44866      }
44867    }
44868    p->pDirty = pPage;
44869
44870    /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
44871    ** pSynced to point to it. Checking the NEED_SYNC flag is an
44872    ** optimization, as if pSynced points to a page with the NEED_SYNC
44873    ** flag set sqlite3PcacheFetchStress() searches through all newer
44874    ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
44875    if( !p->pSynced
44876     && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
44877    ){
44878      p->pSynced = pPage;
44879    }
44880  }
44881  pcacheDump(p);
44882}
44883
44884/*
44885** Wrapper around the pluggable caches xUnpin method. If the cache is
44886** being used for an in-memory database, this function is a no-op.
44887*/
44888static void pcacheUnpin(PgHdr *p){
44889  if( p->pCache->bPurgeable ){
44890    pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
44891    sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
44892    pcacheDump(p->pCache);
44893  }
44894}
44895
44896/*
44897** Compute the number of pages of cache requested.   p->szCache is the
44898** cache size requested by the "PRAGMA cache_size" statement.
44899*/
44900static int numberOfCachePages(PCache *p){
44901  if( p->szCache>=0 ){
44902    /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
44903    ** suggested cache size is set to N. */
44904    return p->szCache;
44905  }else{
44906    /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
44907    ** the number of cache pages is adjusted to use approximately abs(N*1024)
44908    ** bytes of memory. */
44909    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
44910  }
44911}
44912
44913/*************************************************** General Interfaces ******
44914**
44915** Initialize and shutdown the page cache subsystem. Neither of these
44916** functions are threadsafe.
44917*/
44918SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
44919  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
44920    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
44921    ** built-in default page cache is used instead of the application defined
44922    ** page cache. */
44923    sqlite3PCacheSetDefault();
44924  }
44925  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
44926}
44927SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
44928  if( sqlite3GlobalConfig.pcache2.xShutdown ){
44929    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
44930    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
44931  }
44932}
44933
44934/*
44935** Return the size in bytes of a PCache object.
44936*/
44937SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
44938
44939/*
44940** Create a new PCache object. Storage space to hold the object
44941** has already been allocated and is passed in as the p pointer.
44942** The caller discovers how much space needs to be allocated by
44943** calling sqlite3PcacheSize().
44944**
44945** szExtra is some extra space allocated for each page.  The first
44946** 8 bytes of the extra space will be zeroed as the page is allocated,
44947** but remaining content will be uninitialized.  Though it is opaque
44948** to this module, the extra space really ends up being the MemPage
44949** structure in the pager.
44950*/
44951SQLITE_PRIVATE int sqlite3PcacheOpen(
44952  int szPage,                  /* Size of every page */
44953  int szExtra,                 /* Extra space associated with each page */
44954  int bPurgeable,              /* True if pages are on backing store */
44955  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
44956  void *pStress,               /* Argument to xStress */
44957  PCache *p                    /* Preallocated space for the PCache */
44958){
44959  memset(p, 0, sizeof(PCache));
44960  p->szPage = 1;
44961  p->szExtra = szExtra;
44962  assert( szExtra>=8 );  /* First 8 bytes will be zeroed */
44963  p->bPurgeable = bPurgeable;
44964  p->eCreate = 2;
44965  p->xStress = xStress;
44966  p->pStress = pStress;
44967  p->szCache = 100;
44968  p->szSpill = 1;
44969  pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
44970  return sqlite3PcacheSetPageSize(p, szPage);
44971}
44972
44973/*
44974** Change the page size for PCache object. The caller must ensure that there
44975** are no outstanding page references when this function is called.
44976*/
44977SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
44978  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
44979  if( pCache->szPage ){
44980    sqlite3_pcache *pNew;
44981    pNew = sqlite3GlobalConfig.pcache2.xCreate(
44982                szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
44983                pCache->bPurgeable
44984    );
44985    if( pNew==0 ) return SQLITE_NOMEM_BKPT;
44986    sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
44987    if( pCache->pCache ){
44988      sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
44989    }
44990    pCache->pCache = pNew;
44991    pCache->szPage = szPage;
44992    pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
44993  }
44994  return SQLITE_OK;
44995}
44996
44997/*
44998** Try to obtain a page from the cache.
44999**
45000** This routine returns a pointer to an sqlite3_pcache_page object if
45001** such an object is already in cache, or if a new one is created.
45002** This routine returns a NULL pointer if the object was not in cache
45003** and could not be created.
45004**
45005** The createFlags should be 0 to check for existing pages and should
45006** be 3 (not 1, but 3) to try to create a new page.
45007**
45008** If the createFlag is 0, then NULL is always returned if the page
45009** is not already in the cache.  If createFlag is 1, then a new page
45010** is created only if that can be done without spilling dirty pages
45011** and without exceeding the cache size limit.
45012**
45013** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
45014** initialize the sqlite3_pcache_page object and convert it into a
45015** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
45016** routines are split this way for performance reasons. When separated
45017** they can both (usually) operate without having to push values to
45018** the stack on entry and pop them back off on exit, which saves a
45019** lot of pushing and popping.
45020*/
45021SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
45022  PCache *pCache,       /* Obtain the page from this cache */
45023  Pgno pgno,            /* Page number to obtain */
45024  int createFlag        /* If true, create page if it does not exist already */
45025){
45026  int eCreate;
45027  sqlite3_pcache_page *pRes;
45028
45029  assert( pCache!=0 );
45030  assert( pCache->pCache!=0 );
45031  assert( createFlag==3 || createFlag==0 );
45032  assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
45033
45034  /* eCreate defines what to do if the page does not exist.
45035  **    0     Do not allocate a new page.  (createFlag==0)
45036  **    1     Allocate a new page if doing so is inexpensive.
45037  **          (createFlag==1 AND bPurgeable AND pDirty)
45038  **    2     Allocate a new page even it doing so is difficult.
45039  **          (createFlag==1 AND !(bPurgeable AND pDirty)
45040  */
45041  eCreate = createFlag & pCache->eCreate;
45042  assert( eCreate==0 || eCreate==1 || eCreate==2 );
45043  assert( createFlag==0 || pCache->eCreate==eCreate );
45044  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
45045  pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
45046  pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
45047               createFlag?" create":"",pRes));
45048  return pRes;
45049}
45050
45051/*
45052** If the sqlite3PcacheFetch() routine is unable to allocate a new
45053** page because no clean pages are available for reuse and the cache
45054** size limit has been reached, then this routine can be invoked to
45055** try harder to allocate a page.  This routine might invoke the stress
45056** callback to spill dirty pages to the journal.  It will then try to
45057** allocate the new page and will only fail to allocate a new page on
45058** an OOM error.
45059**
45060** This routine should be invoked only after sqlite3PcacheFetch() fails.
45061*/
45062SQLITE_PRIVATE int sqlite3PcacheFetchStress(
45063  PCache *pCache,                 /* Obtain the page from this cache */
45064  Pgno pgno,                      /* Page number to obtain */
45065  sqlite3_pcache_page **ppPage    /* Write result here */
45066){
45067  PgHdr *pPg;
45068  if( pCache->eCreate==2 ) return 0;
45069
45070  if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
45071    /* Find a dirty page to write-out and recycle. First try to find a
45072    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
45073    ** cleared), but if that is not possible settle for any other
45074    ** unreferenced dirty page.
45075    **
45076    ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
45077    ** flag is currently referenced, then the following may leave pSynced
45078    ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
45079    ** cleared). This is Ok, as pSynced is just an optimization.  */
45080    for(pPg=pCache->pSynced;
45081        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
45082        pPg=pPg->pDirtyPrev
45083    );
45084    pCache->pSynced = pPg;
45085    if( !pPg ){
45086      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
45087    }
45088    if( pPg ){
45089      int rc;
45090#ifdef SQLITE_LOG_CACHE_SPILL
45091      sqlite3_log(SQLITE_FULL,
45092                  "spill page %d making room for %d - cache used: %d/%d",
45093                  pPg->pgno, pgno,
45094                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
45095                numberOfCachePages(pCache));
45096#endif
45097      pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
45098      rc = pCache->xStress(pCache->pStress, pPg);
45099      pcacheDump(pCache);
45100      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
45101        return rc;
45102      }
45103    }
45104  }
45105  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
45106  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
45107}
45108
45109/*
45110** This is a helper routine for sqlite3PcacheFetchFinish()
45111**
45112** In the uncommon case where the page being fetched has not been
45113** initialized, this routine is invoked to do the initialization.
45114** This routine is broken out into a separate function since it
45115** requires extra stack manipulation that can be avoided in the common
45116** case.
45117*/
45118static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
45119  PCache *pCache,             /* Obtain the page from this cache */
45120  Pgno pgno,                  /* Page number obtained */
45121  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
45122){
45123  PgHdr *pPgHdr;
45124  assert( pPage!=0 );
45125  pPgHdr = (PgHdr*)pPage->pExtra;
45126  assert( pPgHdr->pPage==0 );
45127  memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
45128  pPgHdr->pPage = pPage;
45129  pPgHdr->pData = pPage->pBuf;
45130  pPgHdr->pExtra = (void *)&pPgHdr[1];
45131  memset(pPgHdr->pExtra, 0, 8);
45132  pPgHdr->pCache = pCache;
45133  pPgHdr->pgno = pgno;
45134  pPgHdr->flags = PGHDR_CLEAN;
45135  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
45136}
45137
45138/*
45139** This routine converts the sqlite3_pcache_page object returned by
45140** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
45141** must be called after sqlite3PcacheFetch() in order to get a usable
45142** result.
45143*/
45144SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
45145  PCache *pCache,             /* Obtain the page from this cache */
45146  Pgno pgno,                  /* Page number obtained */
45147  sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
45148){
45149  PgHdr *pPgHdr;
45150
45151  assert( pPage!=0 );
45152  pPgHdr = (PgHdr *)pPage->pExtra;
45153
45154  if( !pPgHdr->pPage ){
45155    return pcacheFetchFinishWithInit(pCache, pgno, pPage);
45156  }
45157  pCache->nRefSum++;
45158  pPgHdr->nRef++;
45159  assert( sqlite3PcachePageSanity(pPgHdr) );
45160  return pPgHdr;
45161}
45162
45163/*
45164** Decrement the reference count on a page. If the page is clean and the
45165** reference count drops to 0, then it is made eligible for recycling.
45166*/
45167SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
45168  assert( p->nRef>0 );
45169  p->pCache->nRefSum--;
45170  if( (--p->nRef)==0 ){
45171    if( p->flags&PGHDR_CLEAN ){
45172      pcacheUnpin(p);
45173    }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
45174      /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
45175      ** then page p is already at the head of the dirty list and the
45176      ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
45177      ** tag above.  */
45178      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
45179    }
45180  }
45181}
45182
45183/*
45184** Increase the reference count of a supplied page by 1.
45185*/
45186SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
45187  assert(p->nRef>0);
45188  assert( sqlite3PcachePageSanity(p) );
45189  p->nRef++;
45190  p->pCache->nRefSum++;
45191}
45192
45193/*
45194** Drop a page from the cache. There must be exactly one reference to the
45195** page. This function deletes that reference, so after it returns the
45196** page pointed to by p is invalid.
45197*/
45198SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
45199  assert( p->nRef==1 );
45200  assert( sqlite3PcachePageSanity(p) );
45201  if( p->flags&PGHDR_DIRTY ){
45202    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
45203  }
45204  p->pCache->nRefSum--;
45205  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
45206}
45207
45208/*
45209** Make sure the page is marked as dirty. If it isn't dirty already,
45210** make it so.
45211*/
45212SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
45213  assert( p->nRef>0 );
45214  assert( sqlite3PcachePageSanity(p) );
45215  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
45216    p->flags &= ~PGHDR_DONT_WRITE;
45217    if( p->flags & PGHDR_CLEAN ){
45218      p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
45219      pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
45220      assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
45221      pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
45222    }
45223    assert( sqlite3PcachePageSanity(p) );
45224  }
45225}
45226
45227/*
45228** Make sure the page is marked as clean. If it isn't clean already,
45229** make it so.
45230*/
45231SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
45232  assert( sqlite3PcachePageSanity(p) );
45233  if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
45234    assert( (p->flags & PGHDR_CLEAN)==0 );
45235    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
45236    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
45237    p->flags |= PGHDR_CLEAN;
45238    pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
45239    assert( sqlite3PcachePageSanity(p) );
45240    if( p->nRef==0 ){
45241      pcacheUnpin(p);
45242    }
45243  }
45244}
45245
45246/*
45247** Make every page in the cache clean.
45248*/
45249SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
45250  PgHdr *p;
45251  pcacheTrace(("%p.CLEAN-ALL\n",pCache));
45252  while( (p = pCache->pDirty)!=0 ){
45253    sqlite3PcacheMakeClean(p);
45254  }
45255}
45256
45257/*
45258** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
45259*/
45260SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
45261  PgHdr *p;
45262  pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
45263  for(p=pCache->pDirty; p; p=p->pDirtyNext){
45264    p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
45265  }
45266  pCache->pSynced = pCache->pDirtyTail;
45267}
45268
45269/*
45270** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
45271*/
45272SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
45273  PgHdr *p;
45274  for(p=pCache->pDirty; p; p=p->pDirtyNext){
45275    p->flags &= ~PGHDR_NEED_SYNC;
45276  }
45277  pCache->pSynced = pCache->pDirtyTail;
45278}
45279
45280/*
45281** Change the page number of page p to newPgno.
45282*/
45283SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
45284  PCache *pCache = p->pCache;
45285  assert( p->nRef>0 );
45286  assert( newPgno>0 );
45287  assert( sqlite3PcachePageSanity(p) );
45288  pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
45289  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
45290  p->pgno = newPgno;
45291  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
45292    pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
45293  }
45294}
45295
45296/*
45297** Drop every cache entry whose page number is greater than "pgno". The
45298** caller must ensure that there are no outstanding references to any pages
45299** other than page 1 with a page number greater than pgno.
45300**
45301** If there is a reference to page 1 and the pgno parameter passed to this
45302** function is 0, then the data area associated with page 1 is zeroed, but
45303** the page object is not dropped.
45304*/
45305SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
45306  if( pCache->pCache ){
45307    PgHdr *p;
45308    PgHdr *pNext;
45309    pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
45310    for(p=pCache->pDirty; p; p=pNext){
45311      pNext = p->pDirtyNext;
45312      /* This routine never gets call with a positive pgno except right
45313      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
45314      ** it must be that pgno==0.
45315      */
45316      assert( p->pgno>0 );
45317      if( p->pgno>pgno ){
45318        assert( p->flags&PGHDR_DIRTY );
45319        sqlite3PcacheMakeClean(p);
45320      }
45321    }
45322    if( pgno==0 && pCache->nRefSum ){
45323      sqlite3_pcache_page *pPage1;
45324      pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
45325      if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
45326                             ** pCache->nRefSum>0 */
45327        memset(pPage1->pBuf, 0, pCache->szPage);
45328        pgno = 1;
45329      }
45330    }
45331    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
45332  }
45333}
45334
45335/*
45336** Close a cache.
45337*/
45338SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
45339  assert( pCache->pCache!=0 );
45340  pcacheTrace(("%p.CLOSE\n",pCache));
45341  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
45342}
45343
45344/*
45345** Discard the contents of the cache.
45346*/
45347SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
45348  sqlite3PcacheTruncate(pCache, 0);
45349}
45350
45351/*
45352** Merge two lists of pages connected by pDirty and in pgno order.
45353** Do not bother fixing the pDirtyPrev pointers.
45354*/
45355static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
45356  PgHdr result, *pTail;
45357  pTail = &result;
45358  assert( pA!=0 && pB!=0 );
45359  for(;;){
45360    if( pA->pgno<pB->pgno ){
45361      pTail->pDirty = pA;
45362      pTail = pA;
45363      pA = pA->pDirty;
45364      if( pA==0 ){
45365        pTail->pDirty = pB;
45366        break;
45367      }
45368    }else{
45369      pTail->pDirty = pB;
45370      pTail = pB;
45371      pB = pB->pDirty;
45372      if( pB==0 ){
45373        pTail->pDirty = pA;
45374        break;
45375      }
45376    }
45377  }
45378  return result.pDirty;
45379}
45380
45381/*
45382** Sort the list of pages in accending order by pgno.  Pages are
45383** connected by pDirty pointers.  The pDirtyPrev pointers are
45384** corrupted by this sort.
45385**
45386** Since there cannot be more than 2^31 distinct pages in a database,
45387** there cannot be more than 31 buckets required by the merge sorter.
45388** One extra bucket is added to catch overflow in case something
45389** ever changes to make the previous sentence incorrect.
45390*/
45391#define N_SORT_BUCKET  32
45392static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
45393  PgHdr *a[N_SORT_BUCKET], *p;
45394  int i;
45395  memset(a, 0, sizeof(a));
45396  while( pIn ){
45397    p = pIn;
45398    pIn = p->pDirty;
45399    p->pDirty = 0;
45400    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
45401      if( a[i]==0 ){
45402        a[i] = p;
45403        break;
45404      }else{
45405        p = pcacheMergeDirtyList(a[i], p);
45406        a[i] = 0;
45407      }
45408    }
45409    if( NEVER(i==N_SORT_BUCKET-1) ){
45410      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
45411      ** the input list.  But that is impossible.
45412      */
45413      a[i] = pcacheMergeDirtyList(a[i], p);
45414    }
45415  }
45416  p = a[0];
45417  for(i=1; i<N_SORT_BUCKET; i++){
45418    if( a[i]==0 ) continue;
45419    p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
45420  }
45421  return p;
45422}
45423
45424/*
45425** Return a list of all dirty pages in the cache, sorted by page number.
45426*/
45427SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
45428  PgHdr *p;
45429  for(p=pCache->pDirty; p; p=p->pDirtyNext){
45430    p->pDirty = p->pDirtyNext;
45431  }
45432  return pcacheSortDirtyList(pCache->pDirty);
45433}
45434
45435/*
45436** Return the total number of references to all pages held by the cache.
45437**
45438** This is not the total number of pages referenced, but the sum of the
45439** reference count for all pages.
45440*/
45441SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
45442  return pCache->nRefSum;
45443}
45444
45445/*
45446** Return the number of references to the page supplied as an argument.
45447*/
45448SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
45449  return p->nRef;
45450}
45451
45452/*
45453** Return the total number of pages in the cache.
45454*/
45455SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
45456  assert( pCache->pCache!=0 );
45457  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
45458}
45459
45460#ifdef SQLITE_TEST
45461/*
45462** Get the suggested cache-size value.
45463*/
45464SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
45465  return numberOfCachePages(pCache);
45466}
45467#endif
45468
45469/*
45470** Set the suggested cache-size value.
45471*/
45472SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
45473  assert( pCache->pCache!=0 );
45474  pCache->szCache = mxPage;
45475  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
45476                                         numberOfCachePages(pCache));
45477}
45478
45479/*
45480** Set the suggested cache-spill value.  Make no changes if if the
45481** argument is zero.  Return the effective cache-spill size, which will
45482** be the larger of the szSpill and szCache.
45483*/
45484SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
45485  int res;
45486  assert( p->pCache!=0 );
45487  if( mxPage ){
45488    if( mxPage<0 ){
45489      mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
45490    }
45491    p->szSpill = mxPage;
45492  }
45493  res = numberOfCachePages(p);
45494  if( res<p->szSpill ) res = p->szSpill;
45495  return res;
45496}
45497
45498/*
45499** Free up as much memory as possible from the page cache.
45500*/
45501SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
45502  assert( pCache->pCache!=0 );
45503  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
45504}
45505
45506/*
45507** Return the size of the header added by this middleware layer
45508** in the page-cache hierarchy.
45509*/
45510SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
45511
45512/*
45513** Return the number of dirty pages currently in the cache, as a percentage
45514** of the configured cache size.
45515*/
45516SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
45517  PgHdr *pDirty;
45518  int nDirty = 0;
45519  int nCache = numberOfCachePages(pCache);
45520  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
45521  return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
45522}
45523
45524#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
45525/*
45526** For all dirty pages currently in the cache, invoke the specified
45527** callback. This is only used if the SQLITE_CHECK_PAGES macro is
45528** defined.
45529*/
45530SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
45531  PgHdr *pDirty;
45532  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
45533    xIter(pDirty);
45534  }
45535}
45536#endif
45537
45538/************** End of pcache.c **********************************************/
45539/************** Begin file pcache1.c *****************************************/
45540/*
45541** 2008 November 05
45542**
45543** The author disclaims copyright to this source code.  In place of
45544** a legal notice, here is a blessing:
45545**
45546**    May you do good and not evil.
45547**    May you find forgiveness for yourself and forgive others.
45548**    May you share freely, never taking more than you give.
45549**
45550*************************************************************************
45551**
45552** This file implements the default page cache implementation (the
45553** sqlite3_pcache interface). It also contains part of the implementation
45554** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
45555** If the default page cache implementation is overridden, then neither of
45556** these two features are available.
45557**
45558** A Page cache line looks like this:
45559**
45560**  -------------------------------------------------------------
45561**  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
45562**  -------------------------------------------------------------
45563**
45564** The database page content is up front (so that buffer overreads tend to
45565** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
45566** is the extension added by the btree.c module containing information such
45567** as the database page number and how that database page is used.  PgHdr
45568** is added by the pcache.c layer and contains information used to keep track
45569** of which pages are "dirty".  PgHdr1 is an extension added by this
45570** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
45571** PgHdr1 contains information needed to look up a page by its page number.
45572** The superclass sqlite3_pcache_page.pBuf points to the start of the
45573** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
45574**
45575** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
45576** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
45577** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
45578** size can vary according to architecture, compile-time options, and
45579** SQLite library version number.
45580**
45581** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
45582** using a separate memory allocation from the database page content.  This
45583** seeks to overcome the "clownshoe" problem (also called "internal
45584** fragmentation" in academic literature) of allocating a few bytes more
45585** than a power of two with the memory allocator rounding up to the next
45586** power of two, and leaving the rounded-up space unused.
45587**
45588** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
45589** with this module.  Information is passed back and forth as PgHdr1 pointers.
45590**
45591** The pcache.c and pager.c modules deal pointers to PgHdr objects.
45592** The btree.c module deals with pointers to MemPage objects.
45593**
45594** SOURCE OF PAGE CACHE MEMORY:
45595**
45596** Memory for a page might come from any of three sources:
45597**
45598**    (1)  The general-purpose memory allocator - sqlite3Malloc()
45599**    (2)  Global page-cache memory provided using sqlite3_config() with
45600**         SQLITE_CONFIG_PAGECACHE.
45601**    (3)  PCache-local bulk allocation.
45602**
45603** The third case is a chunk of heap memory (defaulting to 100 pages worth)
45604** that is allocated when the page cache is created.  The size of the local
45605** bulk allocation can be adjusted using
45606**
45607**     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
45608**
45609** If N is positive, then N pages worth of memory are allocated using a single
45610** sqlite3Malloc() call and that memory is used for the first N pages allocated.
45611** Or if N is negative, then -1024*N bytes of memory are allocated and used
45612** for as many pages as can be accomodated.
45613**
45614** Only one of (2) or (3) can be used.  Once the memory available to (2) or
45615** (3) is exhausted, subsequent allocations fail over to the general-purpose
45616** memory allocator (1).
45617**
45618** Earlier versions of SQLite used only methods (1) and (2).  But experiments
45619** show that method (3) with N==100 provides about a 5% performance boost for
45620** common workloads.
45621*/
45622/* #include "sqliteInt.h" */
45623
45624typedef struct PCache1 PCache1;
45625typedef struct PgHdr1 PgHdr1;
45626typedef struct PgFreeslot PgFreeslot;
45627typedef struct PGroup PGroup;
45628
45629/*
45630** Each cache entry is represented by an instance of the following
45631** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
45632** PgHdr1.pCache->szPage bytes is allocated directly before this structure
45633** in memory.
45634*/
45635struct PgHdr1 {
45636  sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
45637  unsigned int iKey;             /* Key value (page number) */
45638  u8 isPinned;                   /* Page in use, not on the LRU list */
45639  u8 isBulkLocal;                /* This page from bulk local storage */
45640  u8 isAnchor;                   /* This is the PGroup.lru element */
45641  PgHdr1 *pNext;                 /* Next in hash table chain */
45642  PCache1 *pCache;               /* Cache that currently owns this page */
45643  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
45644  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
45645};
45646
45647/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
45648** of one or more PCaches that are able to recycle each other's unpinned
45649** pages when they are under memory pressure.  A PGroup is an instance of
45650** the following object.
45651**
45652** This page cache implementation works in one of two modes:
45653**
45654**   (1)  Every PCache is the sole member of its own PGroup.  There is
45655**        one PGroup per PCache.
45656**
45657**   (2)  There is a single global PGroup that all PCaches are a member
45658**        of.
45659**
45660** Mode 1 uses more memory (since PCache instances are not able to rob
45661** unused pages from other PCaches) but it also operates without a mutex,
45662** and is therefore often faster.  Mode 2 requires a mutex in order to be
45663** threadsafe, but recycles pages more efficiently.
45664**
45665** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
45666** PGroup which is the pcache1.grp global variable and its mutex is
45667** SQLITE_MUTEX_STATIC_LRU.
45668*/
45669struct PGroup {
45670  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
45671  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
45672  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
45673  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
45674  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
45675  PgHdr1 lru;                    /* The beginning and end of the LRU list */
45676};
45677
45678/* Each page cache is an instance of the following object.  Every
45679** open database file (including each in-memory database and each
45680** temporary or transient database) has a single page cache which
45681** is an instance of this object.
45682**
45683** Pointers to structures of this type are cast and returned as
45684** opaque sqlite3_pcache* handles.
45685*/
45686struct PCache1 {
45687  /* Cache configuration parameters. Page size (szPage) and the purgeable
45688  ** flag (bPurgeable) are set when the cache is created. nMax may be
45689  ** modified at any time by a call to the pcache1Cachesize() method.
45690  ** The PGroup mutex must be held when accessing nMax.
45691  */
45692  PGroup *pGroup;                     /* PGroup this cache belongs to */
45693  int szPage;                         /* Size of database content section */
45694  int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
45695  int szAlloc;                        /* Total size of one pcache line */
45696  int bPurgeable;                     /* True if cache is purgeable */
45697  unsigned int nMin;                  /* Minimum number of pages reserved */
45698  unsigned int nMax;                  /* Configured "cache_size" value */
45699  unsigned int n90pct;                /* nMax*9/10 */
45700  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
45701
45702  /* Hash table of all pages. The following variables may only be accessed
45703  ** when the accessor is holding the PGroup mutex.
45704  */
45705  unsigned int nRecyclable;           /* Number of pages in the LRU list */
45706  unsigned int nPage;                 /* Total number of pages in apHash */
45707  unsigned int nHash;                 /* Number of slots in apHash[] */
45708  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
45709  PgHdr1 *pFree;                      /* List of unused pcache-local pages */
45710  void *pBulk;                        /* Bulk memory used by pcache-local */
45711};
45712
45713/*
45714** Free slots in the allocator used to divide up the global page cache
45715** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
45716*/
45717struct PgFreeslot {
45718  PgFreeslot *pNext;  /* Next free slot */
45719};
45720
45721/*
45722** Global data used by this cache.
45723*/
45724static SQLITE_WSD struct PCacheGlobal {
45725  PGroup grp;                    /* The global PGroup for mode (2) */
45726
45727  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
45728  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
45729  ** fixed at sqlite3_initialize() time and do not require mutex protection.
45730  ** The nFreeSlot and pFree values do require mutex protection.
45731  */
45732  int isInit;                    /* True if initialized */
45733  int separateCache;             /* Use a new PGroup for each PCache */
45734  int nInitPage;                 /* Initial bulk allocation size */
45735  int szSlot;                    /* Size of each free slot */
45736  int nSlot;                     /* The number of pcache slots */
45737  int nReserve;                  /* Try to keep nFreeSlot above this */
45738  void *pStart, *pEnd;           /* Bounds of global page cache memory */
45739  /* Above requires no mutex.  Use mutex below for variable that follow. */
45740  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
45741  PgFreeslot *pFree;             /* Free page blocks */
45742  int nFreeSlot;                 /* Number of unused pcache slots */
45743  /* The following value requires a mutex to change.  We skip the mutex on
45744  ** reading because (1) most platforms read a 32-bit integer atomically and
45745  ** (2) even if an incorrect value is read, no great harm is done since this
45746  ** is really just an optimization. */
45747  int bUnderPressure;            /* True if low on PAGECACHE memory */
45748} pcache1_g;
45749
45750/*
45751** All code in this file should access the global structure above via the
45752** alias "pcache1". This ensures that the WSD emulation is used when
45753** compiling for systems that do not support real WSD.
45754*/
45755#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
45756
45757/*
45758** Macros to enter and leave the PCache LRU mutex.
45759*/
45760#if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
45761# define pcache1EnterMutex(X)  assert((X)->mutex==0)
45762# define pcache1LeaveMutex(X)  assert((X)->mutex==0)
45763# define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
45764#else
45765# define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
45766# define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
45767# define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
45768#endif
45769
45770/******************************************************************************/
45771/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
45772
45773
45774/*
45775** This function is called during initialization if a static buffer is
45776** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
45777** verb to sqlite3_config(). Parameter pBuf points to an allocation large
45778** enough to contain 'n' buffers of 'sz' bytes each.
45779**
45780** This routine is called from sqlite3_initialize() and so it is guaranteed
45781** to be serialized already.  There is no need for further mutexing.
45782*/
45783SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
45784  if( pcache1.isInit ){
45785    PgFreeslot *p;
45786    if( pBuf==0 ) sz = n = 0;
45787    sz = ROUNDDOWN8(sz);
45788    pcache1.szSlot = sz;
45789    pcache1.nSlot = pcache1.nFreeSlot = n;
45790    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
45791    pcache1.pStart = pBuf;
45792    pcache1.pFree = 0;
45793    pcache1.bUnderPressure = 0;
45794    while( n-- ){
45795      p = (PgFreeslot*)pBuf;
45796      p->pNext = pcache1.pFree;
45797      pcache1.pFree = p;
45798      pBuf = (void*)&((char*)pBuf)[sz];
45799    }
45800    pcache1.pEnd = pBuf;
45801  }
45802}
45803
45804/*
45805** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
45806** true if pCache->pFree ends up containing one or more free pages.
45807*/
45808static int pcache1InitBulk(PCache1 *pCache){
45809  i64 szBulk;
45810  char *zBulk;
45811  if( pcache1.nInitPage==0 ) return 0;
45812  /* Do not bother with a bulk allocation if the cache size very small */
45813  if( pCache->nMax<3 ) return 0;
45814  sqlite3BeginBenignMalloc();
45815  if( pcache1.nInitPage>0 ){
45816    szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
45817  }else{
45818    szBulk = -1024 * (i64)pcache1.nInitPage;
45819  }
45820  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
45821    szBulk = pCache->szAlloc*(i64)pCache->nMax;
45822  }
45823  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
45824  sqlite3EndBenignMalloc();
45825  if( zBulk ){
45826    int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
45827    do{
45828      PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
45829      pX->page.pBuf = zBulk;
45830      pX->page.pExtra = &pX[1];
45831      pX->isBulkLocal = 1;
45832      pX->isAnchor = 0;
45833      pX->pNext = pCache->pFree;
45834      pCache->pFree = pX;
45835      zBulk += pCache->szAlloc;
45836    }while( --nBulk );
45837  }
45838  return pCache->pFree!=0;
45839}
45840
45841/*
45842** Malloc function used within this file to allocate space from the buffer
45843** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
45844** such buffer exists or there is no space left in it, this function falls
45845** back to sqlite3Malloc().
45846**
45847** Multiple threads can run this routine at the same time.  Global variables
45848** in pcache1 need to be protected via mutex.
45849*/
45850static void *pcache1Alloc(int nByte){
45851  void *p = 0;
45852  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45853  if( nByte<=pcache1.szSlot ){
45854    sqlite3_mutex_enter(pcache1.mutex);
45855    p = (PgHdr1 *)pcache1.pFree;
45856    if( p ){
45857      pcache1.pFree = pcache1.pFree->pNext;
45858      pcache1.nFreeSlot--;
45859      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
45860      assert( pcache1.nFreeSlot>=0 );
45861      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
45862      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
45863    }
45864    sqlite3_mutex_leave(pcache1.mutex);
45865  }
45866  if( p==0 ){
45867    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
45868    ** it from sqlite3Malloc instead.
45869    */
45870    p = sqlite3Malloc(nByte);
45871#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
45872    if( p ){
45873      int sz = sqlite3MallocSize(p);
45874      sqlite3_mutex_enter(pcache1.mutex);
45875      sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
45876      sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
45877      sqlite3_mutex_leave(pcache1.mutex);
45878    }
45879#endif
45880    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
45881  }
45882  return p;
45883}
45884
45885/*
45886** Free an allocated buffer obtained from pcache1Alloc().
45887*/
45888static void pcache1Free(void *p){
45889  if( p==0 ) return;
45890  if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
45891    PgFreeslot *pSlot;
45892    sqlite3_mutex_enter(pcache1.mutex);
45893    sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
45894    pSlot = (PgFreeslot*)p;
45895    pSlot->pNext = pcache1.pFree;
45896    pcache1.pFree = pSlot;
45897    pcache1.nFreeSlot++;
45898    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
45899    assert( pcache1.nFreeSlot<=pcache1.nSlot );
45900    sqlite3_mutex_leave(pcache1.mutex);
45901  }else{
45902    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
45903    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
45904#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
45905    {
45906      int nFreed = 0;
45907      nFreed = sqlite3MallocSize(p);
45908      sqlite3_mutex_enter(pcache1.mutex);
45909      sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
45910      sqlite3_mutex_leave(pcache1.mutex);
45911    }
45912#endif
45913    sqlite3_free(p);
45914  }
45915}
45916
45917#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45918/*
45919** Return the size of a pcache allocation
45920*/
45921static int pcache1MemSize(void *p){
45922  if( p>=pcache1.pStart && p<pcache1.pEnd ){
45923    return pcache1.szSlot;
45924  }else{
45925    int iSize;
45926    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
45927    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
45928    iSize = sqlite3MallocSize(p);
45929    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
45930    return iSize;
45931  }
45932}
45933#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45934
45935/*
45936** Allocate a new page object initially associated with cache pCache.
45937*/
45938static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
45939  PgHdr1 *p = 0;
45940  void *pPg;
45941
45942  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45943  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
45944    p = pCache->pFree;
45945    pCache->pFree = p->pNext;
45946    p->pNext = 0;
45947  }else{
45948#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45949    /* The group mutex must be released before pcache1Alloc() is called. This
45950    ** is because it might call sqlite3_release_memory(), which assumes that
45951    ** this mutex is not held. */
45952    assert( pcache1.separateCache==0 );
45953    assert( pCache->pGroup==&pcache1.grp );
45954    pcache1LeaveMutex(pCache->pGroup);
45955#endif
45956    if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
45957#ifdef SQLITE_PCACHE_SEPARATE_HEADER
45958    pPg = pcache1Alloc(pCache->szPage);
45959    p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
45960    if( !pPg || !p ){
45961      pcache1Free(pPg);
45962      sqlite3_free(p);
45963      pPg = 0;
45964    }
45965#else
45966    pPg = pcache1Alloc(pCache->szAlloc);
45967    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
45968#endif
45969    if( benignMalloc ){ sqlite3EndBenignMalloc(); }
45970#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45971    pcache1EnterMutex(pCache->pGroup);
45972#endif
45973    if( pPg==0 ) return 0;
45974    p->page.pBuf = pPg;
45975    p->page.pExtra = &p[1];
45976    p->isBulkLocal = 0;
45977    p->isAnchor = 0;
45978  }
45979  if( pCache->bPurgeable ){
45980    pCache->pGroup->nCurrentPage++;
45981  }
45982  return p;
45983}
45984
45985/*
45986** Free a page object allocated by pcache1AllocPage().
45987*/
45988static void pcache1FreePage(PgHdr1 *p){
45989  PCache1 *pCache;
45990  assert( p!=0 );
45991  pCache = p->pCache;
45992  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
45993  if( p->isBulkLocal ){
45994    p->pNext = pCache->pFree;
45995    pCache->pFree = p;
45996  }else{
45997    pcache1Free(p->page.pBuf);
45998#ifdef SQLITE_PCACHE_SEPARATE_HEADER
45999    sqlite3_free(p);
46000#endif
46001  }
46002  if( pCache->bPurgeable ){
46003    pCache->pGroup->nCurrentPage--;
46004  }
46005}
46006
46007/*
46008** Malloc function used by SQLite to obtain space from the buffer configured
46009** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
46010** exists, this function falls back to sqlite3Malloc().
46011*/
46012SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
46013  return pcache1Alloc(sz);
46014}
46015
46016/*
46017** Free an allocated buffer obtained from sqlite3PageMalloc().
46018*/
46019SQLITE_PRIVATE void sqlite3PageFree(void *p){
46020  pcache1Free(p);
46021}
46022
46023
46024/*
46025** Return true if it desirable to avoid allocating a new page cache
46026** entry.
46027**
46028** If memory was allocated specifically to the page cache using
46029** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
46030** it is desirable to avoid allocating a new page cache entry because
46031** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
46032** for all page cache needs and we should not need to spill the
46033** allocation onto the heap.
46034**
46035** Or, the heap is used for all page cache memory but the heap is
46036** under memory pressure, then again it is desirable to avoid
46037** allocating a new page cache entry in order to avoid stressing
46038** the heap even further.
46039*/
46040static int pcache1UnderMemoryPressure(PCache1 *pCache){
46041  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
46042    return pcache1.bUnderPressure;
46043  }else{
46044    return sqlite3HeapNearlyFull();
46045  }
46046}
46047
46048/******************************************************************************/
46049/******** General Implementation Functions ************************************/
46050
46051/*
46052** This function is used to resize the hash table used by the cache passed
46053** as the first argument.
46054**
46055** The PCache mutex must be held when this function is called.
46056*/
46057static void pcache1ResizeHash(PCache1 *p){
46058  PgHdr1 **apNew;
46059  unsigned int nNew;
46060  unsigned int i;
46061
46062  assert( sqlite3_mutex_held(p->pGroup->mutex) );
46063
46064  nNew = p->nHash*2;
46065  if( nNew<256 ){
46066    nNew = 256;
46067  }
46068
46069  pcache1LeaveMutex(p->pGroup);
46070  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
46071  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
46072  if( p->nHash ){ sqlite3EndBenignMalloc(); }
46073  pcache1EnterMutex(p->pGroup);
46074  if( apNew ){
46075    for(i=0; i<p->nHash; i++){
46076      PgHdr1 *pPage;
46077      PgHdr1 *pNext = p->apHash[i];
46078      while( (pPage = pNext)!=0 ){
46079        unsigned int h = pPage->iKey % nNew;
46080        pNext = pPage->pNext;
46081        pPage->pNext = apNew[h];
46082        apNew[h] = pPage;
46083      }
46084    }
46085    sqlite3_free(p->apHash);
46086    p->apHash = apNew;
46087    p->nHash = nNew;
46088  }
46089}
46090
46091/*
46092** This function is used internally to remove the page pPage from the
46093** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
46094** LRU list, then this function is a no-op.
46095**
46096** The PGroup mutex must be held when this function is called.
46097*/
46098static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
46099  PCache1 *pCache;
46100
46101  assert( pPage!=0 );
46102  assert( pPage->isPinned==0 );
46103  pCache = pPage->pCache;
46104  assert( pPage->pLruNext );
46105  assert( pPage->pLruPrev );
46106  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
46107  pPage->pLruPrev->pLruNext = pPage->pLruNext;
46108  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
46109  pPage->pLruNext = 0;
46110  pPage->pLruPrev = 0;
46111  pPage->isPinned = 1;
46112  assert( pPage->isAnchor==0 );
46113  assert( pCache->pGroup->lru.isAnchor==1 );
46114  pCache->nRecyclable--;
46115  return pPage;
46116}
46117
46118
46119/*
46120** Remove the page supplied as an argument from the hash table
46121** (PCache1.apHash structure) that it is currently stored in.
46122** Also free the page if freePage is true.
46123**
46124** The PGroup mutex must be held when this function is called.
46125*/
46126static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
46127  unsigned int h;
46128  PCache1 *pCache = pPage->pCache;
46129  PgHdr1 **pp;
46130
46131  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
46132  h = pPage->iKey % pCache->nHash;
46133  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
46134  *pp = (*pp)->pNext;
46135
46136  pCache->nPage--;
46137  if( freeFlag ) pcache1FreePage(pPage);
46138}
46139
46140/*
46141** If there are currently more than nMaxPage pages allocated, try
46142** to recycle pages to reduce the number allocated to nMaxPage.
46143*/
46144static void pcache1EnforceMaxPage(PCache1 *pCache){
46145  PGroup *pGroup = pCache->pGroup;
46146  PgHdr1 *p;
46147  assert( sqlite3_mutex_held(pGroup->mutex) );
46148  while( pGroup->nCurrentPage>pGroup->nMaxPage
46149      && (p=pGroup->lru.pLruPrev)->isAnchor==0
46150  ){
46151    assert( p->pCache->pGroup==pGroup );
46152    assert( p->isPinned==0 );
46153    pcache1PinPage(p);
46154    pcache1RemoveFromHash(p, 1);
46155  }
46156  if( pCache->nPage==0 && pCache->pBulk ){
46157    sqlite3_free(pCache->pBulk);
46158    pCache->pBulk = pCache->pFree = 0;
46159  }
46160}
46161
46162/*
46163** Discard all pages from cache pCache with a page number (key value)
46164** greater than or equal to iLimit. Any pinned pages that meet this
46165** criteria are unpinned before they are discarded.
46166**
46167** The PCache mutex must be held when this function is called.
46168*/
46169static void pcache1TruncateUnsafe(
46170  PCache1 *pCache,             /* The cache to truncate */
46171  unsigned int iLimit          /* Drop pages with this pgno or larger */
46172){
46173  TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
46174  unsigned int h, iStop;
46175  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
46176  assert( pCache->iMaxKey >= iLimit );
46177  assert( pCache->nHash > 0 );
46178  if( pCache->iMaxKey - iLimit < pCache->nHash ){
46179    /* If we are just shaving the last few pages off the end of the
46180    ** cache, then there is no point in scanning the entire hash table.
46181    ** Only scan those hash slots that might contain pages that need to
46182    ** be removed. */
46183    h = iLimit % pCache->nHash;
46184    iStop = pCache->iMaxKey % pCache->nHash;
46185    TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
46186  }else{
46187    /* This is the general case where many pages are being removed.
46188    ** It is necessary to scan the entire hash table */
46189    h = pCache->nHash/2;
46190    iStop = h - 1;
46191  }
46192  for(;;){
46193    PgHdr1 **pp;
46194    PgHdr1 *pPage;
46195    assert( h<pCache->nHash );
46196    pp = &pCache->apHash[h];
46197    while( (pPage = *pp)!=0 ){
46198      if( pPage->iKey>=iLimit ){
46199        pCache->nPage--;
46200        *pp = pPage->pNext;
46201        if( !pPage->isPinned ) pcache1PinPage(pPage);
46202        pcache1FreePage(pPage);
46203      }else{
46204        pp = &pPage->pNext;
46205        TESTONLY( if( nPage>=0 ) nPage++; )
46206      }
46207    }
46208    if( h==iStop ) break;
46209    h = (h+1) % pCache->nHash;
46210  }
46211  assert( nPage<0 || pCache->nPage==(unsigned)nPage );
46212}
46213
46214/******************************************************************************/
46215/******** sqlite3_pcache Methods **********************************************/
46216
46217/*
46218** Implementation of the sqlite3_pcache.xInit method.
46219*/
46220static int pcache1Init(void *NotUsed){
46221  UNUSED_PARAMETER(NotUsed);
46222  assert( pcache1.isInit==0 );
46223  memset(&pcache1, 0, sizeof(pcache1));
46224
46225
46226  /*
46227  ** The pcache1.separateCache variable is true if each PCache has its own
46228  ** private PGroup (mode-1).  pcache1.separateCache is false if the single
46229  ** PGroup in pcache1.grp is used for all page caches (mode-2).
46230  **
46231  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
46232  **
46233  **   *  Use a unified cache in single-threaded applications that have
46234  **      configured a start-time buffer for use as page-cache memory using
46235  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
46236  **      pBuf argument.
46237  **
46238  **   *  Otherwise use separate caches (mode-1)
46239  */
46240#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
46241  pcache1.separateCache = 0;
46242#elif SQLITE_THREADSAFE
46243  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
46244                          || sqlite3GlobalConfig.bCoreMutex>0;
46245#else
46246  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
46247#endif
46248
46249#if SQLITE_THREADSAFE
46250  if( sqlite3GlobalConfig.bCoreMutex ){
46251    pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
46252    pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
46253  }
46254#endif
46255  if( pcache1.separateCache
46256   && sqlite3GlobalConfig.nPage!=0
46257   && sqlite3GlobalConfig.pPage==0
46258  ){
46259    pcache1.nInitPage = sqlite3GlobalConfig.nPage;
46260  }else{
46261    pcache1.nInitPage = 0;
46262  }
46263  pcache1.grp.mxPinned = 10;
46264  pcache1.isInit = 1;
46265  return SQLITE_OK;
46266}
46267
46268/*
46269** Implementation of the sqlite3_pcache.xShutdown method.
46270** Note that the static mutex allocated in xInit does
46271** not need to be freed.
46272*/
46273static void pcache1Shutdown(void *NotUsed){
46274  UNUSED_PARAMETER(NotUsed);
46275  assert( pcache1.isInit!=0 );
46276  memset(&pcache1, 0, sizeof(pcache1));
46277}
46278
46279/* forward declaration */
46280static void pcache1Destroy(sqlite3_pcache *p);
46281
46282/*
46283** Implementation of the sqlite3_pcache.xCreate method.
46284**
46285** Allocate a new cache.
46286*/
46287static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
46288  PCache1 *pCache;      /* The newly created page cache */
46289  PGroup *pGroup;       /* The group the new page cache will belong to */
46290  int sz;               /* Bytes of memory required to allocate the new cache */
46291
46292  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
46293  assert( szExtra < 300 );
46294
46295  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
46296  pCache = (PCache1 *)sqlite3MallocZero(sz);
46297  if( pCache ){
46298    if( pcache1.separateCache ){
46299      pGroup = (PGroup*)&pCache[1];
46300      pGroup->mxPinned = 10;
46301    }else{
46302      pGroup = &pcache1.grp;
46303    }
46304    if( pGroup->lru.isAnchor==0 ){
46305      pGroup->lru.isAnchor = 1;
46306      pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
46307    }
46308    pCache->pGroup = pGroup;
46309    pCache->szPage = szPage;
46310    pCache->szExtra = szExtra;
46311    pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
46312    pCache->bPurgeable = (bPurgeable ? 1 : 0);
46313    pcache1EnterMutex(pGroup);
46314    pcache1ResizeHash(pCache);
46315    if( bPurgeable ){
46316      pCache->nMin = 10;
46317      pGroup->nMinPage += pCache->nMin;
46318      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
46319    }
46320    pcache1LeaveMutex(pGroup);
46321    if( pCache->nHash==0 ){
46322      pcache1Destroy((sqlite3_pcache*)pCache);
46323      pCache = 0;
46324    }
46325  }
46326  return (sqlite3_pcache *)pCache;
46327}
46328
46329/*
46330** Implementation of the sqlite3_pcache.xCachesize method.
46331**
46332** Configure the cache_size limit for a cache.
46333*/
46334static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
46335  PCache1 *pCache = (PCache1 *)p;
46336  if( pCache->bPurgeable ){
46337    PGroup *pGroup = pCache->pGroup;
46338    pcache1EnterMutex(pGroup);
46339    pGroup->nMaxPage += (nMax - pCache->nMax);
46340    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
46341    pCache->nMax = nMax;
46342    pCache->n90pct = pCache->nMax*9/10;
46343    pcache1EnforceMaxPage(pCache);
46344    pcache1LeaveMutex(pGroup);
46345  }
46346}
46347
46348/*
46349** Implementation of the sqlite3_pcache.xShrink method.
46350**
46351** Free up as much memory as possible.
46352*/
46353static void pcache1Shrink(sqlite3_pcache *p){
46354  PCache1 *pCache = (PCache1*)p;
46355  if( pCache->bPurgeable ){
46356    PGroup *pGroup = pCache->pGroup;
46357    int savedMaxPage;
46358    pcache1EnterMutex(pGroup);
46359    savedMaxPage = pGroup->nMaxPage;
46360    pGroup->nMaxPage = 0;
46361    pcache1EnforceMaxPage(pCache);
46362    pGroup->nMaxPage = savedMaxPage;
46363    pcache1LeaveMutex(pGroup);
46364  }
46365}
46366
46367/*
46368** Implementation of the sqlite3_pcache.xPagecount method.
46369*/
46370static int pcache1Pagecount(sqlite3_pcache *p){
46371  int n;
46372  PCache1 *pCache = (PCache1*)p;
46373  pcache1EnterMutex(pCache->pGroup);
46374  n = pCache->nPage;
46375  pcache1LeaveMutex(pCache->pGroup);
46376  return n;
46377}
46378
46379
46380/*
46381** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
46382** in the header of the pcache1Fetch() procedure.
46383**
46384** This steps are broken out into a separate procedure because they are
46385** usually not needed, and by avoiding the stack initialization required
46386** for these steps, the main pcache1Fetch() procedure can run faster.
46387*/
46388static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
46389  PCache1 *pCache,
46390  unsigned int iKey,
46391  int createFlag
46392){
46393  unsigned int nPinned;
46394  PGroup *pGroup = pCache->pGroup;
46395  PgHdr1 *pPage = 0;
46396
46397  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
46398  assert( pCache->nPage >= pCache->nRecyclable );
46399  nPinned = pCache->nPage - pCache->nRecyclable;
46400  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
46401  assert( pCache->n90pct == pCache->nMax*9/10 );
46402  if( createFlag==1 && (
46403        nPinned>=pGroup->mxPinned
46404     || nPinned>=pCache->n90pct
46405     || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
46406  )){
46407    return 0;
46408  }
46409
46410  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
46411  assert( pCache->nHash>0 && pCache->apHash );
46412
46413  /* Step 4. Try to recycle a page. */
46414  if( pCache->bPurgeable
46415   && !pGroup->lru.pLruPrev->isAnchor
46416   && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
46417  ){
46418    PCache1 *pOther;
46419    pPage = pGroup->lru.pLruPrev;
46420    assert( pPage->isPinned==0 );
46421    pcache1RemoveFromHash(pPage, 0);
46422    pcache1PinPage(pPage);
46423    pOther = pPage->pCache;
46424    if( pOther->szAlloc != pCache->szAlloc ){
46425      pcache1FreePage(pPage);
46426      pPage = 0;
46427    }else{
46428      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
46429    }
46430  }
46431
46432  /* Step 5. If a usable page buffer has still not been found,
46433  ** attempt to allocate a new one.
46434  */
46435  if( !pPage ){
46436    pPage = pcache1AllocPage(pCache, createFlag==1);
46437  }
46438
46439  if( pPage ){
46440    unsigned int h = iKey % pCache->nHash;
46441    pCache->nPage++;
46442    pPage->iKey = iKey;
46443    pPage->pNext = pCache->apHash[h];
46444    pPage->pCache = pCache;
46445    pPage->pLruPrev = 0;
46446    pPage->pLruNext = 0;
46447    pPage->isPinned = 1;
46448    *(void **)pPage->page.pExtra = 0;
46449    pCache->apHash[h] = pPage;
46450    if( iKey>pCache->iMaxKey ){
46451      pCache->iMaxKey = iKey;
46452    }
46453  }
46454  return pPage;
46455}
46456
46457/*
46458** Implementation of the sqlite3_pcache.xFetch method.
46459**
46460** Fetch a page by key value.
46461**
46462** Whether or not a new page may be allocated by this function depends on
46463** the value of the createFlag argument.  0 means do not allocate a new
46464** page.  1 means allocate a new page if space is easily available.  2
46465** means to try really hard to allocate a new page.
46466**
46467** For a non-purgeable cache (a cache used as the storage for an in-memory
46468** database) there is really no difference between createFlag 1 and 2.  So
46469** the calling function (pcache.c) will never have a createFlag of 1 on
46470** a non-purgeable cache.
46471**
46472** There are three different approaches to obtaining space for a page,
46473** depending on the value of parameter createFlag (which may be 0, 1 or 2).
46474**
46475**   1. Regardless of the value of createFlag, the cache is searched for a
46476**      copy of the requested page. If one is found, it is returned.
46477**
46478**   2. If createFlag==0 and the page is not already in the cache, NULL is
46479**      returned.
46480**
46481**   3. If createFlag is 1, and the page is not already in the cache, then
46482**      return NULL (do not allocate a new page) if any of the following
46483**      conditions are true:
46484**
46485**       (a) the number of pages pinned by the cache is greater than
46486**           PCache1.nMax, or
46487**
46488**       (b) the number of pages pinned by the cache is greater than
46489**           the sum of nMax for all purgeable caches, less the sum of
46490**           nMin for all other purgeable caches, or
46491**
46492**   4. If none of the first three conditions apply and the cache is marked
46493**      as purgeable, and if one of the following is true:
46494**
46495**       (a) The number of pages allocated for the cache is already
46496**           PCache1.nMax, or
46497**
46498**       (b) The number of pages allocated for all purgeable caches is
46499**           already equal to or greater than the sum of nMax for all
46500**           purgeable caches,
46501**
46502**       (c) The system is under memory pressure and wants to avoid
46503**           unnecessary pages cache entry allocations
46504**
46505**      then attempt to recycle a page from the LRU list. If it is the right
46506**      size, return the recycled buffer. Otherwise, free the buffer and
46507**      proceed to step 5.
46508**
46509**   5. Otherwise, allocate and return a new page buffer.
46510**
46511** There are two versions of this routine.  pcache1FetchWithMutex() is
46512** the general case.  pcache1FetchNoMutex() is a faster implementation for
46513** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
46514** invokes the appropriate routine.
46515*/
46516static PgHdr1 *pcache1FetchNoMutex(
46517  sqlite3_pcache *p,
46518  unsigned int iKey,
46519  int createFlag
46520){
46521  PCache1 *pCache = (PCache1 *)p;
46522  PgHdr1 *pPage = 0;
46523
46524  /* Step 1: Search the hash table for an existing entry. */
46525  pPage = pCache->apHash[iKey % pCache->nHash];
46526  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
46527
46528  /* Step 2: If the page was found in the hash table, then return it.
46529  ** If the page was not in the hash table and createFlag is 0, abort.
46530  ** Otherwise (page not in hash and createFlag!=0) continue with
46531  ** subsequent steps to try to create the page. */
46532  if( pPage ){
46533    if( !pPage->isPinned ){
46534      return pcache1PinPage(pPage);
46535    }else{
46536      return pPage;
46537    }
46538  }else if( createFlag ){
46539    /* Steps 3, 4, and 5 implemented by this subroutine */
46540    return pcache1FetchStage2(pCache, iKey, createFlag);
46541  }else{
46542    return 0;
46543  }
46544}
46545#if PCACHE1_MIGHT_USE_GROUP_MUTEX
46546static PgHdr1 *pcache1FetchWithMutex(
46547  sqlite3_pcache *p,
46548  unsigned int iKey,
46549  int createFlag
46550){
46551  PCache1 *pCache = (PCache1 *)p;
46552  PgHdr1 *pPage;
46553
46554  pcache1EnterMutex(pCache->pGroup);
46555  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
46556  assert( pPage==0 || pCache->iMaxKey>=iKey );
46557  pcache1LeaveMutex(pCache->pGroup);
46558  return pPage;
46559}
46560#endif
46561static sqlite3_pcache_page *pcache1Fetch(
46562  sqlite3_pcache *p,
46563  unsigned int iKey,
46564  int createFlag
46565){
46566#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
46567  PCache1 *pCache = (PCache1 *)p;
46568#endif
46569
46570  assert( offsetof(PgHdr1,page)==0 );
46571  assert( pCache->bPurgeable || createFlag!=1 );
46572  assert( pCache->bPurgeable || pCache->nMin==0 );
46573  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
46574  assert( pCache->nMin==0 || pCache->bPurgeable );
46575  assert( pCache->nHash>0 );
46576#if PCACHE1_MIGHT_USE_GROUP_MUTEX
46577  if( pCache->pGroup->mutex ){
46578    return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
46579  }else
46580#endif
46581  {
46582    return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
46583  }
46584}
46585
46586
46587/*
46588** Implementation of the sqlite3_pcache.xUnpin method.
46589**
46590** Mark a page as unpinned (eligible for asynchronous recycling).
46591*/
46592static void pcache1Unpin(
46593  sqlite3_pcache *p,
46594  sqlite3_pcache_page *pPg,
46595  int reuseUnlikely
46596){
46597  PCache1 *pCache = (PCache1 *)p;
46598  PgHdr1 *pPage = (PgHdr1 *)pPg;
46599  PGroup *pGroup = pCache->pGroup;
46600
46601  assert( pPage->pCache==pCache );
46602  pcache1EnterMutex(pGroup);
46603
46604  /* It is an error to call this function if the page is already
46605  ** part of the PGroup LRU list.
46606  */
46607  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
46608  assert( pPage->isPinned==1 );
46609
46610  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
46611    pcache1RemoveFromHash(pPage, 1);
46612  }else{
46613    /* Add the page to the PGroup LRU list. */
46614    PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
46615    pPage->pLruPrev = &pGroup->lru;
46616    (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
46617    *ppFirst = pPage;
46618    pCache->nRecyclable++;
46619    pPage->isPinned = 0;
46620  }
46621
46622  pcache1LeaveMutex(pCache->pGroup);
46623}
46624
46625/*
46626** Implementation of the sqlite3_pcache.xRekey method.
46627*/
46628static void pcache1Rekey(
46629  sqlite3_pcache *p,
46630  sqlite3_pcache_page *pPg,
46631  unsigned int iOld,
46632  unsigned int iNew
46633){
46634  PCache1 *pCache = (PCache1 *)p;
46635  PgHdr1 *pPage = (PgHdr1 *)pPg;
46636  PgHdr1 **pp;
46637  unsigned int h;
46638  assert( pPage->iKey==iOld );
46639  assert( pPage->pCache==pCache );
46640
46641  pcache1EnterMutex(pCache->pGroup);
46642
46643  h = iOld%pCache->nHash;
46644  pp = &pCache->apHash[h];
46645  while( (*pp)!=pPage ){
46646    pp = &(*pp)->pNext;
46647  }
46648  *pp = pPage->pNext;
46649
46650  h = iNew%pCache->nHash;
46651  pPage->iKey = iNew;
46652  pPage->pNext = pCache->apHash[h];
46653  pCache->apHash[h] = pPage;
46654  if( iNew>pCache->iMaxKey ){
46655    pCache->iMaxKey = iNew;
46656  }
46657
46658  pcache1LeaveMutex(pCache->pGroup);
46659}
46660
46661/*
46662** Implementation of the sqlite3_pcache.xTruncate method.
46663**
46664** Discard all unpinned pages in the cache with a page number equal to
46665** or greater than parameter iLimit. Any pinned pages with a page number
46666** equal to or greater than iLimit are implicitly unpinned.
46667*/
46668static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
46669  PCache1 *pCache = (PCache1 *)p;
46670  pcache1EnterMutex(pCache->pGroup);
46671  if( iLimit<=pCache->iMaxKey ){
46672    pcache1TruncateUnsafe(pCache, iLimit);
46673    pCache->iMaxKey = iLimit-1;
46674  }
46675  pcache1LeaveMutex(pCache->pGroup);
46676}
46677
46678/*
46679** Implementation of the sqlite3_pcache.xDestroy method.
46680**
46681** Destroy a cache allocated using pcache1Create().
46682*/
46683static void pcache1Destroy(sqlite3_pcache *p){
46684  PCache1 *pCache = (PCache1 *)p;
46685  PGroup *pGroup = pCache->pGroup;
46686  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
46687  pcache1EnterMutex(pGroup);
46688  if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
46689  assert( pGroup->nMaxPage >= pCache->nMax );
46690  pGroup->nMaxPage -= pCache->nMax;
46691  assert( pGroup->nMinPage >= pCache->nMin );
46692  pGroup->nMinPage -= pCache->nMin;
46693  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
46694  pcache1EnforceMaxPage(pCache);
46695  pcache1LeaveMutex(pGroup);
46696  sqlite3_free(pCache->pBulk);
46697  sqlite3_free(pCache->apHash);
46698  sqlite3_free(pCache);
46699}
46700
46701/*
46702** This function is called during initialization (sqlite3_initialize()) to
46703** install the default pluggable cache module, assuming the user has not
46704** already provided an alternative.
46705*/
46706SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
46707  static const sqlite3_pcache_methods2 defaultMethods = {
46708    1,                       /* iVersion */
46709    0,                       /* pArg */
46710    pcache1Init,             /* xInit */
46711    pcache1Shutdown,         /* xShutdown */
46712    pcache1Create,           /* xCreate */
46713    pcache1Cachesize,        /* xCachesize */
46714    pcache1Pagecount,        /* xPagecount */
46715    pcache1Fetch,            /* xFetch */
46716    pcache1Unpin,            /* xUnpin */
46717    pcache1Rekey,            /* xRekey */
46718    pcache1Truncate,         /* xTruncate */
46719    pcache1Destroy,          /* xDestroy */
46720    pcache1Shrink            /* xShrink */
46721  };
46722  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
46723}
46724
46725/*
46726** Return the size of the header on each page of this PCACHE implementation.
46727*/
46728SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
46729
46730/*
46731** Return the global mutex used by this PCACHE implementation.  The
46732** sqlite3_status() routine needs access to this mutex.
46733*/
46734SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
46735  return pcache1.mutex;
46736}
46737
46738#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
46739/*
46740** This function is called to free superfluous dynamically allocated memory
46741** held by the pager system. Memory in use by any SQLite pager allocated
46742** by the current thread may be sqlite3_free()ed.
46743**
46744** nReq is the number of bytes of memory required. Once this much has
46745** been released, the function returns. The return value is the total number
46746** of bytes of memory released.
46747*/
46748SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
46749  int nFree = 0;
46750  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
46751  assert( sqlite3_mutex_notheld(pcache1.mutex) );
46752  if( sqlite3GlobalConfig.pPage==0 ){
46753    PgHdr1 *p;
46754    pcache1EnterMutex(&pcache1.grp);
46755    while( (nReq<0 || nFree<nReq)
46756       &&  (p=pcache1.grp.lru.pLruPrev)!=0
46757       &&  p->isAnchor==0
46758    ){
46759      nFree += pcache1MemSize(p->page.pBuf);
46760#ifdef SQLITE_PCACHE_SEPARATE_HEADER
46761      nFree += sqlite3MemSize(p);
46762#endif
46763      assert( p->isPinned==0 );
46764      pcache1PinPage(p);
46765      pcache1RemoveFromHash(p, 1);
46766    }
46767    pcache1LeaveMutex(&pcache1.grp);
46768  }
46769  return nFree;
46770}
46771#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
46772
46773#ifdef SQLITE_TEST
46774/*
46775** This function is used by test procedures to inspect the internal state
46776** of the global cache.
46777*/
46778SQLITE_PRIVATE void sqlite3PcacheStats(
46779  int *pnCurrent,      /* OUT: Total number of pages cached */
46780  int *pnMax,          /* OUT: Global maximum cache size */
46781  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
46782  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
46783){
46784  PgHdr1 *p;
46785  int nRecyclable = 0;
46786  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
46787    assert( p->isPinned==0 );
46788    nRecyclable++;
46789  }
46790  *pnCurrent = pcache1.grp.nCurrentPage;
46791  *pnMax = (int)pcache1.grp.nMaxPage;
46792  *pnMin = (int)pcache1.grp.nMinPage;
46793  *pnRecyclable = nRecyclable;
46794}
46795#endif
46796
46797/************** End of pcache1.c *********************************************/
46798/************** Begin file rowset.c ******************************************/
46799/*
46800** 2008 December 3
46801**
46802** The author disclaims copyright to this source code.  In place of
46803** a legal notice, here is a blessing:
46804**
46805**    May you do good and not evil.
46806**    May you find forgiveness for yourself and forgive others.
46807**    May you share freely, never taking more than you give.
46808**
46809*************************************************************************
46810**
46811** This module implements an object we call a "RowSet".
46812**
46813** The RowSet object is a collection of rowids.  Rowids
46814** are inserted into the RowSet in an arbitrary order.  Inserts
46815** can be intermixed with tests to see if a given rowid has been
46816** previously inserted into the RowSet.
46817**
46818** After all inserts are finished, it is possible to extract the
46819** elements of the RowSet in sorted order.  Once this extraction
46820** process has started, no new elements may be inserted.
46821**
46822** Hence, the primitive operations for a RowSet are:
46823**
46824**    CREATE
46825**    INSERT
46826**    TEST
46827**    SMALLEST
46828**    DESTROY
46829**
46830** The CREATE and DESTROY primitives are the constructor and destructor,
46831** obviously.  The INSERT primitive adds a new element to the RowSet.
46832** TEST checks to see if an element is already in the RowSet.  SMALLEST
46833** extracts the least value from the RowSet.
46834**
46835** The INSERT primitive might allocate additional memory.  Memory is
46836** allocated in chunks so most INSERTs do no allocation.  There is an
46837** upper bound on the size of allocated memory.  No memory is freed
46838** until DESTROY.
46839**
46840** The TEST primitive includes a "batch" number.  The TEST primitive
46841** will only see elements that were inserted before the last change
46842** in the batch number.  In other words, if an INSERT occurs between
46843** two TESTs where the TESTs have the same batch nubmer, then the
46844** value added by the INSERT will not be visible to the second TEST.
46845** The initial batch number is zero, so if the very first TEST contains
46846** a non-zero batch number, it will see all prior INSERTs.
46847**
46848** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
46849** that is attempted.
46850**
46851** The cost of an INSERT is roughly constant.  (Sometimes new memory
46852** has to be allocated on an INSERT.)  The cost of a TEST with a new
46853** batch number is O(NlogN) where N is the number of elements in the RowSet.
46854** The cost of a TEST using the same batch number is O(logN).  The cost
46855** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
46856** primitives are constant time.  The cost of DESTROY is O(N).
46857**
46858** TEST and SMALLEST may not be used by the same RowSet.  This used to
46859** be possible, but the feature was not used, so it was removed in order
46860** to simplify the code.
46861*/
46862/* #include "sqliteInt.h" */
46863
46864
46865/*
46866** Target size for allocation chunks.
46867*/
46868#define ROWSET_ALLOCATION_SIZE 1024
46869
46870/*
46871** The number of rowset entries per allocation chunk.
46872*/
46873#define ROWSET_ENTRY_PER_CHUNK  \
46874                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
46875
46876/*
46877** Each entry in a RowSet is an instance of the following object.
46878**
46879** This same object is reused to store a linked list of trees of RowSetEntry
46880** objects.  In that alternative use, pRight points to the next entry
46881** in the list, pLeft points to the tree, and v is unused.  The
46882** RowSet.pForest value points to the head of this forest list.
46883*/
46884struct RowSetEntry {
46885  i64 v;                        /* ROWID value for this entry */
46886  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
46887  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
46888};
46889
46890/*
46891** RowSetEntry objects are allocated in large chunks (instances of the
46892** following structure) to reduce memory allocation overhead.  The
46893** chunks are kept on a linked list so that they can be deallocated
46894** when the RowSet is destroyed.
46895*/
46896struct RowSetChunk {
46897  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
46898  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
46899};
46900
46901/*
46902** A RowSet in an instance of the following structure.
46903**
46904** A typedef of this structure if found in sqliteInt.h.
46905*/
46906struct RowSet {
46907  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
46908  sqlite3 *db;                   /* The database connection */
46909  struct RowSetEntry *pEntry;    /* List of entries using pRight */
46910  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
46911  struct RowSetEntry *pFresh;    /* Source of new entry objects */
46912  struct RowSetEntry *pForest;   /* List of binary trees of entries */
46913  u16 nFresh;                    /* Number of objects on pFresh */
46914  u16 rsFlags;                   /* Various flags */
46915  int iBatch;                    /* Current insert batch */
46916};
46917
46918/*
46919** Allowed values for RowSet.rsFlags
46920*/
46921#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
46922#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
46923
46924/*
46925** Turn bulk memory into a RowSet object.  N bytes of memory
46926** are available at pSpace.  The db pointer is used as a memory context
46927** for any subsequent allocations that need to occur.
46928** Return a pointer to the new RowSet object.
46929**
46930** It must be the case that N is sufficient to make a Rowset.  If not
46931** an assertion fault occurs.
46932**
46933** If N is larger than the minimum, use the surplus as an initial
46934** allocation of entries available to be filled.
46935*/
46936SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
46937  RowSet *p;
46938  assert( N >= ROUND8(sizeof(*p)) );
46939  p = pSpace;
46940  p->pChunk = 0;
46941  p->db = db;
46942  p->pEntry = 0;
46943  p->pLast = 0;
46944  p->pForest = 0;
46945  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
46946  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
46947  p->rsFlags = ROWSET_SORTED;
46948  p->iBatch = 0;
46949  return p;
46950}
46951
46952/*
46953** Deallocate all chunks from a RowSet.  This frees all memory that
46954** the RowSet has allocated over its lifetime.  This routine is
46955** the destructor for the RowSet.
46956*/
46957SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
46958  struct RowSetChunk *pChunk, *pNextChunk;
46959  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
46960    pNextChunk = pChunk->pNextChunk;
46961    sqlite3DbFree(p->db, pChunk);
46962  }
46963  p->pChunk = 0;
46964  p->nFresh = 0;
46965  p->pEntry = 0;
46966  p->pLast = 0;
46967  p->pForest = 0;
46968  p->rsFlags = ROWSET_SORTED;
46969}
46970
46971/*
46972** Allocate a new RowSetEntry object that is associated with the
46973** given RowSet.  Return a pointer to the new and completely uninitialized
46974** objected.
46975**
46976** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
46977** routine returns NULL.
46978*/
46979static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
46980  assert( p!=0 );
46981  if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
46982    /* We could allocate a fresh RowSetEntry each time one is needed, but it
46983    ** is more efficient to pull a preallocated entry from the pool */
46984    struct RowSetChunk *pNew;
46985    pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
46986    if( pNew==0 ){
46987      return 0;
46988    }
46989    pNew->pNextChunk = p->pChunk;
46990    p->pChunk = pNew;
46991    p->pFresh = pNew->aEntry;
46992    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
46993  }
46994  p->nFresh--;
46995  return p->pFresh++;
46996}
46997
46998/*
46999** Insert a new value into a RowSet.
47000**
47001** The mallocFailed flag of the database connection is set if a
47002** memory allocation fails.
47003*/
47004SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
47005  struct RowSetEntry *pEntry;  /* The new entry */
47006  struct RowSetEntry *pLast;   /* The last prior entry */
47007
47008  /* This routine is never called after sqlite3RowSetNext() */
47009  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
47010
47011  pEntry = rowSetEntryAlloc(p);
47012  if( pEntry==0 ) return;
47013  pEntry->v = rowid;
47014  pEntry->pRight = 0;
47015  pLast = p->pLast;
47016  if( pLast ){
47017    if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
47018      /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
47019      ** where possible */
47020      p->rsFlags &= ~ROWSET_SORTED;
47021    }
47022    pLast->pRight = pEntry;
47023  }else{
47024    p->pEntry = pEntry;
47025  }
47026  p->pLast = pEntry;
47027}
47028
47029/*
47030** Merge two lists of RowSetEntry objects.  Remove duplicates.
47031**
47032** The input lists are connected via pRight pointers and are
47033** assumed to each already be in sorted order.
47034*/
47035static struct RowSetEntry *rowSetEntryMerge(
47036  struct RowSetEntry *pA,    /* First sorted list to be merged */
47037  struct RowSetEntry *pB     /* Second sorted list to be merged */
47038){
47039  struct RowSetEntry head;
47040  struct RowSetEntry *pTail;
47041
47042  pTail = &head;
47043  assert( pA!=0 && pB!=0 );
47044  for(;;){
47045    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
47046    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
47047    if( pA->v<=pB->v ){
47048      if( pA->v<pB->v ) pTail = pTail->pRight = pA;
47049      pA = pA->pRight;
47050      if( pA==0 ){
47051        pTail->pRight = pB;
47052        break;
47053      }
47054    }else{
47055      pTail = pTail->pRight = pB;
47056      pB = pB->pRight;
47057      if( pB==0 ){
47058        pTail->pRight = pA;
47059        break;
47060      }
47061    }
47062  }
47063  return head.pRight;
47064}
47065
47066/*
47067** Sort all elements on the list of RowSetEntry objects into order of
47068** increasing v.
47069*/
47070static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
47071  unsigned int i;
47072  struct RowSetEntry *pNext, *aBucket[40];
47073
47074  memset(aBucket, 0, sizeof(aBucket));
47075  while( pIn ){
47076    pNext = pIn->pRight;
47077    pIn->pRight = 0;
47078    for(i=0; aBucket[i]; i++){
47079      pIn = rowSetEntryMerge(aBucket[i], pIn);
47080      aBucket[i] = 0;
47081    }
47082    aBucket[i] = pIn;
47083    pIn = pNext;
47084  }
47085  pIn = aBucket[0];
47086  for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
47087    if( aBucket[i]==0 ) continue;
47088    pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
47089  }
47090  return pIn;
47091}
47092
47093
47094/*
47095** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
47096** Convert this tree into a linked list connected by the pRight pointers
47097** and return pointers to the first and last elements of the new list.
47098*/
47099static void rowSetTreeToList(
47100  struct RowSetEntry *pIn,         /* Root of the input tree */
47101  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
47102  struct RowSetEntry **ppLast      /* Write tail of the output list here */
47103){
47104  assert( pIn!=0 );
47105  if( pIn->pLeft ){
47106    struct RowSetEntry *p;
47107    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
47108    p->pRight = pIn;
47109  }else{
47110    *ppFirst = pIn;
47111  }
47112  if( pIn->pRight ){
47113    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
47114  }else{
47115    *ppLast = pIn;
47116  }
47117  assert( (*ppLast)->pRight==0 );
47118}
47119
47120
47121/*
47122** Convert a sorted list of elements (connected by pRight) into a binary
47123** tree with depth of iDepth.  A depth of 1 means the tree contains a single
47124** node taken from the head of *ppList.  A depth of 2 means a tree with
47125** three nodes.  And so forth.
47126**
47127** Use as many entries from the input list as required and update the
47128** *ppList to point to the unused elements of the list.  If the input
47129** list contains too few elements, then construct an incomplete tree
47130** and leave *ppList set to NULL.
47131**
47132** Return a pointer to the root of the constructed binary tree.
47133*/
47134static struct RowSetEntry *rowSetNDeepTree(
47135  struct RowSetEntry **ppList,
47136  int iDepth
47137){
47138  struct RowSetEntry *p;         /* Root of the new tree */
47139  struct RowSetEntry *pLeft;     /* Left subtree */
47140  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
47141    /* Prevent unnecessary deep recursion when we run out of entries */
47142    return 0;
47143  }
47144  if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
47145    /* This branch causes a *balanced* tree to be generated.  A valid tree
47146    ** is still generated without this branch, but the tree is wildly
47147    ** unbalanced and inefficient. */
47148    pLeft = rowSetNDeepTree(ppList, iDepth-1);
47149    p = *ppList;
47150    if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
47151      /* It is safe to always return here, but the resulting tree
47152      ** would be unbalanced */
47153      return pLeft;
47154    }
47155    p->pLeft = pLeft;
47156    *ppList = p->pRight;
47157    p->pRight = rowSetNDeepTree(ppList, iDepth-1);
47158  }else{
47159    p = *ppList;
47160    *ppList = p->pRight;
47161    p->pLeft = p->pRight = 0;
47162  }
47163  return p;
47164}
47165
47166/*
47167** Convert a sorted list of elements into a binary tree. Make the tree
47168** as deep as it needs to be in order to contain the entire list.
47169*/
47170static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
47171  int iDepth;           /* Depth of the tree so far */
47172  struct RowSetEntry *p;       /* Current tree root */
47173  struct RowSetEntry *pLeft;   /* Left subtree */
47174
47175  assert( pList!=0 );
47176  p = pList;
47177  pList = p->pRight;
47178  p->pLeft = p->pRight = 0;
47179  for(iDepth=1; pList; iDepth++){
47180    pLeft = p;
47181    p = pList;
47182    pList = p->pRight;
47183    p->pLeft = pLeft;
47184    p->pRight = rowSetNDeepTree(&pList, iDepth);
47185  }
47186  return p;
47187}
47188
47189/*
47190** Extract the smallest element from the RowSet.
47191** Write the element into *pRowid.  Return 1 on success.  Return
47192** 0 if the RowSet is already empty.
47193**
47194** After this routine has been called, the sqlite3RowSetInsert()
47195** routine may not be called again.
47196**
47197** This routine may not be called after sqlite3RowSetTest() has
47198** been used.  Older versions of RowSet allowed that, but as the
47199** capability was not used by the code generator, it was removed
47200** for code economy.
47201*/
47202SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
47203  assert( p!=0 );
47204  assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
47205
47206  /* Merge the forest into a single sorted list on first call */
47207  if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
47208    if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
47209      p->pEntry = rowSetEntrySort(p->pEntry);
47210    }
47211    p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
47212  }
47213
47214  /* Return the next entry on the list */
47215  if( p->pEntry ){
47216    *pRowid = p->pEntry->v;
47217    p->pEntry = p->pEntry->pRight;
47218    if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
47219      /* Free memory immediately, rather than waiting on sqlite3_finalize() */
47220      sqlite3RowSetClear(p);
47221    }
47222    return 1;
47223  }else{
47224    return 0;
47225  }
47226}
47227
47228/*
47229** Check to see if element iRowid was inserted into the rowset as
47230** part of any insert batch prior to iBatch.  Return 1 or 0.
47231**
47232** If this is the first test of a new batch and if there exist entries
47233** on pRowSet->pEntry, then sort those entries into the forest at
47234** pRowSet->pForest so that they can be tested.
47235*/
47236SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
47237  struct RowSetEntry *p, *pTree;
47238
47239  /* This routine is never called after sqlite3RowSetNext() */
47240  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
47241
47242  /* Sort entries into the forest on the first test of a new batch.
47243  ** To save unnecessary work, only do this when the batch number changes.
47244  */
47245  if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
47246    p = pRowSet->pEntry;
47247    if( p ){
47248      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
47249      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
47250        /* Only sort the current set of entiries if they need it */
47251        p = rowSetEntrySort(p);
47252      }
47253      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
47254        ppPrevTree = &pTree->pRight;
47255        if( pTree->pLeft==0 ){
47256          pTree->pLeft = rowSetListToTree(p);
47257          break;
47258        }else{
47259          struct RowSetEntry *pAux, *pTail;
47260          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
47261          pTree->pLeft = 0;
47262          p = rowSetEntryMerge(pAux, p);
47263        }
47264      }
47265      if( pTree==0 ){
47266        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
47267        if( pTree ){
47268          pTree->v = 0;
47269          pTree->pRight = 0;
47270          pTree->pLeft = rowSetListToTree(p);
47271        }
47272      }
47273      pRowSet->pEntry = 0;
47274      pRowSet->pLast = 0;
47275      pRowSet->rsFlags |= ROWSET_SORTED;
47276    }
47277    pRowSet->iBatch = iBatch;
47278  }
47279
47280  /* Test to see if the iRowid value appears anywhere in the forest.
47281  ** Return 1 if it does and 0 if not.
47282  */
47283  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
47284    p = pTree->pLeft;
47285    while( p ){
47286      if( p->v<iRowid ){
47287        p = p->pRight;
47288      }else if( p->v>iRowid ){
47289        p = p->pLeft;
47290      }else{
47291        return 1;
47292      }
47293    }
47294  }
47295  return 0;
47296}
47297
47298/************** End of rowset.c **********************************************/
47299/************** Begin file pager.c *******************************************/
47300/*
47301** 2001 September 15
47302**
47303** The author disclaims copyright to this source code.  In place of
47304** a legal notice, here is a blessing:
47305**
47306**    May you do good and not evil.
47307**    May you find forgiveness for yourself and forgive others.
47308**    May you share freely, never taking more than you give.
47309**
47310*************************************************************************
47311** This is the implementation of the page cache subsystem or "pager".
47312**
47313** The pager is used to access a database disk file.  It implements
47314** atomic commit and rollback through the use of a journal file that
47315** is separate from the database file.  The pager also implements file
47316** locking to prevent two processes from writing the same database
47317** file simultaneously, or one process from reading the database while
47318** another is writing.
47319*/
47320#ifndef SQLITE_OMIT_DISKIO
47321/* #include "sqliteInt.h" */
47322/************** Include wal.h in the middle of pager.c ***********************/
47323/************** Begin file wal.h *********************************************/
47324/*
47325** 2010 February 1
47326**
47327** The author disclaims copyright to this source code.  In place of
47328** a legal notice, here is a blessing:
47329**
47330**    May you do good and not evil.
47331**    May you find forgiveness for yourself and forgive others.
47332**    May you share freely, never taking more than you give.
47333**
47334*************************************************************************
47335** This header file defines the interface to the write-ahead logging
47336** system. Refer to the comments below and the header comment attached to
47337** the implementation of each function in log.c for further details.
47338*/
47339
47340#ifndef SQLITE_WAL_H
47341#define SQLITE_WAL_H
47342
47343/* #include "sqliteInt.h" */
47344
47345/* Additional values that can be added to the sync_flags argument of
47346** sqlite3WalFrames():
47347*/
47348#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
47349#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
47350
47351#ifdef SQLITE_OMIT_WAL
47352# define sqlite3WalOpen(x,y,z)                   0
47353# define sqlite3WalLimit(x,y)
47354# define sqlite3WalClose(v,w,x,y,z)              0
47355# define sqlite3WalBeginReadTransaction(y,z)     0
47356# define sqlite3WalEndReadTransaction(z)
47357# define sqlite3WalDbsize(y)                     0
47358# define sqlite3WalBeginWriteTransaction(y)      0
47359# define sqlite3WalEndWriteTransaction(x)        0
47360# define sqlite3WalUndo(x,y,z)                   0
47361# define sqlite3WalSavepoint(y,z)
47362# define sqlite3WalSavepointUndo(y,z)            0
47363# define sqlite3WalFrames(u,v,w,x,y,z)           0
47364# define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
47365# define sqlite3WalCallback(z)                   0
47366# define sqlite3WalExclusiveMode(y,z)            0
47367# define sqlite3WalHeapMemory(z)                 0
47368# define sqlite3WalFramesize(z)                  0
47369# define sqlite3WalFindFrame(x,y,z)              0
47370# define sqlite3WalFile(x)                       0
47371#else
47372
47373#define WAL_SAVEPOINT_NDATA 4
47374
47375/* Connection to a write-ahead log (WAL) file.
47376** There is one object of this type for each pager.
47377*/
47378typedef struct Wal Wal;
47379
47380/* Open and close a connection to a write-ahead log. */
47381SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
47382SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
47383
47384/* Set the limiting size of a WAL file. */
47385SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
47386
47387/* Used by readers to open (lock) and close (unlock) a snapshot.  A
47388** snapshot is like a read-transaction.  It is the state of the database
47389** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
47390** preserves the current state even if the other threads or processes
47391** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
47392** transaction and releases the lock.
47393*/
47394SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
47395SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
47396
47397/* Read a page from the write-ahead log, if it is present. */
47398SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
47399SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
47400
47401/* If the WAL is not empty, return the size of the database. */
47402SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
47403
47404/* Obtain or release the WRITER lock. */
47405SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
47406SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
47407
47408/* Undo any frames written (but not committed) to the log */
47409SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
47410
47411/* Return an integer that records the current (uncommitted) write
47412** position in the WAL */
47413SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
47414
47415/* Move the write position of the WAL back to iFrame.  Called in
47416** response to a ROLLBACK TO command. */
47417SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
47418
47419/* Write a frame or frames to the log. */
47420SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
47421
47422/* Copy pages from the log to the database file */
47423SQLITE_PRIVATE int sqlite3WalCheckpoint(
47424  Wal *pWal,                      /* Write-ahead log connection */
47425  sqlite3 *db,                    /* Check this handle's interrupt flag */
47426  int eMode,                      /* One of PASSIVE, FULL and RESTART */
47427  int (*xBusy)(void*),            /* Function to call when busy */
47428  void *pBusyArg,                 /* Context argument for xBusyHandler */
47429  int sync_flags,                 /* Flags to sync db file with (or 0) */
47430  int nBuf,                       /* Size of buffer nBuf */
47431  u8 *zBuf,                       /* Temporary buffer to use */
47432  int *pnLog,                     /* OUT: Number of frames in WAL */
47433  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
47434);
47435
47436/* Return the value to pass to a sqlite3_wal_hook callback, the
47437** number of frames in the WAL at the point of the last commit since
47438** sqlite3WalCallback() was called.  If no commits have occurred since
47439** the last call, then return 0.
47440*/
47441SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
47442
47443/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
47444** by the pager layer on the database file.
47445*/
47446SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
47447
47448/* Return true if the argument is non-NULL and the WAL module is using
47449** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
47450** WAL module is using shared-memory, return false.
47451*/
47452SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
47453
47454#ifdef SQLITE_ENABLE_SNAPSHOT
47455SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
47456SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
47457SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
47458#endif
47459
47460#ifdef SQLITE_ENABLE_ZIPVFS
47461/* If the WAL file is not empty, return the number of bytes of content
47462** stored in each frame (i.e. the db page-size when the WAL was created).
47463*/
47464SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
47465#endif
47466
47467/* Return the sqlite3_file object for the WAL file */
47468SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
47469
47470#endif /* ifndef SQLITE_OMIT_WAL */
47471#endif /* SQLITE_WAL_H */
47472
47473/************** End of wal.h *************************************************/
47474/************** Continuing where we left off in pager.c **********************/
47475
47476
47477/******************* NOTES ON THE DESIGN OF THE PAGER ************************
47478**
47479** This comment block describes invariants that hold when using a rollback
47480** journal.  These invariants do not apply for journal_mode=WAL,
47481** journal_mode=MEMORY, or journal_mode=OFF.
47482**
47483** Within this comment block, a page is deemed to have been synced
47484** automatically as soon as it is written when PRAGMA synchronous=OFF.
47485** Otherwise, the page is not synced until the xSync method of the VFS
47486** is called successfully on the file containing the page.
47487**
47488** Definition:  A page of the database file is said to be "overwriteable" if
47489** one or more of the following are true about the page:
47490**
47491**     (a)  The original content of the page as it was at the beginning of
47492**          the transaction has been written into the rollback journal and
47493**          synced.
47494**
47495**     (b)  The page was a freelist leaf page at the start of the transaction.
47496**
47497**     (c)  The page number is greater than the largest page that existed in
47498**          the database file at the start of the transaction.
47499**
47500** (1) A page of the database file is never overwritten unless one of the
47501**     following are true:
47502**
47503**     (a) The page and all other pages on the same sector are overwriteable.
47504**
47505**     (b) The atomic page write optimization is enabled, and the entire
47506**         transaction other than the update of the transaction sequence
47507**         number consists of a single page change.
47508**
47509** (2) The content of a page written into the rollback journal exactly matches
47510**     both the content in the database when the rollback journal was written
47511**     and the content in the database at the beginning of the current
47512**     transaction.
47513**
47514** (3) Writes to the database file are an integer multiple of the page size
47515**     in length and are aligned on a page boundary.
47516**
47517** (4) Reads from the database file are either aligned on a page boundary and
47518**     an integer multiple of the page size in length or are taken from the
47519**     first 100 bytes of the database file.
47520**
47521** (5) All writes to the database file are synced prior to the rollback journal
47522**     being deleted, truncated, or zeroed.
47523**
47524** (6) If a master journal file is used, then all writes to the database file
47525**     are synced prior to the master journal being deleted.
47526**
47527** Definition: Two databases (or the same database at two points it time)
47528** are said to be "logically equivalent" if they give the same answer to
47529** all queries.  Note in particular the content of freelist leaf
47530** pages can be changed arbitrarily without affecting the logical equivalence
47531** of the database.
47532**
47533** (7) At any time, if any subset, including the empty set and the total set,
47534**     of the unsynced changes to a rollback journal are removed and the
47535**     journal is rolled back, the resulting database file will be logically
47536**     equivalent to the database file at the beginning of the transaction.
47537**
47538** (8) When a transaction is rolled back, the xTruncate method of the VFS
47539**     is called to restore the database file to the same size it was at
47540**     the beginning of the transaction.  (In some VFSes, the xTruncate
47541**     method is a no-op, but that does not change the fact the SQLite will
47542**     invoke it.)
47543**
47544** (9) Whenever the database file is modified, at least one bit in the range
47545**     of bytes from 24 through 39 inclusive will be changed prior to releasing
47546**     the EXCLUSIVE lock, thus signaling other connections on the same
47547**     database to flush their caches.
47548**
47549** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
47550**      than one billion transactions.
47551**
47552** (11) A database file is well-formed at the beginning and at the conclusion
47553**      of every transaction.
47554**
47555** (12) An EXCLUSIVE lock is held on the database file when writing to
47556**      the database file.
47557**
47558** (13) A SHARED lock is held on the database file while reading any
47559**      content out of the database file.
47560**
47561******************************************************************************/
47562
47563/*
47564** Macros for troubleshooting.  Normally turned off
47565*/
47566#if 0
47567int sqlite3PagerTrace=1;  /* True to enable tracing */
47568#define sqlite3DebugPrintf printf
47569#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
47570#else
47571#define PAGERTRACE(X)
47572#endif
47573
47574/*
47575** The following two macros are used within the PAGERTRACE() macros above
47576** to print out file-descriptors.
47577**
47578** PAGERID() takes a pointer to a Pager struct as its argument. The
47579** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
47580** struct as its argument.
47581*/
47582#define PAGERID(p) ((int)(p->fd))
47583#define FILEHANDLEID(fd) ((int)fd)
47584
47585/*
47586** The Pager.eState variable stores the current 'state' of a pager. A
47587** pager may be in any one of the seven states shown in the following
47588** state diagram.
47589**
47590**                            OPEN <------+------+
47591**                              |         |      |
47592**                              V         |      |
47593**               +---------> READER-------+      |
47594**               |              |                |
47595**               |              V                |
47596**               |<-------WRITER_LOCKED------> ERROR
47597**               |              |                ^
47598**               |              V                |
47599**               |<------WRITER_CACHEMOD-------->|
47600**               |              |                |
47601**               |              V                |
47602**               |<-------WRITER_DBMOD---------->|
47603**               |              |                |
47604**               |              V                |
47605**               +<------WRITER_FINISHED-------->+
47606**
47607**
47608** List of state transitions and the C [function] that performs each:
47609**
47610**   OPEN              -> READER              [sqlite3PagerSharedLock]
47611**   READER            -> OPEN                [pager_unlock]
47612**
47613**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
47614**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
47615**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
47616**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
47617**   WRITER_***        -> READER              [pager_end_transaction]
47618**
47619**   WRITER_***        -> ERROR               [pager_error]
47620**   ERROR             -> OPEN                [pager_unlock]
47621**
47622**
47623**  OPEN:
47624**
47625**    The pager starts up in this state. Nothing is guaranteed in this
47626**    state - the file may or may not be locked and the database size is
47627**    unknown. The database may not be read or written.
47628**
47629**    * No read or write transaction is active.
47630**    * Any lock, or no lock at all, may be held on the database file.
47631**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
47632**
47633**  READER:
47634**
47635**    In this state all the requirements for reading the database in
47636**    rollback (non-WAL) mode are met. Unless the pager is (or recently
47637**    was) in exclusive-locking mode, a user-level read transaction is
47638**    open. The database size is known in this state.
47639**
47640**    A connection running with locking_mode=normal enters this state when
47641**    it opens a read-transaction on the database and returns to state
47642**    OPEN after the read-transaction is completed. However a connection
47643**    running in locking_mode=exclusive (including temp databases) remains in
47644**    this state even after the read-transaction is closed. The only way
47645**    a locking_mode=exclusive connection can transition from READER to OPEN
47646**    is via the ERROR state (see below).
47647**
47648**    * A read transaction may be active (but a write-transaction cannot).
47649**    * A SHARED or greater lock is held on the database file.
47650**    * The dbSize variable may be trusted (even if a user-level read
47651**      transaction is not active). The dbOrigSize and dbFileSize variables
47652**      may not be trusted at this point.
47653**    * If the database is a WAL database, then the WAL connection is open.
47654**    * Even if a read-transaction is not open, it is guaranteed that
47655**      there is no hot-journal in the file-system.
47656**
47657**  WRITER_LOCKED:
47658**
47659**    The pager moves to this state from READER when a write-transaction
47660**    is first opened on the database. In WRITER_LOCKED state, all locks
47661**    required to start a write-transaction are held, but no actual
47662**    modifications to the cache or database have taken place.
47663**
47664**    In rollback mode, a RESERVED or (if the transaction was opened with
47665**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
47666**    moving to this state, but the journal file is not written to or opened
47667**    to in this state. If the transaction is committed or rolled back while
47668**    in WRITER_LOCKED state, all that is required is to unlock the database
47669**    file.
47670**
47671**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
47672**    If the connection is running with locking_mode=exclusive, an attempt
47673**    is made to obtain an EXCLUSIVE lock on the database file.
47674**
47675**    * A write transaction is active.
47676**    * If the connection is open in rollback-mode, a RESERVED or greater
47677**      lock is held on the database file.
47678**    * If the connection is open in WAL-mode, a WAL write transaction
47679**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
47680**      called).
47681**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
47682**    * The contents of the pager cache have not been modified.
47683**    * The journal file may or may not be open.
47684**    * Nothing (not even the first header) has been written to the journal.
47685**
47686**  WRITER_CACHEMOD:
47687**
47688**    A pager moves from WRITER_LOCKED state to this state when a page is
47689**    first modified by the upper layer. In rollback mode the journal file
47690**    is opened (if it is not already open) and a header written to the
47691**    start of it. The database file on disk has not been modified.
47692**
47693**    * A write transaction is active.
47694**    * A RESERVED or greater lock is held on the database file.
47695**    * The journal file is open and the first header has been written
47696**      to it, but the header has not been synced to disk.
47697**    * The contents of the page cache have been modified.
47698**
47699**  WRITER_DBMOD:
47700**
47701**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
47702**    when it modifies the contents of the database file. WAL connections
47703**    never enter this state (since they do not modify the database file,
47704**    just the log file).
47705**
47706**    * A write transaction is active.
47707**    * An EXCLUSIVE or greater lock is held on the database file.
47708**    * The journal file is open and the first header has been written
47709**      and synced to disk.
47710**    * The contents of the page cache have been modified (and possibly
47711**      written to disk).
47712**
47713**  WRITER_FINISHED:
47714**
47715**    It is not possible for a WAL connection to enter this state.
47716**
47717**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
47718**    state after the entire transaction has been successfully written into the
47719**    database file. In this state the transaction may be committed simply
47720**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
47721**    not possible to modify the database further. At this point, the upper
47722**    layer must either commit or rollback the transaction.
47723**
47724**    * A write transaction is active.
47725**    * An EXCLUSIVE or greater lock is held on the database file.
47726**    * All writing and syncing of journal and database data has finished.
47727**      If no error occurred, all that remains is to finalize the journal to
47728**      commit the transaction. If an error did occur, the caller will need
47729**      to rollback the transaction.
47730**
47731**  ERROR:
47732**
47733**    The ERROR state is entered when an IO or disk-full error (including
47734**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
47735**    difficult to be sure that the in-memory pager state (cache contents,
47736**    db size etc.) are consistent with the contents of the file-system.
47737**
47738**    Temporary pager files may enter the ERROR state, but in-memory pagers
47739**    cannot.
47740**
47741**    For example, if an IO error occurs while performing a rollback,
47742**    the contents of the page-cache may be left in an inconsistent state.
47743**    At this point it would be dangerous to change back to READER state
47744**    (as usually happens after a rollback). Any subsequent readers might
47745**    report database corruption (due to the inconsistent cache), and if
47746**    they upgrade to writers, they may inadvertently corrupt the database
47747**    file. To avoid this hazard, the pager switches into the ERROR state
47748**    instead of READER following such an error.
47749**
47750**    Once it has entered the ERROR state, any attempt to use the pager
47751**    to read or write data returns an error. Eventually, once all
47752**    outstanding transactions have been abandoned, the pager is able to
47753**    transition back to OPEN state, discarding the contents of the
47754**    page-cache and any other in-memory state at the same time. Everything
47755**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
47756**    when a read-transaction is next opened on the pager (transitioning
47757**    the pager into READER state). At that point the system has recovered
47758**    from the error.
47759**
47760**    Specifically, the pager jumps into the ERROR state if:
47761**
47762**      1. An error occurs while attempting a rollback. This happens in
47763**         function sqlite3PagerRollback().
47764**
47765**      2. An error occurs while attempting to finalize a journal file
47766**         following a commit in function sqlite3PagerCommitPhaseTwo().
47767**
47768**      3. An error occurs while attempting to write to the journal or
47769**         database file in function pagerStress() in order to free up
47770**         memory.
47771**
47772**    In other cases, the error is returned to the b-tree layer. The b-tree
47773**    layer then attempts a rollback operation. If the error condition
47774**    persists, the pager enters the ERROR state via condition (1) above.
47775**
47776**    Condition (3) is necessary because it can be triggered by a read-only
47777**    statement executed within a transaction. In this case, if the error
47778**    code were simply returned to the user, the b-tree layer would not
47779**    automatically attempt a rollback, as it assumes that an error in a
47780**    read-only statement cannot leave the pager in an internally inconsistent
47781**    state.
47782**
47783**    * The Pager.errCode variable is set to something other than SQLITE_OK.
47784**    * There are one or more outstanding references to pages (after the
47785**      last reference is dropped the pager should move back to OPEN state).
47786**    * The pager is not an in-memory pager.
47787**
47788**
47789** Notes:
47790**
47791**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
47792**     connection is open in WAL mode. A WAL connection is always in one
47793**     of the first four states.
47794**
47795**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
47796**     state. There are two exceptions: immediately after exclusive-mode has
47797**     been turned on (and before any read or write transactions are
47798**     executed), and when the pager is leaving the "error state".
47799**
47800**   * See also: assert_pager_state().
47801*/
47802#define PAGER_OPEN                  0
47803#define PAGER_READER                1
47804#define PAGER_WRITER_LOCKED         2
47805#define PAGER_WRITER_CACHEMOD       3
47806#define PAGER_WRITER_DBMOD          4
47807#define PAGER_WRITER_FINISHED       5
47808#define PAGER_ERROR                 6
47809
47810/*
47811** The Pager.eLock variable is almost always set to one of the
47812** following locking-states, according to the lock currently held on
47813** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
47814** This variable is kept up to date as locks are taken and released by
47815** the pagerLockDb() and pagerUnlockDb() wrappers.
47816**
47817** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
47818** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
47819** the operation was successful. In these circumstances pagerLockDb() and
47820** pagerUnlockDb() take a conservative approach - eLock is always updated
47821** when unlocking the file, and only updated when locking the file if the
47822** VFS call is successful. This way, the Pager.eLock variable may be set
47823** to a less exclusive (lower) value than the lock that is actually held
47824** at the system level, but it is never set to a more exclusive value.
47825**
47826** This is usually safe. If an xUnlock fails or appears to fail, there may
47827** be a few redundant xLock() calls or a lock may be held for longer than
47828** required, but nothing really goes wrong.
47829**
47830** The exception is when the database file is unlocked as the pager moves
47831** from ERROR to OPEN state. At this point there may be a hot-journal file
47832** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
47833** transition, by the same pager or any other). If the call to xUnlock()
47834** fails at this point and the pager is left holding an EXCLUSIVE lock, this
47835** can confuse the call to xCheckReservedLock() call made later as part
47836** of hot-journal detection.
47837**
47838** xCheckReservedLock() is defined as returning true "if there is a RESERVED
47839** lock held by this process or any others". So xCheckReservedLock may
47840** return true because the caller itself is holding an EXCLUSIVE lock (but
47841** doesn't know it because of a previous error in xUnlock). If this happens
47842** a hot-journal may be mistaken for a journal being created by an active
47843** transaction in another process, causing SQLite to read from the database
47844** without rolling it back.
47845**
47846** To work around this, if a call to xUnlock() fails when unlocking the
47847** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
47848** is only changed back to a real locking state after a successful call
47849** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
47850** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
47851** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
47852** lock on the database file before attempting to roll it back. See function
47853** PagerSharedLock() for more detail.
47854**
47855** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
47856** PAGER_OPEN state.
47857*/
47858#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
47859
47860/*
47861** A macro used for invoking the codec if there is one
47862*/
47863#ifdef SQLITE_HAS_CODEC
47864# define CODEC1(P,D,N,X,E) \
47865    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
47866# define CODEC2(P,D,N,X,E,O) \
47867    if( P->xCodec==0 ){ O=(char*)D; }else \
47868    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
47869#else
47870# define CODEC1(P,D,N,X,E)   /* NO-OP */
47871# define CODEC2(P,D,N,X,E,O) O=(char*)D
47872#endif
47873
47874/*
47875** The maximum allowed sector size. 64KiB. If the xSectorsize() method
47876** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
47877** This could conceivably cause corruption following a power failure on
47878** such a system. This is currently an undocumented limit.
47879*/
47880#define MAX_SECTOR_SIZE 0x10000
47881
47882
47883/*
47884** An instance of the following structure is allocated for each active
47885** savepoint and statement transaction in the system. All such structures
47886** are stored in the Pager.aSavepoint[] array, which is allocated and
47887** resized using sqlite3Realloc().
47888**
47889** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
47890** set to 0. If a journal-header is written into the main journal while
47891** the savepoint is active, then iHdrOffset is set to the byte offset
47892** immediately following the last journal record written into the main
47893** journal before the journal-header. This is required during savepoint
47894** rollback (see pagerPlaybackSavepoint()).
47895*/
47896typedef struct PagerSavepoint PagerSavepoint;
47897struct PagerSavepoint {
47898  i64 iOffset;                 /* Starting offset in main journal */
47899  i64 iHdrOffset;              /* See above */
47900  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
47901  Pgno nOrig;                  /* Original number of pages in file */
47902  Pgno iSubRec;                /* Index of first record in sub-journal */
47903#ifndef SQLITE_OMIT_WAL
47904  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
47905#endif
47906};
47907
47908/*
47909** Bits of the Pager.doNotSpill flag.  See further description below.
47910*/
47911#define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
47912#define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
47913#define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
47914
47915/*
47916** An open page cache is an instance of struct Pager. A description of
47917** some of the more important member variables follows:
47918**
47919** eState
47920**
47921**   The current 'state' of the pager object. See the comment and state
47922**   diagram above for a description of the pager state.
47923**
47924** eLock
47925**
47926**   For a real on-disk database, the current lock held on the database file -
47927**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
47928**
47929**   For a temporary or in-memory database (neither of which require any
47930**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
47931**   databases always have Pager.exclusiveMode==1, this tricks the pager
47932**   logic into thinking that it already has all the locks it will ever
47933**   need (and no reason to release them).
47934**
47935**   In some (obscure) circumstances, this variable may also be set to
47936**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
47937**   details.
47938**
47939** changeCountDone
47940**
47941**   This boolean variable is used to make sure that the change-counter
47942**   (the 4-byte header field at byte offset 24 of the database file) is
47943**   not updated more often than necessary.
47944**
47945**   It is set to true when the change-counter field is updated, which
47946**   can only happen if an exclusive lock is held on the database file.
47947**   It is cleared (set to false) whenever an exclusive lock is
47948**   relinquished on the database file. Each time a transaction is committed,
47949**   The changeCountDone flag is inspected. If it is true, the work of
47950**   updating the change-counter is omitted for the current transaction.
47951**
47952**   This mechanism means that when running in exclusive mode, a connection
47953**   need only update the change-counter once, for the first transaction
47954**   committed.
47955**
47956** setMaster
47957**
47958**   When PagerCommitPhaseOne() is called to commit a transaction, it may
47959**   (or may not) specify a master-journal name to be written into the
47960**   journal file before it is synced to disk.
47961**
47962**   Whether or not a journal file contains a master-journal pointer affects
47963**   the way in which the journal file is finalized after the transaction is
47964**   committed or rolled back when running in "journal_mode=PERSIST" mode.
47965**   If a journal file does not contain a master-journal pointer, it is
47966**   finalized by overwriting the first journal header with zeroes. If
47967**   it does contain a master-journal pointer the journal file is finalized
47968**   by truncating it to zero bytes, just as if the connection were
47969**   running in "journal_mode=truncate" mode.
47970**
47971**   Journal files that contain master journal pointers cannot be finalized
47972**   simply by overwriting the first journal-header with zeroes, as the
47973**   master journal pointer could interfere with hot-journal rollback of any
47974**   subsequently interrupted transaction that reuses the journal file.
47975**
47976**   The flag is cleared as soon as the journal file is finalized (either
47977**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
47978**   journal file from being successfully finalized, the setMaster flag
47979**   is cleared anyway (and the pager will move to ERROR state).
47980**
47981** doNotSpill
47982**
47983**   This variables control the behavior of cache-spills  (calls made by
47984**   the pcache module to the pagerStress() routine to write cached data
47985**   to the file-system in order to free up memory).
47986**
47987**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
47988**   writing to the database from pagerStress() is disabled altogether.
47989**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
47990**   comes up during savepoint rollback that requires the pcache module
47991**   to allocate a new page to prevent the journal file from being written
47992**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
47993**   case is a user preference.
47994**
47995**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
47996**   pagerStress() is permitted, but syncing the journal file is not.
47997**   This flag is set by sqlite3PagerWrite() when the file-system sector-size
47998**   is larger than the database page-size in order to prevent a journal sync
47999**   from happening in between the journalling of two pages on the same sector.
48000**
48001** subjInMemory
48002**
48003**   This is a boolean variable. If true, then any required sub-journal
48004**   is opened as an in-memory journal file. If false, then in-memory
48005**   sub-journals are only used for in-memory pager files.
48006**
48007**   This variable is updated by the upper layer each time a new
48008**   write-transaction is opened.
48009**
48010** dbSize, dbOrigSize, dbFileSize
48011**
48012**   Variable dbSize is set to the number of pages in the database file.
48013**   It is valid in PAGER_READER and higher states (all states except for
48014**   OPEN and ERROR).
48015**
48016**   dbSize is set based on the size of the database file, which may be
48017**   larger than the size of the database (the value stored at offset
48018**   28 of the database header by the btree). If the size of the file
48019**   is not an integer multiple of the page-size, the value stored in
48020**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
48021**   Except, any file that is greater than 0 bytes in size is considered
48022**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
48023**   to dbSize==1).
48024**
48025**   During a write-transaction, if pages with page-numbers greater than
48026**   dbSize are modified in the cache, dbSize is updated accordingly.
48027**   Similarly, if the database is truncated using PagerTruncateImage(),
48028**   dbSize is updated.
48029**
48030**   Variables dbOrigSize and dbFileSize are valid in states
48031**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
48032**   variable at the start of the transaction. It is used during rollback,
48033**   and to determine whether or not pages need to be journalled before
48034**   being modified.
48035**
48036**   Throughout a write-transaction, dbFileSize contains the size of
48037**   the file on disk in pages. It is set to a copy of dbSize when the
48038**   write-transaction is first opened, and updated when VFS calls are made
48039**   to write or truncate the database file on disk.
48040**
48041**   The only reason the dbFileSize variable is required is to suppress
48042**   unnecessary calls to xTruncate() after committing a transaction. If,
48043**   when a transaction is committed, the dbFileSize variable indicates
48044**   that the database file is larger than the database image (Pager.dbSize),
48045**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
48046**   to measure the database file on disk, and then truncates it if required.
48047**   dbFileSize is not used when rolling back a transaction. In this case
48048**   pager_truncate() is called unconditionally (which means there may be
48049**   a call to xFilesize() that is not strictly required). In either case,
48050**   pager_truncate() may cause the file to become smaller or larger.
48051**
48052** dbHintSize
48053**
48054**   The dbHintSize variable is used to limit the number of calls made to
48055**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
48056**
48057**   dbHintSize is set to a copy of the dbSize variable when a
48058**   write-transaction is opened (at the same time as dbFileSize and
48059**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
48060**   dbHintSize is increased to the number of pages that correspond to the
48061**   size-hint passed to the method call. See pager_write_pagelist() for
48062**   details.
48063**
48064** errCode
48065**
48066**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
48067**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
48068**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
48069**   sub-codes.
48070*/
48071struct Pager {
48072  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
48073  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
48074  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
48075  u8 useJournal;              /* Use a rollback journal on this file */
48076  u8 noSync;                  /* Do not sync the journal if true */
48077  u8 fullSync;                /* Do extra syncs of the journal for robustness */
48078  u8 extraSync;               /* sync directory after journal delete */
48079  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
48080  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
48081  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
48082  u8 tempFile;                /* zFilename is a temporary or immutable file */
48083  u8 noLock;                  /* Do not lock (except in WAL mode) */
48084  u8 readOnly;                /* True for a read-only database */
48085  u8 memDb;                   /* True to inhibit all file I/O */
48086
48087  /**************************************************************************
48088  ** The following block contains those class members that change during
48089  ** routine operation.  Class members not in this block are either fixed
48090  ** when the pager is first created or else only change when there is a
48091  ** significant mode change (such as changing the page_size, locking_mode,
48092  ** or the journal_mode).  From another view, these class members describe
48093  ** the "state" of the pager, while other class members describe the
48094  ** "configuration" of the pager.
48095  */
48096  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
48097  u8 eLock;                   /* Current lock held on database file */
48098  u8 changeCountDone;         /* Set after incrementing the change-counter */
48099  u8 setMaster;               /* True if a m-j name has been written to jrnl */
48100  u8 doNotSpill;              /* Do not spill the cache when non-zero */
48101  u8 subjInMemory;            /* True to use in-memory sub-journals */
48102  u8 bUseFetch;               /* True to use xFetch() */
48103  u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
48104  Pgno dbSize;                /* Number of pages in the database */
48105  Pgno dbOrigSize;            /* dbSize before the current transaction */
48106  Pgno dbFileSize;            /* Number of pages in the database file */
48107  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
48108  int errCode;                /* One of several kinds of errors */
48109  int nRec;                   /* Pages journalled since last j-header written */
48110  u32 cksumInit;              /* Quasi-random value added to every checksum */
48111  u32 nSubRec;                /* Number of records written to sub-journal */
48112  Bitvec *pInJournal;         /* One bit for each page in the database file */
48113  sqlite3_file *fd;           /* File descriptor for database */
48114  sqlite3_file *jfd;          /* File descriptor for main journal */
48115  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
48116  i64 journalOff;             /* Current write offset in the journal file */
48117  i64 journalHdr;             /* Byte offset to previous journal header */
48118  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
48119  PagerSavepoint *aSavepoint; /* Array of active savepoints */
48120  int nSavepoint;             /* Number of elements in aSavepoint[] */
48121  u32 iDataVersion;           /* Changes whenever database content changes */
48122  char dbFileVers[16];        /* Changes whenever database file changes */
48123
48124  int nMmapOut;               /* Number of mmap pages currently outstanding */
48125  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
48126  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
48127  /*
48128  ** End of the routinely-changing class members
48129  ***************************************************************************/
48130
48131  u16 nExtra;                 /* Add this many bytes to each in-memory page */
48132  i16 nReserve;               /* Number of unused bytes at end of each page */
48133  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
48134  u32 sectorSize;             /* Assumed sector size during rollback */
48135  int pageSize;               /* Number of bytes in a page */
48136  Pgno mxPgno;                /* Maximum allowed size of the database */
48137  i64 journalSizeLimit;       /* Size limit for persistent journal files */
48138  char *zFilename;            /* Name of the database file */
48139  char *zJournal;             /* Name of the journal file */
48140  int (*xBusyHandler)(void*); /* Function to call when busy */
48141  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
48142  int aStat[3];               /* Total cache hits, misses and writes */
48143#ifdef SQLITE_TEST
48144  int nRead;                  /* Database pages read */
48145#endif
48146  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
48147  int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
48148#ifdef SQLITE_HAS_CODEC
48149  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
48150  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
48151  void (*xCodecFree)(void*);             /* Destructor for the codec */
48152  void *pCodec;               /* First argument to xCodec... methods */
48153#endif
48154  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
48155  PCache *pPCache;            /* Pointer to page cache object */
48156#ifndef SQLITE_OMIT_WAL
48157  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
48158  char *zWal;                 /* File name for write-ahead log */
48159#endif
48160};
48161
48162/*
48163** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
48164** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
48165** or CACHE_WRITE to sqlite3_db_status().
48166*/
48167#define PAGER_STAT_HIT   0
48168#define PAGER_STAT_MISS  1
48169#define PAGER_STAT_WRITE 2
48170
48171/*
48172** The following global variables hold counters used for
48173** testing purposes only.  These variables do not exist in
48174** a non-testing build.  These variables are not thread-safe.
48175*/
48176#ifdef SQLITE_TEST
48177SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
48178SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
48179SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
48180# define PAGER_INCR(v)  v++
48181#else
48182# define PAGER_INCR(v)
48183#endif
48184
48185
48186
48187/*
48188** Journal files begin with the following magic string.  The data
48189** was obtained from /dev/random.  It is used only as a sanity check.
48190**
48191** Since version 2.8.0, the journal format contains additional sanity
48192** checking information.  If the power fails while the journal is being
48193** written, semi-random garbage data might appear in the journal
48194** file after power is restored.  If an attempt is then made
48195** to roll the journal back, the database could be corrupted.  The additional
48196** sanity checking data is an attempt to discover the garbage in the
48197** journal and ignore it.
48198**
48199** The sanity checking information for the new journal format consists
48200** of a 32-bit checksum on each page of data.  The checksum covers both
48201** the page number and the pPager->pageSize bytes of data for the page.
48202** This cksum is initialized to a 32-bit random value that appears in the
48203** journal file right after the header.  The random initializer is important,
48204** because garbage data that appears at the end of a journal is likely
48205** data that was once in other files that have now been deleted.  If the
48206** garbage data came from an obsolete journal file, the checksums might
48207** be correct.  But by initializing the checksum to random value which
48208** is different for every journal, we minimize that risk.
48209*/
48210static const unsigned char aJournalMagic[] = {
48211  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
48212};
48213
48214/*
48215** The size of the of each page record in the journal is given by
48216** the following macro.
48217*/
48218#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
48219
48220/*
48221** The journal header size for this pager. This is usually the same
48222** size as a single disk sector. See also setSectorSize().
48223*/
48224#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
48225
48226/*
48227** The macro MEMDB is true if we are dealing with an in-memory database.
48228** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
48229** the value of MEMDB will be a constant and the compiler will optimize
48230** out code that would never execute.
48231*/
48232#ifdef SQLITE_OMIT_MEMORYDB
48233# define MEMDB 0
48234#else
48235# define MEMDB pPager->memDb
48236#endif
48237
48238/*
48239** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
48240** interfaces to access the database using memory-mapped I/O.
48241*/
48242#if SQLITE_MAX_MMAP_SIZE>0
48243# define USEFETCH(x) ((x)->bUseFetch)
48244#else
48245# define USEFETCH(x) 0
48246#endif
48247
48248/*
48249** The maximum legal page number is (2^31 - 1).
48250*/
48251#define PAGER_MAX_PGNO 2147483647
48252
48253/*
48254** The argument to this macro is a file descriptor (type sqlite3_file*).
48255** Return 0 if it is not open, or non-zero (but not 1) if it is.
48256**
48257** This is so that expressions can be written as:
48258**
48259**   if( isOpen(pPager->jfd) ){ ...
48260**
48261** instead of
48262**
48263**   if( pPager->jfd->pMethods ){ ...
48264*/
48265#define isOpen(pFd) ((pFd)->pMethods!=0)
48266
48267/*
48268** Return true if this pager uses a write-ahead log to read page pgno.
48269** Return false if the pager reads pgno directly from the database.
48270*/
48271#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
48272SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
48273  u32 iRead = 0;
48274  int rc;
48275  if( pPager->pWal==0 ) return 0;
48276  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
48277  return rc || iRead;
48278}
48279#endif
48280#ifndef SQLITE_OMIT_WAL
48281# define pagerUseWal(x) ((x)->pWal!=0)
48282#else
48283# define pagerUseWal(x) 0
48284# define pagerRollbackWal(x) 0
48285# define pagerWalFrames(v,w,x,y) 0
48286# define pagerOpenWalIfPresent(z) SQLITE_OK
48287# define pagerBeginReadTransaction(z) SQLITE_OK
48288#endif
48289
48290#ifndef NDEBUG
48291/*
48292** Usage:
48293**
48294**   assert( assert_pager_state(pPager) );
48295**
48296** This function runs many asserts to try to find inconsistencies in
48297** the internal state of the Pager object.
48298*/
48299static int assert_pager_state(Pager *p){
48300  Pager *pPager = p;
48301
48302  /* State must be valid. */
48303  assert( p->eState==PAGER_OPEN
48304       || p->eState==PAGER_READER
48305       || p->eState==PAGER_WRITER_LOCKED
48306       || p->eState==PAGER_WRITER_CACHEMOD
48307       || p->eState==PAGER_WRITER_DBMOD
48308       || p->eState==PAGER_WRITER_FINISHED
48309       || p->eState==PAGER_ERROR
48310  );
48311
48312  /* Regardless of the current state, a temp-file connection always behaves
48313  ** as if it has an exclusive lock on the database file. It never updates
48314  ** the change-counter field, so the changeCountDone flag is always set.
48315  */
48316  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
48317  assert( p->tempFile==0 || pPager->changeCountDone );
48318
48319  /* If the useJournal flag is clear, the journal-mode must be "OFF".
48320  ** And if the journal-mode is "OFF", the journal file must not be open.
48321  */
48322  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
48323  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
48324
48325  /* Check that MEMDB implies noSync. And an in-memory journal. Since
48326  ** this means an in-memory pager performs no IO at all, it cannot encounter
48327  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
48328  ** a journal file. (although the in-memory journal implementation may
48329  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
48330  ** is therefore not possible for an in-memory pager to enter the ERROR
48331  ** state.
48332  */
48333  if( MEMDB ){
48334    assert( !isOpen(p->fd) );
48335    assert( p->noSync );
48336    assert( p->journalMode==PAGER_JOURNALMODE_OFF
48337         || p->journalMode==PAGER_JOURNALMODE_MEMORY
48338    );
48339    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
48340    assert( pagerUseWal(p)==0 );
48341  }
48342
48343  /* If changeCountDone is set, a RESERVED lock or greater must be held
48344  ** on the file.
48345  */
48346  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
48347  assert( p->eLock!=PENDING_LOCK );
48348
48349  switch( p->eState ){
48350    case PAGER_OPEN:
48351      assert( !MEMDB );
48352      assert( pPager->errCode==SQLITE_OK );
48353      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
48354      break;
48355
48356    case PAGER_READER:
48357      assert( pPager->errCode==SQLITE_OK );
48358      assert( p->eLock!=UNKNOWN_LOCK );
48359      assert( p->eLock>=SHARED_LOCK );
48360      break;
48361
48362    case PAGER_WRITER_LOCKED:
48363      assert( p->eLock!=UNKNOWN_LOCK );
48364      assert( pPager->errCode==SQLITE_OK );
48365      if( !pagerUseWal(pPager) ){
48366        assert( p->eLock>=RESERVED_LOCK );
48367      }
48368      assert( pPager->dbSize==pPager->dbOrigSize );
48369      assert( pPager->dbOrigSize==pPager->dbFileSize );
48370      assert( pPager->dbOrigSize==pPager->dbHintSize );
48371      assert( pPager->setMaster==0 );
48372      break;
48373
48374    case PAGER_WRITER_CACHEMOD:
48375      assert( p->eLock!=UNKNOWN_LOCK );
48376      assert( pPager->errCode==SQLITE_OK );
48377      if( !pagerUseWal(pPager) ){
48378        /* It is possible that if journal_mode=wal here that neither the
48379        ** journal file nor the WAL file are open. This happens during
48380        ** a rollback transaction that switches from journal_mode=off
48381        ** to journal_mode=wal.
48382        */
48383        assert( p->eLock>=RESERVED_LOCK );
48384        assert( isOpen(p->jfd)
48385             || p->journalMode==PAGER_JOURNALMODE_OFF
48386             || p->journalMode==PAGER_JOURNALMODE_WAL
48387        );
48388      }
48389      assert( pPager->dbOrigSize==pPager->dbFileSize );
48390      assert( pPager->dbOrigSize==pPager->dbHintSize );
48391      break;
48392
48393    case PAGER_WRITER_DBMOD:
48394      assert( p->eLock==EXCLUSIVE_LOCK );
48395      assert( pPager->errCode==SQLITE_OK );
48396      assert( !pagerUseWal(pPager) );
48397      assert( p->eLock>=EXCLUSIVE_LOCK );
48398      assert( isOpen(p->jfd)
48399           || p->journalMode==PAGER_JOURNALMODE_OFF
48400           || p->journalMode==PAGER_JOURNALMODE_WAL
48401      );
48402      assert( pPager->dbOrigSize<=pPager->dbHintSize );
48403      break;
48404
48405    case PAGER_WRITER_FINISHED:
48406      assert( p->eLock==EXCLUSIVE_LOCK );
48407      assert( pPager->errCode==SQLITE_OK );
48408      assert( !pagerUseWal(pPager) );
48409      assert( isOpen(p->jfd)
48410           || p->journalMode==PAGER_JOURNALMODE_OFF
48411           || p->journalMode==PAGER_JOURNALMODE_WAL
48412      );
48413      break;
48414
48415    case PAGER_ERROR:
48416      /* There must be at least one outstanding reference to the pager if
48417      ** in ERROR state. Otherwise the pager should have already dropped
48418      ** back to OPEN state.
48419      */
48420      assert( pPager->errCode!=SQLITE_OK );
48421      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
48422      break;
48423  }
48424
48425  return 1;
48426}
48427#endif /* ifndef NDEBUG */
48428
48429#ifdef SQLITE_DEBUG
48430/*
48431** Return a pointer to a human readable string in a static buffer
48432** containing the state of the Pager object passed as an argument. This
48433** is intended to be used within debuggers. For example, as an alternative
48434** to "print *pPager" in gdb:
48435**
48436** (gdb) printf "%s", print_pager_state(pPager)
48437*/
48438static char *print_pager_state(Pager *p){
48439  static char zRet[1024];
48440
48441  sqlite3_snprintf(1024, zRet,
48442      "Filename:      %s\n"
48443      "State:         %s errCode=%d\n"
48444      "Lock:          %s\n"
48445      "Locking mode:  locking_mode=%s\n"
48446      "Journal mode:  journal_mode=%s\n"
48447      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
48448      "Journal:       journalOff=%lld journalHdr=%lld\n"
48449      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
48450      , p->zFilename
48451      , p->eState==PAGER_OPEN            ? "OPEN" :
48452        p->eState==PAGER_READER          ? "READER" :
48453        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
48454        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
48455        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
48456        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
48457        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
48458      , (int)p->errCode
48459      , p->eLock==NO_LOCK         ? "NO_LOCK" :
48460        p->eLock==RESERVED_LOCK   ? "RESERVED" :
48461        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
48462        p->eLock==SHARED_LOCK     ? "SHARED" :
48463        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
48464      , p->exclusiveMode ? "exclusive" : "normal"
48465      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
48466        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
48467        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
48468        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
48469        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
48470        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
48471      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
48472      , p->journalOff, p->journalHdr
48473      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
48474  );
48475
48476  return zRet;
48477}
48478#endif
48479
48480/* Forward references to the various page getters */
48481static int getPageNormal(Pager*,Pgno,DbPage**,int);
48482static int getPageError(Pager*,Pgno,DbPage**,int);
48483#if SQLITE_MAX_MMAP_SIZE>0
48484static int getPageMMap(Pager*,Pgno,DbPage**,int);
48485#endif
48486
48487/*
48488** Set the Pager.xGet method for the appropriate routine used to fetch
48489** content from the pager.
48490*/
48491static void setGetterMethod(Pager *pPager){
48492  if( pPager->errCode ){
48493    pPager->xGet = getPageError;
48494#if SQLITE_MAX_MMAP_SIZE>0
48495  }else if( USEFETCH(pPager)
48496#ifdef SQLITE_HAS_CODEC
48497   && pPager->xCodec==0
48498#endif
48499  ){
48500    pPager->xGet = getPageMMap;
48501#endif /* SQLITE_MAX_MMAP_SIZE>0 */
48502  }else{
48503    pPager->xGet = getPageNormal;
48504  }
48505}
48506
48507/*
48508** Return true if it is necessary to write page *pPg into the sub-journal.
48509** A page needs to be written into the sub-journal if there exists one
48510** or more open savepoints for which:
48511**
48512**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
48513**   * The bit corresponding to the page-number is not set in
48514**     PagerSavepoint.pInSavepoint.
48515*/
48516static int subjRequiresPage(PgHdr *pPg){
48517  Pager *pPager = pPg->pPager;
48518  PagerSavepoint *p;
48519  Pgno pgno = pPg->pgno;
48520  int i;
48521  for(i=0; i<pPager->nSavepoint; i++){
48522    p = &pPager->aSavepoint[i];
48523    if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
48524      return 1;
48525    }
48526  }
48527  return 0;
48528}
48529
48530#ifdef SQLITE_DEBUG
48531/*
48532** Return true if the page is already in the journal file.
48533*/
48534static int pageInJournal(Pager *pPager, PgHdr *pPg){
48535  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
48536}
48537#endif
48538
48539/*
48540** Read a 32-bit integer from the given file descriptor.  Store the integer
48541** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
48542** error code is something goes wrong.
48543**
48544** All values are stored on disk as big-endian.
48545*/
48546static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
48547  unsigned char ac[4];
48548  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
48549  if( rc==SQLITE_OK ){
48550    *pRes = sqlite3Get4byte(ac);
48551  }
48552  return rc;
48553}
48554
48555/*
48556** Write a 32-bit integer into a string buffer in big-endian byte order.
48557*/
48558#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
48559
48560
48561/*
48562** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
48563** on success or an error code is something goes wrong.
48564*/
48565static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
48566  char ac[4];
48567  put32bits(ac, val);
48568  return sqlite3OsWrite(fd, ac, 4, offset);
48569}
48570
48571/*
48572** Unlock the database file to level eLock, which must be either NO_LOCK
48573** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
48574** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
48575**
48576** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
48577** called, do not modify it. See the comment above the #define of
48578** UNKNOWN_LOCK for an explanation of this.
48579*/
48580static int pagerUnlockDb(Pager *pPager, int eLock){
48581  int rc = SQLITE_OK;
48582
48583  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
48584  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
48585  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
48586  if( isOpen(pPager->fd) ){
48587    assert( pPager->eLock>=eLock );
48588    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
48589    if( pPager->eLock!=UNKNOWN_LOCK ){
48590      pPager->eLock = (u8)eLock;
48591    }
48592    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
48593  }
48594  return rc;
48595}
48596
48597/*
48598** Lock the database file to level eLock, which must be either SHARED_LOCK,
48599** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
48600** Pager.eLock variable to the new locking state.
48601**
48602** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
48603** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
48604** See the comment above the #define of UNKNOWN_LOCK for an explanation
48605** of this.
48606*/
48607static int pagerLockDb(Pager *pPager, int eLock){
48608  int rc = SQLITE_OK;
48609
48610  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
48611  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
48612    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
48613    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
48614      pPager->eLock = (u8)eLock;
48615      IOTRACE(("LOCK %p %d\n", pPager, eLock))
48616    }
48617  }
48618  return rc;
48619}
48620
48621/*
48622** This function determines whether or not the atomic-write optimization
48623** can be used with this pager. The optimization can be used if:
48624**
48625**  (a) the value returned by OsDeviceCharacteristics() indicates that
48626**      a database page may be written atomically, and
48627**  (b) the value returned by OsSectorSize() is less than or equal
48628**      to the page size.
48629**
48630** The optimization is also always enabled for temporary files. It is
48631** an error to call this function if pPager is opened on an in-memory
48632** database.
48633**
48634** If the optimization cannot be used, 0 is returned. If it can be used,
48635** then the value returned is the size of the journal file when it
48636** contains rollback data for exactly one page.
48637*/
48638#ifdef SQLITE_ENABLE_ATOMIC_WRITE
48639static int jrnlBufferSize(Pager *pPager){
48640  assert( !MEMDB );
48641  if( !pPager->tempFile ){
48642    int dc;                           /* Device characteristics */
48643    int nSector;                      /* Sector size */
48644    int szPage;                       /* Page size */
48645
48646    assert( isOpen(pPager->fd) );
48647    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
48648    nSector = pPager->sectorSize;
48649    szPage = pPager->pageSize;
48650
48651    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
48652    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
48653    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
48654      return 0;
48655    }
48656  }
48657
48658  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
48659}
48660#else
48661# define jrnlBufferSize(x) 0
48662#endif
48663
48664/*
48665** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
48666** on the cache using a hash function.  This is used for testing
48667** and debugging only.
48668*/
48669#ifdef SQLITE_CHECK_PAGES
48670/*
48671** Return a 32-bit hash of the page data for pPage.
48672*/
48673static u32 pager_datahash(int nByte, unsigned char *pData){
48674  u32 hash = 0;
48675  int i;
48676  for(i=0; i<nByte; i++){
48677    hash = (hash*1039) + pData[i];
48678  }
48679  return hash;
48680}
48681static u32 pager_pagehash(PgHdr *pPage){
48682  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
48683}
48684static void pager_set_pagehash(PgHdr *pPage){
48685  pPage->pageHash = pager_pagehash(pPage);
48686}
48687
48688/*
48689** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
48690** is defined, and NDEBUG is not defined, an assert() statement checks
48691** that the page is either dirty or still matches the calculated page-hash.
48692*/
48693#define CHECK_PAGE(x) checkPage(x)
48694static void checkPage(PgHdr *pPg){
48695  Pager *pPager = pPg->pPager;
48696  assert( pPager->eState!=PAGER_ERROR );
48697  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
48698}
48699
48700#else
48701#define pager_datahash(X,Y)  0
48702#define pager_pagehash(X)  0
48703#define pager_set_pagehash(X)
48704#define CHECK_PAGE(x)
48705#endif  /* SQLITE_CHECK_PAGES */
48706
48707/*
48708** When this is called the journal file for pager pPager must be open.
48709** This function attempts to read a master journal file name from the
48710** end of the file and, if successful, copies it into memory supplied
48711** by the caller. See comments above writeMasterJournal() for the format
48712** used to store a master journal file name at the end of a journal file.
48713**
48714** zMaster must point to a buffer of at least nMaster bytes allocated by
48715** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
48716** enough space to write the master journal name). If the master journal
48717** name in the journal is longer than nMaster bytes (including a
48718** nul-terminator), then this is handled as if no master journal name
48719** were present in the journal.
48720**
48721** If a master journal file name is present at the end of the journal
48722** file, then it is copied into the buffer pointed to by zMaster. A
48723** nul-terminator byte is appended to the buffer following the master
48724** journal file name.
48725**
48726** If it is determined that no master journal file name is present
48727** zMaster[0] is set to 0 and SQLITE_OK returned.
48728**
48729** If an error occurs while reading from the journal file, an SQLite
48730** error code is returned.
48731*/
48732static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
48733  int rc;                    /* Return code */
48734  u32 len;                   /* Length in bytes of master journal name */
48735  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
48736  u32 cksum;                 /* MJ checksum value read from journal */
48737  u32 u;                     /* Unsigned loop counter */
48738  unsigned char aMagic[8];   /* A buffer to hold the magic header */
48739  zMaster[0] = '\0';
48740
48741  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
48742   || szJ<16
48743   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
48744   || len>=nMaster
48745   || len==0
48746   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
48747   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
48748   || memcmp(aMagic, aJournalMagic, 8)
48749   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
48750  ){
48751    return rc;
48752  }
48753
48754  /* See if the checksum matches the master journal name */
48755  for(u=0; u<len; u++){
48756    cksum -= zMaster[u];
48757  }
48758  if( cksum ){
48759    /* If the checksum doesn't add up, then one or more of the disk sectors
48760    ** containing the master journal filename is corrupted. This means
48761    ** definitely roll back, so just return SQLITE_OK and report a (nul)
48762    ** master-journal filename.
48763    */
48764    len = 0;
48765  }
48766  zMaster[len] = '\0';
48767
48768  return SQLITE_OK;
48769}
48770
48771/*
48772** Return the offset of the sector boundary at or immediately
48773** following the value in pPager->journalOff, assuming a sector
48774** size of pPager->sectorSize bytes.
48775**
48776** i.e for a sector size of 512:
48777**
48778**   Pager.journalOff          Return value
48779**   ---------------------------------------
48780**   0                         0
48781**   512                       512
48782**   100                       512
48783**   2000                      2048
48784**
48785*/
48786static i64 journalHdrOffset(Pager *pPager){
48787  i64 offset = 0;
48788  i64 c = pPager->journalOff;
48789  if( c ){
48790    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
48791  }
48792  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
48793  assert( offset>=c );
48794  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
48795  return offset;
48796}
48797
48798/*
48799** The journal file must be open when this function is called.
48800**
48801** This function is a no-op if the journal file has not been written to
48802** within the current transaction (i.e. if Pager.journalOff==0).
48803**
48804** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
48805** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
48806** zero the 28-byte header at the start of the journal file. In either case,
48807** if the pager is not in no-sync mode, sync the journal file immediately
48808** after writing or truncating it.
48809**
48810** If Pager.journalSizeLimit is set to a positive, non-zero value, and
48811** following the truncation or zeroing described above the size of the
48812** journal file in bytes is larger than this value, then truncate the
48813** journal file to Pager.journalSizeLimit bytes. The journal file does
48814** not need to be synced following this operation.
48815**
48816** If an IO error occurs, abandon processing and return the IO error code.
48817** Otherwise, return SQLITE_OK.
48818*/
48819static int zeroJournalHdr(Pager *pPager, int doTruncate){
48820  int rc = SQLITE_OK;                               /* Return code */
48821  assert( isOpen(pPager->jfd) );
48822  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
48823  if( pPager->journalOff ){
48824    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
48825
48826    IOTRACE(("JZEROHDR %p\n", pPager))
48827    if( doTruncate || iLimit==0 ){
48828      rc = sqlite3OsTruncate(pPager->jfd, 0);
48829    }else{
48830      static const char zeroHdr[28] = {0};
48831      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
48832    }
48833    if( rc==SQLITE_OK && !pPager->noSync ){
48834      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
48835    }
48836
48837    /* At this point the transaction is committed but the write lock
48838    ** is still held on the file. If there is a size limit configured for
48839    ** the persistent journal and the journal file currently consumes more
48840    ** space than that limit allows for, truncate it now. There is no need
48841    ** to sync the file following this operation.
48842    */
48843    if( rc==SQLITE_OK && iLimit>0 ){
48844      i64 sz;
48845      rc = sqlite3OsFileSize(pPager->jfd, &sz);
48846      if( rc==SQLITE_OK && sz>iLimit ){
48847        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
48848      }
48849    }
48850  }
48851  return rc;
48852}
48853
48854/*
48855** The journal file must be open when this routine is called. A journal
48856** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
48857** current location.
48858**
48859** The format for the journal header is as follows:
48860** - 8 bytes: Magic identifying journal format.
48861** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
48862** - 4 bytes: Random number used for page hash.
48863** - 4 bytes: Initial database page count.
48864** - 4 bytes: Sector size used by the process that wrote this journal.
48865** - 4 bytes: Database page size.
48866**
48867** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
48868*/
48869static int writeJournalHdr(Pager *pPager){
48870  int rc = SQLITE_OK;                 /* Return code */
48871  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
48872  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
48873  u32 nWrite;                         /* Bytes of header sector written */
48874  int ii;                             /* Loop counter */
48875
48876  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
48877
48878  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
48879    nHeader = JOURNAL_HDR_SZ(pPager);
48880  }
48881
48882  /* If there are active savepoints and any of them were created
48883  ** since the most recent journal header was written, update the
48884  ** PagerSavepoint.iHdrOffset fields now.
48885  */
48886  for(ii=0; ii<pPager->nSavepoint; ii++){
48887    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
48888      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
48889    }
48890  }
48891
48892  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
48893
48894  /*
48895  ** Write the nRec Field - the number of page records that follow this
48896  ** journal header. Normally, zero is written to this value at this time.
48897  ** After the records are added to the journal (and the journal synced,
48898  ** if in full-sync mode), the zero is overwritten with the true number
48899  ** of records (see syncJournal()).
48900  **
48901  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
48902  ** reading the journal this value tells SQLite to assume that the
48903  ** rest of the journal file contains valid page records. This assumption
48904  ** is dangerous, as if a failure occurred whilst writing to the journal
48905  ** file it may contain some garbage data. There are two scenarios
48906  ** where this risk can be ignored:
48907  **
48908  **   * When the pager is in no-sync mode. Corruption can follow a
48909  **     power failure in this case anyway.
48910  **
48911  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
48912  **     that garbage data is never appended to the journal file.
48913  */
48914  assert( isOpen(pPager->fd) || pPager->noSync );
48915  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
48916   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
48917  ){
48918    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
48919    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
48920  }else{
48921    memset(zHeader, 0, sizeof(aJournalMagic)+4);
48922  }
48923
48924  /* The random check-hash initializer */
48925  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
48926  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
48927  /* The initial database size */
48928  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
48929  /* The assumed sector size for this process */
48930  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
48931
48932  /* The page size */
48933  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
48934
48935  /* Initializing the tail of the buffer is not necessary.  Everything
48936  ** works find if the following memset() is omitted.  But initializing
48937  ** the memory prevents valgrind from complaining, so we are willing to
48938  ** take the performance hit.
48939  */
48940  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
48941         nHeader-(sizeof(aJournalMagic)+20));
48942
48943  /* In theory, it is only necessary to write the 28 bytes that the
48944  ** journal header consumes to the journal file here. Then increment the
48945  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
48946  ** record is written to the following sector (leaving a gap in the file
48947  ** that will be implicitly filled in by the OS).
48948  **
48949  ** However it has been discovered that on some systems this pattern can
48950  ** be significantly slower than contiguously writing data to the file,
48951  ** even if that means explicitly writing data to the block of
48952  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
48953  ** is done.
48954  **
48955  ** The loop is required here in case the sector-size is larger than the
48956  ** database page size. Since the zHeader buffer is only Pager.pageSize
48957  ** bytes in size, more than one call to sqlite3OsWrite() may be required
48958  ** to populate the entire journal header sector.
48959  */
48960  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
48961    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
48962    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
48963    assert( pPager->journalHdr <= pPager->journalOff );
48964    pPager->journalOff += nHeader;
48965  }
48966
48967  return rc;
48968}
48969
48970/*
48971** The journal file must be open when this is called. A journal header file
48972** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
48973** file. The current location in the journal file is given by
48974** pPager->journalOff. See comments above function writeJournalHdr() for
48975** a description of the journal header format.
48976**
48977** If the header is read successfully, *pNRec is set to the number of
48978** page records following this header and *pDbSize is set to the size of the
48979** database before the transaction began, in pages. Also, pPager->cksumInit
48980** is set to the value read from the journal header. SQLITE_OK is returned
48981** in this case.
48982**
48983** If the journal header file appears to be corrupted, SQLITE_DONE is
48984** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
48985** cannot be read from the journal file an error code is returned.
48986*/
48987static int readJournalHdr(
48988  Pager *pPager,               /* Pager object */
48989  int isHot,
48990  i64 journalSize,             /* Size of the open journal file in bytes */
48991  u32 *pNRec,                  /* OUT: Value read from the nRec field */
48992  u32 *pDbSize                 /* OUT: Value of original database size field */
48993){
48994  int rc;                      /* Return code */
48995  unsigned char aMagic[8];     /* A buffer to hold the magic header */
48996  i64 iHdrOff;                 /* Offset of journal header being read */
48997
48998  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
48999
49000  /* Advance Pager.journalOff to the start of the next sector. If the
49001  ** journal file is too small for there to be a header stored at this
49002  ** point, return SQLITE_DONE.
49003  */
49004  pPager->journalOff = journalHdrOffset(pPager);
49005  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
49006    return SQLITE_DONE;
49007  }
49008  iHdrOff = pPager->journalOff;
49009
49010  /* Read in the first 8 bytes of the journal header. If they do not match
49011  ** the  magic string found at the start of each journal header, return
49012  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
49013  ** proceed.
49014  */
49015  if( isHot || iHdrOff!=pPager->journalHdr ){
49016    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
49017    if( rc ){
49018      return rc;
49019    }
49020    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
49021      return SQLITE_DONE;
49022    }
49023  }
49024
49025  /* Read the first three 32-bit fields of the journal header: The nRec
49026  ** field, the checksum-initializer and the database size at the start
49027  ** of the transaction. Return an error code if anything goes wrong.
49028  */
49029  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
49030   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
49031   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
49032  ){
49033    return rc;
49034  }
49035
49036  if( pPager->journalOff==0 ){
49037    u32 iPageSize;               /* Page-size field of journal header */
49038    u32 iSectorSize;             /* Sector-size field of journal header */
49039
49040    /* Read the page-size and sector-size journal header fields. */
49041    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
49042     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
49043    ){
49044      return rc;
49045    }
49046
49047    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
49048    ** journal header to zero. In this case, assume that the Pager.pageSize
49049    ** variable is already set to the correct page size.
49050    */
49051    if( iPageSize==0 ){
49052      iPageSize = pPager->pageSize;
49053    }
49054
49055    /* Check that the values read from the page-size and sector-size fields
49056    ** are within range. To be 'in range', both values need to be a power
49057    ** of two greater than or equal to 512 or 32, and not greater than their
49058    ** respective compile time maximum limits.
49059    */
49060    if( iPageSize<512                  || iSectorSize<32
49061     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
49062     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
49063    ){
49064      /* If the either the page-size or sector-size in the journal-header is
49065      ** invalid, then the process that wrote the journal-header must have
49066      ** crashed before the header was synced. In this case stop reading
49067      ** the journal file here.
49068      */
49069      return SQLITE_DONE;
49070    }
49071
49072    /* Update the page-size to match the value read from the journal.
49073    ** Use a testcase() macro to make sure that malloc failure within
49074    ** PagerSetPagesize() is tested.
49075    */
49076    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
49077    testcase( rc!=SQLITE_OK );
49078
49079    /* Update the assumed sector-size to match the value used by
49080    ** the process that created this journal. If this journal was
49081    ** created by a process other than this one, then this routine
49082    ** is being called from within pager_playback(). The local value
49083    ** of Pager.sectorSize is restored at the end of that routine.
49084    */
49085    pPager->sectorSize = iSectorSize;
49086  }
49087
49088  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
49089  return rc;
49090}
49091
49092
49093/*
49094** Write the supplied master journal name into the journal file for pager
49095** pPager at the current location. The master journal name must be the last
49096** thing written to a journal file. If the pager is in full-sync mode, the
49097** journal file descriptor is advanced to the next sector boundary before
49098** anything is written. The format is:
49099**
49100**   + 4 bytes: PAGER_MJ_PGNO.
49101**   + N bytes: Master journal filename in utf-8.
49102**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
49103**   + 4 bytes: Master journal name checksum.
49104**   + 8 bytes: aJournalMagic[].
49105**
49106** The master journal page checksum is the sum of the bytes in the master
49107** journal name, where each byte is interpreted as a signed 8-bit integer.
49108**
49109** If zMaster is a NULL pointer (occurs for a single database transaction),
49110** this call is a no-op.
49111*/
49112static int writeMasterJournal(Pager *pPager, const char *zMaster){
49113  int rc;                          /* Return code */
49114  int nMaster;                     /* Length of string zMaster */
49115  i64 iHdrOff;                     /* Offset of header in journal file */
49116  i64 jrnlSize;                    /* Size of journal file on disk */
49117  u32 cksum = 0;                   /* Checksum of string zMaster */
49118
49119  assert( pPager->setMaster==0 );
49120  assert( !pagerUseWal(pPager) );
49121
49122  if( !zMaster
49123   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
49124   || !isOpen(pPager->jfd)
49125  ){
49126    return SQLITE_OK;
49127  }
49128  pPager->setMaster = 1;
49129  assert( pPager->journalHdr <= pPager->journalOff );
49130
49131  /* Calculate the length in bytes and the checksum of zMaster */
49132  for(nMaster=0; zMaster[nMaster]; nMaster++){
49133    cksum += zMaster[nMaster];
49134  }
49135
49136  /* If in full-sync mode, advance to the next disk sector before writing
49137  ** the master journal name. This is in case the previous page written to
49138  ** the journal has already been synced.
49139  */
49140  if( pPager->fullSync ){
49141    pPager->journalOff = journalHdrOffset(pPager);
49142  }
49143  iHdrOff = pPager->journalOff;
49144
49145  /* Write the master journal data to the end of the journal file. If
49146  ** an error occurs, return the error code to the caller.
49147  */
49148  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
49149   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
49150   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
49151   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
49152   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
49153                                 iHdrOff+4+nMaster+8)))
49154  ){
49155    return rc;
49156  }
49157  pPager->journalOff += (nMaster+20);
49158
49159  /* If the pager is in peristent-journal mode, then the physical
49160  ** journal-file may extend past the end of the master-journal name
49161  ** and 8 bytes of magic data just written to the file. This is
49162  ** dangerous because the code to rollback a hot-journal file
49163  ** will not be able to find the master-journal name to determine
49164  ** whether or not the journal is hot.
49165  **
49166  ** Easiest thing to do in this scenario is to truncate the journal
49167  ** file to the required size.
49168  */
49169  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
49170   && jrnlSize>pPager->journalOff
49171  ){
49172    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
49173  }
49174  return rc;
49175}
49176
49177/*
49178** Discard the entire contents of the in-memory page-cache.
49179*/
49180static void pager_reset(Pager *pPager){
49181  pPager->iDataVersion++;
49182  sqlite3BackupRestart(pPager->pBackup);
49183  sqlite3PcacheClear(pPager->pPCache);
49184}
49185
49186/*
49187** Return the pPager->iDataVersion value
49188*/
49189SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
49190  assert( pPager->eState>PAGER_OPEN );
49191  return pPager->iDataVersion;
49192}
49193
49194/*
49195** Free all structures in the Pager.aSavepoint[] array and set both
49196** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
49197** if it is open and the pager is not in exclusive mode.
49198*/
49199static void releaseAllSavepoints(Pager *pPager){
49200  int ii;               /* Iterator for looping through Pager.aSavepoint */
49201  for(ii=0; ii<pPager->nSavepoint; ii++){
49202    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
49203  }
49204  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
49205    sqlite3OsClose(pPager->sjfd);
49206  }
49207  sqlite3_free(pPager->aSavepoint);
49208  pPager->aSavepoint = 0;
49209  pPager->nSavepoint = 0;
49210  pPager->nSubRec = 0;
49211}
49212
49213/*
49214** Set the bit number pgno in the PagerSavepoint.pInSavepoint
49215** bitvecs of all open savepoints. Return SQLITE_OK if successful
49216** or SQLITE_NOMEM if a malloc failure occurs.
49217*/
49218static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
49219  int ii;                   /* Loop counter */
49220  int rc = SQLITE_OK;       /* Result code */
49221
49222  for(ii=0; ii<pPager->nSavepoint; ii++){
49223    PagerSavepoint *p = &pPager->aSavepoint[ii];
49224    if( pgno<=p->nOrig ){
49225      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
49226      testcase( rc==SQLITE_NOMEM );
49227      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
49228    }
49229  }
49230  return rc;
49231}
49232
49233/*
49234** This function is a no-op if the pager is in exclusive mode and not
49235** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
49236** state.
49237**
49238** If the pager is not in exclusive-access mode, the database file is
49239** completely unlocked. If the file is unlocked and the file-system does
49240** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
49241** closed (if it is open).
49242**
49243** If the pager is in ERROR state when this function is called, the
49244** contents of the pager cache are discarded before switching back to
49245** the OPEN state. Regardless of whether the pager is in exclusive-mode
49246** or not, any journal file left in the file-system will be treated
49247** as a hot-journal and rolled back the next time a read-transaction
49248** is opened (by this or by any other connection).
49249*/
49250static void pager_unlock(Pager *pPager){
49251
49252  assert( pPager->eState==PAGER_READER
49253       || pPager->eState==PAGER_OPEN
49254       || pPager->eState==PAGER_ERROR
49255  );
49256
49257  sqlite3BitvecDestroy(pPager->pInJournal);
49258  pPager->pInJournal = 0;
49259  releaseAllSavepoints(pPager);
49260
49261  if( pagerUseWal(pPager) ){
49262    assert( !isOpen(pPager->jfd) );
49263    sqlite3WalEndReadTransaction(pPager->pWal);
49264    pPager->eState = PAGER_OPEN;
49265  }else if( !pPager->exclusiveMode ){
49266    int rc;                       /* Error code returned by pagerUnlockDb() */
49267    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
49268
49269    /* If the operating system support deletion of open files, then
49270    ** close the journal file when dropping the database lock.  Otherwise
49271    ** another connection with journal_mode=delete might delete the file
49272    ** out from under us.
49273    */
49274    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
49275    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
49276    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
49277    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
49278    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
49279    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
49280    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
49281     || 1!=(pPager->journalMode & 5)
49282    ){
49283      sqlite3OsClose(pPager->jfd);
49284    }
49285
49286    /* If the pager is in the ERROR state and the call to unlock the database
49287    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
49288    ** above the #define for UNKNOWN_LOCK for an explanation of why this
49289    ** is necessary.
49290    */
49291    rc = pagerUnlockDb(pPager, NO_LOCK);
49292    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
49293      pPager->eLock = UNKNOWN_LOCK;
49294    }
49295
49296    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
49297    ** without clearing the error code. This is intentional - the error
49298    ** code is cleared and the cache reset in the block below.
49299    */
49300    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
49301    pPager->changeCountDone = 0;
49302    pPager->eState = PAGER_OPEN;
49303  }
49304
49305  /* If Pager.errCode is set, the contents of the pager cache cannot be
49306  ** trusted. Now that there are no outstanding references to the pager,
49307  ** it can safely move back to PAGER_OPEN state. This happens in both
49308  ** normal and exclusive-locking mode.
49309  */
49310  assert( pPager->errCode==SQLITE_OK || !MEMDB );
49311  if( pPager->errCode ){
49312    if( pPager->tempFile==0 ){
49313      pager_reset(pPager);
49314      pPager->changeCountDone = 0;
49315      pPager->eState = PAGER_OPEN;
49316    }else{
49317      pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
49318    }
49319    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
49320    pPager->errCode = SQLITE_OK;
49321    setGetterMethod(pPager);
49322  }
49323
49324  pPager->journalOff = 0;
49325  pPager->journalHdr = 0;
49326  pPager->setMaster = 0;
49327}
49328
49329/*
49330** This function is called whenever an IOERR or FULL error that requires
49331** the pager to transition into the ERROR state may ahve occurred.
49332** The first argument is a pointer to the pager structure, the second
49333** the error-code about to be returned by a pager API function. The
49334** value returned is a copy of the second argument to this function.
49335**
49336** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
49337** IOERR sub-codes, the pager enters the ERROR state and the error code
49338** is stored in Pager.errCode. While the pager remains in the ERROR state,
49339** all major API calls on the Pager will immediately return Pager.errCode.
49340**
49341** The ERROR state indicates that the contents of the pager-cache
49342** cannot be trusted. This state can be cleared by completely discarding
49343** the contents of the pager-cache. If a transaction was active when
49344** the persistent error occurred, then the rollback journal may need
49345** to be replayed to restore the contents of the database file (as if
49346** it were a hot-journal).
49347*/
49348static int pager_error(Pager *pPager, int rc){
49349  int rc2 = rc & 0xff;
49350  assert( rc==SQLITE_OK || !MEMDB );
49351  assert(
49352       pPager->errCode==SQLITE_FULL ||
49353       pPager->errCode==SQLITE_OK ||
49354       (pPager->errCode & 0xff)==SQLITE_IOERR
49355  );
49356  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
49357    pPager->errCode = rc;
49358    pPager->eState = PAGER_ERROR;
49359    setGetterMethod(pPager);
49360  }
49361  return rc;
49362}
49363
49364static int pager_truncate(Pager *pPager, Pgno nPage);
49365
49366/*
49367** The write transaction open on pPager is being committed (bCommit==1)
49368** or rolled back (bCommit==0).
49369**
49370** Return TRUE if and only if all dirty pages should be flushed to disk.
49371**
49372** Rules:
49373**
49374**   *  For non-TEMP databases, always sync to disk.  This is necessary
49375**      for transactions to be durable.
49376**
49377**   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
49378**      file has been created already (via a spill on pagerStress()) and
49379**      when the number of dirty pages in memory exceeds 25% of the total
49380**      cache size.
49381*/
49382static int pagerFlushOnCommit(Pager *pPager, int bCommit){
49383  if( pPager->tempFile==0 ) return 1;
49384  if( !bCommit ) return 0;
49385  if( !isOpen(pPager->fd) ) return 0;
49386  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
49387}
49388
49389/*
49390** This routine ends a transaction. A transaction is usually ended by
49391** either a COMMIT or a ROLLBACK operation. This routine may be called
49392** after rollback of a hot-journal, or if an error occurs while opening
49393** the journal file or writing the very first journal-header of a
49394** database transaction.
49395**
49396** This routine is never called in PAGER_ERROR state. If it is called
49397** in PAGER_NONE or PAGER_SHARED state and the lock held is less
49398** exclusive than a RESERVED lock, it is a no-op.
49399**
49400** Otherwise, any active savepoints are released.
49401**
49402** If the journal file is open, then it is "finalized". Once a journal
49403** file has been finalized it is not possible to use it to roll back a
49404** transaction. Nor will it be considered to be a hot-journal by this
49405** or any other database connection. Exactly how a journal is finalized
49406** depends on whether or not the pager is running in exclusive mode and
49407** the current journal-mode (Pager.journalMode value), as follows:
49408**
49409**   journalMode==MEMORY
49410**     Journal file descriptor is simply closed. This destroys an
49411**     in-memory journal.
49412**
49413**   journalMode==TRUNCATE
49414**     Journal file is truncated to zero bytes in size.
49415**
49416**   journalMode==PERSIST
49417**     The first 28 bytes of the journal file are zeroed. This invalidates
49418**     the first journal header in the file, and hence the entire journal
49419**     file. An invalid journal file cannot be rolled back.
49420**
49421**   journalMode==DELETE
49422**     The journal file is closed and deleted using sqlite3OsDelete().
49423**
49424**     If the pager is running in exclusive mode, this method of finalizing
49425**     the journal file is never used. Instead, if the journalMode is
49426**     DELETE and the pager is in exclusive mode, the method described under
49427**     journalMode==PERSIST is used instead.
49428**
49429** After the journal is finalized, the pager moves to PAGER_READER state.
49430** If running in non-exclusive rollback mode, the lock on the file is
49431** downgraded to a SHARED_LOCK.
49432**
49433** SQLITE_OK is returned if no error occurs. If an error occurs during
49434** any of the IO operations to finalize the journal file or unlock the
49435** database then the IO error code is returned to the user. If the
49436** operation to finalize the journal file fails, then the code still
49437** tries to unlock the database file if not in exclusive mode. If the
49438** unlock operation fails as well, then the first error code related
49439** to the first error encountered (the journal finalization one) is
49440** returned.
49441*/
49442static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
49443  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
49444  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
49445
49446  /* Do nothing if the pager does not have an open write transaction
49447  ** or at least a RESERVED lock. This function may be called when there
49448  ** is no write-transaction active but a RESERVED or greater lock is
49449  ** held under two circumstances:
49450  **
49451  **   1. After a successful hot-journal rollback, it is called with
49452  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
49453  **
49454  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
49455  **      lock switches back to locking_mode=normal and then executes a
49456  **      read-transaction, this function is called with eState==PAGER_READER
49457  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
49458  */
49459  assert( assert_pager_state(pPager) );
49460  assert( pPager->eState!=PAGER_ERROR );
49461  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
49462    return SQLITE_OK;
49463  }
49464
49465  releaseAllSavepoints(pPager);
49466  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
49467  if( isOpen(pPager->jfd) ){
49468    assert( !pagerUseWal(pPager) );
49469
49470    /* Finalize the journal file. */
49471    if( sqlite3JournalIsInMemory(pPager->jfd) ){
49472      /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
49473      sqlite3OsClose(pPager->jfd);
49474    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
49475      if( pPager->journalOff==0 ){
49476        rc = SQLITE_OK;
49477      }else{
49478        rc = sqlite3OsTruncate(pPager->jfd, 0);
49479        if( rc==SQLITE_OK && pPager->fullSync ){
49480          /* Make sure the new file size is written into the inode right away.
49481          ** Otherwise the journal might resurrect following a power loss and
49482          ** cause the last transaction to roll back.  See
49483          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
49484          */
49485          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
49486        }
49487      }
49488      pPager->journalOff = 0;
49489    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
49490      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
49491    ){
49492      rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
49493      pPager->journalOff = 0;
49494    }else{
49495      /* This branch may be executed with Pager.journalMode==MEMORY if
49496      ** a hot-journal was just rolled back. In this case the journal
49497      ** file should be closed and deleted. If this connection writes to
49498      ** the database file, it will do so using an in-memory journal.
49499      */
49500      int bDelete = !pPager->tempFile;
49501      assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
49502      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
49503           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
49504           || pPager->journalMode==PAGER_JOURNALMODE_WAL
49505      );
49506      sqlite3OsClose(pPager->jfd);
49507      if( bDelete ){
49508        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
49509      }
49510    }
49511  }
49512
49513#ifdef SQLITE_CHECK_PAGES
49514  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
49515  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
49516    PgHdr *p = sqlite3PagerLookup(pPager, 1);
49517    if( p ){
49518      p->pageHash = 0;
49519      sqlite3PagerUnrefNotNull(p);
49520    }
49521  }
49522#endif
49523
49524  sqlite3BitvecDestroy(pPager->pInJournal);
49525  pPager->pInJournal = 0;
49526  pPager->nRec = 0;
49527  if( rc==SQLITE_OK ){
49528    if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
49529      sqlite3PcacheCleanAll(pPager->pPCache);
49530    }else{
49531      sqlite3PcacheClearWritable(pPager->pPCache);
49532    }
49533    sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
49534  }
49535
49536  if( pagerUseWal(pPager) ){
49537    /* Drop the WAL write-lock, if any. Also, if the connection was in
49538    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
49539    ** lock held on the database file.
49540    */
49541    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
49542    assert( rc2==SQLITE_OK );
49543  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
49544    /* This branch is taken when committing a transaction in rollback-journal
49545    ** mode if the database file on disk is larger than the database image.
49546    ** At this point the journal has been finalized and the transaction
49547    ** successfully committed, but the EXCLUSIVE lock is still held on the
49548    ** file. So it is safe to truncate the database file to its minimum
49549    ** required size.  */
49550    assert( pPager->eLock==EXCLUSIVE_LOCK );
49551    rc = pager_truncate(pPager, pPager->dbSize);
49552  }
49553
49554  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
49555    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
49556    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
49557  }
49558
49559  if( !pPager->exclusiveMode
49560   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
49561  ){
49562    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
49563    pPager->changeCountDone = 0;
49564  }
49565  pPager->eState = PAGER_READER;
49566  pPager->setMaster = 0;
49567
49568  return (rc==SQLITE_OK?rc2:rc);
49569}
49570
49571/*
49572** Execute a rollback if a transaction is active and unlock the
49573** database file.
49574**
49575** If the pager has already entered the ERROR state, do not attempt
49576** the rollback at this time. Instead, pager_unlock() is called. The
49577** call to pager_unlock() will discard all in-memory pages, unlock
49578** the database file and move the pager back to OPEN state. If this
49579** means that there is a hot-journal left in the file-system, the next
49580** connection to obtain a shared lock on the pager (which may be this one)
49581** will roll it back.
49582**
49583** If the pager has not already entered the ERROR state, but an IO or
49584** malloc error occurs during a rollback, then this will itself cause
49585** the pager to enter the ERROR state. Which will be cleared by the
49586** call to pager_unlock(), as described above.
49587*/
49588static void pagerUnlockAndRollback(Pager *pPager){
49589  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
49590    assert( assert_pager_state(pPager) );
49591    if( pPager->eState>=PAGER_WRITER_LOCKED ){
49592      sqlite3BeginBenignMalloc();
49593      sqlite3PagerRollback(pPager);
49594      sqlite3EndBenignMalloc();
49595    }else if( !pPager->exclusiveMode ){
49596      assert( pPager->eState==PAGER_READER );
49597      pager_end_transaction(pPager, 0, 0);
49598    }
49599  }
49600  pager_unlock(pPager);
49601}
49602
49603/*
49604** Parameter aData must point to a buffer of pPager->pageSize bytes
49605** of data. Compute and return a checksum based ont the contents of the
49606** page of data and the current value of pPager->cksumInit.
49607**
49608** This is not a real checksum. It is really just the sum of the
49609** random initial value (pPager->cksumInit) and every 200th byte
49610** of the page data, starting with byte offset (pPager->pageSize%200).
49611** Each byte is interpreted as an 8-bit unsigned integer.
49612**
49613** Changing the formula used to compute this checksum results in an
49614** incompatible journal file format.
49615**
49616** If journal corruption occurs due to a power failure, the most likely
49617** scenario is that one end or the other of the record will be changed.
49618** It is much less likely that the two ends of the journal record will be
49619** correct and the middle be corrupt.  Thus, this "checksum" scheme,
49620** though fast and simple, catches the mostly likely kind of corruption.
49621*/
49622static u32 pager_cksum(Pager *pPager, const u8 *aData){
49623  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
49624  int i = pPager->pageSize-200;          /* Loop counter */
49625  while( i>0 ){
49626    cksum += aData[i];
49627    i -= 200;
49628  }
49629  return cksum;
49630}
49631
49632/*
49633** Report the current page size and number of reserved bytes back
49634** to the codec.
49635*/
49636#ifdef SQLITE_HAS_CODEC
49637static void pagerReportSize(Pager *pPager){
49638  if( pPager->xCodecSizeChng ){
49639    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
49640                           (int)pPager->nReserve);
49641  }
49642}
49643#else
49644# define pagerReportSize(X)     /* No-op if we do not support a codec */
49645#endif
49646
49647#ifdef SQLITE_HAS_CODEC
49648/*
49649** Make sure the number of reserved bits is the same in the destination
49650** pager as it is in the source.  This comes up when a VACUUM changes the
49651** number of reserved bits to the "optimal" amount.
49652*/
49653SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
49654  if( pDest->nReserve!=pSrc->nReserve ){
49655    pDest->nReserve = pSrc->nReserve;
49656    pagerReportSize(pDest);
49657  }
49658}
49659#endif
49660
49661/*
49662** Read a single page from either the journal file (if isMainJrnl==1) or
49663** from the sub-journal (if isMainJrnl==0) and playback that page.
49664** The page begins at offset *pOffset into the file. The *pOffset
49665** value is increased to the start of the next page in the journal.
49666**
49667** The main rollback journal uses checksums - the statement journal does
49668** not.
49669**
49670** If the page number of the page record read from the (sub-)journal file
49671** is greater than the current value of Pager.dbSize, then playback is
49672** skipped and SQLITE_OK is returned.
49673**
49674** If pDone is not NULL, then it is a record of pages that have already
49675** been played back.  If the page at *pOffset has already been played back
49676** (if the corresponding pDone bit is set) then skip the playback.
49677** Make sure the pDone bit corresponding to the *pOffset page is set
49678** prior to returning.
49679**
49680** If the page record is successfully read from the (sub-)journal file
49681** and played back, then SQLITE_OK is returned. If an IO error occurs
49682** while reading the record from the (sub-)journal file or while writing
49683** to the database file, then the IO error code is returned. If data
49684** is successfully read from the (sub-)journal file but appears to be
49685** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
49686** two circumstances:
49687**
49688**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
49689**   * If the record is being rolled back from the main journal file
49690**     and the checksum field does not match the record content.
49691**
49692** Neither of these two scenarios are possible during a savepoint rollback.
49693**
49694** If this is a savepoint rollback, then memory may have to be dynamically
49695** allocated by this function. If this is the case and an allocation fails,
49696** SQLITE_NOMEM is returned.
49697*/
49698static int pager_playback_one_page(
49699  Pager *pPager,                /* The pager being played back */
49700  i64 *pOffset,                 /* Offset of record to playback */
49701  Bitvec *pDone,                /* Bitvec of pages already played back */
49702  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
49703  int isSavepnt                 /* True for a savepoint rollback */
49704){
49705  int rc;
49706  PgHdr *pPg;                   /* An existing page in the cache */
49707  Pgno pgno;                    /* The page number of a page in journal */
49708  u32 cksum;                    /* Checksum used for sanity checking */
49709  char *aData;                  /* Temporary storage for the page */
49710  sqlite3_file *jfd;            /* The file descriptor for the journal file */
49711  int isSynced;                 /* True if journal page is synced */
49712#ifdef SQLITE_HAS_CODEC
49713  /* The jrnlEnc flag is true if Journal pages should be passed through
49714  ** the codec.  It is false for pure in-memory journals. */
49715  const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
49716#endif
49717
49718  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
49719  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
49720  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
49721  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
49722
49723  aData = pPager->pTmpSpace;
49724  assert( aData );         /* Temp storage must have already been allocated */
49725  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
49726
49727  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
49728  ** or savepoint rollback done at the request of the caller) or this is
49729  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
49730  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
49731  ** only reads from the main journal, not the sub-journal.
49732  */
49733  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
49734       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
49735  );
49736  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
49737
49738  /* Read the page number and page data from the journal or sub-journal
49739  ** file. Return an error code to the caller if an IO error occurs.
49740  */
49741  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
49742  rc = read32bits(jfd, *pOffset, &pgno);
49743  if( rc!=SQLITE_OK ) return rc;
49744  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
49745  if( rc!=SQLITE_OK ) return rc;
49746  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
49747
49748  /* Sanity checking on the page.  This is more important that I originally
49749  ** thought.  If a power failure occurs while the journal is being written,
49750  ** it could cause invalid data to be written into the journal.  We need to
49751  ** detect this invalid data (with high probability) and ignore it.
49752  */
49753  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
49754    assert( !isSavepnt );
49755    return SQLITE_DONE;
49756  }
49757  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
49758    return SQLITE_OK;
49759  }
49760  if( isMainJrnl ){
49761    rc = read32bits(jfd, (*pOffset)-4, &cksum);
49762    if( rc ) return rc;
49763    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
49764      return SQLITE_DONE;
49765    }
49766  }
49767
49768  /* If this page has already been played back before during the current
49769  ** rollback, then don't bother to play it back again.
49770  */
49771  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
49772    return rc;
49773  }
49774
49775  /* When playing back page 1, restore the nReserve setting
49776  */
49777  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
49778    pPager->nReserve = ((u8*)aData)[20];
49779    pagerReportSize(pPager);
49780  }
49781
49782  /* If the pager is in CACHEMOD state, then there must be a copy of this
49783  ** page in the pager cache. In this case just update the pager cache,
49784  ** not the database file. The page is left marked dirty in this case.
49785  **
49786  ** An exception to the above rule: If the database is in no-sync mode
49787  ** and a page is moved during an incremental vacuum then the page may
49788  ** not be in the pager cache. Later: if a malloc() or IO error occurs
49789  ** during a Movepage() call, then the page may not be in the cache
49790  ** either. So the condition described in the above paragraph is not
49791  ** assert()able.
49792  **
49793  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
49794  ** pager cache if it exists and the main file. The page is then marked
49795  ** not dirty. Since this code is only executed in PAGER_OPEN state for
49796  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
49797  ** if the pager is in OPEN state.
49798  **
49799  ** Ticket #1171:  The statement journal might contain page content that is
49800  ** different from the page content at the start of the transaction.
49801  ** This occurs when a page is changed prior to the start of a statement
49802  ** then changed again within the statement.  When rolling back such a
49803  ** statement we must not write to the original database unless we know
49804  ** for certain that original page contents are synced into the main rollback
49805  ** journal.  Otherwise, a power loss might leave modified data in the
49806  ** database file without an entry in the rollback journal that can
49807  ** restore the database to its original form.  Two conditions must be
49808  ** met before writing to the database files. (1) the database must be
49809  ** locked.  (2) we know that the original page content is fully synced
49810  ** in the main journal either because the page is not in cache or else
49811  ** the page is marked as needSync==0.
49812  **
49813  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
49814  ** is possible to fail a statement on a database that does not yet exist.
49815  ** Do not attempt to write if database file has never been opened.
49816  */
49817  if( pagerUseWal(pPager) ){
49818    pPg = 0;
49819  }else{
49820    pPg = sqlite3PagerLookup(pPager, pgno);
49821  }
49822  assert( pPg || !MEMDB );
49823  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
49824  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
49825           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
49826           (isMainJrnl?"main-journal":"sub-journal")
49827  ));
49828  if( isMainJrnl ){
49829    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
49830  }else{
49831    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
49832  }
49833  if( isOpen(pPager->fd)
49834   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49835   && isSynced
49836  ){
49837    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
49838    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
49839    assert( !pagerUseWal(pPager) );
49840
49841    /* Write the data read from the journal back into the database file.
49842    ** This is usually safe even for an encrypted database - as the data
49843    ** was encrypted before it was written to the journal file. The exception
49844    ** is if the data was just read from an in-memory sub-journal. In that
49845    ** case it must be encrypted here before it is copied into the database
49846    ** file.  */
49847#ifdef SQLITE_HAS_CODEC
49848    if( !jrnlEnc ){
49849      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
49850      rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
49851      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
49852    }else
49853#endif
49854    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
49855
49856    if( pgno>pPager->dbFileSize ){
49857      pPager->dbFileSize = pgno;
49858    }
49859    if( pPager->pBackup ){
49860#ifdef SQLITE_HAS_CODEC
49861      if( jrnlEnc ){
49862        CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
49863        sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
49864        CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
49865      }else
49866#endif
49867      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
49868    }
49869  }else if( !isMainJrnl && pPg==0 ){
49870    /* If this is a rollback of a savepoint and data was not written to
49871    ** the database and the page is not in-memory, there is a potential
49872    ** problem. When the page is next fetched by the b-tree layer, it
49873    ** will be read from the database file, which may or may not be
49874    ** current.
49875    **
49876    ** There are a couple of different ways this can happen. All are quite
49877    ** obscure. When running in synchronous mode, this can only happen
49878    ** if the page is on the free-list at the start of the transaction, then
49879    ** populated, then moved using sqlite3PagerMovepage().
49880    **
49881    ** The solution is to add an in-memory page to the cache containing
49882    ** the data just read from the sub-journal. Mark the page as dirty
49883    ** and if the pager requires a journal-sync, then mark the page as
49884    ** requiring a journal-sync before it is written.
49885    */
49886    assert( isSavepnt );
49887    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
49888    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
49889    rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
49890    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
49891    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
49892    if( rc!=SQLITE_OK ) return rc;
49893    sqlite3PcacheMakeDirty(pPg);
49894  }
49895  if( pPg ){
49896    /* No page should ever be explicitly rolled back that is in use, except
49897    ** for page 1 which is held in use in order to keep the lock on the
49898    ** database active. However such a page may be rolled back as a result
49899    ** of an internal error resulting in an automatic call to
49900    ** sqlite3PagerRollback().
49901    */
49902    void *pData;
49903    pData = pPg->pData;
49904    memcpy(pData, (u8*)aData, pPager->pageSize);
49905    pPager->xReiniter(pPg);
49906    /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
49907    ** that call was dangerous and had no detectable benefit since the cache
49908    ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
49909    ** has been removed. */
49910    pager_set_pagehash(pPg);
49911
49912    /* If this was page 1, then restore the value of Pager.dbFileVers.
49913    ** Do this before any decoding. */
49914    if( pgno==1 ){
49915      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
49916    }
49917
49918    /* Decode the page just read from disk */
49919#if SQLITE_HAS_CODEC
49920    if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
49921#endif
49922    sqlite3PcacheRelease(pPg);
49923  }
49924  return rc;
49925}
49926
49927/*
49928** Parameter zMaster is the name of a master journal file. A single journal
49929** file that referred to the master journal file has just been rolled back.
49930** This routine checks if it is possible to delete the master journal file,
49931** and does so if it is.
49932**
49933** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
49934** available for use within this function.
49935**
49936** When a master journal file is created, it is populated with the names
49937** of all of its child journals, one after another, formatted as utf-8
49938** encoded text. The end of each child journal file is marked with a
49939** nul-terminator byte (0x00). i.e. the entire contents of a master journal
49940** file for a transaction involving two databases might be:
49941**
49942**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
49943**
49944** A master journal file may only be deleted once all of its child
49945** journals have been rolled back.
49946**
49947** This function reads the contents of the master-journal file into
49948** memory and loops through each of the child journal names. For
49949** each child journal, it checks if:
49950**
49951**   * if the child journal exists, and if so
49952**   * if the child journal contains a reference to master journal
49953**     file zMaster
49954**
49955** If a child journal can be found that matches both of the criteria
49956** above, this function returns without doing anything. Otherwise, if
49957** no such child journal can be found, file zMaster is deleted from
49958** the file-system using sqlite3OsDelete().
49959**
49960** If an IO error within this function, an error code is returned. This
49961** function allocates memory by calling sqlite3Malloc(). If an allocation
49962** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
49963** occur, SQLITE_OK is returned.
49964**
49965** TODO: This function allocates a single block of memory to load
49966** the entire contents of the master journal file. This could be
49967** a couple of kilobytes or so - potentially larger than the page
49968** size.
49969*/
49970static int pager_delmaster(Pager *pPager, const char *zMaster){
49971  sqlite3_vfs *pVfs = pPager->pVfs;
49972  int rc;                   /* Return code */
49973  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
49974  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
49975  char *zMasterJournal = 0; /* Contents of master journal file */
49976  i64 nMasterJournal;       /* Size of master journal file */
49977  char *zJournal;           /* Pointer to one journal within MJ file */
49978  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
49979  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
49980
49981  /* Allocate space for both the pJournal and pMaster file descriptors.
49982  ** If successful, open the master journal file for reading.
49983  */
49984  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
49985  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
49986  if( !pMaster ){
49987    rc = SQLITE_NOMEM_BKPT;
49988  }else{
49989    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
49990    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
49991  }
49992  if( rc!=SQLITE_OK ) goto delmaster_out;
49993
49994  /* Load the entire master journal file into space obtained from
49995  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
49996  ** sufficient space (in zMasterPtr) to hold the names of master
49997  ** journal files extracted from regular rollback-journals.
49998  */
49999  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
50000  if( rc!=SQLITE_OK ) goto delmaster_out;
50001  nMasterPtr = pVfs->mxPathname+1;
50002  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
50003  if( !zMasterJournal ){
50004    rc = SQLITE_NOMEM_BKPT;
50005    goto delmaster_out;
50006  }
50007  zMasterPtr = &zMasterJournal[nMasterJournal+1];
50008  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
50009  if( rc!=SQLITE_OK ) goto delmaster_out;
50010  zMasterJournal[nMasterJournal] = 0;
50011
50012  zJournal = zMasterJournal;
50013  while( (zJournal-zMasterJournal)<nMasterJournal ){
50014    int exists;
50015    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
50016    if( rc!=SQLITE_OK ){
50017      goto delmaster_out;
50018    }
50019    if( exists ){
50020      /* One of the journals pointed to by the master journal exists.
50021      ** Open it and check if it points at the master journal. If
50022      ** so, return without deleting the master journal file.
50023      */
50024      int c;
50025      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
50026      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
50027      if( rc!=SQLITE_OK ){
50028        goto delmaster_out;
50029      }
50030
50031      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
50032      sqlite3OsClose(pJournal);
50033      if( rc!=SQLITE_OK ){
50034        goto delmaster_out;
50035      }
50036
50037      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
50038      if( c ){
50039        /* We have a match. Do not delete the master journal file. */
50040        goto delmaster_out;
50041      }
50042    }
50043    zJournal += (sqlite3Strlen30(zJournal)+1);
50044  }
50045
50046  sqlite3OsClose(pMaster);
50047  rc = sqlite3OsDelete(pVfs, zMaster, 0);
50048
50049delmaster_out:
50050  sqlite3_free(zMasterJournal);
50051  if( pMaster ){
50052    sqlite3OsClose(pMaster);
50053    assert( !isOpen(pJournal) );
50054    sqlite3_free(pMaster);
50055  }
50056  return rc;
50057}
50058
50059
50060/*
50061** This function is used to change the actual size of the database
50062** file in the file-system. This only happens when committing a transaction,
50063** or rolling back a transaction (including rolling back a hot-journal).
50064**
50065** If the main database file is not open, or the pager is not in either
50066** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
50067** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
50068** If the file on disk is currently larger than nPage pages, then use the VFS
50069** xTruncate() method to truncate it.
50070**
50071** Or, it might be the case that the file on disk is smaller than
50072** nPage pages. Some operating system implementations can get confused if
50073** you try to truncate a file to some size that is larger than it
50074** currently is, so detect this case and write a single zero byte to
50075** the end of the new file instead.
50076**
50077** If successful, return SQLITE_OK. If an IO error occurs while modifying
50078** the database file, return the error code to the caller.
50079*/
50080static int pager_truncate(Pager *pPager, Pgno nPage){
50081  int rc = SQLITE_OK;
50082  assert( pPager->eState!=PAGER_ERROR );
50083  assert( pPager->eState!=PAGER_READER );
50084
50085  if( isOpen(pPager->fd)
50086   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
50087  ){
50088    i64 currentSize, newSize;
50089    int szPage = pPager->pageSize;
50090    assert( pPager->eLock==EXCLUSIVE_LOCK );
50091    /* TODO: Is it safe to use Pager.dbFileSize here? */
50092    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
50093    newSize = szPage*(i64)nPage;
50094    if( rc==SQLITE_OK && currentSize!=newSize ){
50095      if( currentSize>newSize ){
50096        rc = sqlite3OsTruncate(pPager->fd, newSize);
50097      }else if( (currentSize+szPage)<=newSize ){
50098        char *pTmp = pPager->pTmpSpace;
50099        memset(pTmp, 0, szPage);
50100        testcase( (newSize-szPage) == currentSize );
50101        testcase( (newSize-szPage) >  currentSize );
50102        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
50103      }
50104      if( rc==SQLITE_OK ){
50105        pPager->dbFileSize = nPage;
50106      }
50107    }
50108  }
50109  return rc;
50110}
50111
50112/*
50113** Return a sanitized version of the sector-size of OS file pFile. The
50114** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
50115*/
50116SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
50117  int iRet = sqlite3OsSectorSize(pFile);
50118  if( iRet<32 ){
50119    iRet = 512;
50120  }else if( iRet>MAX_SECTOR_SIZE ){
50121    assert( MAX_SECTOR_SIZE>=512 );
50122    iRet = MAX_SECTOR_SIZE;
50123  }
50124  return iRet;
50125}
50126
50127/*
50128** Set the value of the Pager.sectorSize variable for the given
50129** pager based on the value returned by the xSectorSize method
50130** of the open database file. The sector size will be used
50131** to determine the size and alignment of journal header and
50132** master journal pointers within created journal files.
50133**
50134** For temporary files the effective sector size is always 512 bytes.
50135**
50136** Otherwise, for non-temporary files, the effective sector size is
50137** the value returned by the xSectorSize() method rounded up to 32 if
50138** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
50139** is greater than MAX_SECTOR_SIZE.
50140**
50141** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
50142** the effective sector size to its minimum value (512).  The purpose of
50143** pPager->sectorSize is to define the "blast radius" of bytes that
50144** might change if a crash occurs while writing to a single byte in
50145** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
50146** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
50147** size.  For backwards compatibility of the rollback journal file format,
50148** we cannot reduce the effective sector size below 512.
50149*/
50150static void setSectorSize(Pager *pPager){
50151  assert( isOpen(pPager->fd) || pPager->tempFile );
50152
50153  if( pPager->tempFile
50154   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
50155              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
50156  ){
50157    /* Sector size doesn't matter for temporary files. Also, the file
50158    ** may not have been opened yet, in which case the OsSectorSize()
50159    ** call will segfault. */
50160    pPager->sectorSize = 512;
50161  }else{
50162    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
50163  }
50164}
50165
50166/*
50167** Playback the journal and thus restore the database file to
50168** the state it was in before we started making changes.
50169**
50170** The journal file format is as follows:
50171**
50172**  (1)  8 byte prefix.  A copy of aJournalMagic[].
50173**  (2)  4 byte big-endian integer which is the number of valid page records
50174**       in the journal.  If this value is 0xffffffff, then compute the
50175**       number of page records from the journal size.
50176**  (3)  4 byte big-endian integer which is the initial value for the
50177**       sanity checksum.
50178**  (4)  4 byte integer which is the number of pages to truncate the
50179**       database to during a rollback.
50180**  (5)  4 byte big-endian integer which is the sector size.  The header
50181**       is this many bytes in size.
50182**  (6)  4 byte big-endian integer which is the page size.
50183**  (7)  zero padding out to the next sector size.
50184**  (8)  Zero or more pages instances, each as follows:
50185**        +  4 byte page number.
50186**        +  pPager->pageSize bytes of data.
50187**        +  4 byte checksum
50188**
50189** When we speak of the journal header, we mean the first 7 items above.
50190** Each entry in the journal is an instance of the 8th item.
50191**
50192** Call the value from the second bullet "nRec".  nRec is the number of
50193** valid page entries in the journal.  In most cases, you can compute the
50194** value of nRec from the size of the journal file.  But if a power
50195** failure occurred while the journal was being written, it could be the
50196** case that the size of the journal file had already been increased but
50197** the extra entries had not yet made it safely to disk.  In such a case,
50198** the value of nRec computed from the file size would be too large.  For
50199** that reason, we always use the nRec value in the header.
50200**
50201** If the nRec value is 0xffffffff it means that nRec should be computed
50202** from the file size.  This value is used when the user selects the
50203** no-sync option for the journal.  A power failure could lead to corruption
50204** in this case.  But for things like temporary table (which will be
50205** deleted when the power is restored) we don't care.
50206**
50207** If the file opened as the journal file is not a well-formed
50208** journal file then all pages up to the first corrupted page are rolled
50209** back (or no pages if the journal header is corrupted). The journal file
50210** is then deleted and SQLITE_OK returned, just as if no corruption had
50211** been encountered.
50212**
50213** If an I/O or malloc() error occurs, the journal-file is not deleted
50214** and an error code is returned.
50215**
50216** The isHot parameter indicates that we are trying to rollback a journal
50217** that might be a hot journal.  Or, it could be that the journal is
50218** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
50219** If the journal really is hot, reset the pager cache prior rolling
50220** back any content.  If the journal is merely persistent, no reset is
50221** needed.
50222*/
50223static int pager_playback(Pager *pPager, int isHot){
50224  sqlite3_vfs *pVfs = pPager->pVfs;
50225  i64 szJ;                 /* Size of the journal file in bytes */
50226  u32 nRec;                /* Number of Records in the journal */
50227  u32 u;                   /* Unsigned loop counter */
50228  Pgno mxPg = 0;           /* Size of the original file in pages */
50229  int rc;                  /* Result code of a subroutine */
50230  int res = 1;             /* Value returned by sqlite3OsAccess() */
50231  char *zMaster = 0;       /* Name of master journal file if any */
50232  int needPagerReset;      /* True to reset page prior to first page rollback */
50233  int nPlayback = 0;       /* Total number of pages restored from journal */
50234
50235  /* Figure out how many records are in the journal.  Abort early if
50236  ** the journal is empty.
50237  */
50238  assert( isOpen(pPager->jfd) );
50239  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
50240  if( rc!=SQLITE_OK ){
50241    goto end_playback;
50242  }
50243
50244  /* Read the master journal name from the journal, if it is present.
50245  ** If a master journal file name is specified, but the file is not
50246  ** present on disk, then the journal is not hot and does not need to be
50247  ** played back.
50248  **
50249  ** TODO: Technically the following is an error because it assumes that
50250  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
50251  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
50252  ** mxPathname is 512, which is the same as the minimum allowable value
50253  ** for pageSize.
50254  */
50255  zMaster = pPager->pTmpSpace;
50256  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
50257  if( rc==SQLITE_OK && zMaster[0] ){
50258    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
50259  }
50260  zMaster = 0;
50261  if( rc!=SQLITE_OK || !res ){
50262    goto end_playback;
50263  }
50264  pPager->journalOff = 0;
50265  needPagerReset = isHot;
50266
50267  /* This loop terminates either when a readJournalHdr() or
50268  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
50269  ** occurs.
50270  */
50271  while( 1 ){
50272    /* Read the next journal header from the journal file.  If there are
50273    ** not enough bytes left in the journal file for a complete header, or
50274    ** it is corrupted, then a process must have failed while writing it.
50275    ** This indicates nothing more needs to be rolled back.
50276    */
50277    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
50278    if( rc!=SQLITE_OK ){
50279      if( rc==SQLITE_DONE ){
50280        rc = SQLITE_OK;
50281      }
50282      goto end_playback;
50283    }
50284
50285    /* If nRec is 0xffffffff, then this journal was created by a process
50286    ** working in no-sync mode. This means that the rest of the journal
50287    ** file consists of pages, there are no more journal headers. Compute
50288    ** the value of nRec based on this assumption.
50289    */
50290    if( nRec==0xffffffff ){
50291      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
50292      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
50293    }
50294
50295    /* If nRec is 0 and this rollback is of a transaction created by this
50296    ** process and if this is the final header in the journal, then it means
50297    ** that this part of the journal was being filled but has not yet been
50298    ** synced to disk.  Compute the number of pages based on the remaining
50299    ** size of the file.
50300    **
50301    ** The third term of the test was added to fix ticket #2565.
50302    ** When rolling back a hot journal, nRec==0 always means that the next
50303    ** chunk of the journal contains zero pages to be rolled back.  But
50304    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
50305    ** the journal, it means that the journal might contain additional
50306    ** pages that need to be rolled back and that the number of pages
50307    ** should be computed based on the journal file size.
50308    */
50309    if( nRec==0 && !isHot &&
50310        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
50311      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
50312    }
50313
50314    /* If this is the first header read from the journal, truncate the
50315    ** database file back to its original size.
50316    */
50317    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
50318      rc = pager_truncate(pPager, mxPg);
50319      if( rc!=SQLITE_OK ){
50320        goto end_playback;
50321      }
50322      pPager->dbSize = mxPg;
50323    }
50324
50325    /* Copy original pages out of the journal and back into the
50326    ** database file and/or page cache.
50327    */
50328    for(u=0; u<nRec; u++){
50329      if( needPagerReset ){
50330        pager_reset(pPager);
50331        needPagerReset = 0;
50332      }
50333      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
50334      if( rc==SQLITE_OK ){
50335        nPlayback++;
50336      }else{
50337        if( rc==SQLITE_DONE ){
50338          pPager->journalOff = szJ;
50339          break;
50340        }else if( rc==SQLITE_IOERR_SHORT_READ ){
50341          /* If the journal has been truncated, simply stop reading and
50342          ** processing the journal. This might happen if the journal was
50343          ** not completely written and synced prior to a crash.  In that
50344          ** case, the database should have never been written in the
50345          ** first place so it is OK to simply abandon the rollback. */
50346          rc = SQLITE_OK;
50347          goto end_playback;
50348        }else{
50349          /* If we are unable to rollback, quit and return the error
50350          ** code.  This will cause the pager to enter the error state
50351          ** so that no further harm will be done.  Perhaps the next
50352          ** process to come along will be able to rollback the database.
50353          */
50354          goto end_playback;
50355        }
50356      }
50357    }
50358  }
50359  /*NOTREACHED*/
50360  assert( 0 );
50361
50362end_playback:
50363  /* Following a rollback, the database file should be back in its original
50364  ** state prior to the start of the transaction, so invoke the
50365  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
50366  ** assertion that the transaction counter was modified.
50367  */
50368#ifdef SQLITE_DEBUG
50369  if( pPager->fd->pMethods ){
50370    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
50371  }
50372#endif
50373
50374  /* If this playback is happening automatically as a result of an IO or
50375  ** malloc error that occurred after the change-counter was updated but
50376  ** before the transaction was committed, then the change-counter
50377  ** modification may just have been reverted. If this happens in exclusive
50378  ** mode, then subsequent transactions performed by the connection will not
50379  ** update the change-counter at all. This may lead to cache inconsistency
50380  ** problems for other processes at some point in the future. So, just
50381  ** in case this has happened, clear the changeCountDone flag now.
50382  */
50383  pPager->changeCountDone = pPager->tempFile;
50384
50385  if( rc==SQLITE_OK ){
50386    zMaster = pPager->pTmpSpace;
50387    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
50388    testcase( rc!=SQLITE_OK );
50389  }
50390  if( rc==SQLITE_OK
50391   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
50392  ){
50393    rc = sqlite3PagerSync(pPager, 0);
50394  }
50395  if( rc==SQLITE_OK ){
50396    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
50397    testcase( rc!=SQLITE_OK );
50398  }
50399  if( rc==SQLITE_OK && zMaster[0] && res ){
50400    /* If there was a master journal and this routine will return success,
50401    ** see if it is possible to delete the master journal.
50402    */
50403    rc = pager_delmaster(pPager, zMaster);
50404    testcase( rc!=SQLITE_OK );
50405  }
50406  if( isHot && nPlayback ){
50407    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
50408                nPlayback, pPager->zJournal);
50409  }
50410
50411  /* The Pager.sectorSize variable may have been updated while rolling
50412  ** back a journal created by a process with a different sector size
50413  ** value. Reset it to the correct value for this process.
50414  */
50415  setSectorSize(pPager);
50416  return rc;
50417}
50418
50419
50420/*
50421** Read the content for page pPg out of the database file and into
50422** pPg->pData. A shared lock or greater must be held on the database
50423** file before this function is called.
50424**
50425** If page 1 is read, then the value of Pager.dbFileVers[] is set to
50426** the value read from the database file.
50427**
50428** If an IO error occurs, then the IO error is returned to the caller.
50429** Otherwise, SQLITE_OK is returned.
50430*/
50431static int readDbPage(PgHdr *pPg, u32 iFrame){
50432  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
50433  Pgno pgno = pPg->pgno;       /* Page number to read */
50434  int rc = SQLITE_OK;          /* Return code */
50435  int pgsz = pPager->pageSize; /* Number of bytes to read */
50436
50437  assert( pPager->eState>=PAGER_READER && !MEMDB );
50438  assert( isOpen(pPager->fd) );
50439
50440#ifndef SQLITE_OMIT_WAL
50441  if( iFrame ){
50442    /* Try to pull the page from the write-ahead log. */
50443    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
50444  }else
50445#endif
50446  {
50447    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
50448    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
50449    if( rc==SQLITE_IOERR_SHORT_READ ){
50450      rc = SQLITE_OK;
50451    }
50452  }
50453
50454  if( pgno==1 ){
50455    if( rc ){
50456      /* If the read is unsuccessful, set the dbFileVers[] to something
50457      ** that will never be a valid file version.  dbFileVers[] is a copy
50458      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
50459      ** zero or the size of the database in page. Bytes 32..35 and 35..39
50460      ** should be page numbers which are never 0xffffffff.  So filling
50461      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
50462      **
50463      ** For an encrypted database, the situation is more complex:  bytes
50464      ** 24..39 of the database are white noise.  But the probability of
50465      ** white noise equaling 16 bytes of 0xff is vanishingly small so
50466      ** we should still be ok.
50467      */
50468      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
50469    }else{
50470      u8 *dbFileVers = &((u8*)pPg->pData)[24];
50471      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
50472    }
50473  }
50474  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
50475
50476  PAGER_INCR(sqlite3_pager_readdb_count);
50477  PAGER_INCR(pPager->nRead);
50478  IOTRACE(("PGIN %p %d\n", pPager, pgno));
50479  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
50480               PAGERID(pPager), pgno, pager_pagehash(pPg)));
50481
50482  return rc;
50483}
50484
50485/*
50486** Update the value of the change-counter at offsets 24 and 92 in
50487** the header and the sqlite version number at offset 96.
50488**
50489** This is an unconditional update.  See also the pager_incr_changecounter()
50490** routine which only updates the change-counter if the update is actually
50491** needed, as determined by the pPager->changeCountDone state variable.
50492*/
50493static void pager_write_changecounter(PgHdr *pPg){
50494  u32 change_counter;
50495
50496  /* Increment the value just read and write it back to byte 24. */
50497  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
50498  put32bits(((char*)pPg->pData)+24, change_counter);
50499
50500  /* Also store the SQLite version number in bytes 96..99 and in
50501  ** bytes 92..95 store the change counter for which the version number
50502  ** is valid. */
50503  put32bits(((char*)pPg->pData)+92, change_counter);
50504  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
50505}
50506
50507#ifndef SQLITE_OMIT_WAL
50508/*
50509** This function is invoked once for each page that has already been
50510** written into the log file when a WAL transaction is rolled back.
50511** Parameter iPg is the page number of said page. The pCtx argument
50512** is actually a pointer to the Pager structure.
50513**
50514** If page iPg is present in the cache, and has no outstanding references,
50515** it is discarded. Otherwise, if there are one or more outstanding
50516** references, the page content is reloaded from the database. If the
50517** attempt to reload content from the database is required and fails,
50518** return an SQLite error code. Otherwise, SQLITE_OK.
50519*/
50520static int pagerUndoCallback(void *pCtx, Pgno iPg){
50521  int rc = SQLITE_OK;
50522  Pager *pPager = (Pager *)pCtx;
50523  PgHdr *pPg;
50524
50525  assert( pagerUseWal(pPager) );
50526  pPg = sqlite3PagerLookup(pPager, iPg);
50527  if( pPg ){
50528    if( sqlite3PcachePageRefcount(pPg)==1 ){
50529      sqlite3PcacheDrop(pPg);
50530    }else{
50531      u32 iFrame = 0;
50532      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
50533      if( rc==SQLITE_OK ){
50534        rc = readDbPage(pPg, iFrame);
50535      }
50536      if( rc==SQLITE_OK ){
50537        pPager->xReiniter(pPg);
50538      }
50539      sqlite3PagerUnrefNotNull(pPg);
50540    }
50541  }
50542
50543  /* Normally, if a transaction is rolled back, any backup processes are
50544  ** updated as data is copied out of the rollback journal and into the
50545  ** database. This is not generally possible with a WAL database, as
50546  ** rollback involves simply truncating the log file. Therefore, if one
50547  ** or more frames have already been written to the log (and therefore
50548  ** also copied into the backup databases) as part of this transaction,
50549  ** the backups must be restarted.
50550  */
50551  sqlite3BackupRestart(pPager->pBackup);
50552
50553  return rc;
50554}
50555
50556/*
50557** This function is called to rollback a transaction on a WAL database.
50558*/
50559static int pagerRollbackWal(Pager *pPager){
50560  int rc;                         /* Return Code */
50561  PgHdr *pList;                   /* List of dirty pages to revert */
50562
50563  /* For all pages in the cache that are currently dirty or have already
50564  ** been written (but not committed) to the log file, do one of the
50565  ** following:
50566  **
50567  **   + Discard the cached page (if refcount==0), or
50568  **   + Reload page content from the database (if refcount>0).
50569  */
50570  pPager->dbSize = pPager->dbOrigSize;
50571  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
50572  pList = sqlite3PcacheDirtyList(pPager->pPCache);
50573  while( pList && rc==SQLITE_OK ){
50574    PgHdr *pNext = pList->pDirty;
50575    rc = pagerUndoCallback((void *)pPager, pList->pgno);
50576    pList = pNext;
50577  }
50578
50579  return rc;
50580}
50581
50582/*
50583** This function is a wrapper around sqlite3WalFrames(). As well as logging
50584** the contents of the list of pages headed by pList (connected by pDirty),
50585** this function notifies any active backup processes that the pages have
50586** changed.
50587**
50588** The list of pages passed into this routine is always sorted by page number.
50589** Hence, if page 1 appears anywhere on the list, it will be the first page.
50590*/
50591static int pagerWalFrames(
50592  Pager *pPager,                  /* Pager object */
50593  PgHdr *pList,                   /* List of frames to log */
50594  Pgno nTruncate,                 /* Database size after this commit */
50595  int isCommit                    /* True if this is a commit */
50596){
50597  int rc;                         /* Return code */
50598  int nList;                      /* Number of pages in pList */
50599  PgHdr *p;                       /* For looping over pages */
50600
50601  assert( pPager->pWal );
50602  assert( pList );
50603#ifdef SQLITE_DEBUG
50604  /* Verify that the page list is in accending order */
50605  for(p=pList; p && p->pDirty; p=p->pDirty){
50606    assert( p->pgno < p->pDirty->pgno );
50607  }
50608#endif
50609
50610  assert( pList->pDirty==0 || isCommit );
50611  if( isCommit ){
50612    /* If a WAL transaction is being committed, there is no point in writing
50613    ** any pages with page numbers greater than nTruncate into the WAL file.
50614    ** They will never be read by any client. So remove them from the pDirty
50615    ** list here. */
50616    PgHdr **ppNext = &pList;
50617    nList = 0;
50618    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
50619      if( p->pgno<=nTruncate ){
50620        ppNext = &p->pDirty;
50621        nList++;
50622      }
50623    }
50624    assert( pList );
50625  }else{
50626    nList = 1;
50627  }
50628  pPager->aStat[PAGER_STAT_WRITE] += nList;
50629
50630  if( pList->pgno==1 ) pager_write_changecounter(pList);
50631  rc = sqlite3WalFrames(pPager->pWal,
50632      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
50633  );
50634  if( rc==SQLITE_OK && pPager->pBackup ){
50635    for(p=pList; p; p=p->pDirty){
50636      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
50637    }
50638  }
50639
50640#ifdef SQLITE_CHECK_PAGES
50641  pList = sqlite3PcacheDirtyList(pPager->pPCache);
50642  for(p=pList; p; p=p->pDirty){
50643    pager_set_pagehash(p);
50644  }
50645#endif
50646
50647  return rc;
50648}
50649
50650/*
50651** Begin a read transaction on the WAL.
50652**
50653** This routine used to be called "pagerOpenSnapshot()" because it essentially
50654** makes a snapshot of the database at the current point in time and preserves
50655** that snapshot for use by the reader in spite of concurrently changes by
50656** other writers or checkpointers.
50657*/
50658static int pagerBeginReadTransaction(Pager *pPager){
50659  int rc;                         /* Return code */
50660  int changed = 0;                /* True if cache must be reset */
50661
50662  assert( pagerUseWal(pPager) );
50663  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
50664
50665  /* sqlite3WalEndReadTransaction() was not called for the previous
50666  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
50667  ** are in locking_mode=NORMAL and EndRead() was previously called,
50668  ** the duplicate call is harmless.
50669  */
50670  sqlite3WalEndReadTransaction(pPager->pWal);
50671
50672  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
50673  if( rc!=SQLITE_OK || changed ){
50674    pager_reset(pPager);
50675    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
50676  }
50677
50678  return rc;
50679}
50680#endif
50681
50682/*
50683** This function is called as part of the transition from PAGER_OPEN
50684** to PAGER_READER state to determine the size of the database file
50685** in pages (assuming the page size currently stored in Pager.pageSize).
50686**
50687** If no error occurs, SQLITE_OK is returned and the size of the database
50688** in pages is stored in *pnPage. Otherwise, an error code (perhaps
50689** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
50690*/
50691static int pagerPagecount(Pager *pPager, Pgno *pnPage){
50692  Pgno nPage;                     /* Value to return via *pnPage */
50693
50694  /* Query the WAL sub-system for the database size. The WalDbsize()
50695  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
50696  ** if the database size is not available. The database size is not
50697  ** available from the WAL sub-system if the log file is empty or
50698  ** contains no valid committed transactions.
50699  */
50700  assert( pPager->eState==PAGER_OPEN );
50701  assert( pPager->eLock>=SHARED_LOCK );
50702  assert( isOpen(pPager->fd) );
50703  assert( pPager->tempFile==0 );
50704  nPage = sqlite3WalDbsize(pPager->pWal);
50705
50706  /* If the number of pages in the database is not available from the
50707  ** WAL sub-system, determine the page count based on the size of
50708  ** the database file.  If the size of the database file is not an
50709  ** integer multiple of the page-size, round up the result.
50710  */
50711  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
50712    i64 n = 0;                    /* Size of db file in bytes */
50713    int rc = sqlite3OsFileSize(pPager->fd, &n);
50714    if( rc!=SQLITE_OK ){
50715      return rc;
50716    }
50717    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
50718  }
50719
50720  /* If the current number of pages in the file is greater than the
50721  ** configured maximum pager number, increase the allowed limit so
50722  ** that the file can be read.
50723  */
50724  if( nPage>pPager->mxPgno ){
50725    pPager->mxPgno = (Pgno)nPage;
50726  }
50727
50728  *pnPage = nPage;
50729  return SQLITE_OK;
50730}
50731
50732#ifndef SQLITE_OMIT_WAL
50733/*
50734** Check if the *-wal file that corresponds to the database opened by pPager
50735** exists if the database is not empy, or verify that the *-wal file does
50736** not exist (by deleting it) if the database file is empty.
50737**
50738** If the database is not empty and the *-wal file exists, open the pager
50739** in WAL mode.  If the database is empty or if no *-wal file exists and
50740** if no error occurs, make sure Pager.journalMode is not set to
50741** PAGER_JOURNALMODE_WAL.
50742**
50743** Return SQLITE_OK or an error code.
50744**
50745** The caller must hold a SHARED lock on the database file to call this
50746** function. Because an EXCLUSIVE lock on the db file is required to delete
50747** a WAL on a none-empty database, this ensures there is no race condition
50748** between the xAccess() below and an xDelete() being executed by some
50749** other connection.
50750*/
50751static int pagerOpenWalIfPresent(Pager *pPager){
50752  int rc = SQLITE_OK;
50753  assert( pPager->eState==PAGER_OPEN );
50754  assert( pPager->eLock>=SHARED_LOCK );
50755
50756  if( !pPager->tempFile ){
50757    int isWal;                    /* True if WAL file exists */
50758    rc = sqlite3OsAccess(
50759        pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
50760    );
50761    if( rc==SQLITE_OK ){
50762      if( isWal ){
50763        Pgno nPage;                   /* Size of the database file */
50764
50765        rc = pagerPagecount(pPager, &nPage);
50766        if( rc ) return rc;
50767        if( nPage==0 ){
50768          rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
50769        }else{
50770          testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
50771          rc = sqlite3PagerOpenWal(pPager, 0);
50772        }
50773      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
50774        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
50775      }
50776    }
50777  }
50778  return rc;
50779}
50780#endif
50781
50782/*
50783** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
50784** the entire master journal file. The case pSavepoint==NULL occurs when
50785** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
50786** savepoint.
50787**
50788** When pSavepoint is not NULL (meaning a non-transaction savepoint is
50789** being rolled back), then the rollback consists of up to three stages,
50790** performed in the order specified:
50791**
50792**   * Pages are played back from the main journal starting at byte
50793**     offset PagerSavepoint.iOffset and continuing to
50794**     PagerSavepoint.iHdrOffset, or to the end of the main journal
50795**     file if PagerSavepoint.iHdrOffset is zero.
50796**
50797**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
50798**     back starting from the journal header immediately following
50799**     PagerSavepoint.iHdrOffset to the end of the main journal file.
50800**
50801**   * Pages are then played back from the sub-journal file, starting
50802**     with the PagerSavepoint.iSubRec and continuing to the end of
50803**     the journal file.
50804**
50805** Throughout the rollback process, each time a page is rolled back, the
50806** corresponding bit is set in a bitvec structure (variable pDone in the
50807** implementation below). This is used to ensure that a page is only
50808** rolled back the first time it is encountered in either journal.
50809**
50810** If pSavepoint is NULL, then pages are only played back from the main
50811** journal file. There is no need for a bitvec in this case.
50812**
50813** In either case, before playback commences the Pager.dbSize variable
50814** is reset to the value that it held at the start of the savepoint
50815** (or transaction). No page with a page-number greater than this value
50816** is played back. If one is encountered it is simply skipped.
50817*/
50818static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
50819  i64 szJ;                 /* Effective size of the main journal */
50820  i64 iHdrOff;             /* End of first segment of main-journal records */
50821  int rc = SQLITE_OK;      /* Return code */
50822  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
50823
50824  assert( pPager->eState!=PAGER_ERROR );
50825  assert( pPager->eState>=PAGER_WRITER_LOCKED );
50826
50827  /* Allocate a bitvec to use to store the set of pages rolled back */
50828  if( pSavepoint ){
50829    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
50830    if( !pDone ){
50831      return SQLITE_NOMEM_BKPT;
50832    }
50833  }
50834
50835  /* Set the database size back to the value it was before the savepoint
50836  ** being reverted was opened.
50837  */
50838  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
50839  pPager->changeCountDone = pPager->tempFile;
50840
50841  if( !pSavepoint && pagerUseWal(pPager) ){
50842    return pagerRollbackWal(pPager);
50843  }
50844
50845  /* Use pPager->journalOff as the effective size of the main rollback
50846  ** journal.  The actual file might be larger than this in
50847  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
50848  ** past pPager->journalOff is off-limits to us.
50849  */
50850  szJ = pPager->journalOff;
50851  assert( pagerUseWal(pPager)==0 || szJ==0 );
50852
50853  /* Begin by rolling back records from the main journal starting at
50854  ** PagerSavepoint.iOffset and continuing to the next journal header.
50855  ** There might be records in the main journal that have a page number
50856  ** greater than the current database size (pPager->dbSize) but those
50857  ** will be skipped automatically.  Pages are added to pDone as they
50858  ** are played back.
50859  */
50860  if( pSavepoint && !pagerUseWal(pPager) ){
50861    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
50862    pPager->journalOff = pSavepoint->iOffset;
50863    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
50864      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
50865    }
50866    assert( rc!=SQLITE_DONE );
50867  }else{
50868    pPager->journalOff = 0;
50869  }
50870
50871  /* Continue rolling back records out of the main journal starting at
50872  ** the first journal header seen and continuing until the effective end
50873  ** of the main journal file.  Continue to skip out-of-range pages and
50874  ** continue adding pages rolled back to pDone.
50875  */
50876  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
50877    u32 ii;            /* Loop counter */
50878    u32 nJRec = 0;     /* Number of Journal Records */
50879    u32 dummy;
50880    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
50881    assert( rc!=SQLITE_DONE );
50882
50883    /*
50884    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
50885    ** test is related to ticket #2565.  See the discussion in the
50886    ** pager_playback() function for additional information.
50887    */
50888    if( nJRec==0
50889     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
50890    ){
50891      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
50892    }
50893    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
50894      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
50895    }
50896    assert( rc!=SQLITE_DONE );
50897  }
50898  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
50899
50900  /* Finally,  rollback pages from the sub-journal.  Page that were
50901  ** previously rolled back out of the main journal (and are hence in pDone)
50902  ** will be skipped.  Out-of-range pages are also skipped.
50903  */
50904  if( pSavepoint ){
50905    u32 ii;            /* Loop counter */
50906    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
50907
50908    if( pagerUseWal(pPager) ){
50909      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
50910    }
50911    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
50912      assert( offset==(i64)ii*(4+pPager->pageSize) );
50913      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
50914    }
50915    assert( rc!=SQLITE_DONE );
50916  }
50917
50918  sqlite3BitvecDestroy(pDone);
50919  if( rc==SQLITE_OK ){
50920    pPager->journalOff = szJ;
50921  }
50922
50923  return rc;
50924}
50925
50926/*
50927** Change the maximum number of in-memory pages that are allowed
50928** before attempting to recycle clean and unused pages.
50929*/
50930SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
50931  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
50932}
50933
50934/*
50935** Change the maximum number of in-memory pages that are allowed
50936** before attempting to spill pages to journal.
50937*/
50938SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
50939  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
50940}
50941
50942/*
50943** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
50944*/
50945static void pagerFixMaplimit(Pager *pPager){
50946#if SQLITE_MAX_MMAP_SIZE>0
50947  sqlite3_file *fd = pPager->fd;
50948  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
50949    sqlite3_int64 sz;
50950    sz = pPager->szMmap;
50951    pPager->bUseFetch = (sz>0);
50952    setGetterMethod(pPager);
50953    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
50954  }
50955#endif
50956}
50957
50958/*
50959** Change the maximum size of any memory mapping made of the database file.
50960*/
50961SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
50962  pPager->szMmap = szMmap;
50963  pagerFixMaplimit(pPager);
50964}
50965
50966/*
50967** Free as much memory as possible from the pager.
50968*/
50969SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
50970  sqlite3PcacheShrink(pPager->pPCache);
50971}
50972
50973/*
50974** Adjust settings of the pager to those specified in the pgFlags parameter.
50975**
50976** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
50977** of the database to damage due to OS crashes or power failures by
50978** changing the number of syncs()s when writing the journals.
50979** There are four levels:
50980**
50981**    OFF       sqlite3OsSync() is never called.  This is the default
50982**              for temporary and transient files.
50983**
50984**    NORMAL    The journal is synced once before writes begin on the
50985**              database.  This is normally adequate protection, but
50986**              it is theoretically possible, though very unlikely,
50987**              that an inopertune power failure could leave the journal
50988**              in a state which would cause damage to the database
50989**              when it is rolled back.
50990**
50991**    FULL      The journal is synced twice before writes begin on the
50992**              database (with some additional information - the nRec field
50993**              of the journal header - being written in between the two
50994**              syncs).  If we assume that writing a
50995**              single disk sector is atomic, then this mode provides
50996**              assurance that the journal will not be corrupted to the
50997**              point of causing damage to the database during rollback.
50998**
50999**    EXTRA     This is like FULL except that is also syncs the directory
51000**              that contains the rollback journal after the rollback
51001**              journal is unlinked.
51002**
51003** The above is for a rollback-journal mode.  For WAL mode, OFF continues
51004** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
51005** prior to the start of checkpoint and that the database file is synced
51006** at the conclusion of the checkpoint if the entire content of the WAL
51007** was written back into the database.  But no sync operations occur for
51008** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
51009** file is synced following each commit operation, in addition to the
51010** syncs associated with NORMAL.  There is no difference between FULL
51011** and EXTRA for WAL mode.
51012**
51013** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
51014** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
51015** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
51016** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
51017** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
51018** synchronous=FULL versus synchronous=NORMAL setting determines when
51019** the xSync primitive is called and is relevant to all platforms.
51020**
51021** Numeric values associated with these states are OFF==1, NORMAL=2,
51022** and FULL=3.
51023*/
51024#ifndef SQLITE_OMIT_PAGER_PRAGMAS
51025SQLITE_PRIVATE void sqlite3PagerSetFlags(
51026  Pager *pPager,        /* The pager to set safety level for */
51027  unsigned pgFlags      /* Various flags */
51028){
51029  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
51030  if( pPager->tempFile ){
51031    pPager->noSync = 1;
51032    pPager->fullSync = 0;
51033    pPager->extraSync = 0;
51034  }else{
51035    pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
51036    pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
51037    pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
51038  }
51039  if( pPager->noSync ){
51040    pPager->syncFlags = 0;
51041    pPager->ckptSyncFlags = 0;
51042  }else if( pgFlags & PAGER_FULLFSYNC ){
51043    pPager->syncFlags = SQLITE_SYNC_FULL;
51044    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
51045  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
51046    pPager->syncFlags = SQLITE_SYNC_NORMAL;
51047    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
51048  }else{
51049    pPager->syncFlags = SQLITE_SYNC_NORMAL;
51050    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
51051  }
51052  pPager->walSyncFlags = pPager->syncFlags;
51053  if( pPager->fullSync ){
51054    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
51055  }
51056  if( pgFlags & PAGER_CACHESPILL ){
51057    pPager->doNotSpill &= ~SPILLFLAG_OFF;
51058  }else{
51059    pPager->doNotSpill |= SPILLFLAG_OFF;
51060  }
51061}
51062#endif
51063
51064/*
51065** The following global variable is incremented whenever the library
51066** attempts to open a temporary file.  This information is used for
51067** testing and analysis only.
51068*/
51069#ifdef SQLITE_TEST
51070SQLITE_API int sqlite3_opentemp_count = 0;
51071#endif
51072
51073/*
51074** Open a temporary file.
51075**
51076** Write the file descriptor into *pFile. Return SQLITE_OK on success
51077** or some other error code if we fail. The OS will automatically
51078** delete the temporary file when it is closed.
51079**
51080** The flags passed to the VFS layer xOpen() call are those specified
51081** by parameter vfsFlags ORed with the following:
51082**
51083**     SQLITE_OPEN_READWRITE
51084**     SQLITE_OPEN_CREATE
51085**     SQLITE_OPEN_EXCLUSIVE
51086**     SQLITE_OPEN_DELETEONCLOSE
51087*/
51088static int pagerOpentemp(
51089  Pager *pPager,        /* The pager object */
51090  sqlite3_file *pFile,  /* Write the file descriptor here */
51091  int vfsFlags          /* Flags passed through to the VFS */
51092){
51093  int rc;               /* Return code */
51094
51095#ifdef SQLITE_TEST
51096  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
51097#endif
51098
51099  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
51100            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
51101  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
51102  assert( rc!=SQLITE_OK || isOpen(pFile) );
51103  return rc;
51104}
51105
51106/*
51107** Set the busy handler function.
51108**
51109** The pager invokes the busy-handler if sqlite3OsLock() returns
51110** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
51111** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
51112** lock. It does *not* invoke the busy handler when upgrading from
51113** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
51114** (which occurs during hot-journal rollback). Summary:
51115**
51116**   Transition                        | Invokes xBusyHandler
51117**   --------------------------------------------------------
51118**   NO_LOCK       -> SHARED_LOCK      | Yes
51119**   SHARED_LOCK   -> RESERVED_LOCK    | No
51120**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
51121**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
51122**
51123** If the busy-handler callback returns non-zero, the lock is
51124** retried. If it returns zero, then the SQLITE_BUSY error is
51125** returned to the caller of the pager API function.
51126*/
51127SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
51128  Pager *pPager,                       /* Pager object */
51129  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
51130  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
51131){
51132  pPager->xBusyHandler = xBusyHandler;
51133  pPager->pBusyHandlerArg = pBusyHandlerArg;
51134
51135  if( isOpen(pPager->fd) ){
51136    void **ap = (void **)&pPager->xBusyHandler;
51137    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
51138    assert( ap[1]==pBusyHandlerArg );
51139    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
51140  }
51141}
51142
51143/*
51144** Change the page size used by the Pager object. The new page size
51145** is passed in *pPageSize.
51146**
51147** If the pager is in the error state when this function is called, it
51148** is a no-op. The value returned is the error state error code (i.e.
51149** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
51150**
51151** Otherwise, if all of the following are true:
51152**
51153**   * the new page size (value of *pPageSize) is valid (a power
51154**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
51155**
51156**   * there are no outstanding page references, and
51157**
51158**   * the database is either not an in-memory database or it is
51159**     an in-memory database that currently consists of zero pages.
51160**
51161** then the pager object page size is set to *pPageSize.
51162**
51163** If the page size is changed, then this function uses sqlite3PagerMalloc()
51164** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
51165** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
51166** In all other cases, SQLITE_OK is returned.
51167**
51168** If the page size is not changed, either because one of the enumerated
51169** conditions above is not true, the pager was in error state when this
51170** function was called, or because the memory allocation attempt failed,
51171** then *pPageSize is set to the old, retained page size before returning.
51172*/
51173SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
51174  int rc = SQLITE_OK;
51175
51176  /* It is not possible to do a full assert_pager_state() here, as this
51177  ** function may be called from within PagerOpen(), before the state
51178  ** of the Pager object is internally consistent.
51179  **
51180  ** At one point this function returned an error if the pager was in
51181  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
51182  ** there is at least one outstanding page reference, this function
51183  ** is a no-op for that case anyhow.
51184  */
51185
51186  u32 pageSize = *pPageSize;
51187  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
51188  if( (pPager->memDb==0 || pPager->dbSize==0)
51189   && sqlite3PcacheRefCount(pPager->pPCache)==0
51190   && pageSize && pageSize!=(u32)pPager->pageSize
51191  ){
51192    char *pNew = NULL;             /* New temp space */
51193    i64 nByte = 0;
51194
51195    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
51196      rc = sqlite3OsFileSize(pPager->fd, &nByte);
51197    }
51198    if( rc==SQLITE_OK ){
51199      pNew = (char *)sqlite3PageMalloc(pageSize);
51200      if( !pNew ) rc = SQLITE_NOMEM_BKPT;
51201    }
51202
51203    if( rc==SQLITE_OK ){
51204      pager_reset(pPager);
51205      rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
51206    }
51207    if( rc==SQLITE_OK ){
51208      sqlite3PageFree(pPager->pTmpSpace);
51209      pPager->pTmpSpace = pNew;
51210      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
51211      pPager->pageSize = pageSize;
51212    }else{
51213      sqlite3PageFree(pNew);
51214    }
51215  }
51216
51217  *pPageSize = pPager->pageSize;
51218  if( rc==SQLITE_OK ){
51219    if( nReserve<0 ) nReserve = pPager->nReserve;
51220    assert( nReserve>=0 && nReserve<1000 );
51221    pPager->nReserve = (i16)nReserve;
51222    pagerReportSize(pPager);
51223    pagerFixMaplimit(pPager);
51224  }
51225  return rc;
51226}
51227
51228/*
51229** Return a pointer to the "temporary page" buffer held internally
51230** by the pager.  This is a buffer that is big enough to hold the
51231** entire content of a database page.  This buffer is used internally
51232** during rollback and will be overwritten whenever a rollback
51233** occurs.  But other modules are free to use it too, as long as
51234** no rollbacks are happening.
51235*/
51236SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
51237  return pPager->pTmpSpace;
51238}
51239
51240/*
51241** Attempt to set the maximum database page count if mxPage is positive.
51242** Make no changes if mxPage is zero or negative.  And never reduce the
51243** maximum page count below the current size of the database.
51244**
51245** Regardless of mxPage, return the current maximum page count.
51246*/
51247SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
51248  if( mxPage>0 ){
51249    pPager->mxPgno = mxPage;
51250  }
51251  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
51252  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
51253  return pPager->mxPgno;
51254}
51255
51256/*
51257** The following set of routines are used to disable the simulated
51258** I/O error mechanism.  These routines are used to avoid simulated
51259** errors in places where we do not care about errors.
51260**
51261** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
51262** and generate no code.
51263*/
51264#ifdef SQLITE_TEST
51265SQLITE_API extern int sqlite3_io_error_pending;
51266SQLITE_API extern int sqlite3_io_error_hit;
51267static int saved_cnt;
51268void disable_simulated_io_errors(void){
51269  saved_cnt = sqlite3_io_error_pending;
51270  sqlite3_io_error_pending = -1;
51271}
51272void enable_simulated_io_errors(void){
51273  sqlite3_io_error_pending = saved_cnt;
51274}
51275#else
51276# define disable_simulated_io_errors()
51277# define enable_simulated_io_errors()
51278#endif
51279
51280/*
51281** Read the first N bytes from the beginning of the file into memory
51282** that pDest points to.
51283**
51284** If the pager was opened on a transient file (zFilename==""), or
51285** opened on a file less than N bytes in size, the output buffer is
51286** zeroed and SQLITE_OK returned. The rationale for this is that this
51287** function is used to read database headers, and a new transient or
51288** zero sized database has a header than consists entirely of zeroes.
51289**
51290** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
51291** the error code is returned to the caller and the contents of the
51292** output buffer undefined.
51293*/
51294SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
51295  int rc = SQLITE_OK;
51296  memset(pDest, 0, N);
51297  assert( isOpen(pPager->fd) || pPager->tempFile );
51298
51299  /* This routine is only called by btree immediately after creating
51300  ** the Pager object.  There has not been an opportunity to transition
51301  ** to WAL mode yet.
51302  */
51303  assert( !pagerUseWal(pPager) );
51304
51305  if( isOpen(pPager->fd) ){
51306    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
51307    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
51308    if( rc==SQLITE_IOERR_SHORT_READ ){
51309      rc = SQLITE_OK;
51310    }
51311  }
51312  return rc;
51313}
51314
51315/*
51316** This function may only be called when a read-transaction is open on
51317** the pager. It returns the total number of pages in the database.
51318**
51319** However, if the file is between 1 and <page-size> bytes in size, then
51320** this is considered a 1 page file.
51321*/
51322SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
51323  assert( pPager->eState>=PAGER_READER );
51324  assert( pPager->eState!=PAGER_WRITER_FINISHED );
51325  *pnPage = (int)pPager->dbSize;
51326}
51327
51328
51329/*
51330** Try to obtain a lock of type locktype on the database file. If
51331** a similar or greater lock is already held, this function is a no-op
51332** (returning SQLITE_OK immediately).
51333**
51334** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
51335** the busy callback if the lock is currently not available. Repeat
51336** until the busy callback returns false or until the attempt to
51337** obtain the lock succeeds.
51338**
51339** Return SQLITE_OK on success and an error code if we cannot obtain
51340** the lock. If the lock is obtained successfully, set the Pager.state
51341** variable to locktype before returning.
51342*/
51343static int pager_wait_on_lock(Pager *pPager, int locktype){
51344  int rc;                              /* Return code */
51345
51346  /* Check that this is either a no-op (because the requested lock is
51347  ** already held), or one of the transitions that the busy-handler
51348  ** may be invoked during, according to the comment above
51349  ** sqlite3PagerSetBusyhandler().
51350  */
51351  assert( (pPager->eLock>=locktype)
51352       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
51353       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
51354  );
51355
51356  do {
51357    rc = pagerLockDb(pPager, locktype);
51358  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
51359  return rc;
51360}
51361
51362/*
51363** Function assertTruncateConstraint(pPager) checks that one of the
51364** following is true for all dirty pages currently in the page-cache:
51365**
51366**   a) The page number is less than or equal to the size of the
51367**      current database image, in pages, OR
51368**
51369**   b) if the page content were written at this time, it would not
51370**      be necessary to write the current content out to the sub-journal
51371**      (as determined by function subjRequiresPage()).
51372**
51373** If the condition asserted by this function were not true, and the
51374** dirty page were to be discarded from the cache via the pagerStress()
51375** routine, pagerStress() would not write the current page content to
51376** the database file. If a savepoint transaction were rolled back after
51377** this happened, the correct behavior would be to restore the current
51378** content of the page. However, since this content is not present in either
51379** the database file or the portion of the rollback journal and
51380** sub-journal rolled back the content could not be restored and the
51381** database image would become corrupt. It is therefore fortunate that
51382** this circumstance cannot arise.
51383*/
51384#if defined(SQLITE_DEBUG)
51385static void assertTruncateConstraintCb(PgHdr *pPg){
51386  assert( pPg->flags&PGHDR_DIRTY );
51387  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
51388}
51389static void assertTruncateConstraint(Pager *pPager){
51390  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
51391}
51392#else
51393# define assertTruncateConstraint(pPager)
51394#endif
51395
51396/*
51397** Truncate the in-memory database file image to nPage pages. This
51398** function does not actually modify the database file on disk. It
51399** just sets the internal state of the pager object so that the
51400** truncation will be done when the current transaction is committed.
51401**
51402** This function is only called right before committing a transaction.
51403** Once this function has been called, the transaction must either be
51404** rolled back or committed. It is not safe to call this function and
51405** then continue writing to the database.
51406*/
51407SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
51408  assert( pPager->dbSize>=nPage );
51409  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
51410  pPager->dbSize = nPage;
51411
51412  /* At one point the code here called assertTruncateConstraint() to
51413  ** ensure that all pages being truncated away by this operation are,
51414  ** if one or more savepoints are open, present in the savepoint
51415  ** journal so that they can be restored if the savepoint is rolled
51416  ** back. This is no longer necessary as this function is now only
51417  ** called right before committing a transaction. So although the
51418  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
51419  ** they cannot be rolled back. So the assertTruncateConstraint() call
51420  ** is no longer correct. */
51421}
51422
51423
51424/*
51425** This function is called before attempting a hot-journal rollback. It
51426** syncs the journal file to disk, then sets pPager->journalHdr to the
51427** size of the journal file so that the pager_playback() routine knows
51428** that the entire journal file has been synced.
51429**
51430** Syncing a hot-journal to disk before attempting to roll it back ensures
51431** that if a power-failure occurs during the rollback, the process that
51432** attempts rollback following system recovery sees the same journal
51433** content as this process.
51434**
51435** If everything goes as planned, SQLITE_OK is returned. Otherwise,
51436** an SQLite error code.
51437*/
51438static int pagerSyncHotJournal(Pager *pPager){
51439  int rc = SQLITE_OK;
51440  if( !pPager->noSync ){
51441    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
51442  }
51443  if( rc==SQLITE_OK ){
51444    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
51445  }
51446  return rc;
51447}
51448
51449#if SQLITE_MAX_MMAP_SIZE>0
51450/*
51451** Obtain a reference to a memory mapped page object for page number pgno.
51452** The new object will use the pointer pData, obtained from xFetch().
51453** If successful, set *ppPage to point to the new page reference
51454** and return SQLITE_OK. Otherwise, return an SQLite error code and set
51455** *ppPage to zero.
51456**
51457** Page references obtained by calling this function should be released
51458** by calling pagerReleaseMapPage().
51459*/
51460static int pagerAcquireMapPage(
51461  Pager *pPager,                  /* Pager object */
51462  Pgno pgno,                      /* Page number */
51463  void *pData,                    /* xFetch()'d data for this page */
51464  PgHdr **ppPage                  /* OUT: Acquired page object */
51465){
51466  PgHdr *p;                       /* Memory mapped page to return */
51467
51468  if( pPager->pMmapFreelist ){
51469    *ppPage = p = pPager->pMmapFreelist;
51470    pPager->pMmapFreelist = p->pDirty;
51471    p->pDirty = 0;
51472    assert( pPager->nExtra>=8 );
51473    memset(p->pExtra, 0, 8);
51474  }else{
51475    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
51476    if( p==0 ){
51477      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
51478      return SQLITE_NOMEM_BKPT;
51479    }
51480    p->pExtra = (void *)&p[1];
51481    p->flags = PGHDR_MMAP;
51482    p->nRef = 1;
51483    p->pPager = pPager;
51484  }
51485
51486  assert( p->pExtra==(void *)&p[1] );
51487  assert( p->pPage==0 );
51488  assert( p->flags==PGHDR_MMAP );
51489  assert( p->pPager==pPager );
51490  assert( p->nRef==1 );
51491
51492  p->pgno = pgno;
51493  p->pData = pData;
51494  pPager->nMmapOut++;
51495
51496  return SQLITE_OK;
51497}
51498#endif
51499
51500/*
51501** Release a reference to page pPg. pPg must have been returned by an
51502** earlier call to pagerAcquireMapPage().
51503*/
51504static void pagerReleaseMapPage(PgHdr *pPg){
51505  Pager *pPager = pPg->pPager;
51506  pPager->nMmapOut--;
51507  pPg->pDirty = pPager->pMmapFreelist;
51508  pPager->pMmapFreelist = pPg;
51509
51510  assert( pPager->fd->pMethods->iVersion>=3 );
51511  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
51512}
51513
51514/*
51515** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
51516*/
51517static void pagerFreeMapHdrs(Pager *pPager){
51518  PgHdr *p;
51519  PgHdr *pNext;
51520  for(p=pPager->pMmapFreelist; p; p=pNext){
51521    pNext = p->pDirty;
51522    sqlite3_free(p);
51523  }
51524}
51525
51526
51527/*
51528** Shutdown the page cache.  Free all memory and close all files.
51529**
51530** If a transaction was in progress when this routine is called, that
51531** transaction is rolled back.  All outstanding pages are invalidated
51532** and their memory is freed.  Any attempt to use a page associated
51533** with this page cache after this function returns will likely
51534** result in a coredump.
51535**
51536** This function always succeeds. If a transaction is active an attempt
51537** is made to roll it back. If an error occurs during the rollback
51538** a hot journal may be left in the filesystem but no error is returned
51539** to the caller.
51540*/
51541SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
51542  u8 *pTmp = (u8 *)pPager->pTmpSpace;
51543
51544  assert( db || pagerUseWal(pPager)==0 );
51545  assert( assert_pager_state(pPager) );
51546  disable_simulated_io_errors();
51547  sqlite3BeginBenignMalloc();
51548  pagerFreeMapHdrs(pPager);
51549  /* pPager->errCode = 0; */
51550  pPager->exclusiveMode = 0;
51551#ifndef SQLITE_OMIT_WAL
51552  assert( db || pPager->pWal==0 );
51553  sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags, pPager->pageSize,
51554      (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp)
51555  );
51556  pPager->pWal = 0;
51557#endif
51558  pager_reset(pPager);
51559  if( MEMDB ){
51560    pager_unlock(pPager);
51561  }else{
51562    /* If it is open, sync the journal file before calling UnlockAndRollback.
51563    ** If this is not done, then an unsynced portion of the open journal
51564    ** file may be played back into the database. If a power failure occurs
51565    ** while this is happening, the database could become corrupt.
51566    **
51567    ** If an error occurs while trying to sync the journal, shift the pager
51568    ** into the ERROR state. This causes UnlockAndRollback to unlock the
51569    ** database and close the journal file without attempting to roll it
51570    ** back or finalize it. The next database user will have to do hot-journal
51571    ** rollback before accessing the database file.
51572    */
51573    if( isOpen(pPager->jfd) ){
51574      pager_error(pPager, pagerSyncHotJournal(pPager));
51575    }
51576    pagerUnlockAndRollback(pPager);
51577  }
51578  sqlite3EndBenignMalloc();
51579  enable_simulated_io_errors();
51580  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
51581  IOTRACE(("CLOSE %p\n", pPager))
51582  sqlite3OsClose(pPager->jfd);
51583  sqlite3OsClose(pPager->fd);
51584  sqlite3PageFree(pTmp);
51585  sqlite3PcacheClose(pPager->pPCache);
51586
51587#ifdef SQLITE_HAS_CODEC
51588  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
51589#endif
51590
51591  assert( !pPager->aSavepoint && !pPager->pInJournal );
51592  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
51593
51594  sqlite3_free(pPager);
51595  return SQLITE_OK;
51596}
51597
51598#if !defined(NDEBUG) || defined(SQLITE_TEST)
51599/*
51600** Return the page number for page pPg.
51601*/
51602SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
51603  return pPg->pgno;
51604}
51605#endif
51606
51607/*
51608** Increment the reference count for page pPg.
51609*/
51610SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
51611  sqlite3PcacheRef(pPg);
51612}
51613
51614/*
51615** Sync the journal. In other words, make sure all the pages that have
51616** been written to the journal have actually reached the surface of the
51617** disk and can be restored in the event of a hot-journal rollback.
51618**
51619** If the Pager.noSync flag is set, then this function is a no-op.
51620** Otherwise, the actions required depend on the journal-mode and the
51621** device characteristics of the file-system, as follows:
51622**
51623**   * If the journal file is an in-memory journal file, no action need
51624**     be taken.
51625**
51626**   * Otherwise, if the device does not support the SAFE_APPEND property,
51627**     then the nRec field of the most recently written journal header
51628**     is updated to contain the number of journal records that have
51629**     been written following it. If the pager is operating in full-sync
51630**     mode, then the journal file is synced before this field is updated.
51631**
51632**   * If the device does not support the SEQUENTIAL property, then
51633**     journal file is synced.
51634**
51635** Or, in pseudo-code:
51636**
51637**   if( NOT <in-memory journal> ){
51638**     if( NOT SAFE_APPEND ){
51639**       if( <full-sync mode> ) xSync(<journal file>);
51640**       <update nRec field>
51641**     }
51642**     if( NOT SEQUENTIAL ) xSync(<journal file>);
51643**   }
51644**
51645** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
51646** page currently held in memory before returning SQLITE_OK. If an IO
51647** error is encountered, then the IO error code is returned to the caller.
51648*/
51649static int syncJournal(Pager *pPager, int newHdr){
51650  int rc;                         /* Return code */
51651
51652  assert( pPager->eState==PAGER_WRITER_CACHEMOD
51653       || pPager->eState==PAGER_WRITER_DBMOD
51654  );
51655  assert( assert_pager_state(pPager) );
51656  assert( !pagerUseWal(pPager) );
51657
51658  rc = sqlite3PagerExclusiveLock(pPager);
51659  if( rc!=SQLITE_OK ) return rc;
51660
51661  if( !pPager->noSync ){
51662    assert( !pPager->tempFile );
51663    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
51664      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
51665      assert( isOpen(pPager->jfd) );
51666
51667      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
51668        /* This block deals with an obscure problem. If the last connection
51669        ** that wrote to this database was operating in persistent-journal
51670        ** mode, then the journal file may at this point actually be larger
51671        ** than Pager.journalOff bytes. If the next thing in the journal
51672        ** file happens to be a journal-header (written as part of the
51673        ** previous connection's transaction), and a crash or power-failure
51674        ** occurs after nRec is updated but before this connection writes
51675        ** anything else to the journal file (or commits/rolls back its
51676        ** transaction), then SQLite may become confused when doing the
51677        ** hot-journal rollback following recovery. It may roll back all
51678        ** of this connections data, then proceed to rolling back the old,
51679        ** out-of-date data that follows it. Database corruption.
51680        **
51681        ** To work around this, if the journal file does appear to contain
51682        ** a valid header following Pager.journalOff, then write a 0x00
51683        ** byte to the start of it to prevent it from being recognized.
51684        **
51685        ** Variable iNextHdrOffset is set to the offset at which this
51686        ** problematic header will occur, if it exists. aMagic is used
51687        ** as a temporary buffer to inspect the first couple of bytes of
51688        ** the potential journal header.
51689        */
51690        i64 iNextHdrOffset;
51691        u8 aMagic[8];
51692        u8 zHeader[sizeof(aJournalMagic)+4];
51693
51694        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
51695        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
51696
51697        iNextHdrOffset = journalHdrOffset(pPager);
51698        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
51699        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
51700          static const u8 zerobyte = 0;
51701          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
51702        }
51703        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51704          return rc;
51705        }
51706
51707        /* Write the nRec value into the journal file header. If in
51708        ** full-synchronous mode, sync the journal first. This ensures that
51709        ** all data has really hit the disk before nRec is updated to mark
51710        ** it as a candidate for rollback.
51711        **
51712        ** This is not required if the persistent media supports the
51713        ** SAFE_APPEND property. Because in this case it is not possible
51714        ** for garbage data to be appended to the file, the nRec field
51715        ** is populated with 0xFFFFFFFF when the journal header is written
51716        ** and never needs to be updated.
51717        */
51718        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
51719          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
51720          IOTRACE(("JSYNC %p\n", pPager))
51721          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
51722          if( rc!=SQLITE_OK ) return rc;
51723        }
51724        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
51725        rc = sqlite3OsWrite(
51726            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
51727        );
51728        if( rc!=SQLITE_OK ) return rc;
51729      }
51730      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
51731        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
51732        IOTRACE(("JSYNC %p\n", pPager))
51733        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
51734          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
51735        );
51736        if( rc!=SQLITE_OK ) return rc;
51737      }
51738
51739      pPager->journalHdr = pPager->journalOff;
51740      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
51741        pPager->nRec = 0;
51742        rc = writeJournalHdr(pPager);
51743        if( rc!=SQLITE_OK ) return rc;
51744      }
51745    }else{
51746      pPager->journalHdr = pPager->journalOff;
51747    }
51748  }
51749
51750  /* Unless the pager is in noSync mode, the journal file was just
51751  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
51752  ** all pages.
51753  */
51754  sqlite3PcacheClearSyncFlags(pPager->pPCache);
51755  pPager->eState = PAGER_WRITER_DBMOD;
51756  assert( assert_pager_state(pPager) );
51757  return SQLITE_OK;
51758}
51759
51760/*
51761** The argument is the first in a linked list of dirty pages connected
51762** by the PgHdr.pDirty pointer. This function writes each one of the
51763** in-memory pages in the list to the database file. The argument may
51764** be NULL, representing an empty list. In this case this function is
51765** a no-op.
51766**
51767** The pager must hold at least a RESERVED lock when this function
51768** is called. Before writing anything to the database file, this lock
51769** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
51770** SQLITE_BUSY is returned and no data is written to the database file.
51771**
51772** If the pager is a temp-file pager and the actual file-system file
51773** is not yet open, it is created and opened before any data is
51774** written out.
51775**
51776** Once the lock has been upgraded and, if necessary, the file opened,
51777** the pages are written out to the database file in list order. Writing
51778** a page is skipped if it meets either of the following criteria:
51779**
51780**   * The page number is greater than Pager.dbSize, or
51781**   * The PGHDR_DONT_WRITE flag is set on the page.
51782**
51783** If writing out a page causes the database file to grow, Pager.dbFileSize
51784** is updated accordingly. If page 1 is written out, then the value cached
51785** in Pager.dbFileVers[] is updated to match the new value stored in
51786** the database file.
51787**
51788** If everything is successful, SQLITE_OK is returned. If an IO error
51789** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
51790** be obtained, SQLITE_BUSY is returned.
51791*/
51792static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
51793  int rc = SQLITE_OK;                  /* Return code */
51794
51795  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
51796  assert( !pagerUseWal(pPager) );
51797  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
51798  assert( pPager->eLock==EXCLUSIVE_LOCK );
51799  assert( isOpen(pPager->fd) || pList->pDirty==0 );
51800
51801  /* If the file is a temp-file has not yet been opened, open it now. It
51802  ** is not possible for rc to be other than SQLITE_OK if this branch
51803  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
51804  */
51805  if( !isOpen(pPager->fd) ){
51806    assert( pPager->tempFile && rc==SQLITE_OK );
51807    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
51808  }
51809
51810  /* Before the first write, give the VFS a hint of what the final
51811  ** file size will be.
51812  */
51813  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
51814  if( rc==SQLITE_OK
51815   && pPager->dbHintSize<pPager->dbSize
51816   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
51817  ){
51818    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
51819    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
51820    pPager->dbHintSize = pPager->dbSize;
51821  }
51822
51823  while( rc==SQLITE_OK && pList ){
51824    Pgno pgno = pList->pgno;
51825
51826    /* If there are dirty pages in the page cache with page numbers greater
51827    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
51828    ** make the file smaller (presumably by auto-vacuum code). Do not write
51829    ** any such pages to the file.
51830    **
51831    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
51832    ** set (set by sqlite3PagerDontWrite()).
51833    */
51834    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
51835      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
51836      char *pData;                                   /* Data to write */
51837
51838      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
51839      if( pList->pgno==1 ) pager_write_changecounter(pList);
51840
51841      /* Encode the database */
51842      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
51843
51844      /* Write out the page data. */
51845      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
51846
51847      /* If page 1 was just written, update Pager.dbFileVers to match
51848      ** the value now stored in the database file. If writing this
51849      ** page caused the database file to grow, update dbFileSize.
51850      */
51851      if( pgno==1 ){
51852        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
51853      }
51854      if( pgno>pPager->dbFileSize ){
51855        pPager->dbFileSize = pgno;
51856      }
51857      pPager->aStat[PAGER_STAT_WRITE]++;
51858
51859      /* Update any backup objects copying the contents of this pager. */
51860      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
51861
51862      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
51863                   PAGERID(pPager), pgno, pager_pagehash(pList)));
51864      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
51865      PAGER_INCR(sqlite3_pager_writedb_count);
51866    }else{
51867      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
51868    }
51869    pager_set_pagehash(pList);
51870    pList = pList->pDirty;
51871  }
51872
51873  return rc;
51874}
51875
51876/*
51877** Ensure that the sub-journal file is open. If it is already open, this
51878** function is a no-op.
51879**
51880** SQLITE_OK is returned if everything goes according to plan. An
51881** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
51882** fails.
51883*/
51884static int openSubJournal(Pager *pPager){
51885  int rc = SQLITE_OK;
51886  if( !isOpen(pPager->sjfd) ){
51887    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
51888      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
51889      | SQLITE_OPEN_DELETEONCLOSE;
51890    int nStmtSpill = sqlite3Config.nStmtSpill;
51891    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
51892      nStmtSpill = -1;
51893    }
51894    rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
51895  }
51896  return rc;
51897}
51898
51899/*
51900** Append a record of the current state of page pPg to the sub-journal.
51901**
51902** If successful, set the bit corresponding to pPg->pgno in the bitvecs
51903** for all open savepoints before returning.
51904**
51905** This function returns SQLITE_OK if everything is successful, an IO
51906** error code if the attempt to write to the sub-journal fails, or
51907** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
51908** bitvec.
51909*/
51910static int subjournalPage(PgHdr *pPg){
51911  int rc = SQLITE_OK;
51912  Pager *pPager = pPg->pPager;
51913  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51914
51915    /* Open the sub-journal, if it has not already been opened */
51916    assert( pPager->useJournal );
51917    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
51918    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
51919    assert( pagerUseWal(pPager)
51920         || pageInJournal(pPager, pPg)
51921         || pPg->pgno>pPager->dbOrigSize
51922    );
51923    rc = openSubJournal(pPager);
51924
51925    /* If the sub-journal was opened successfully (or was already open),
51926    ** write the journal record into the file.  */
51927    if( rc==SQLITE_OK ){
51928      void *pData = pPg->pData;
51929      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
51930      char *pData2;
51931
51932#if SQLITE_HAS_CODEC
51933      if( !pPager->subjInMemory ){
51934        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
51935      }else
51936#endif
51937      pData2 = pData;
51938      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
51939      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
51940      if( rc==SQLITE_OK ){
51941        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
51942      }
51943    }
51944  }
51945  if( rc==SQLITE_OK ){
51946    pPager->nSubRec++;
51947    assert( pPager->nSavepoint>0 );
51948    rc = addToSavepointBitvecs(pPager, pPg->pgno);
51949  }
51950  return rc;
51951}
51952static int subjournalPageIfRequired(PgHdr *pPg){
51953  if( subjRequiresPage(pPg) ){
51954    return subjournalPage(pPg);
51955  }else{
51956    return SQLITE_OK;
51957  }
51958}
51959
51960/*
51961** This function is called by the pcache layer when it has reached some
51962** soft memory limit. The first argument is a pointer to a Pager object
51963** (cast as a void*). The pager is always 'purgeable' (not an in-memory
51964** database). The second argument is a reference to a page that is
51965** currently dirty but has no outstanding references. The page
51966** is always associated with the Pager object passed as the first
51967** argument.
51968**
51969** The job of this function is to make pPg clean by writing its contents
51970** out to the database file, if possible. This may involve syncing the
51971** journal file.
51972**
51973** If successful, sqlite3PcacheMakeClean() is called on the page and
51974** SQLITE_OK returned. If an IO error occurs while trying to make the
51975** page clean, the IO error code is returned. If the page cannot be
51976** made clean for some other reason, but no error occurs, then SQLITE_OK
51977** is returned by sqlite3PcacheMakeClean() is not called.
51978*/
51979static int pagerStress(void *p, PgHdr *pPg){
51980  Pager *pPager = (Pager *)p;
51981  int rc = SQLITE_OK;
51982
51983  assert( pPg->pPager==pPager );
51984  assert( pPg->flags&PGHDR_DIRTY );
51985
51986  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
51987  ** journal (and adding a new header) is not allowed.  This occurs
51988  ** during calls to sqlite3PagerWrite() while trying to journal multiple
51989  ** pages belonging to the same sector.
51990  **
51991  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
51992  ** regardless of whether or not a sync is required.  This is set during
51993  ** a rollback or by user request, respectively.
51994  **
51995  ** Spilling is also prohibited when in an error state since that could
51996  ** lead to database corruption.   In the current implementation it
51997  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
51998  ** while in the error state, hence it is impossible for this routine to
51999  ** be called in the error state.  Nevertheless, we include a NEVER()
52000  ** test for the error state as a safeguard against future changes.
52001  */
52002  if( NEVER(pPager->errCode) ) return SQLITE_OK;
52003  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
52004  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
52005  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
52006  if( pPager->doNotSpill
52007   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
52008      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
52009  ){
52010    return SQLITE_OK;
52011  }
52012
52013  pPg->pDirty = 0;
52014  if( pagerUseWal(pPager) ){
52015    /* Write a single frame for this page to the log. */
52016    rc = subjournalPageIfRequired(pPg);
52017    if( rc==SQLITE_OK ){
52018      rc = pagerWalFrames(pPager, pPg, 0, 0);
52019    }
52020  }else{
52021
52022    /* Sync the journal file if required. */
52023    if( pPg->flags&PGHDR_NEED_SYNC
52024     || pPager->eState==PAGER_WRITER_CACHEMOD
52025    ){
52026      rc = syncJournal(pPager, 1);
52027    }
52028
52029    /* Write the contents of the page out to the database file. */
52030    if( rc==SQLITE_OK ){
52031      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
52032      rc = pager_write_pagelist(pPager, pPg);
52033    }
52034  }
52035
52036  /* Mark the page as clean. */
52037  if( rc==SQLITE_OK ){
52038    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
52039    sqlite3PcacheMakeClean(pPg);
52040  }
52041
52042  return pager_error(pPager, rc);
52043}
52044
52045/*
52046** Flush all unreferenced dirty pages to disk.
52047*/
52048SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
52049  int rc = pPager->errCode;
52050  if( !MEMDB ){
52051    PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52052    assert( assert_pager_state(pPager) );
52053    while( rc==SQLITE_OK && pList ){
52054      PgHdr *pNext = pList->pDirty;
52055      if( pList->nRef==0 ){
52056        rc = pagerStress((void*)pPager, pList);
52057      }
52058      pList = pNext;
52059    }
52060  }
52061
52062  return rc;
52063}
52064
52065/*
52066** Allocate and initialize a new Pager object and put a pointer to it
52067** in *ppPager. The pager should eventually be freed by passing it
52068** to sqlite3PagerClose().
52069**
52070** The zFilename argument is the path to the database file to open.
52071** If zFilename is NULL then a randomly-named temporary file is created
52072** and used as the file to be cached. Temporary files are be deleted
52073** automatically when they are closed. If zFilename is ":memory:" then
52074** all information is held in cache. It is never written to disk.
52075** This can be used to implement an in-memory database.
52076**
52077** The nExtra parameter specifies the number of bytes of space allocated
52078** along with each page reference. This space is available to the user
52079** via the sqlite3PagerGetExtra() API.  When a new page is allocated, the
52080** first 8 bytes of this space are zeroed but the remainder is uninitialized.
52081** (The extra space is used by btree as the MemPage object.)
52082**
52083** The flags argument is used to specify properties that affect the
52084** operation of the pager. It should be passed some bitwise combination
52085** of the PAGER_* flags.
52086**
52087** The vfsFlags parameter is a bitmask to pass to the flags parameter
52088** of the xOpen() method of the supplied VFS when opening files.
52089**
52090** If the pager object is allocated and the specified file opened
52091** successfully, SQLITE_OK is returned and *ppPager set to point to
52092** the new pager object. If an error occurs, *ppPager is set to NULL
52093** and error code returned. This function may return SQLITE_NOMEM
52094** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
52095** various SQLITE_IO_XXX errors.
52096*/
52097SQLITE_PRIVATE int sqlite3PagerOpen(
52098  sqlite3_vfs *pVfs,       /* The virtual file system to use */
52099  Pager **ppPager,         /* OUT: Return the Pager structure here */
52100  const char *zFilename,   /* Name of the database file to open */
52101  int nExtra,              /* Extra bytes append to each in-memory page */
52102  int flags,               /* flags controlling this file */
52103  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
52104  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
52105){
52106  u8 *pPtr;
52107  Pager *pPager = 0;       /* Pager object to allocate and return */
52108  int rc = SQLITE_OK;      /* Return code */
52109  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
52110  int memDb = 0;           /* True if this is an in-memory file */
52111  int readOnly = 0;        /* True if this is a read-only file */
52112  int journalFileSize;     /* Bytes to allocate for each journal fd */
52113  char *zPathname = 0;     /* Full path to database file */
52114  int nPathname = 0;       /* Number of bytes in zPathname */
52115  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
52116  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
52117  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
52118  const char *zUri = 0;    /* URI args to copy */
52119  int nUri = 0;            /* Number of bytes of URI args at *zUri */
52120
52121  /* Figure out how much space is required for each journal file-handle
52122  ** (there are two of them, the main journal and the sub-journal).  */
52123  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
52124
52125  /* Set the output variable to NULL in case an error occurs. */
52126  *ppPager = 0;
52127
52128#ifndef SQLITE_OMIT_MEMORYDB
52129  if( flags & PAGER_MEMORY ){
52130    memDb = 1;
52131    if( zFilename && zFilename[0] ){
52132      zPathname = sqlite3DbStrDup(0, zFilename);
52133      if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
52134      nPathname = sqlite3Strlen30(zPathname);
52135      zFilename = 0;
52136    }
52137  }
52138#endif
52139
52140  /* Compute and store the full pathname in an allocated buffer pointed
52141  ** to by zPathname, length nPathname. Or, if this is a temporary file,
52142  ** leave both nPathname and zPathname set to 0.
52143  */
52144  if( zFilename && zFilename[0] ){
52145    const char *z;
52146    nPathname = pVfs->mxPathname+1;
52147    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
52148    if( zPathname==0 ){
52149      return SQLITE_NOMEM_BKPT;
52150    }
52151    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
52152    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
52153    nPathname = sqlite3Strlen30(zPathname);
52154    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
52155    while( *z ){
52156      z += sqlite3Strlen30(z)+1;
52157      z += sqlite3Strlen30(z)+1;
52158    }
52159    nUri = (int)(&z[1] - zUri);
52160    assert( nUri>=0 );
52161    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
52162      /* This branch is taken when the journal path required by
52163      ** the database being opened will be more than pVfs->mxPathname
52164      ** bytes in length. This means the database cannot be opened,
52165      ** as it will not be possible to open the journal file or even
52166      ** check for a hot-journal before reading.
52167      */
52168      rc = SQLITE_CANTOPEN_BKPT;
52169    }
52170    if( rc!=SQLITE_OK ){
52171      sqlite3DbFree(0, zPathname);
52172      return rc;
52173    }
52174  }
52175
52176  /* Allocate memory for the Pager structure, PCache object, the
52177  ** three file descriptors, the database file name and the journal
52178  ** file name. The layout in memory is as follows:
52179  **
52180  **     Pager object                    (sizeof(Pager) bytes)
52181  **     PCache object                   (sqlite3PcacheSize() bytes)
52182  **     Database file handle            (pVfs->szOsFile bytes)
52183  **     Sub-journal file handle         (journalFileSize bytes)
52184  **     Main journal file handle        (journalFileSize bytes)
52185  **     Database file name              (nPathname+1 bytes)
52186  **     Journal file name               (nPathname+8+1 bytes)
52187  */
52188  pPtr = (u8 *)sqlite3MallocZero(
52189    ROUND8(sizeof(*pPager)) +      /* Pager structure */
52190    ROUND8(pcacheSize) +           /* PCache object */
52191    ROUND8(pVfs->szOsFile) +       /* The main db file */
52192    journalFileSize * 2 +          /* The two journal files */
52193    nPathname + 1 + nUri +         /* zFilename */
52194    nPathname + 8 + 2              /* zJournal */
52195#ifndef SQLITE_OMIT_WAL
52196    + nPathname + 4 + 2            /* zWal */
52197#endif
52198  );
52199  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
52200  if( !pPtr ){
52201    sqlite3DbFree(0, zPathname);
52202    return SQLITE_NOMEM_BKPT;
52203  }
52204  pPager =              (Pager*)(pPtr);
52205  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
52206  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
52207  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
52208  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
52209  pPager->zFilename =    (char*)(pPtr += journalFileSize);
52210  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
52211
52212  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
52213  if( zPathname ){
52214    assert( nPathname>0 );
52215    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
52216    memcpy(pPager->zFilename, zPathname, nPathname);
52217    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
52218    memcpy(pPager->zJournal, zPathname, nPathname);
52219    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
52220    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
52221#ifndef SQLITE_OMIT_WAL
52222    pPager->zWal = &pPager->zJournal[nPathname+8+1];
52223    memcpy(pPager->zWal, zPathname, nPathname);
52224    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
52225    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
52226#endif
52227    sqlite3DbFree(0, zPathname);
52228  }
52229  pPager->pVfs = pVfs;
52230  pPager->vfsFlags = vfsFlags;
52231
52232  /* Open the pager file.
52233  */
52234  if( zFilename && zFilename[0] ){
52235    int fout = 0;                    /* VFS flags returned by xOpen() */
52236    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
52237    assert( !memDb );
52238    readOnly = (fout&SQLITE_OPEN_READONLY);
52239
52240    /* If the file was successfully opened for read/write access,
52241    ** choose a default page size in case we have to create the
52242    ** database file. The default page size is the maximum of:
52243    **
52244    **    + SQLITE_DEFAULT_PAGE_SIZE,
52245    **    + The value returned by sqlite3OsSectorSize()
52246    **    + The largest page size that can be written atomically.
52247    */
52248    if( rc==SQLITE_OK ){
52249      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
52250      if( !readOnly ){
52251        setSectorSize(pPager);
52252        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
52253        if( szPageDflt<pPager->sectorSize ){
52254          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
52255            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
52256          }else{
52257            szPageDflt = (u32)pPager->sectorSize;
52258          }
52259        }
52260#ifdef SQLITE_ENABLE_ATOMIC_WRITE
52261        {
52262          int ii;
52263          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
52264          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
52265          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
52266          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
52267            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
52268              szPageDflt = ii;
52269            }
52270          }
52271        }
52272#endif
52273      }
52274      pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
52275      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
52276       || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
52277          vfsFlags |= SQLITE_OPEN_READONLY;
52278          goto act_like_temp_file;
52279      }
52280    }
52281  }else{
52282    /* If a temporary file is requested, it is not opened immediately.
52283    ** In this case we accept the default page size and delay actually
52284    ** opening the file until the first call to OsWrite().
52285    **
52286    ** This branch is also run for an in-memory database. An in-memory
52287    ** database is the same as a temp-file that is never written out to
52288    ** disk and uses an in-memory rollback journal.
52289    **
52290    ** This branch also runs for files marked as immutable.
52291    */
52292act_like_temp_file:
52293    tempFile = 1;
52294    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
52295    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
52296    pPager->noLock = 1;                /* Do no locking */
52297    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
52298  }
52299
52300  /* The following call to PagerSetPagesize() serves to set the value of
52301  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
52302  */
52303  if( rc==SQLITE_OK ){
52304    assert( pPager->memDb==0 );
52305    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
52306    testcase( rc!=SQLITE_OK );
52307  }
52308
52309  /* Initialize the PCache object. */
52310  if( rc==SQLITE_OK ){
52311    nExtra = ROUND8(nExtra);
52312    assert( nExtra>=8 && nExtra<1000 );
52313    rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
52314                       !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
52315  }
52316
52317  /* If an error occurred above, free the  Pager structure and close the file.
52318  */
52319  if( rc!=SQLITE_OK ){
52320    sqlite3OsClose(pPager->fd);
52321    sqlite3PageFree(pPager->pTmpSpace);
52322    sqlite3_free(pPager);
52323    return rc;
52324  }
52325
52326  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
52327  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
52328
52329  pPager->useJournal = (u8)useJournal;
52330  /* pPager->stmtOpen = 0; */
52331  /* pPager->stmtInUse = 0; */
52332  /* pPager->nRef = 0; */
52333  /* pPager->stmtSize = 0; */
52334  /* pPager->stmtJSize = 0; */
52335  /* pPager->nPage = 0; */
52336  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
52337  /* pPager->state = PAGER_UNLOCK; */
52338  /* pPager->errMask = 0; */
52339  pPager->tempFile = (u8)tempFile;
52340  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
52341          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
52342  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
52343  pPager->exclusiveMode = (u8)tempFile;
52344  pPager->changeCountDone = pPager->tempFile;
52345  pPager->memDb = (u8)memDb;
52346  pPager->readOnly = (u8)readOnly;
52347  assert( useJournal || pPager->tempFile );
52348  pPager->noSync = pPager->tempFile;
52349  if( pPager->noSync ){
52350    assert( pPager->fullSync==0 );
52351    assert( pPager->extraSync==0 );
52352    assert( pPager->syncFlags==0 );
52353    assert( pPager->walSyncFlags==0 );
52354    assert( pPager->ckptSyncFlags==0 );
52355  }else{
52356    pPager->fullSync = 1;
52357    pPager->extraSync = 0;
52358    pPager->syncFlags = SQLITE_SYNC_NORMAL;
52359    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
52360    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
52361  }
52362  /* pPager->pFirst = 0; */
52363  /* pPager->pFirstSynced = 0; */
52364  /* pPager->pLast = 0; */
52365  pPager->nExtra = (u16)nExtra;
52366  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
52367  assert( isOpen(pPager->fd) || tempFile );
52368  setSectorSize(pPager);
52369  if( !useJournal ){
52370    pPager->journalMode = PAGER_JOURNALMODE_OFF;
52371  }else if( memDb ){
52372    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
52373  }
52374  /* pPager->xBusyHandler = 0; */
52375  /* pPager->pBusyHandlerArg = 0; */
52376  pPager->xReiniter = xReinit;
52377  setGetterMethod(pPager);
52378  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
52379  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
52380
52381  *ppPager = pPager;
52382  return SQLITE_OK;
52383}
52384
52385
52386/* Verify that the database file has not be deleted or renamed out from
52387** under the pager.  Return SQLITE_OK if the database is still were it ought
52388** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
52389** code from sqlite3OsAccess()) if the database has gone missing.
52390*/
52391static int databaseIsUnmoved(Pager *pPager){
52392  int bHasMoved = 0;
52393  int rc;
52394
52395  if( pPager->tempFile ) return SQLITE_OK;
52396  if( pPager->dbSize==0 ) return SQLITE_OK;
52397  assert( pPager->zFilename && pPager->zFilename[0] );
52398  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
52399  if( rc==SQLITE_NOTFOUND ){
52400    /* If the HAS_MOVED file-control is unimplemented, assume that the file
52401    ** has not been moved.  That is the historical behavior of SQLite: prior to
52402    ** version 3.8.3, it never checked */
52403    rc = SQLITE_OK;
52404  }else if( rc==SQLITE_OK && bHasMoved ){
52405    rc = SQLITE_READONLY_DBMOVED;
52406  }
52407  return rc;
52408}
52409
52410
52411/*
52412** This function is called after transitioning from PAGER_UNLOCK to
52413** PAGER_SHARED state. It tests if there is a hot journal present in
52414** the file-system for the given pager. A hot journal is one that
52415** needs to be played back. According to this function, a hot-journal
52416** file exists if the following criteria are met:
52417**
52418**   * The journal file exists in the file system, and
52419**   * No process holds a RESERVED or greater lock on the database file, and
52420**   * The database file itself is greater than 0 bytes in size, and
52421**   * The first byte of the journal file exists and is not 0x00.
52422**
52423** If the current size of the database file is 0 but a journal file
52424** exists, that is probably an old journal left over from a prior
52425** database with the same name. In this case the journal file is
52426** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
52427** is returned.
52428**
52429** This routine does not check if there is a master journal filename
52430** at the end of the file. If there is, and that master journal file
52431** does not exist, then the journal file is not really hot. In this
52432** case this routine will return a false-positive. The pager_playback()
52433** routine will discover that the journal file is not really hot and
52434** will not roll it back.
52435**
52436** If a hot-journal file is found to exist, *pExists is set to 1 and
52437** SQLITE_OK returned. If no hot-journal file is present, *pExists is
52438** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
52439** to determine whether or not a hot-journal file exists, the IO error
52440** code is returned and the value of *pExists is undefined.
52441*/
52442static int hasHotJournal(Pager *pPager, int *pExists){
52443  sqlite3_vfs * const pVfs = pPager->pVfs;
52444  int rc = SQLITE_OK;           /* Return code */
52445  int exists = 1;               /* True if a journal file is present */
52446  int jrnlOpen = !!isOpen(pPager->jfd);
52447
52448  assert( pPager->useJournal );
52449  assert( isOpen(pPager->fd) );
52450  assert( pPager->eState==PAGER_OPEN );
52451
52452  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
52453    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
52454  ));
52455
52456  *pExists = 0;
52457  if( !jrnlOpen ){
52458    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
52459  }
52460  if( rc==SQLITE_OK && exists ){
52461    int locked = 0;             /* True if some process holds a RESERVED lock */
52462
52463    /* Race condition here:  Another process might have been holding the
52464    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
52465    ** call above, but then delete the journal and drop the lock before
52466    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
52467    ** is the case, this routine might think there is a hot journal when
52468    ** in fact there is none.  This results in a false-positive which will
52469    ** be dealt with by the playback routine.  Ticket #3883.
52470    */
52471    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
52472    if( rc==SQLITE_OK && !locked ){
52473      Pgno nPage;                 /* Number of pages in database file */
52474
52475      assert( pPager->tempFile==0 );
52476      rc = pagerPagecount(pPager, &nPage);
52477      if( rc==SQLITE_OK ){
52478        /* If the database is zero pages in size, that means that either (1) the
52479        ** journal is a remnant from a prior database with the same name where
52480        ** the database file but not the journal was deleted, or (2) the initial
52481        ** transaction that populates a new database is being rolled back.
52482        ** In either case, the journal file can be deleted.  However, take care
52483        ** not to delete the journal file if it is already open due to
52484        ** journal_mode=PERSIST.
52485        */
52486        if( nPage==0 && !jrnlOpen ){
52487          sqlite3BeginBenignMalloc();
52488          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
52489            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
52490            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
52491          }
52492          sqlite3EndBenignMalloc();
52493        }else{
52494          /* The journal file exists and no other connection has a reserved
52495          ** or greater lock on the database file. Now check that there is
52496          ** at least one non-zero bytes at the start of the journal file.
52497          ** If there is, then we consider this journal to be hot. If not,
52498          ** it can be ignored.
52499          */
52500          if( !jrnlOpen ){
52501            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
52502            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
52503          }
52504          if( rc==SQLITE_OK ){
52505            u8 first = 0;
52506            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
52507            if( rc==SQLITE_IOERR_SHORT_READ ){
52508              rc = SQLITE_OK;
52509            }
52510            if( !jrnlOpen ){
52511              sqlite3OsClose(pPager->jfd);
52512            }
52513            *pExists = (first!=0);
52514          }else if( rc==SQLITE_CANTOPEN ){
52515            /* If we cannot open the rollback journal file in order to see if
52516            ** it has a zero header, that might be due to an I/O error, or
52517            ** it might be due to the race condition described above and in
52518            ** ticket #3883.  Either way, assume that the journal is hot.
52519            ** This might be a false positive.  But if it is, then the
52520            ** automatic journal playback and recovery mechanism will deal
52521            ** with it under an EXCLUSIVE lock where we do not need to
52522            ** worry so much with race conditions.
52523            */
52524            *pExists = 1;
52525            rc = SQLITE_OK;
52526          }
52527        }
52528      }
52529    }
52530  }
52531
52532  return rc;
52533}
52534
52535/*
52536** This function is called to obtain a shared lock on the database file.
52537** It is illegal to call sqlite3PagerGet() until after this function
52538** has been successfully called. If a shared-lock is already held when
52539** this function is called, it is a no-op.
52540**
52541** The following operations are also performed by this function.
52542**
52543**   1) If the pager is currently in PAGER_OPEN state (no lock held
52544**      on the database file), then an attempt is made to obtain a
52545**      SHARED lock on the database file. Immediately after obtaining
52546**      the SHARED lock, the file-system is checked for a hot-journal,
52547**      which is played back if present. Following any hot-journal
52548**      rollback, the contents of the cache are validated by checking
52549**      the 'change-counter' field of the database file header and
52550**      discarded if they are found to be invalid.
52551**
52552**   2) If the pager is running in exclusive-mode, and there are currently
52553**      no outstanding references to any pages, and is in the error state,
52554**      then an attempt is made to clear the error state by discarding
52555**      the contents of the page cache and rolling back any open journal
52556**      file.
52557**
52558** If everything is successful, SQLITE_OK is returned. If an IO error
52559** occurs while locking the database, checking for a hot-journal file or
52560** rolling back a journal file, the IO error code is returned.
52561*/
52562SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
52563  int rc = SQLITE_OK;                /* Return code */
52564
52565  /* This routine is only called from b-tree and only when there are no
52566  ** outstanding pages. This implies that the pager state should either
52567  ** be OPEN or READER. READER is only possible if the pager is or was in
52568  ** exclusive access mode.  */
52569  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
52570  assert( assert_pager_state(pPager) );
52571  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
52572  assert( pPager->errCode==SQLITE_OK );
52573
52574  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
52575    int bHotJournal = 1;          /* True if there exists a hot journal-file */
52576
52577    assert( !MEMDB );
52578    assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
52579
52580    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
52581    if( rc!=SQLITE_OK ){
52582      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
52583      goto failed;
52584    }
52585
52586    /* If a journal file exists, and there is no RESERVED lock on the
52587    ** database file, then it either needs to be played back or deleted.
52588    */
52589    if( pPager->eLock<=SHARED_LOCK ){
52590      rc = hasHotJournal(pPager, &bHotJournal);
52591    }
52592    if( rc!=SQLITE_OK ){
52593      goto failed;
52594    }
52595    if( bHotJournal ){
52596      if( pPager->readOnly ){
52597        rc = SQLITE_READONLY_ROLLBACK;
52598        goto failed;
52599      }
52600
52601      /* Get an EXCLUSIVE lock on the database file. At this point it is
52602      ** important that a RESERVED lock is not obtained on the way to the
52603      ** EXCLUSIVE lock. If it were, another process might open the
52604      ** database file, detect the RESERVED lock, and conclude that the
52605      ** database is safe to read while this process is still rolling the
52606      ** hot-journal back.
52607      **
52608      ** Because the intermediate RESERVED lock is not requested, any
52609      ** other process attempting to access the database file will get to
52610      ** this point in the code and fail to obtain its own EXCLUSIVE lock
52611      ** on the database file.
52612      **
52613      ** Unless the pager is in locking_mode=exclusive mode, the lock is
52614      ** downgraded to SHARED_LOCK before this function returns.
52615      */
52616      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
52617      if( rc!=SQLITE_OK ){
52618        goto failed;
52619      }
52620
52621      /* If it is not already open and the file exists on disk, open the
52622      ** journal for read/write access. Write access is required because
52623      ** in exclusive-access mode the file descriptor will be kept open
52624      ** and possibly used for a transaction later on. Also, write-access
52625      ** is usually required to finalize the journal in journal_mode=persist
52626      ** mode (and also for journal_mode=truncate on some systems).
52627      **
52628      ** If the journal does not exist, it usually means that some
52629      ** other connection managed to get in and roll it back before
52630      ** this connection obtained the exclusive lock above. Or, it
52631      ** may mean that the pager was in the error-state when this
52632      ** function was called and the journal file does not exist.
52633      */
52634      if( !isOpen(pPager->jfd) ){
52635        sqlite3_vfs * const pVfs = pPager->pVfs;
52636        int bExists;              /* True if journal file exists */
52637        rc = sqlite3OsAccess(
52638            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
52639        if( rc==SQLITE_OK && bExists ){
52640          int fout = 0;
52641          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
52642          assert( !pPager->tempFile );
52643          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
52644          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
52645          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
52646            rc = SQLITE_CANTOPEN_BKPT;
52647            sqlite3OsClose(pPager->jfd);
52648          }
52649        }
52650      }
52651
52652      /* Playback and delete the journal.  Drop the database write
52653      ** lock and reacquire the read lock. Purge the cache before
52654      ** playing back the hot-journal so that we don't end up with
52655      ** an inconsistent cache.  Sync the hot journal before playing
52656      ** it back since the process that crashed and left the hot journal
52657      ** probably did not sync it and we are required to always sync
52658      ** the journal before playing it back.
52659      */
52660      if( isOpen(pPager->jfd) ){
52661        assert( rc==SQLITE_OK );
52662        rc = pagerSyncHotJournal(pPager);
52663        if( rc==SQLITE_OK ){
52664          rc = pager_playback(pPager, !pPager->tempFile);
52665          pPager->eState = PAGER_OPEN;
52666        }
52667      }else if( !pPager->exclusiveMode ){
52668        pagerUnlockDb(pPager, SHARED_LOCK);
52669      }
52670
52671      if( rc!=SQLITE_OK ){
52672        /* This branch is taken if an error occurs while trying to open
52673        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
52674        ** pager_unlock() routine will be called before returning to unlock
52675        ** the file. If the unlock attempt fails, then Pager.eLock must be
52676        ** set to UNKNOWN_LOCK (see the comment above the #define for
52677        ** UNKNOWN_LOCK above for an explanation).
52678        **
52679        ** In order to get pager_unlock() to do this, set Pager.eState to
52680        ** PAGER_ERROR now. This is not actually counted as a transition
52681        ** to ERROR state in the state diagram at the top of this file,
52682        ** since we know that the same call to pager_unlock() will very
52683        ** shortly transition the pager object to the OPEN state. Calling
52684        ** assert_pager_state() would fail now, as it should not be possible
52685        ** to be in ERROR state when there are zero outstanding page
52686        ** references.
52687        */
52688        pager_error(pPager, rc);
52689        goto failed;
52690      }
52691
52692      assert( pPager->eState==PAGER_OPEN );
52693      assert( (pPager->eLock==SHARED_LOCK)
52694           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
52695      );
52696    }
52697
52698    if( !pPager->tempFile && pPager->hasHeldSharedLock ){
52699      /* The shared-lock has just been acquired then check to
52700      ** see if the database has been modified.  If the database has changed,
52701      ** flush the cache.  The hasHeldSharedLock flag prevents this from
52702      ** occurring on the very first access to a file, in order to save a
52703      ** single unnecessary sqlite3OsRead() call at the start-up.
52704      **
52705      ** Database changes are detected by looking at 15 bytes beginning
52706      ** at offset 24 into the file.  The first 4 of these 16 bytes are
52707      ** a 32-bit counter that is incremented with each change.  The
52708      ** other bytes change randomly with each file change when
52709      ** a codec is in use.
52710      **
52711      ** There is a vanishingly small chance that a change will not be
52712      ** detected.  The chance of an undetected change is so small that
52713      ** it can be neglected.
52714      */
52715      char dbFileVers[sizeof(pPager->dbFileVers)];
52716
52717      IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
52718      rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
52719      if( rc!=SQLITE_OK ){
52720        if( rc!=SQLITE_IOERR_SHORT_READ ){
52721          goto failed;
52722        }
52723        memset(dbFileVers, 0, sizeof(dbFileVers));
52724      }
52725
52726      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
52727        pager_reset(pPager);
52728
52729        /* Unmap the database file. It is possible that external processes
52730        ** may have truncated the database file and then extended it back
52731        ** to its original size while this process was not holding a lock.
52732        ** In this case there may exist a Pager.pMap mapping that appears
52733        ** to be the right size but is not actually valid. Avoid this
52734        ** possibility by unmapping the db here. */
52735        if( USEFETCH(pPager) ){
52736          sqlite3OsUnfetch(pPager->fd, 0, 0);
52737        }
52738      }
52739    }
52740
52741    /* If there is a WAL file in the file-system, open this database in WAL
52742    ** mode. Otherwise, the following function call is a no-op.
52743    */
52744    rc = pagerOpenWalIfPresent(pPager);
52745#ifndef SQLITE_OMIT_WAL
52746    assert( pPager->pWal==0 || rc==SQLITE_OK );
52747#endif
52748  }
52749
52750  if( pagerUseWal(pPager) ){
52751    assert( rc==SQLITE_OK );
52752    rc = pagerBeginReadTransaction(pPager);
52753  }
52754
52755  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
52756    rc = pagerPagecount(pPager, &pPager->dbSize);
52757  }
52758
52759 failed:
52760  if( rc!=SQLITE_OK ){
52761    assert( !MEMDB );
52762    pager_unlock(pPager);
52763    assert( pPager->eState==PAGER_OPEN );
52764  }else{
52765    pPager->eState = PAGER_READER;
52766    pPager->hasHeldSharedLock = 1;
52767  }
52768  return rc;
52769}
52770
52771/*
52772** If the reference count has reached zero, rollback any active
52773** transaction and unlock the pager.
52774**
52775** Except, in locking_mode=EXCLUSIVE when there is nothing to in
52776** the rollback journal, the unlock is not performed and there is
52777** nothing to rollback, so this routine is a no-op.
52778*/
52779static void pagerUnlockIfUnused(Pager *pPager){
52780  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
52781    pagerUnlockAndRollback(pPager);
52782  }
52783}
52784
52785/*
52786** The page getter methods each try to acquire a reference to a
52787** page with page number pgno. If the requested reference is
52788** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
52789**
52790** There are different implementations of the getter method depending
52791** on the current state of the pager.
52792**
52793**     getPageNormal()         --  The normal getter
52794**     getPageError()          --  Used if the pager is in an error state
52795**     getPageMmap()           --  Used if memory-mapped I/O is enabled
52796**
52797** If the requested page is already in the cache, it is returned.
52798** Otherwise, a new page object is allocated and populated with data
52799** read from the database file. In some cases, the pcache module may
52800** choose not to allocate a new page object and may reuse an existing
52801** object with no outstanding references.
52802**
52803** The extra data appended to a page is always initialized to zeros the
52804** first time a page is loaded into memory. If the page requested is
52805** already in the cache when this function is called, then the extra
52806** data is left as it was when the page object was last used.
52807**
52808** If the database image is smaller than the requested page or if
52809** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
52810** requested page is not already stored in the cache, then no
52811** actual disk read occurs. In this case the memory image of the
52812** page is initialized to all zeros.
52813**
52814** If PAGER_GET_NOCONTENT is true, it means that we do not care about
52815** the contents of the page. This occurs in two scenarios:
52816**
52817**   a) When reading a free-list leaf page from the database, and
52818**
52819**   b) When a savepoint is being rolled back and we need to load
52820**      a new page into the cache to be filled with the data read
52821**      from the savepoint journal.
52822**
52823** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
52824** of being read from the database. Additionally, the bits corresponding
52825** to pgno in Pager.pInJournal (bitvec of pages already written to the
52826** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
52827** savepoints are set. This means if the page is made writable at any
52828** point in the future, using a call to sqlite3PagerWrite(), its contents
52829** will not be journaled. This saves IO.
52830**
52831** The acquisition might fail for several reasons.  In all cases,
52832** an appropriate error code is returned and *ppPage is set to NULL.
52833**
52834** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
52835** to find a page in the in-memory cache first.  If the page is not already
52836** in memory, this routine goes to disk to read it in whereas Lookup()
52837** just returns 0.  This routine acquires a read-lock the first time it
52838** has to go to disk, and could also playback an old journal if necessary.
52839** Since Lookup() never goes to disk, it never has to deal with locks
52840** or journal files.
52841*/
52842static int getPageNormal(
52843  Pager *pPager,      /* The pager open on the database file */
52844  Pgno pgno,          /* Page number to fetch */
52845  DbPage **ppPage,    /* Write a pointer to the page here */
52846  int flags           /* PAGER_GET_XXX flags */
52847){
52848  int rc = SQLITE_OK;
52849  PgHdr *pPg;
52850  u8 noContent;                   /* True if PAGER_GET_NOCONTENT is set */
52851  sqlite3_pcache_page *pBase;
52852
52853  assert( pPager->errCode==SQLITE_OK );
52854  assert( pPager->eState>=PAGER_READER );
52855  assert( assert_pager_state(pPager) );
52856  assert( pPager->hasHeldSharedLock==1 );
52857
52858  if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
52859  pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
52860  if( pBase==0 ){
52861    pPg = 0;
52862    rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
52863    if( rc!=SQLITE_OK ) goto pager_acquire_err;
52864    if( pBase==0 ){
52865      rc = SQLITE_NOMEM_BKPT;
52866      goto pager_acquire_err;
52867    }
52868  }
52869  pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
52870  assert( pPg==(*ppPage) );
52871  assert( pPg->pgno==pgno );
52872  assert( pPg->pPager==pPager || pPg->pPager==0 );
52873
52874  noContent = (flags & PAGER_GET_NOCONTENT)!=0;
52875  if( pPg->pPager && !noContent ){
52876    /* In this case the pcache already contains an initialized copy of
52877    ** the page. Return without further ado.  */
52878    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
52879    pPager->aStat[PAGER_STAT_HIT]++;
52880    return SQLITE_OK;
52881
52882  }else{
52883    /* The pager cache has created a new page. Its content needs to
52884    ** be initialized. But first some error checks:
52885    **
52886    ** (1) The maximum page number is 2^31
52887    ** (2) Never try to fetch the locking page
52888    */
52889    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
52890      rc = SQLITE_CORRUPT_BKPT;
52891      goto pager_acquire_err;
52892    }
52893
52894    pPg->pPager = pPager;
52895
52896    assert( !isOpen(pPager->fd) || !MEMDB );
52897    if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
52898      if( pgno>pPager->mxPgno ){
52899        rc = SQLITE_FULL;
52900        goto pager_acquire_err;
52901      }
52902      if( noContent ){
52903        /* Failure to set the bits in the InJournal bit-vectors is benign.
52904        ** It merely means that we might do some extra work to journal a
52905        ** page that does not need to be journaled.  Nevertheless, be sure
52906        ** to test the case where a malloc error occurs while trying to set
52907        ** a bit in a bit vector.
52908        */
52909        sqlite3BeginBenignMalloc();
52910        if( pgno<=pPager->dbOrigSize ){
52911          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
52912          testcase( rc==SQLITE_NOMEM );
52913        }
52914        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
52915        testcase( rc==SQLITE_NOMEM );
52916        sqlite3EndBenignMalloc();
52917      }
52918      memset(pPg->pData, 0, pPager->pageSize);
52919      IOTRACE(("ZERO %p %d\n", pPager, pgno));
52920    }else{
52921      u32 iFrame = 0;                 /* Frame to read from WAL file */
52922      if( pagerUseWal(pPager) ){
52923        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
52924        if( rc!=SQLITE_OK ) goto pager_acquire_err;
52925      }
52926      assert( pPg->pPager==pPager );
52927      pPager->aStat[PAGER_STAT_MISS]++;
52928      rc = readDbPage(pPg, iFrame);
52929      if( rc!=SQLITE_OK ){
52930        goto pager_acquire_err;
52931      }
52932    }
52933    pager_set_pagehash(pPg);
52934  }
52935  return SQLITE_OK;
52936
52937pager_acquire_err:
52938  assert( rc!=SQLITE_OK );
52939  if( pPg ){
52940    sqlite3PcacheDrop(pPg);
52941  }
52942  pagerUnlockIfUnused(pPager);
52943  *ppPage = 0;
52944  return rc;
52945}
52946
52947#if SQLITE_MAX_MMAP_SIZE>0
52948/* The page getter for when memory-mapped I/O is enabled */
52949static int getPageMMap(
52950  Pager *pPager,      /* The pager open on the database file */
52951  Pgno pgno,          /* Page number to fetch */
52952  DbPage **ppPage,    /* Write a pointer to the page here */
52953  int flags           /* PAGER_GET_XXX flags */
52954){
52955  int rc = SQLITE_OK;
52956  PgHdr *pPg = 0;
52957  u32 iFrame = 0;                 /* Frame to read from WAL file */
52958
52959  /* It is acceptable to use a read-only (mmap) page for any page except
52960  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
52961  ** flag was specified by the caller. And so long as the db is not a
52962  ** temporary or in-memory database.  */
52963  const int bMmapOk = (pgno>1
52964   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
52965  );
52966
52967  assert( USEFETCH(pPager) );
52968#ifdef SQLITE_HAS_CODEC
52969  assert( pPager->xCodec==0 );
52970#endif
52971
52972  /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
52973  ** allows the compiler optimizer to reuse the results of the "pgno>1"
52974  ** test in the previous statement, and avoid testing pgno==0 in the
52975  ** common case where pgno is large. */
52976  if( pgno<=1 && pgno==0 ){
52977    return SQLITE_CORRUPT_BKPT;
52978  }
52979  assert( pPager->eState>=PAGER_READER );
52980  assert( assert_pager_state(pPager) );
52981  assert( pPager->hasHeldSharedLock==1 );
52982  assert( pPager->errCode==SQLITE_OK );
52983
52984  if( bMmapOk && pagerUseWal(pPager) ){
52985    rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
52986    if( rc!=SQLITE_OK ){
52987      *ppPage = 0;
52988      return rc;
52989    }
52990  }
52991  if( bMmapOk && iFrame==0 ){
52992    void *pData = 0;
52993    rc = sqlite3OsFetch(pPager->fd,
52994        (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
52995    );
52996    if( rc==SQLITE_OK && pData ){
52997      if( pPager->eState>PAGER_READER || pPager->tempFile ){
52998        pPg = sqlite3PagerLookup(pPager, pgno);
52999      }
53000      if( pPg==0 ){
53001        rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
53002     }else{
53003        sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
53004      }
53005      if( pPg ){
53006        assert( rc==SQLITE_OK );
53007        *ppPage = pPg;
53008        return SQLITE_OK;
53009      }
53010    }
53011    if( rc!=SQLITE_OK ){
53012      *ppPage = 0;
53013      return rc;
53014    }
53015  }
53016  return getPageNormal(pPager, pgno, ppPage, flags);
53017}
53018#endif /* SQLITE_MAX_MMAP_SIZE>0 */
53019
53020/* The page getter method for when the pager is an error state */
53021static int getPageError(
53022  Pager *pPager,      /* The pager open on the database file */
53023  Pgno pgno,          /* Page number to fetch */
53024  DbPage **ppPage,    /* Write a pointer to the page here */
53025  int flags           /* PAGER_GET_XXX flags */
53026){
53027  UNUSED_PARAMETER(pgno);
53028  UNUSED_PARAMETER(flags);
53029  assert( pPager->errCode!=SQLITE_OK );
53030  *ppPage = 0;
53031  return pPager->errCode;
53032}
53033
53034
53035/* Dispatch all page fetch requests to the appropriate getter method.
53036*/
53037SQLITE_PRIVATE int sqlite3PagerGet(
53038  Pager *pPager,      /* The pager open on the database file */
53039  Pgno pgno,          /* Page number to fetch */
53040  DbPage **ppPage,    /* Write a pointer to the page here */
53041  int flags           /* PAGER_GET_XXX flags */
53042){
53043  return pPager->xGet(pPager, pgno, ppPage, flags);
53044}
53045
53046/*
53047** Acquire a page if it is already in the in-memory cache.  Do
53048** not read the page from disk.  Return a pointer to the page,
53049** or 0 if the page is not in cache.
53050**
53051** See also sqlite3PagerGet().  The difference between this routine
53052** and sqlite3PagerGet() is that _get() will go to the disk and read
53053** in the page if the page is not already in cache.  This routine
53054** returns NULL if the page is not in cache or if a disk I/O error
53055** has ever happened.
53056*/
53057SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
53058  sqlite3_pcache_page *pPage;
53059  assert( pPager!=0 );
53060  assert( pgno!=0 );
53061  assert( pPager->pPCache!=0 );
53062  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
53063  assert( pPage==0 || pPager->hasHeldSharedLock );
53064  if( pPage==0 ) return 0;
53065  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
53066}
53067
53068/*
53069** Release a page reference.
53070**
53071** If the number of references to the page drop to zero, then the
53072** page is added to the LRU list.  When all references to all pages
53073** are released, a rollback occurs and the lock on the database is
53074** removed.
53075*/
53076SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
53077  Pager *pPager;
53078  assert( pPg!=0 );
53079  pPager = pPg->pPager;
53080  if( pPg->flags & PGHDR_MMAP ){
53081    pagerReleaseMapPage(pPg);
53082  }else{
53083    sqlite3PcacheRelease(pPg);
53084  }
53085  pagerUnlockIfUnused(pPager);
53086}
53087SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
53088  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
53089}
53090
53091/*
53092** This function is called at the start of every write transaction.
53093** There must already be a RESERVED or EXCLUSIVE lock on the database
53094** file when this routine is called.
53095**
53096** Open the journal file for pager pPager and write a journal header
53097** to the start of it. If there are active savepoints, open the sub-journal
53098** as well. This function is only used when the journal file is being
53099** opened to write a rollback log for a transaction. It is not used
53100** when opening a hot journal file to roll it back.
53101**
53102** If the journal file is already open (as it may be in exclusive mode),
53103** then this function just writes a journal header to the start of the
53104** already open file.
53105**
53106** Whether or not the journal file is opened by this function, the
53107** Pager.pInJournal bitvec structure is allocated.
53108**
53109** Return SQLITE_OK if everything is successful. Otherwise, return
53110** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
53111** an IO error code if opening or writing the journal file fails.
53112*/
53113static int pager_open_journal(Pager *pPager){
53114  int rc = SQLITE_OK;                        /* Return code */
53115  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
53116
53117  assert( pPager->eState==PAGER_WRITER_LOCKED );
53118  assert( assert_pager_state(pPager) );
53119  assert( pPager->pInJournal==0 );
53120
53121  /* If already in the error state, this function is a no-op.  But on
53122  ** the other hand, this routine is never called if we are already in
53123  ** an error state. */
53124  if( NEVER(pPager->errCode) ) return pPager->errCode;
53125
53126  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
53127    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
53128    if( pPager->pInJournal==0 ){
53129      return SQLITE_NOMEM_BKPT;
53130    }
53131
53132    /* Open the journal file if it is not already open. */
53133    if( !isOpen(pPager->jfd) ){
53134      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
53135        sqlite3MemJournalOpen(pPager->jfd);
53136      }else{
53137        int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
53138        int nSpill;
53139
53140        if( pPager->tempFile ){
53141          flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
53142          nSpill = sqlite3Config.nStmtSpill;
53143        }else{
53144          flags |= SQLITE_OPEN_MAIN_JOURNAL;
53145          nSpill = jrnlBufferSize(pPager);
53146        }
53147
53148        /* Verify that the database still has the same name as it did when
53149        ** it was originally opened. */
53150        rc = databaseIsUnmoved(pPager);
53151        if( rc==SQLITE_OK ){
53152          rc = sqlite3JournalOpen (
53153              pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
53154          );
53155        }
53156      }
53157      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
53158    }
53159
53160
53161    /* Write the first journal header to the journal file and open
53162    ** the sub-journal if necessary.
53163    */
53164    if( rc==SQLITE_OK ){
53165      /* TODO: Check if all of these are really required. */
53166      pPager->nRec = 0;
53167      pPager->journalOff = 0;
53168      pPager->setMaster = 0;
53169      pPager->journalHdr = 0;
53170      rc = writeJournalHdr(pPager);
53171    }
53172  }
53173
53174  if( rc!=SQLITE_OK ){
53175    sqlite3BitvecDestroy(pPager->pInJournal);
53176    pPager->pInJournal = 0;
53177  }else{
53178    assert( pPager->eState==PAGER_WRITER_LOCKED );
53179    pPager->eState = PAGER_WRITER_CACHEMOD;
53180  }
53181
53182  return rc;
53183}
53184
53185/*
53186** Begin a write-transaction on the specified pager object. If a
53187** write-transaction has already been opened, this function is a no-op.
53188**
53189** If the exFlag argument is false, then acquire at least a RESERVED
53190** lock on the database file. If exFlag is true, then acquire at least
53191** an EXCLUSIVE lock. If such a lock is already held, no locking
53192** functions need be called.
53193**
53194** If the subjInMemory argument is non-zero, then any sub-journal opened
53195** within this transaction will be opened as an in-memory file. This
53196** has no effect if the sub-journal is already opened (as it may be when
53197** running in exclusive mode) or if the transaction does not require a
53198** sub-journal. If the subjInMemory argument is zero, then any required
53199** sub-journal is implemented in-memory if pPager is an in-memory database,
53200** or using a temporary file otherwise.
53201*/
53202SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
53203  int rc = SQLITE_OK;
53204
53205  if( pPager->errCode ) return pPager->errCode;
53206  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
53207  pPager->subjInMemory = (u8)subjInMemory;
53208
53209  if( ALWAYS(pPager->eState==PAGER_READER) ){
53210    assert( pPager->pInJournal==0 );
53211
53212    if( pagerUseWal(pPager) ){
53213      /* If the pager is configured to use locking_mode=exclusive, and an
53214      ** exclusive lock on the database is not already held, obtain it now.
53215      */
53216      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
53217        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
53218        if( rc!=SQLITE_OK ){
53219          return rc;
53220        }
53221        (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
53222      }
53223
53224      /* Grab the write lock on the log file. If successful, upgrade to
53225      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
53226      ** The busy-handler is not invoked if another connection already
53227      ** holds the write-lock. If possible, the upper layer will call it.
53228      */
53229      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
53230    }else{
53231      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
53232      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
53233      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
53234      ** lock, but not when obtaining the RESERVED lock.
53235      */
53236      rc = pagerLockDb(pPager, RESERVED_LOCK);
53237      if( rc==SQLITE_OK && exFlag ){
53238        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
53239      }
53240    }
53241
53242    if( rc==SQLITE_OK ){
53243      /* Change to WRITER_LOCKED state.
53244      **
53245      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
53246      ** when it has an open transaction, but never to DBMOD or FINISHED.
53247      ** This is because in those states the code to roll back savepoint
53248      ** transactions may copy data from the sub-journal into the database
53249      ** file as well as into the page cache. Which would be incorrect in
53250      ** WAL mode.
53251      */
53252      pPager->eState = PAGER_WRITER_LOCKED;
53253      pPager->dbHintSize = pPager->dbSize;
53254      pPager->dbFileSize = pPager->dbSize;
53255      pPager->dbOrigSize = pPager->dbSize;
53256      pPager->journalOff = 0;
53257    }
53258
53259    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
53260    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
53261    assert( assert_pager_state(pPager) );
53262  }
53263
53264  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
53265  return rc;
53266}
53267
53268/*
53269** Write page pPg onto the end of the rollback journal.
53270*/
53271static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
53272  Pager *pPager = pPg->pPager;
53273  int rc;
53274  u32 cksum;
53275  char *pData2;
53276  i64 iOff = pPager->journalOff;
53277
53278  /* We should never write to the journal file the page that
53279  ** contains the database locks.  The following assert verifies
53280  ** that we do not. */
53281  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
53282
53283  assert( pPager->journalHdr<=pPager->journalOff );
53284  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
53285  cksum = pager_cksum(pPager, (u8*)pData2);
53286
53287  /* Even if an IO or diskfull error occurs while journalling the
53288  ** page in the block above, set the need-sync flag for the page.
53289  ** Otherwise, when the transaction is rolled back, the logic in
53290  ** playback_one_page() will think that the page needs to be restored
53291  ** in the database file. And if an IO error occurs while doing so,
53292  ** then corruption may follow.
53293  */
53294  pPg->flags |= PGHDR_NEED_SYNC;
53295
53296  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
53297  if( rc!=SQLITE_OK ) return rc;
53298  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
53299  if( rc!=SQLITE_OK ) return rc;
53300  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
53301  if( rc!=SQLITE_OK ) return rc;
53302
53303  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
53304           pPager->journalOff, pPager->pageSize));
53305  PAGER_INCR(sqlite3_pager_writej_count);
53306  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
53307       PAGERID(pPager), pPg->pgno,
53308       ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
53309
53310  pPager->journalOff += 8 + pPager->pageSize;
53311  pPager->nRec++;
53312  assert( pPager->pInJournal!=0 );
53313  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
53314  testcase( rc==SQLITE_NOMEM );
53315  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
53316  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
53317  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
53318  return rc;
53319}
53320
53321/*
53322** Mark a single data page as writeable. The page is written into the
53323** main journal or sub-journal as required. If the page is written into
53324** one of the journals, the corresponding bit is set in the
53325** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
53326** of any open savepoints as appropriate.
53327*/
53328static int pager_write(PgHdr *pPg){
53329  Pager *pPager = pPg->pPager;
53330  int rc = SQLITE_OK;
53331
53332  /* This routine is not called unless a write-transaction has already
53333  ** been started. The journal file may or may not be open at this point.
53334  ** It is never called in the ERROR state.
53335  */
53336  assert( pPager->eState==PAGER_WRITER_LOCKED
53337       || pPager->eState==PAGER_WRITER_CACHEMOD
53338       || pPager->eState==PAGER_WRITER_DBMOD
53339  );
53340  assert( assert_pager_state(pPager) );
53341  assert( pPager->errCode==0 );
53342  assert( pPager->readOnly==0 );
53343  CHECK_PAGE(pPg);
53344
53345  /* The journal file needs to be opened. Higher level routines have already
53346  ** obtained the necessary locks to begin the write-transaction, but the
53347  ** rollback journal might not yet be open. Open it now if this is the case.
53348  **
53349  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
53350  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
53351  ** an error might occur and the pager would end up in WRITER_LOCKED state
53352  ** with pages marked as dirty in the cache.
53353  */
53354  if( pPager->eState==PAGER_WRITER_LOCKED ){
53355    rc = pager_open_journal(pPager);
53356    if( rc!=SQLITE_OK ) return rc;
53357  }
53358  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
53359  assert( assert_pager_state(pPager) );
53360
53361  /* Mark the page that is about to be modified as dirty. */
53362  sqlite3PcacheMakeDirty(pPg);
53363
53364  /* If a rollback journal is in use, them make sure the page that is about
53365  ** to change is in the rollback journal, or if the page is a new page off
53366  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
53367  */
53368  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
53369  if( pPager->pInJournal!=0
53370   && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
53371  ){
53372    assert( pagerUseWal(pPager)==0 );
53373    if( pPg->pgno<=pPager->dbOrigSize ){
53374      rc = pagerAddPageToRollbackJournal(pPg);
53375      if( rc!=SQLITE_OK ){
53376        return rc;
53377      }
53378    }else{
53379      if( pPager->eState!=PAGER_WRITER_DBMOD ){
53380        pPg->flags |= PGHDR_NEED_SYNC;
53381      }
53382      PAGERTRACE(("APPEND %d page %d needSync=%d\n",
53383              PAGERID(pPager), pPg->pgno,
53384             ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
53385    }
53386  }
53387
53388  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
53389  ** and before writing the page into the rollback journal.  Wait until now,
53390  ** after the page has been successfully journalled, before setting the
53391  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
53392  */
53393  pPg->flags |= PGHDR_WRITEABLE;
53394
53395  /* If the statement journal is open and the page is not in it,
53396  ** then write the page into the statement journal.
53397  */
53398  if( pPager->nSavepoint>0 ){
53399    rc = subjournalPageIfRequired(pPg);
53400  }
53401
53402  /* Update the database size and return. */
53403  if( pPager->dbSize<pPg->pgno ){
53404    pPager->dbSize = pPg->pgno;
53405  }
53406  return rc;
53407}
53408
53409/*
53410** This is a variant of sqlite3PagerWrite() that runs when the sector size
53411** is larger than the page size.  SQLite makes the (reasonable) assumption that
53412** all bytes of a sector are written together by hardware.  Hence, all bytes of
53413** a sector need to be journalled in case of a power loss in the middle of
53414** a write.
53415**
53416** Usually, the sector size is less than or equal to the page size, in which
53417** case pages can be individually written.  This routine only runs in the
53418** exceptional case where the page size is smaller than the sector size.
53419*/
53420static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
53421  int rc = SQLITE_OK;          /* Return code */
53422  Pgno nPageCount;             /* Total number of pages in database file */
53423  Pgno pg1;                    /* First page of the sector pPg is located on. */
53424  int nPage = 0;               /* Number of pages starting at pg1 to journal */
53425  int ii;                      /* Loop counter */
53426  int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
53427  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
53428  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
53429
53430  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
53431  ** a journal header to be written between the pages journaled by
53432  ** this function.
53433  */
53434  assert( !MEMDB );
53435  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
53436  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
53437
53438  /* This trick assumes that both the page-size and sector-size are
53439  ** an integer power of 2. It sets variable pg1 to the identifier
53440  ** of the first page of the sector pPg is located on.
53441  */
53442  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
53443
53444  nPageCount = pPager->dbSize;
53445  if( pPg->pgno>nPageCount ){
53446    nPage = (pPg->pgno - pg1)+1;
53447  }else if( (pg1+nPagePerSector-1)>nPageCount ){
53448    nPage = nPageCount+1-pg1;
53449  }else{
53450    nPage = nPagePerSector;
53451  }
53452  assert(nPage>0);
53453  assert(pg1<=pPg->pgno);
53454  assert((pg1+nPage)>pPg->pgno);
53455
53456  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
53457    Pgno pg = pg1+ii;
53458    PgHdr *pPage;
53459    if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
53460      if( pg!=PAGER_MJ_PGNO(pPager) ){
53461        rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
53462        if( rc==SQLITE_OK ){
53463          rc = pager_write(pPage);
53464          if( pPage->flags&PGHDR_NEED_SYNC ){
53465            needSync = 1;
53466          }
53467          sqlite3PagerUnrefNotNull(pPage);
53468        }
53469      }
53470    }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
53471      if( pPage->flags&PGHDR_NEED_SYNC ){
53472        needSync = 1;
53473      }
53474      sqlite3PagerUnrefNotNull(pPage);
53475    }
53476  }
53477
53478  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
53479  ** starting at pg1, then it needs to be set for all of them. Because
53480  ** writing to any of these nPage pages may damage the others, the
53481  ** journal file must contain sync()ed copies of all of them
53482  ** before any of them can be written out to the database file.
53483  */
53484  if( rc==SQLITE_OK && needSync ){
53485    assert( !MEMDB );
53486    for(ii=0; ii<nPage; ii++){
53487      PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
53488      if( pPage ){
53489        pPage->flags |= PGHDR_NEED_SYNC;
53490        sqlite3PagerUnrefNotNull(pPage);
53491      }
53492    }
53493  }
53494
53495  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
53496  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
53497  return rc;
53498}
53499
53500/*
53501** Mark a data page as writeable. This routine must be called before
53502** making changes to a page. The caller must check the return value
53503** of this function and be careful not to change any page data unless
53504** this routine returns SQLITE_OK.
53505**
53506** The difference between this function and pager_write() is that this
53507** function also deals with the special case where 2 or more pages
53508** fit on a single disk sector. In this case all co-resident pages
53509** must have been written to the journal file before returning.
53510**
53511** If an error occurs, SQLITE_NOMEM or an IO error code is returned
53512** as appropriate. Otherwise, SQLITE_OK.
53513*/
53514SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
53515  Pager *pPager = pPg->pPager;
53516  assert( (pPg->flags & PGHDR_MMAP)==0 );
53517  assert( pPager->eState>=PAGER_WRITER_LOCKED );
53518  assert( assert_pager_state(pPager) );
53519  if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
53520    if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
53521    return SQLITE_OK;
53522  }else if( pPager->errCode ){
53523    return pPager->errCode;
53524  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
53525    assert( pPager->tempFile==0 );
53526    return pagerWriteLargeSector(pPg);
53527  }else{
53528    return pager_write(pPg);
53529  }
53530}
53531
53532/*
53533** Return TRUE if the page given in the argument was previously passed
53534** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
53535** to change the content of the page.
53536*/
53537#ifndef NDEBUG
53538SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
53539  return pPg->flags & PGHDR_WRITEABLE;
53540}
53541#endif
53542
53543/*
53544** A call to this routine tells the pager that it is not necessary to
53545** write the information on page pPg back to the disk, even though
53546** that page might be marked as dirty.  This happens, for example, when
53547** the page has been added as a leaf of the freelist and so its
53548** content no longer matters.
53549**
53550** The overlying software layer calls this routine when all of the data
53551** on the given page is unused. The pager marks the page as clean so
53552** that it does not get written to disk.
53553**
53554** Tests show that this optimization can quadruple the speed of large
53555** DELETE operations.
53556**
53557** This optimization cannot be used with a temp-file, as the page may
53558** have been dirty at the start of the transaction. In that case, if
53559** memory pressure forces page pPg out of the cache, the data does need
53560** to be written out to disk so that it may be read back in if the
53561** current transaction is rolled back.
53562*/
53563SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
53564  Pager *pPager = pPg->pPager;
53565  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
53566    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
53567    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
53568    pPg->flags |= PGHDR_DONT_WRITE;
53569    pPg->flags &= ~PGHDR_WRITEABLE;
53570    testcase( pPg->flags & PGHDR_NEED_SYNC );
53571    pager_set_pagehash(pPg);
53572  }
53573}
53574
53575/*
53576** This routine is called to increment the value of the database file
53577** change-counter, stored as a 4-byte big-endian integer starting at
53578** byte offset 24 of the pager file.  The secondary change counter at
53579** 92 is also updated, as is the SQLite version number at offset 96.
53580**
53581** But this only happens if the pPager->changeCountDone flag is false.
53582** To avoid excess churning of page 1, the update only happens once.
53583** See also the pager_write_changecounter() routine that does an
53584** unconditional update of the change counters.
53585**
53586** If the isDirectMode flag is zero, then this is done by calling
53587** sqlite3PagerWrite() on page 1, then modifying the contents of the
53588** page data. In this case the file will be updated when the current
53589** transaction is committed.
53590**
53591** The isDirectMode flag may only be non-zero if the library was compiled
53592** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
53593** if isDirect is non-zero, then the database file is updated directly
53594** by writing an updated version of page 1 using a call to the
53595** sqlite3OsWrite() function.
53596*/
53597static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
53598  int rc = SQLITE_OK;
53599
53600  assert( pPager->eState==PAGER_WRITER_CACHEMOD
53601       || pPager->eState==PAGER_WRITER_DBMOD
53602  );
53603  assert( assert_pager_state(pPager) );
53604
53605  /* Declare and initialize constant integer 'isDirect'. If the
53606  ** atomic-write optimization is enabled in this build, then isDirect
53607  ** is initialized to the value passed as the isDirectMode parameter
53608  ** to this function. Otherwise, it is always set to zero.
53609  **
53610  ** The idea is that if the atomic-write optimization is not
53611  ** enabled at compile time, the compiler can omit the tests of
53612  ** 'isDirect' below, as well as the block enclosed in the
53613  ** "if( isDirect )" condition.
53614  */
53615#ifndef SQLITE_ENABLE_ATOMIC_WRITE
53616# define DIRECT_MODE 0
53617  assert( isDirectMode==0 );
53618  UNUSED_PARAMETER(isDirectMode);
53619#else
53620# define DIRECT_MODE isDirectMode
53621#endif
53622
53623  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
53624    PgHdr *pPgHdr;                /* Reference to page 1 */
53625
53626    assert( !pPager->tempFile && isOpen(pPager->fd) );
53627
53628    /* Open page 1 of the file for writing. */
53629    rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
53630    assert( pPgHdr==0 || rc==SQLITE_OK );
53631
53632    /* If page one was fetched successfully, and this function is not
53633    ** operating in direct-mode, make page 1 writable.  When not in
53634    ** direct mode, page 1 is always held in cache and hence the PagerGet()
53635    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
53636    */
53637    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
53638      rc = sqlite3PagerWrite(pPgHdr);
53639    }
53640
53641    if( rc==SQLITE_OK ){
53642      /* Actually do the update of the change counter */
53643      pager_write_changecounter(pPgHdr);
53644
53645      /* If running in direct mode, write the contents of page 1 to the file. */
53646      if( DIRECT_MODE ){
53647        const void *zBuf;
53648        assert( pPager->dbFileSize>0 );
53649        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
53650        if( rc==SQLITE_OK ){
53651          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
53652          pPager->aStat[PAGER_STAT_WRITE]++;
53653        }
53654        if( rc==SQLITE_OK ){
53655          /* Update the pager's copy of the change-counter. Otherwise, the
53656          ** next time a read transaction is opened the cache will be
53657          ** flushed (as the change-counter values will not match).  */
53658          const void *pCopy = (const void *)&((const char *)zBuf)[24];
53659          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
53660          pPager->changeCountDone = 1;
53661        }
53662      }else{
53663        pPager->changeCountDone = 1;
53664      }
53665    }
53666
53667    /* Release the page reference. */
53668    sqlite3PagerUnref(pPgHdr);
53669  }
53670  return rc;
53671}
53672
53673/*
53674** Sync the database file to disk. This is a no-op for in-memory databases
53675** or pages with the Pager.noSync flag set.
53676**
53677** If successful, or if called on a pager for which it is a no-op, this
53678** function returns SQLITE_OK. Otherwise, an IO error code is returned.
53679*/
53680SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
53681  int rc = SQLITE_OK;
53682
53683  if( isOpen(pPager->fd) ){
53684    void *pArg = (void*)zMaster;
53685    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
53686    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
53687  }
53688  if( rc==SQLITE_OK && !pPager->noSync ){
53689    assert( !MEMDB );
53690    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
53691  }
53692  return rc;
53693}
53694
53695/*
53696** This function may only be called while a write-transaction is active in
53697** rollback. If the connection is in WAL mode, this call is a no-op.
53698** Otherwise, if the connection does not already have an EXCLUSIVE lock on
53699** the database file, an attempt is made to obtain one.
53700**
53701** If the EXCLUSIVE lock is already held or the attempt to obtain it is
53702** successful, or the connection is in WAL mode, SQLITE_OK is returned.
53703** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
53704** returned.
53705*/
53706SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
53707  int rc = pPager->errCode;
53708  assert( assert_pager_state(pPager) );
53709  if( rc==SQLITE_OK ){
53710    assert( pPager->eState==PAGER_WRITER_CACHEMOD
53711         || pPager->eState==PAGER_WRITER_DBMOD
53712         || pPager->eState==PAGER_WRITER_LOCKED
53713    );
53714    assert( assert_pager_state(pPager) );
53715    if( 0==pagerUseWal(pPager) ){
53716      rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
53717    }
53718  }
53719  return rc;
53720}
53721
53722/*
53723** Sync the database file for the pager pPager. zMaster points to the name
53724** of a master journal file that should be written into the individual
53725** journal file. zMaster may be NULL, which is interpreted as no master
53726** journal (a single database transaction).
53727**
53728** This routine ensures that:
53729**
53730**   * The database file change-counter is updated,
53731**   * the journal is synced (unless the atomic-write optimization is used),
53732**   * all dirty pages are written to the database file,
53733**   * the database file is truncated (if required), and
53734**   * the database file synced.
53735**
53736** The only thing that remains to commit the transaction is to finalize
53737** (delete, truncate or zero the first part of) the journal file (or
53738** delete the master journal file if specified).
53739**
53740** Note that if zMaster==NULL, this does not overwrite a previous value
53741** passed to an sqlite3PagerCommitPhaseOne() call.
53742**
53743** If the final parameter - noSync - is true, then the database file itself
53744** is not synced. The caller must call sqlite3PagerSync() directly to
53745** sync the database file before calling CommitPhaseTwo() to delete the
53746** journal file in this case.
53747*/
53748SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
53749  Pager *pPager,                  /* Pager object */
53750  const char *zMaster,            /* If not NULL, the master journal name */
53751  int noSync                      /* True to omit the xSync on the db file */
53752){
53753  int rc = SQLITE_OK;             /* Return code */
53754
53755  assert( pPager->eState==PAGER_WRITER_LOCKED
53756       || pPager->eState==PAGER_WRITER_CACHEMOD
53757       || pPager->eState==PAGER_WRITER_DBMOD
53758       || pPager->eState==PAGER_ERROR
53759  );
53760  assert( assert_pager_state(pPager) );
53761
53762  /* If a prior error occurred, report that error again. */
53763  if( NEVER(pPager->errCode) ) return pPager->errCode;
53764
53765  /* Provide the ability to easily simulate an I/O error during testing */
53766  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
53767
53768  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
53769      pPager->zFilename, zMaster, pPager->dbSize));
53770
53771  /* If no database changes have been made, return early. */
53772  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
53773
53774  assert( MEMDB==0 || pPager->tempFile );
53775  assert( isOpen(pPager->fd) || pPager->tempFile );
53776  if( 0==pagerFlushOnCommit(pPager, 1) ){
53777    /* If this is an in-memory db, or no pages have been written to, or this
53778    ** function has already been called, it is mostly a no-op.  However, any
53779    ** backup in progress needs to be restarted.  */
53780    sqlite3BackupRestart(pPager->pBackup);
53781  }else{
53782    if( pagerUseWal(pPager) ){
53783      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
53784      PgHdr *pPageOne = 0;
53785      if( pList==0 ){
53786        /* Must have at least one page for the WAL commit flag.
53787        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
53788        rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
53789        pList = pPageOne;
53790        pList->pDirty = 0;
53791      }
53792      assert( rc==SQLITE_OK );
53793      if( ALWAYS(pList) ){
53794        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
53795      }
53796      sqlite3PagerUnref(pPageOne);
53797      if( rc==SQLITE_OK ){
53798        sqlite3PcacheCleanAll(pPager->pPCache);
53799      }
53800    }else{
53801      /* The following block updates the change-counter. Exactly how it
53802      ** does this depends on whether or not the atomic-update optimization
53803      ** was enabled at compile time, and if this transaction meets the
53804      ** runtime criteria to use the operation:
53805      **
53806      **    * The file-system supports the atomic-write property for
53807      **      blocks of size page-size, and
53808      **    * This commit is not part of a multi-file transaction, and
53809      **    * Exactly one page has been modified and store in the journal file.
53810      **
53811      ** If the optimization was not enabled at compile time, then the
53812      ** pager_incr_changecounter() function is called to update the change
53813      ** counter in 'indirect-mode'. If the optimization is compiled in but
53814      ** is not applicable to this transaction, call sqlite3JournalCreate()
53815      ** to make sure the journal file has actually been created, then call
53816      ** pager_incr_changecounter() to update the change-counter in indirect
53817      ** mode.
53818      **
53819      ** Otherwise, if the optimization is both enabled and applicable,
53820      ** then call pager_incr_changecounter() to update the change-counter
53821      ** in 'direct' mode. In this case the journal file will never be
53822      ** created for this transaction.
53823      */
53824  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
53825      PgHdr *pPg;
53826      assert( isOpen(pPager->jfd)
53827           || pPager->journalMode==PAGER_JOURNALMODE_OFF
53828           || pPager->journalMode==PAGER_JOURNALMODE_WAL
53829      );
53830      if( !zMaster && isOpen(pPager->jfd)
53831       && pPager->journalOff==jrnlBufferSize(pPager)
53832       && pPager->dbSize>=pPager->dbOrigSize
53833       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
53834      ){
53835        /* Update the db file change counter via the direct-write method. The
53836        ** following call will modify the in-memory representation of page 1
53837        ** to include the updated change counter and then write page 1
53838        ** directly to the database file. Because of the atomic-write
53839        ** property of the host file-system, this is safe.
53840        */
53841        rc = pager_incr_changecounter(pPager, 1);
53842      }else{
53843        rc = sqlite3JournalCreate(pPager->jfd);
53844        if( rc==SQLITE_OK ){
53845          rc = pager_incr_changecounter(pPager, 0);
53846        }
53847      }
53848  #else
53849      rc = pager_incr_changecounter(pPager, 0);
53850  #endif
53851      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53852
53853      /* Write the master journal name into the journal file. If a master
53854      ** journal file name has already been written to the journal file,
53855      ** or if zMaster is NULL (no master journal), then this call is a no-op.
53856      */
53857      rc = writeMasterJournal(pPager, zMaster);
53858      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53859
53860      /* Sync the journal file and write all dirty pages to the database.
53861      ** If the atomic-update optimization is being used, this sync will not
53862      ** create the journal file or perform any real IO.
53863      **
53864      ** Because the change-counter page was just modified, unless the
53865      ** atomic-update optimization is used it is almost certain that the
53866      ** journal requires a sync here. However, in locking_mode=exclusive
53867      ** on a system under memory pressure it is just possible that this is
53868      ** not the case. In this case it is likely enough that the redundant
53869      ** xSync() call will be changed to a no-op by the OS anyhow.
53870      */
53871      rc = syncJournal(pPager, 0);
53872      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53873
53874      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
53875      if( rc!=SQLITE_OK ){
53876        assert( rc!=SQLITE_IOERR_BLOCKED );
53877        goto commit_phase_one_exit;
53878      }
53879      sqlite3PcacheCleanAll(pPager->pPCache);
53880
53881      /* If the file on disk is smaller than the database image, use
53882      ** pager_truncate to grow the file here. This can happen if the database
53883      ** image was extended as part of the current transaction and then the
53884      ** last page in the db image moved to the free-list. In this case the
53885      ** last page is never written out to disk, leaving the database file
53886      ** undersized. Fix this now if it is the case.  */
53887      if( pPager->dbSize>pPager->dbFileSize ){
53888        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
53889        assert( pPager->eState==PAGER_WRITER_DBMOD );
53890        rc = pager_truncate(pPager, nNew);
53891        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
53892      }
53893
53894      /* Finally, sync the database file. */
53895      if( !noSync ){
53896        rc = sqlite3PagerSync(pPager, zMaster);
53897      }
53898      IOTRACE(("DBSYNC %p\n", pPager))
53899    }
53900  }
53901
53902commit_phase_one_exit:
53903  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
53904    pPager->eState = PAGER_WRITER_FINISHED;
53905  }
53906  return rc;
53907}
53908
53909
53910/*
53911** When this function is called, the database file has been completely
53912** updated to reflect the changes made by the current transaction and
53913** synced to disk. The journal file still exists in the file-system
53914** though, and if a failure occurs at this point it will eventually
53915** be used as a hot-journal and the current transaction rolled back.
53916**
53917** This function finalizes the journal file, either by deleting,
53918** truncating or partially zeroing it, so that it cannot be used
53919** for hot-journal rollback. Once this is done the transaction is
53920** irrevocably committed.
53921**
53922** If an error occurs, an IO error code is returned and the pager
53923** moves into the error state. Otherwise, SQLITE_OK is returned.
53924*/
53925SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
53926  int rc = SQLITE_OK;                  /* Return code */
53927
53928  /* This routine should not be called if a prior error has occurred.
53929  ** But if (due to a coding error elsewhere in the system) it does get
53930  ** called, just return the same error code without doing anything. */
53931  if( NEVER(pPager->errCode) ) return pPager->errCode;
53932
53933  assert( pPager->eState==PAGER_WRITER_LOCKED
53934       || pPager->eState==PAGER_WRITER_FINISHED
53935       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
53936  );
53937  assert( assert_pager_state(pPager) );
53938
53939  /* An optimization. If the database was not actually modified during
53940  ** this transaction, the pager is running in exclusive-mode and is
53941  ** using persistent journals, then this function is a no-op.
53942  **
53943  ** The start of the journal file currently contains a single journal
53944  ** header with the nRec field set to 0. If such a journal is used as
53945  ** a hot-journal during hot-journal rollback, 0 changes will be made
53946  ** to the database file. So there is no need to zero the journal
53947  ** header. Since the pager is in exclusive mode, there is no need
53948  ** to drop any locks either.
53949  */
53950  if( pPager->eState==PAGER_WRITER_LOCKED
53951   && pPager->exclusiveMode
53952   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
53953  ){
53954    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
53955    pPager->eState = PAGER_READER;
53956    return SQLITE_OK;
53957  }
53958
53959  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
53960  pPager->iDataVersion++;
53961  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
53962  return pager_error(pPager, rc);
53963}
53964
53965/*
53966** If a write transaction is open, then all changes made within the
53967** transaction are reverted and the current write-transaction is closed.
53968** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
53969** state if an error occurs.
53970**
53971** If the pager is already in PAGER_ERROR state when this function is called,
53972** it returns Pager.errCode immediately. No work is performed in this case.
53973**
53974** Otherwise, in rollback mode, this function performs two functions:
53975**
53976**   1) It rolls back the journal file, restoring all database file and
53977**      in-memory cache pages to the state they were in when the transaction
53978**      was opened, and
53979**
53980**   2) It finalizes the journal file, so that it is not used for hot
53981**      rollback at any point in the future.
53982**
53983** Finalization of the journal file (task 2) is only performed if the
53984** rollback is successful.
53985**
53986** In WAL mode, all cache-entries containing data modified within the
53987** current transaction are either expelled from the cache or reverted to
53988** their pre-transaction state by re-reading data from the database or
53989** WAL files. The WAL transaction is then closed.
53990*/
53991SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
53992  int rc = SQLITE_OK;                  /* Return code */
53993  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
53994
53995  /* PagerRollback() is a no-op if called in READER or OPEN state. If
53996  ** the pager is already in the ERROR state, the rollback is not
53997  ** attempted here. Instead, the error code is returned to the caller.
53998  */
53999  assert( assert_pager_state(pPager) );
54000  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
54001  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
54002
54003  if( pagerUseWal(pPager) ){
54004    int rc2;
54005    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
54006    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
54007    if( rc==SQLITE_OK ) rc = rc2;
54008  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
54009    int eState = pPager->eState;
54010    rc = pager_end_transaction(pPager, 0, 0);
54011    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
54012      /* This can happen using journal_mode=off. Move the pager to the error
54013      ** state to indicate that the contents of the cache may not be trusted.
54014      ** Any active readers will get SQLITE_ABORT.
54015      */
54016      pPager->errCode = SQLITE_ABORT;
54017      pPager->eState = PAGER_ERROR;
54018      setGetterMethod(pPager);
54019      return rc;
54020    }
54021  }else{
54022    rc = pager_playback(pPager, 0);
54023  }
54024
54025  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
54026  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
54027          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
54028          || rc==SQLITE_CANTOPEN
54029  );
54030
54031  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
54032  ** cache. So call pager_error() on the way out to make any error persistent.
54033  */
54034  return pager_error(pPager, rc);
54035}
54036
54037/*
54038** Return TRUE if the database file is opened read-only.  Return FALSE
54039** if the database is (in theory) writable.
54040*/
54041SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
54042  return pPager->readOnly;
54043}
54044
54045#ifdef SQLITE_DEBUG
54046/*
54047** Return the sum of the reference counts for all pages held by pPager.
54048*/
54049SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
54050  return sqlite3PcacheRefCount(pPager->pPCache);
54051}
54052#endif
54053
54054/*
54055** Return the approximate number of bytes of memory currently
54056** used by the pager and its associated cache.
54057*/
54058SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
54059  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
54060                                     + 5*sizeof(void*);
54061  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
54062           + sqlite3MallocSize(pPager)
54063           + pPager->pageSize;
54064}
54065
54066/*
54067** Return the number of references to the specified page.
54068*/
54069SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
54070  return sqlite3PcachePageRefcount(pPage);
54071}
54072
54073#ifdef SQLITE_TEST
54074/*
54075** This routine is used for testing and analysis only.
54076*/
54077SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
54078  static int a[11];
54079  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
54080  a[1] = sqlite3PcachePagecount(pPager->pPCache);
54081  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
54082  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
54083  a[4] = pPager->eState;
54084  a[5] = pPager->errCode;
54085  a[6] = pPager->aStat[PAGER_STAT_HIT];
54086  a[7] = pPager->aStat[PAGER_STAT_MISS];
54087  a[8] = 0;  /* Used to be pPager->nOvfl */
54088  a[9] = pPager->nRead;
54089  a[10] = pPager->aStat[PAGER_STAT_WRITE];
54090  return a;
54091}
54092#endif
54093
54094/*
54095** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
54096** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
54097** current cache hit or miss count, according to the value of eStat. If the
54098** reset parameter is non-zero, the cache hit or miss count is zeroed before
54099** returning.
54100*/
54101SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
54102
54103  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
54104       || eStat==SQLITE_DBSTATUS_CACHE_MISS
54105       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
54106  );
54107
54108  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
54109  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
54110  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
54111
54112  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
54113  if( reset ){
54114    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
54115  }
54116}
54117
54118/*
54119** Return true if this is an in-memory or temp-file backed pager.
54120*/
54121SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
54122  return pPager->tempFile;
54123}
54124
54125/*
54126** Check that there are at least nSavepoint savepoints open. If there are
54127** currently less than nSavepoints open, then open one or more savepoints
54128** to make up the difference. If the number of savepoints is already
54129** equal to nSavepoint, then this function is a no-op.
54130**
54131** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
54132** occurs while opening the sub-journal file, then an IO error code is
54133** returned. Otherwise, SQLITE_OK.
54134*/
54135static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
54136  int rc = SQLITE_OK;                       /* Return code */
54137  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
54138  int ii;                                   /* Iterator variable */
54139  PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
54140
54141  assert( pPager->eState>=PAGER_WRITER_LOCKED );
54142  assert( assert_pager_state(pPager) );
54143  assert( nSavepoint>nCurrent && pPager->useJournal );
54144
54145  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
54146  ** if the allocation fails. Otherwise, zero the new portion in case a
54147  ** malloc failure occurs while populating it in the for(...) loop below.
54148  */
54149  aNew = (PagerSavepoint *)sqlite3Realloc(
54150      pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
54151  );
54152  if( !aNew ){
54153    return SQLITE_NOMEM_BKPT;
54154  }
54155  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
54156  pPager->aSavepoint = aNew;
54157
54158  /* Populate the PagerSavepoint structures just allocated. */
54159  for(ii=nCurrent; ii<nSavepoint; ii++){
54160    aNew[ii].nOrig = pPager->dbSize;
54161    if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
54162      aNew[ii].iOffset = pPager->journalOff;
54163    }else{
54164      aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
54165    }
54166    aNew[ii].iSubRec = pPager->nSubRec;
54167    aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
54168    if( !aNew[ii].pInSavepoint ){
54169      return SQLITE_NOMEM_BKPT;
54170    }
54171    if( pagerUseWal(pPager) ){
54172      sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
54173    }
54174    pPager->nSavepoint = ii+1;
54175  }
54176  assert( pPager->nSavepoint==nSavepoint );
54177  assertTruncateConstraint(pPager);
54178  return rc;
54179}
54180SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
54181  assert( pPager->eState>=PAGER_WRITER_LOCKED );
54182  assert( assert_pager_state(pPager) );
54183
54184  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
54185    return pagerOpenSavepoint(pPager, nSavepoint);
54186  }else{
54187    return SQLITE_OK;
54188  }
54189}
54190
54191
54192/*
54193** This function is called to rollback or release (commit) a savepoint.
54194** The savepoint to release or rollback need not be the most recently
54195** created savepoint.
54196**
54197** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
54198** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
54199** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
54200** that have occurred since the specified savepoint was created.
54201**
54202** The savepoint to rollback or release is identified by parameter
54203** iSavepoint. A value of 0 means to operate on the outermost savepoint
54204** (the first created). A value of (Pager.nSavepoint-1) means operate
54205** on the most recently created savepoint. If iSavepoint is greater than
54206** (Pager.nSavepoint-1), then this function is a no-op.
54207**
54208** If a negative value is passed to this function, then the current
54209** transaction is rolled back. This is different to calling
54210** sqlite3PagerRollback() because this function does not terminate
54211** the transaction or unlock the database, it just restores the
54212** contents of the database to its original state.
54213**
54214** In any case, all savepoints with an index greater than iSavepoint
54215** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
54216** then savepoint iSavepoint is also destroyed.
54217**
54218** This function may return SQLITE_NOMEM if a memory allocation fails,
54219** or an IO error code if an IO error occurs while rolling back a
54220** savepoint. If no errors occur, SQLITE_OK is returned.
54221*/
54222SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
54223  int rc = pPager->errCode;
54224
54225#ifdef SQLITE_ENABLE_ZIPVFS
54226  if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
54227#endif
54228
54229  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
54230  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
54231
54232  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
54233    int ii;            /* Iterator variable */
54234    int nNew;          /* Number of remaining savepoints after this op. */
54235
54236    /* Figure out how many savepoints will still be active after this
54237    ** operation. Store this value in nNew. Then free resources associated
54238    ** with any savepoints that are destroyed by this operation.
54239    */
54240    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
54241    for(ii=nNew; ii<pPager->nSavepoint; ii++){
54242      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
54243    }
54244    pPager->nSavepoint = nNew;
54245
54246    /* If this is a release of the outermost savepoint, truncate
54247    ** the sub-journal to zero bytes in size. */
54248    if( op==SAVEPOINT_RELEASE ){
54249      if( nNew==0 && isOpen(pPager->sjfd) ){
54250        /* Only truncate if it is an in-memory sub-journal. */
54251        if( sqlite3JournalIsInMemory(pPager->sjfd) ){
54252          rc = sqlite3OsTruncate(pPager->sjfd, 0);
54253          assert( rc==SQLITE_OK );
54254        }
54255        pPager->nSubRec = 0;
54256      }
54257    }
54258    /* Else this is a rollback operation, playback the specified savepoint.
54259    ** If this is a temp-file, it is possible that the journal file has
54260    ** not yet been opened. In this case there have been no changes to
54261    ** the database file, so the playback operation can be skipped.
54262    */
54263    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
54264      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
54265      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
54266      assert(rc!=SQLITE_DONE);
54267    }
54268
54269#ifdef SQLITE_ENABLE_ZIPVFS
54270    /* If the cache has been modified but the savepoint cannot be rolled
54271    ** back journal_mode=off, put the pager in the error state. This way,
54272    ** if the VFS used by this pager includes ZipVFS, the entire transaction
54273    ** can be rolled back at the ZipVFS level.  */
54274    else if(
54275        pPager->journalMode==PAGER_JOURNALMODE_OFF
54276     && pPager->eState>=PAGER_WRITER_CACHEMOD
54277    ){
54278      pPager->errCode = SQLITE_ABORT;
54279      pPager->eState = PAGER_ERROR;
54280      setGetterMethod(pPager);
54281    }
54282#endif
54283  }
54284
54285  return rc;
54286}
54287
54288/*
54289** Return the full pathname of the database file.
54290**
54291** Except, if the pager is in-memory only, then return an empty string if
54292** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
54293** used to report the filename to the user, for compatibility with legacy
54294** behavior.  But when the Btree needs to know the filename for matching to
54295** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
54296** participate in shared-cache.
54297*/
54298SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
54299  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
54300}
54301
54302/*
54303** Return the VFS structure for the pager.
54304*/
54305SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
54306  return pPager->pVfs;
54307}
54308
54309/*
54310** Return the file handle for the database file associated
54311** with the pager.  This might return NULL if the file has
54312** not yet been opened.
54313*/
54314SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
54315  return pPager->fd;
54316}
54317
54318/*
54319** Return the file handle for the journal file (if it exists).
54320** This will be either the rollback journal or the WAL file.
54321*/
54322SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
54323#if SQLITE_OMIT_WAL
54324  return pPager->jfd;
54325#else
54326  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
54327#endif
54328}
54329
54330/*
54331** Return the full pathname of the journal file.
54332*/
54333SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
54334  return pPager->zJournal;
54335}
54336
54337#ifdef SQLITE_HAS_CODEC
54338/*
54339** Set or retrieve the codec for this pager
54340*/
54341SQLITE_PRIVATE void sqlite3PagerSetCodec(
54342  Pager *pPager,
54343  void *(*xCodec)(void*,void*,Pgno,int),
54344  void (*xCodecSizeChng)(void*,int,int),
54345  void (*xCodecFree)(void*),
54346  void *pCodec
54347){
54348  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
54349  pPager->xCodec = pPager->memDb ? 0 : xCodec;
54350  pPager->xCodecSizeChng = xCodecSizeChng;
54351  pPager->xCodecFree = xCodecFree;
54352  pPager->pCodec = pCodec;
54353  setGetterMethod(pPager);
54354  pagerReportSize(pPager);
54355}
54356SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
54357  return pPager->pCodec;
54358}
54359
54360/*
54361** This function is called by the wal module when writing page content
54362** into the log file.
54363**
54364** This function returns a pointer to a buffer containing the encrypted
54365** page content. If a malloc fails, this function may return NULL.
54366*/
54367SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
54368  void *aData = 0;
54369  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
54370  return aData;
54371}
54372
54373/*
54374** Return the current pager state
54375*/
54376SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
54377  return pPager->eState;
54378}
54379#endif /* SQLITE_HAS_CODEC */
54380
54381#ifndef SQLITE_OMIT_AUTOVACUUM
54382/*
54383** Move the page pPg to location pgno in the file.
54384**
54385** There must be no references to the page previously located at
54386** pgno (which we call pPgOld) though that page is allowed to be
54387** in cache.  If the page previously located at pgno is not already
54388** in the rollback journal, it is not put there by by this routine.
54389**
54390** References to the page pPg remain valid. Updating any
54391** meta-data associated with pPg (i.e. data stored in the nExtra bytes
54392** allocated along with the page) is the responsibility of the caller.
54393**
54394** A transaction must be active when this routine is called. It used to be
54395** required that a statement transaction was not active, but this restriction
54396** has been removed (CREATE INDEX needs to move a page when a statement
54397** transaction is active).
54398**
54399** If the fourth argument, isCommit, is non-zero, then this page is being
54400** moved as part of a database reorganization just before the transaction
54401** is being committed. In this case, it is guaranteed that the database page
54402** pPg refers to will not be written to again within this transaction.
54403**
54404** This function may return SQLITE_NOMEM or an IO error code if an error
54405** occurs. Otherwise, it returns SQLITE_OK.
54406*/
54407SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
54408  PgHdr *pPgOld;               /* The page being overwritten. */
54409  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
54410  int rc;                      /* Return code */
54411  Pgno origPgno;               /* The original page number */
54412
54413  assert( pPg->nRef>0 );
54414  assert( pPager->eState==PAGER_WRITER_CACHEMOD
54415       || pPager->eState==PAGER_WRITER_DBMOD
54416  );
54417  assert( assert_pager_state(pPager) );
54418
54419  /* In order to be able to rollback, an in-memory database must journal
54420  ** the page we are moving from.
54421  */
54422  assert( pPager->tempFile || !MEMDB );
54423  if( pPager->tempFile ){
54424    rc = sqlite3PagerWrite(pPg);
54425    if( rc ) return rc;
54426  }
54427
54428  /* If the page being moved is dirty and has not been saved by the latest
54429  ** savepoint, then save the current contents of the page into the
54430  ** sub-journal now. This is required to handle the following scenario:
54431  **
54432  **   BEGIN;
54433  **     <journal page X, then modify it in memory>
54434  **     SAVEPOINT one;
54435  **       <Move page X to location Y>
54436  **     ROLLBACK TO one;
54437  **
54438  ** If page X were not written to the sub-journal here, it would not
54439  ** be possible to restore its contents when the "ROLLBACK TO one"
54440  ** statement were is processed.
54441  **
54442  ** subjournalPage() may need to allocate space to store pPg->pgno into
54443  ** one or more savepoint bitvecs. This is the reason this function
54444  ** may return SQLITE_NOMEM.
54445  */
54446  if( (pPg->flags & PGHDR_DIRTY)!=0
54447   && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
54448  ){
54449    return rc;
54450  }
54451
54452  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
54453      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
54454  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
54455
54456  /* If the journal needs to be sync()ed before page pPg->pgno can
54457  ** be written to, store pPg->pgno in local variable needSyncPgno.
54458  **
54459  ** If the isCommit flag is set, there is no need to remember that
54460  ** the journal needs to be sync()ed before database page pPg->pgno
54461  ** can be written to. The caller has already promised not to write to it.
54462  */
54463  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
54464    needSyncPgno = pPg->pgno;
54465    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
54466            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
54467    assert( pPg->flags&PGHDR_DIRTY );
54468  }
54469
54470  /* If the cache contains a page with page-number pgno, remove it
54471  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
54472  ** page pgno before the 'move' operation, it needs to be retained
54473  ** for the page moved there.
54474  */
54475  pPg->flags &= ~PGHDR_NEED_SYNC;
54476  pPgOld = sqlite3PagerLookup(pPager, pgno);
54477  assert( !pPgOld || pPgOld->nRef==1 );
54478  if( pPgOld ){
54479    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
54480    if( pPager->tempFile ){
54481      /* Do not discard pages from an in-memory database since we might
54482      ** need to rollback later.  Just move the page out of the way. */
54483      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
54484    }else{
54485      sqlite3PcacheDrop(pPgOld);
54486    }
54487  }
54488
54489  origPgno = pPg->pgno;
54490  sqlite3PcacheMove(pPg, pgno);
54491  sqlite3PcacheMakeDirty(pPg);
54492
54493  /* For an in-memory database, make sure the original page continues
54494  ** to exist, in case the transaction needs to roll back.  Use pPgOld
54495  ** as the original page since it has already been allocated.
54496  */
54497  if( pPager->tempFile && pPgOld ){
54498    sqlite3PcacheMove(pPgOld, origPgno);
54499    sqlite3PagerUnrefNotNull(pPgOld);
54500  }
54501
54502  if( needSyncPgno ){
54503    /* If needSyncPgno is non-zero, then the journal file needs to be
54504    ** sync()ed before any data is written to database file page needSyncPgno.
54505    ** Currently, no such page exists in the page-cache and the
54506    ** "is journaled" bitvec flag has been set. This needs to be remedied by
54507    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
54508    ** flag.
54509    **
54510    ** If the attempt to load the page into the page-cache fails, (due
54511    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
54512    ** array. Otherwise, if the page is loaded and written again in
54513    ** this transaction, it may be written to the database file before
54514    ** it is synced into the journal file. This way, it may end up in
54515    ** the journal file twice, but that is not a problem.
54516    */
54517    PgHdr *pPgHdr;
54518    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
54519    if( rc!=SQLITE_OK ){
54520      if( needSyncPgno<=pPager->dbOrigSize ){
54521        assert( pPager->pTmpSpace!=0 );
54522        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
54523      }
54524      return rc;
54525    }
54526    pPgHdr->flags |= PGHDR_NEED_SYNC;
54527    sqlite3PcacheMakeDirty(pPgHdr);
54528    sqlite3PagerUnrefNotNull(pPgHdr);
54529  }
54530
54531  return SQLITE_OK;
54532}
54533#endif
54534
54535/*
54536** The page handle passed as the first argument refers to a dirty page
54537** with a page number other than iNew. This function changes the page's
54538** page number to iNew and sets the value of the PgHdr.flags field to
54539** the value passed as the third parameter.
54540*/
54541SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
54542  assert( pPg->pgno!=iNew );
54543  pPg->flags = flags;
54544  sqlite3PcacheMove(pPg, iNew);
54545}
54546
54547/*
54548** Return a pointer to the data for the specified page.
54549*/
54550SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
54551  assert( pPg->nRef>0 || pPg->pPager->memDb );
54552  return pPg->pData;
54553}
54554
54555/*
54556** Return a pointer to the Pager.nExtra bytes of "extra" space
54557** allocated along with the specified page.
54558*/
54559SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
54560  return pPg->pExtra;
54561}
54562
54563/*
54564** Get/set the locking-mode for this pager. Parameter eMode must be one
54565** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
54566** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
54567** the locking-mode is set to the value specified.
54568**
54569** The returned value is either PAGER_LOCKINGMODE_NORMAL or
54570** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
54571** locking-mode.
54572*/
54573SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
54574  assert( eMode==PAGER_LOCKINGMODE_QUERY
54575            || eMode==PAGER_LOCKINGMODE_NORMAL
54576            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
54577  assert( PAGER_LOCKINGMODE_QUERY<0 );
54578  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
54579  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
54580  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
54581    pPager->exclusiveMode = (u8)eMode;
54582  }
54583  return (int)pPager->exclusiveMode;
54584}
54585
54586/*
54587** Set the journal-mode for this pager. Parameter eMode must be one of:
54588**
54589**    PAGER_JOURNALMODE_DELETE
54590**    PAGER_JOURNALMODE_TRUNCATE
54591**    PAGER_JOURNALMODE_PERSIST
54592**    PAGER_JOURNALMODE_OFF
54593**    PAGER_JOURNALMODE_MEMORY
54594**    PAGER_JOURNALMODE_WAL
54595**
54596** The journalmode is set to the value specified if the change is allowed.
54597** The change may be disallowed for the following reasons:
54598**
54599**   *  An in-memory database can only have its journal_mode set to _OFF
54600**      or _MEMORY.
54601**
54602**   *  Temporary databases cannot have _WAL journalmode.
54603**
54604** The returned indicate the current (possibly updated) journal-mode.
54605*/
54606SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
54607  u8 eOld = pPager->journalMode;    /* Prior journalmode */
54608
54609#ifdef SQLITE_DEBUG
54610  /* The print_pager_state() routine is intended to be used by the debugger
54611  ** only.  We invoke it once here to suppress a compiler warning. */
54612  print_pager_state(pPager);
54613#endif
54614
54615
54616  /* The eMode parameter is always valid */
54617  assert(      eMode==PAGER_JOURNALMODE_DELETE
54618            || eMode==PAGER_JOURNALMODE_TRUNCATE
54619            || eMode==PAGER_JOURNALMODE_PERSIST
54620            || eMode==PAGER_JOURNALMODE_OFF
54621            || eMode==PAGER_JOURNALMODE_WAL
54622            || eMode==PAGER_JOURNALMODE_MEMORY );
54623
54624  /* This routine is only called from the OP_JournalMode opcode, and
54625  ** the logic there will never allow a temporary file to be changed
54626  ** to WAL mode.
54627  */
54628  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
54629
54630  /* Do allow the journalmode of an in-memory database to be set to
54631  ** anything other than MEMORY or OFF
54632  */
54633  if( MEMDB ){
54634    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
54635    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
54636      eMode = eOld;
54637    }
54638  }
54639
54640  if( eMode!=eOld ){
54641
54642    /* Change the journal mode. */
54643    assert( pPager->eState!=PAGER_ERROR );
54644    pPager->journalMode = (u8)eMode;
54645
54646    /* When transistioning from TRUNCATE or PERSIST to any other journal
54647    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
54648    ** delete the journal file.
54649    */
54650    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
54651    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
54652    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
54653    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
54654    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
54655    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
54656
54657    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
54658    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
54659
54660      /* In this case we would like to delete the journal file. If it is
54661      ** not possible, then that is not a problem. Deleting the journal file
54662      ** here is an optimization only.
54663      **
54664      ** Before deleting the journal file, obtain a RESERVED lock on the
54665      ** database file. This ensures that the journal file is not deleted
54666      ** while it is in use by some other client.
54667      */
54668      sqlite3OsClose(pPager->jfd);
54669      if( pPager->eLock>=RESERVED_LOCK ){
54670        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
54671      }else{
54672        int rc = SQLITE_OK;
54673        int state = pPager->eState;
54674        assert( state==PAGER_OPEN || state==PAGER_READER );
54675        if( state==PAGER_OPEN ){
54676          rc = sqlite3PagerSharedLock(pPager);
54677        }
54678        if( pPager->eState==PAGER_READER ){
54679          assert( rc==SQLITE_OK );
54680          rc = pagerLockDb(pPager, RESERVED_LOCK);
54681        }
54682        if( rc==SQLITE_OK ){
54683          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
54684        }
54685        if( rc==SQLITE_OK && state==PAGER_READER ){
54686          pagerUnlockDb(pPager, SHARED_LOCK);
54687        }else if( state==PAGER_OPEN ){
54688          pager_unlock(pPager);
54689        }
54690        assert( state==pPager->eState );
54691      }
54692    }else if( eMode==PAGER_JOURNALMODE_OFF ){
54693      sqlite3OsClose(pPager->jfd);
54694    }
54695  }
54696
54697  /* Return the new journal mode */
54698  return (int)pPager->journalMode;
54699}
54700
54701/*
54702** Return the current journal mode.
54703*/
54704SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
54705  return (int)pPager->journalMode;
54706}
54707
54708/*
54709** Return TRUE if the pager is in a state where it is OK to change the
54710** journalmode.  Journalmode changes can only happen when the database
54711** is unmodified.
54712*/
54713SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
54714  assert( assert_pager_state(pPager) );
54715  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
54716  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
54717  return 1;
54718}
54719
54720/*
54721** Get/set the size-limit used for persistent journal files.
54722**
54723** Setting the size limit to -1 means no limit is enforced.
54724** An attempt to set a limit smaller than -1 is a no-op.
54725*/
54726SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
54727  if( iLimit>=-1 ){
54728    pPager->journalSizeLimit = iLimit;
54729    sqlite3WalLimit(pPager->pWal, iLimit);
54730  }
54731  return pPager->journalSizeLimit;
54732}
54733
54734/*
54735** Return a pointer to the pPager->pBackup variable. The backup module
54736** in backup.c maintains the content of this variable. This module
54737** uses it opaquely as an argument to sqlite3BackupRestart() and
54738** sqlite3BackupUpdate() only.
54739*/
54740SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
54741  return &pPager->pBackup;
54742}
54743
54744#ifndef SQLITE_OMIT_VACUUM
54745/*
54746** Unless this is an in-memory or temporary database, clear the pager cache.
54747*/
54748SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
54749  assert( MEMDB==0 || pPager->tempFile );
54750  if( pPager->tempFile==0 ) pager_reset(pPager);
54751}
54752#endif
54753
54754
54755#ifndef SQLITE_OMIT_WAL
54756/*
54757** This function is called when the user invokes "PRAGMA wal_checkpoint",
54758** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
54759** or wal_blocking_checkpoint() API functions.
54760**
54761** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
54762*/
54763SQLITE_PRIVATE int sqlite3PagerCheckpoint(
54764  Pager *pPager,                  /* Checkpoint on this pager */
54765  sqlite3 *db,                    /* Db handle used to check for interrupts */
54766  int eMode,                      /* Type of checkpoint */
54767  int *pnLog,                     /* OUT: Final number of frames in log */
54768  int *pnCkpt                     /* OUT: Final number of checkpointed frames */
54769){
54770  int rc = SQLITE_OK;
54771  if( pPager->pWal ){
54772    rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
54773        (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
54774        pPager->pBusyHandlerArg,
54775        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
54776        pnLog, pnCkpt
54777    );
54778  }
54779  return rc;
54780}
54781
54782SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
54783  return sqlite3WalCallback(pPager->pWal);
54784}
54785
54786/*
54787** Return true if the underlying VFS for the given pager supports the
54788** primitives necessary for write-ahead logging.
54789*/
54790SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
54791  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
54792  if( pPager->noLock ) return 0;
54793  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
54794}
54795
54796/*
54797** Attempt to take an exclusive lock on the database file. If a PENDING lock
54798** is obtained instead, immediately release it.
54799*/
54800static int pagerExclusiveLock(Pager *pPager){
54801  int rc;                         /* Return code */
54802
54803  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
54804  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
54805  if( rc!=SQLITE_OK ){
54806    /* If the attempt to grab the exclusive lock failed, release the
54807    ** pending lock that may have been obtained instead.  */
54808    pagerUnlockDb(pPager, SHARED_LOCK);
54809  }
54810
54811  return rc;
54812}
54813
54814/*
54815** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
54816** exclusive-locking mode when this function is called, take an EXCLUSIVE
54817** lock on the database file and use heap-memory to store the wal-index
54818** in. Otherwise, use the normal shared-memory.
54819*/
54820static int pagerOpenWal(Pager *pPager){
54821  int rc = SQLITE_OK;
54822
54823  assert( pPager->pWal==0 && pPager->tempFile==0 );
54824  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
54825
54826  /* If the pager is already in exclusive-mode, the WAL module will use
54827  ** heap-memory for the wal-index instead of the VFS shared-memory
54828  ** implementation. Take the exclusive lock now, before opening the WAL
54829  ** file, to make sure this is safe.
54830  */
54831  if( pPager->exclusiveMode ){
54832    rc = pagerExclusiveLock(pPager);
54833  }
54834
54835  /* Open the connection to the log file. If this operation fails,
54836  ** (e.g. due to malloc() failure), return an error code.
54837  */
54838  if( rc==SQLITE_OK ){
54839    rc = sqlite3WalOpen(pPager->pVfs,
54840        pPager->fd, pPager->zWal, pPager->exclusiveMode,
54841        pPager->journalSizeLimit, &pPager->pWal
54842    );
54843  }
54844  pagerFixMaplimit(pPager);
54845
54846  return rc;
54847}
54848
54849
54850/*
54851** The caller must be holding a SHARED lock on the database file to call
54852** this function.
54853**
54854** If the pager passed as the first argument is open on a real database
54855** file (not a temp file or an in-memory database), and the WAL file
54856** is not already open, make an attempt to open it now. If successful,
54857** return SQLITE_OK. If an error occurs or the VFS used by the pager does
54858** not support the xShmXXX() methods, return an error code. *pbOpen is
54859** not modified in either case.
54860**
54861** If the pager is open on a temp-file (or in-memory database), or if
54862** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
54863** without doing anything.
54864*/
54865SQLITE_PRIVATE int sqlite3PagerOpenWal(
54866  Pager *pPager,                  /* Pager object */
54867  int *pbOpen                     /* OUT: Set to true if call is a no-op */
54868){
54869  int rc = SQLITE_OK;             /* Return code */
54870
54871  assert( assert_pager_state(pPager) );
54872  assert( pPager->eState==PAGER_OPEN   || pbOpen );
54873  assert( pPager->eState==PAGER_READER || !pbOpen );
54874  assert( pbOpen==0 || *pbOpen==0 );
54875  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
54876
54877  if( !pPager->tempFile && !pPager->pWal ){
54878    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
54879
54880    /* Close any rollback journal previously open */
54881    sqlite3OsClose(pPager->jfd);
54882
54883    rc = pagerOpenWal(pPager);
54884    if( rc==SQLITE_OK ){
54885      pPager->journalMode = PAGER_JOURNALMODE_WAL;
54886      pPager->eState = PAGER_OPEN;
54887    }
54888  }else{
54889    *pbOpen = 1;
54890  }
54891
54892  return rc;
54893}
54894
54895/*
54896** This function is called to close the connection to the log file prior
54897** to switching from WAL to rollback mode.
54898**
54899** Before closing the log file, this function attempts to take an
54900** EXCLUSIVE lock on the database file. If this cannot be obtained, an
54901** error (SQLITE_BUSY) is returned and the log connection is not closed.
54902** If successful, the EXCLUSIVE lock is not released before returning.
54903*/
54904SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
54905  int rc = SQLITE_OK;
54906
54907  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
54908
54909  /* If the log file is not already open, but does exist in the file-system,
54910  ** it may need to be checkpointed before the connection can switch to
54911  ** rollback mode. Open it now so this can happen.
54912  */
54913  if( !pPager->pWal ){
54914    int logexists = 0;
54915    rc = pagerLockDb(pPager, SHARED_LOCK);
54916    if( rc==SQLITE_OK ){
54917      rc = sqlite3OsAccess(
54918          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
54919      );
54920    }
54921    if( rc==SQLITE_OK && logexists ){
54922      rc = pagerOpenWal(pPager);
54923    }
54924  }
54925
54926  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
54927  ** the database file, the log and log-summary files will be deleted.
54928  */
54929  if( rc==SQLITE_OK && pPager->pWal ){
54930    rc = pagerExclusiveLock(pPager);
54931    if( rc==SQLITE_OK ){
54932      rc = sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags,
54933                           pPager->pageSize, (u8*)pPager->pTmpSpace);
54934      pPager->pWal = 0;
54935      pagerFixMaplimit(pPager);
54936      if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
54937    }
54938  }
54939  return rc;
54940}
54941
54942#ifdef SQLITE_ENABLE_SNAPSHOT
54943/*
54944** If this is a WAL database, obtain a snapshot handle for the snapshot
54945** currently open. Otherwise, return an error.
54946*/
54947SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
54948  int rc = SQLITE_ERROR;
54949  if( pPager->pWal ){
54950    rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
54951  }
54952  return rc;
54953}
54954
54955/*
54956** If this is a WAL database, store a pointer to pSnapshot. Next time a
54957** read transaction is opened, attempt to read from the snapshot it
54958** identifies. If this is not a WAL database, return an error.
54959*/
54960SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
54961  int rc = SQLITE_OK;
54962  if( pPager->pWal ){
54963    sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
54964  }else{
54965    rc = SQLITE_ERROR;
54966  }
54967  return rc;
54968}
54969
54970/*
54971** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
54972** is not a WAL database, return an error.
54973*/
54974SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
54975  int rc;
54976  if( pPager->pWal ){
54977    rc = sqlite3WalSnapshotRecover(pPager->pWal);
54978  }else{
54979    rc = SQLITE_ERROR;
54980  }
54981  return rc;
54982}
54983#endif /* SQLITE_ENABLE_SNAPSHOT */
54984#endif /* !SQLITE_OMIT_WAL */
54985
54986#ifdef SQLITE_ENABLE_ZIPVFS
54987/*
54988** A read-lock must be held on the pager when this function is called. If
54989** the pager is in WAL mode and the WAL file currently contains one or more
54990** frames, return the size in bytes of the page images stored within the
54991** WAL frames. Otherwise, if this is not a WAL database or the WAL file
54992** is empty, return 0.
54993*/
54994SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
54995  assert( pPager->eState>=PAGER_READER );
54996  return sqlite3WalFramesize(pPager->pWal);
54997}
54998#endif
54999
55000#endif /* SQLITE_OMIT_DISKIO */
55001
55002/************** End of pager.c ***********************************************/
55003/************** Begin file wal.c *********************************************/
55004/*
55005** 2010 February 1
55006**
55007** The author disclaims copyright to this source code.  In place of
55008** a legal notice, here is a blessing:
55009**
55010**    May you do good and not evil.
55011**    May you find forgiveness for yourself and forgive others.
55012**    May you share freely, never taking more than you give.
55013**
55014*************************************************************************
55015**
55016** This file contains the implementation of a write-ahead log (WAL) used in
55017** "journal_mode=WAL" mode.
55018**
55019** WRITE-AHEAD LOG (WAL) FILE FORMAT
55020**
55021** A WAL file consists of a header followed by zero or more "frames".
55022** Each frame records the revised content of a single page from the
55023** database file.  All changes to the database are recorded by writing
55024** frames into the WAL.  Transactions commit when a frame is written that
55025** contains a commit marker.  A single WAL can and usually does record
55026** multiple transactions.  Periodically, the content of the WAL is
55027** transferred back into the database file in an operation called a
55028** "checkpoint".
55029**
55030** A single WAL file can be used multiple times.  In other words, the
55031** WAL can fill up with frames and then be checkpointed and then new
55032** frames can overwrite the old ones.  A WAL always grows from beginning
55033** toward the end.  Checksums and counters attached to each frame are
55034** used to determine which frames within the WAL are valid and which
55035** are leftovers from prior checkpoints.
55036**
55037** The WAL header is 32 bytes in size and consists of the following eight
55038** big-endian 32-bit unsigned integer values:
55039**
55040**     0: Magic number.  0x377f0682 or 0x377f0683
55041**     4: File format version.  Currently 3007000
55042**     8: Database page size.  Example: 1024
55043**    12: Checkpoint sequence number
55044**    16: Salt-1, random integer incremented with each checkpoint
55045**    20: Salt-2, a different random integer changing with each ckpt
55046**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
55047**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
55048**
55049** Immediately following the wal-header are zero or more frames. Each
55050** frame consists of a 24-byte frame-header followed by a <page-size> bytes
55051** of page data. The frame-header is six big-endian 32-bit unsigned
55052** integer values, as follows:
55053**
55054**     0: Page number.
55055**     4: For commit records, the size of the database image in pages
55056**        after the commit. For all other records, zero.
55057**     8: Salt-1 (copied from the header)
55058**    12: Salt-2 (copied from the header)
55059**    16: Checksum-1.
55060**    20: Checksum-2.
55061**
55062** A frame is considered valid if and only if the following conditions are
55063** true:
55064**
55065**    (1) The salt-1 and salt-2 values in the frame-header match
55066**        salt values in the wal-header
55067**
55068**    (2) The checksum values in the final 8 bytes of the frame-header
55069**        exactly match the checksum computed consecutively on the
55070**        WAL header and the first 8 bytes and the content of all frames
55071**        up to and including the current frame.
55072**
55073** The checksum is computed using 32-bit big-endian integers if the
55074** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
55075** is computed using little-endian if the magic number is 0x377f0682.
55076** The checksum values are always stored in the frame header in a
55077** big-endian format regardless of which byte order is used to compute
55078** the checksum.  The checksum is computed by interpreting the input as
55079** an even number of unsigned 32-bit integers: x[0] through x[N].  The
55080** algorithm used for the checksum is as follows:
55081**
55082**   for i from 0 to n-1 step 2:
55083**     s0 += x[i] + s1;
55084**     s1 += x[i+1] + s0;
55085**   endfor
55086**
55087** Note that s0 and s1 are both weighted checksums using fibonacci weights
55088** in reverse order (the largest fibonacci weight occurs on the first element
55089** of the sequence being summed.)  The s1 value spans all 32-bit
55090** terms of the sequence whereas s0 omits the final term.
55091**
55092** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
55093** WAL is transferred into the database, then the database is VFS.xSync-ed.
55094** The VFS.xSync operations serve as write barriers - all writes launched
55095** before the xSync must complete before any write that launches after the
55096** xSync begins.
55097**
55098** After each checkpoint, the salt-1 value is incremented and the salt-2
55099** value is randomized.  This prevents old and new frames in the WAL from
55100** being considered valid at the same time and being checkpointing together
55101** following a crash.
55102**
55103** READER ALGORITHM
55104**
55105** To read a page from the database (call it page number P), a reader
55106** first checks the WAL to see if it contains page P.  If so, then the
55107** last valid instance of page P that is a followed by a commit frame
55108** or is a commit frame itself becomes the value read.  If the WAL
55109** contains no copies of page P that are valid and which are a commit
55110** frame or are followed by a commit frame, then page P is read from
55111** the database file.
55112**
55113** To start a read transaction, the reader records the index of the last
55114** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
55115** for all subsequent read operations.  New transactions can be appended
55116** to the WAL, but as long as the reader uses its original mxFrame value
55117** and ignores the newly appended content, it will see a consistent snapshot
55118** of the database from a single point in time.  This technique allows
55119** multiple concurrent readers to view different versions of the database
55120** content simultaneously.
55121**
55122** The reader algorithm in the previous paragraphs works correctly, but
55123** because frames for page P can appear anywhere within the WAL, the
55124** reader has to scan the entire WAL looking for page P frames.  If the
55125** WAL is large (multiple megabytes is typical) that scan can be slow,
55126** and read performance suffers.  To overcome this problem, a separate
55127** data structure called the wal-index is maintained to expedite the
55128** search for frames of a particular page.
55129**
55130** WAL-INDEX FORMAT
55131**
55132** Conceptually, the wal-index is shared memory, though VFS implementations
55133** might choose to implement the wal-index using a mmapped file.  Because
55134** the wal-index is shared memory, SQLite does not support journal_mode=WAL
55135** on a network filesystem.  All users of the database must be able to
55136** share memory.
55137**
55138** The wal-index is transient.  After a crash, the wal-index can (and should
55139** be) reconstructed from the original WAL file.  In fact, the VFS is required
55140** to either truncate or zero the header of the wal-index when the last
55141** connection to it closes.  Because the wal-index is transient, it can
55142** use an architecture-specific format; it does not have to be cross-platform.
55143** Hence, unlike the database and WAL file formats which store all values
55144** as big endian, the wal-index can store multi-byte values in the native
55145** byte order of the host computer.
55146**
55147** The purpose of the wal-index is to answer this question quickly:  Given
55148** a page number P and a maximum frame index M, return the index of the
55149** last frame in the wal before frame M for page P in the WAL, or return
55150** NULL if there are no frames for page P in the WAL prior to M.
55151**
55152** The wal-index consists of a header region, followed by an one or
55153** more index blocks.
55154**
55155** The wal-index header contains the total number of frames within the WAL
55156** in the mxFrame field.
55157**
55158** Each index block except for the first contains information on
55159** HASHTABLE_NPAGE frames. The first index block contains information on
55160** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
55161** HASHTABLE_NPAGE are selected so that together the wal-index header and
55162** first index block are the same size as all other index blocks in the
55163** wal-index.
55164**
55165** Each index block contains two sections, a page-mapping that contains the
55166** database page number associated with each wal frame, and a hash-table
55167** that allows readers to query an index block for a specific page number.
55168** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
55169** for the first index block) 32-bit page numbers. The first entry in the
55170** first index-block contains the database page number corresponding to the
55171** first frame in the WAL file. The first entry in the second index block
55172** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
55173** the log, and so on.
55174**
55175** The last index block in a wal-index usually contains less than the full
55176** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
55177** depending on the contents of the WAL file. This does not change the
55178** allocated size of the page-mapping array - the page-mapping array merely
55179** contains unused entries.
55180**
55181** Even without using the hash table, the last frame for page P
55182** can be found by scanning the page-mapping sections of each index block
55183** starting with the last index block and moving toward the first, and
55184** within each index block, starting at the end and moving toward the
55185** beginning.  The first entry that equals P corresponds to the frame
55186** holding the content for that page.
55187**
55188** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
55189** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
55190** hash table for each page number in the mapping section, so the hash
55191** table is never more than half full.  The expected number of collisions
55192** prior to finding a match is 1.  Each entry of the hash table is an
55193** 1-based index of an entry in the mapping section of the same
55194** index block.   Let K be the 1-based index of the largest entry in
55195** the mapping section.  (For index blocks other than the last, K will
55196** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
55197** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
55198** contain a value of 0.
55199**
55200** To look for page P in the hash table, first compute a hash iKey on
55201** P as follows:
55202**
55203**      iKey = (P * 383) % HASHTABLE_NSLOT
55204**
55205** Then start scanning entries of the hash table, starting with iKey
55206** (wrapping around to the beginning when the end of the hash table is
55207** reached) until an unused hash slot is found. Let the first unused slot
55208** be at index iUnused.  (iUnused might be less than iKey if there was
55209** wrap-around.) Because the hash table is never more than half full,
55210** the search is guaranteed to eventually hit an unused entry.  Let
55211** iMax be the value between iKey and iUnused, closest to iUnused,
55212** where aHash[iMax]==P.  If there is no iMax entry (if there exists
55213** no hash slot such that aHash[i]==p) then page P is not in the
55214** current index block.  Otherwise the iMax-th mapping entry of the
55215** current index block corresponds to the last entry that references
55216** page P.
55217**
55218** A hash search begins with the last index block and moves toward the
55219** first index block, looking for entries corresponding to page P.  On
55220** average, only two or three slots in each index block need to be
55221** examined in order to either find the last entry for page P, or to
55222** establish that no such entry exists in the block.  Each index block
55223** holds over 4000 entries.  So two or three index blocks are sufficient
55224** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
55225** comparisons (on average) suffice to either locate a frame in the
55226** WAL or to establish that the frame does not exist in the WAL.  This
55227** is much faster than scanning the entire 10MB WAL.
55228**
55229** Note that entries are added in order of increasing K.  Hence, one
55230** reader might be using some value K0 and a second reader that started
55231** at a later time (after additional transactions were added to the WAL
55232** and to the wal-index) might be using a different value K1, where K1>K0.
55233** Both readers can use the same hash table and mapping section to get
55234** the correct result.  There may be entries in the hash table with
55235** K>K0 but to the first reader, those entries will appear to be unused
55236** slots in the hash table and so the first reader will get an answer as
55237** if no values greater than K0 had ever been inserted into the hash table
55238** in the first place - which is what reader one wants.  Meanwhile, the
55239** second reader using K1 will see additional values that were inserted
55240** later, which is exactly what reader two wants.
55241**
55242** When a rollback occurs, the value of K is decreased. Hash table entries
55243** that correspond to frames greater than the new K value are removed
55244** from the hash table at this point.
55245*/
55246#ifndef SQLITE_OMIT_WAL
55247
55248/* #include "wal.h" */
55249
55250/*
55251** Trace output macros
55252*/
55253#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
55254SQLITE_PRIVATE int sqlite3WalTrace = 0;
55255# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
55256#else
55257# define WALTRACE(X)
55258#endif
55259
55260/*
55261** The maximum (and only) versions of the wal and wal-index formats
55262** that may be interpreted by this version of SQLite.
55263**
55264** If a client begins recovering a WAL file and finds that (a) the checksum
55265** values in the wal-header are correct and (b) the version field is not
55266** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
55267**
55268** Similarly, if a client successfully reads a wal-index header (i.e. the
55269** checksum test is successful) and finds that the version field is not
55270** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
55271** returns SQLITE_CANTOPEN.
55272*/
55273#define WAL_MAX_VERSION      3007000
55274#define WALINDEX_MAX_VERSION 3007000
55275
55276/*
55277** Indices of various locking bytes.   WAL_NREADER is the number
55278** of available reader locks and should be at least 3.  The default
55279** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
55280*/
55281#define WAL_WRITE_LOCK         0
55282#define WAL_ALL_BUT_WRITE      1
55283#define WAL_CKPT_LOCK          1
55284#define WAL_RECOVER_LOCK       2
55285#define WAL_READ_LOCK(I)       (3+(I))
55286#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
55287
55288
55289/* Object declarations */
55290typedef struct WalIndexHdr WalIndexHdr;
55291typedef struct WalIterator WalIterator;
55292typedef struct WalCkptInfo WalCkptInfo;
55293
55294
55295/*
55296** The following object holds a copy of the wal-index header content.
55297**
55298** The actual header in the wal-index consists of two copies of this
55299** object followed by one instance of the WalCkptInfo object.
55300** For all versions of SQLite through 3.10.0 and probably beyond,
55301** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
55302** the total header size is 136 bytes.
55303**
55304** The szPage value can be any power of 2 between 512 and 32768, inclusive.
55305** Or it can be 1 to represent a 65536-byte page.  The latter case was
55306** added in 3.7.1 when support for 64K pages was added.
55307*/
55308struct WalIndexHdr {
55309  u32 iVersion;                   /* Wal-index version */
55310  u32 unused;                     /* Unused (padding) field */
55311  u32 iChange;                    /* Counter incremented each transaction */
55312  u8 isInit;                      /* 1 when initialized */
55313  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
55314  u16 szPage;                     /* Database page size in bytes. 1==64K */
55315  u32 mxFrame;                    /* Index of last valid frame in the WAL */
55316  u32 nPage;                      /* Size of database in pages */
55317  u32 aFrameCksum[2];             /* Checksum of last frame in log */
55318  u32 aSalt[2];                   /* Two salt values copied from WAL header */
55319  u32 aCksum[2];                  /* Checksum over all prior fields */
55320};
55321
55322/*
55323** A copy of the following object occurs in the wal-index immediately
55324** following the second copy of the WalIndexHdr.  This object stores
55325** information used by checkpoint.
55326**
55327** nBackfill is the number of frames in the WAL that have been written
55328** back into the database. (We call the act of moving content from WAL to
55329** database "backfilling".)  The nBackfill number is never greater than
55330** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
55331** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
55332** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
55333** mxFrame back to zero when the WAL is reset.
55334**
55335** nBackfillAttempted is the largest value of nBackfill that a checkpoint
55336** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
55337** the nBackfillAttempted is set before any backfilling is done and the
55338** nBackfill is only set after all backfilling completes.  So if a checkpoint
55339** crashes, nBackfillAttempted might be larger than nBackfill.  The
55340** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
55341**
55342** The aLock[] field is a set of bytes used for locking.  These bytes should
55343** never be read or written.
55344**
55345** There is one entry in aReadMark[] for each reader lock.  If a reader
55346** holds read-lock K, then the value in aReadMark[K] is no greater than
55347** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
55348** for any aReadMark[] means that entry is unused.  aReadMark[0] is
55349** a special case; its value is never used and it exists as a place-holder
55350** to avoid having to offset aReadMark[] indexs by one.  Readers holding
55351** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
55352** directly from the database.
55353**
55354** The value of aReadMark[K] may only be changed by a thread that
55355** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
55356** aReadMark[K] cannot changed while there is a reader is using that mark
55357** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
55358**
55359** The checkpointer may only transfer frames from WAL to database where
55360** the frame numbers are less than or equal to every aReadMark[] that is
55361** in use (that is, every aReadMark[j] for which there is a corresponding
55362** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
55363** largest value and will increase an unused aReadMark[] to mxFrame if there
55364** is not already an aReadMark[] equal to mxFrame.  The exception to the
55365** previous sentence is when nBackfill equals mxFrame (meaning that everything
55366** in the WAL has been backfilled into the database) then new readers
55367** will choose aReadMark[0] which has value 0 and hence such reader will
55368** get all their all content directly from the database file and ignore
55369** the WAL.
55370**
55371** Writers normally append new frames to the end of the WAL.  However,
55372** if nBackfill equals mxFrame (meaning that all WAL content has been
55373** written back into the database) and if no readers are using the WAL
55374** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
55375** the writer will first "reset" the WAL back to the beginning and start
55376** writing new content beginning at frame 1.
55377**
55378** We assume that 32-bit loads are atomic and so no locks are needed in
55379** order to read from any aReadMark[] entries.
55380*/
55381struct WalCkptInfo {
55382  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
55383  u32 aReadMark[WAL_NREADER];     /* Reader marks */
55384  u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
55385  u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
55386  u32 notUsed0;                   /* Available for future enhancements */
55387};
55388#define READMARK_NOT_USED  0xffffffff
55389
55390
55391/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
55392** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
55393** only support mandatory file-locks, we do not read or write data
55394** from the region of the file on which locks are applied.
55395*/
55396#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
55397#define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
55398
55399/* Size of header before each frame in wal */
55400#define WAL_FRAME_HDRSIZE 24
55401
55402/* Size of write ahead log header, including checksum. */
55403/* #define WAL_HDRSIZE 24 */
55404#define WAL_HDRSIZE 32
55405
55406/* WAL magic value. Either this value, or the same value with the least
55407** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
55408** big-endian format in the first 4 bytes of a WAL file.
55409**
55410** If the LSB is set, then the checksums for each frame within the WAL
55411** file are calculated by treating all data as an array of 32-bit
55412** big-endian words. Otherwise, they are calculated by interpreting
55413** all data as 32-bit little-endian words.
55414*/
55415#define WAL_MAGIC 0x377f0682
55416
55417/*
55418** Return the offset of frame iFrame in the write-ahead log file,
55419** assuming a database page size of szPage bytes. The offset returned
55420** is to the start of the write-ahead log frame-header.
55421*/
55422#define walFrameOffset(iFrame, szPage) (                               \
55423  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
55424)
55425
55426/*
55427** An open write-ahead log file is represented by an instance of the
55428** following object.
55429*/
55430struct Wal {
55431  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
55432  sqlite3_file *pDbFd;       /* File handle for the database file */
55433  sqlite3_file *pWalFd;      /* File handle for WAL file */
55434  u32 iCallback;             /* Value to pass to log callback (or 0) */
55435  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
55436  int nWiData;               /* Size of array apWiData */
55437  int szFirstBlock;          /* Size of first block written to WAL file */
55438  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
55439  u32 szPage;                /* Database page size */
55440  i16 readLock;              /* Which read lock is being held.  -1 for none */
55441  u8 syncFlags;              /* Flags to use to sync header writes */
55442  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
55443  u8 writeLock;              /* True if in a write transaction */
55444  u8 ckptLock;               /* True if holding a checkpoint lock */
55445  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
55446  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
55447  u8 syncHeader;             /* Fsync the WAL header if true */
55448  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
55449  WalIndexHdr hdr;           /* Wal-index header for current transaction */
55450  u32 minFrame;              /* Ignore wal frames before this one */
55451  u32 iReCksum;              /* On commit, recalculate checksums from here */
55452  const char *zWalName;      /* Name of WAL file */
55453  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
55454#ifdef SQLITE_DEBUG
55455  u8 lockError;              /* True if a locking error has occurred */
55456#endif
55457#ifdef SQLITE_ENABLE_SNAPSHOT
55458  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
55459#endif
55460};
55461
55462/*
55463** Candidate values for Wal.exclusiveMode.
55464*/
55465#define WAL_NORMAL_MODE     0
55466#define WAL_EXCLUSIVE_MODE  1
55467#define WAL_HEAPMEMORY_MODE 2
55468
55469/*
55470** Possible values for WAL.readOnly
55471*/
55472#define WAL_RDWR        0    /* Normal read/write connection */
55473#define WAL_RDONLY      1    /* The WAL file is readonly */
55474#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
55475
55476/*
55477** Each page of the wal-index mapping contains a hash-table made up of
55478** an array of HASHTABLE_NSLOT elements of the following type.
55479*/
55480typedef u16 ht_slot;
55481
55482/*
55483** This structure is used to implement an iterator that loops through
55484** all frames in the WAL in database page order. Where two or more frames
55485** correspond to the same database page, the iterator visits only the
55486** frame most recently written to the WAL (in other words, the frame with
55487** the largest index).
55488**
55489** The internals of this structure are only accessed by:
55490**
55491**   walIteratorInit() - Create a new iterator,
55492**   walIteratorNext() - Step an iterator,
55493**   walIteratorFree() - Free an iterator.
55494**
55495** This functionality is used by the checkpoint code (see walCheckpoint()).
55496*/
55497struct WalIterator {
55498  int iPrior;                     /* Last result returned from the iterator */
55499  int nSegment;                   /* Number of entries in aSegment[] */
55500  struct WalSegment {
55501    int iNext;                    /* Next slot in aIndex[] not yet returned */
55502    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
55503    u32 *aPgno;                   /* Array of page numbers. */
55504    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
55505    int iZero;                    /* Frame number associated with aPgno[0] */
55506  } aSegment[1];                  /* One for every 32KB page in the wal-index */
55507};
55508
55509/*
55510** Define the parameters of the hash tables in the wal-index file. There
55511** is a hash-table following every HASHTABLE_NPAGE page numbers in the
55512** wal-index.
55513**
55514** Changing any of these constants will alter the wal-index format and
55515** create incompatibilities.
55516*/
55517#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
55518#define HASHTABLE_HASH_1     383                  /* Should be prime */
55519#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
55520
55521/*
55522** The block of page numbers associated with the first hash-table in a
55523** wal-index is smaller than usual. This is so that there is a complete
55524** hash-table on each aligned 32KB page of the wal-index.
55525*/
55526#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
55527
55528/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
55529#define WALINDEX_PGSZ   (                                         \
55530    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
55531)
55532
55533/*
55534** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
55535** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
55536** numbered from zero.
55537**
55538** If this call is successful, *ppPage is set to point to the wal-index
55539** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
55540** then an SQLite error code is returned and *ppPage is set to 0.
55541*/
55542static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
55543  int rc = SQLITE_OK;
55544
55545  /* Enlarge the pWal->apWiData[] array if required */
55546  if( pWal->nWiData<=iPage ){
55547    int nByte = sizeof(u32*)*(iPage+1);
55548    volatile u32 **apNew;
55549    apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
55550    if( !apNew ){
55551      *ppPage = 0;
55552      return SQLITE_NOMEM_BKPT;
55553    }
55554    memset((void*)&apNew[pWal->nWiData], 0,
55555           sizeof(u32*)*(iPage+1-pWal->nWiData));
55556    pWal->apWiData = apNew;
55557    pWal->nWiData = iPage+1;
55558  }
55559
55560  /* Request a pointer to the required page from the VFS */
55561  if( pWal->apWiData[iPage]==0 ){
55562    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
55563      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
55564      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
55565    }else{
55566      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
55567          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
55568      );
55569      if( rc==SQLITE_READONLY ){
55570        pWal->readOnly |= WAL_SHM_RDONLY;
55571        rc = SQLITE_OK;
55572      }
55573    }
55574  }
55575
55576  *ppPage = pWal->apWiData[iPage];
55577  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
55578  return rc;
55579}
55580
55581/*
55582** Return a pointer to the WalCkptInfo structure in the wal-index.
55583*/
55584static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
55585  assert( pWal->nWiData>0 && pWal->apWiData[0] );
55586  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
55587}
55588
55589/*
55590** Return a pointer to the WalIndexHdr structure in the wal-index.
55591*/
55592static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
55593  assert( pWal->nWiData>0 && pWal->apWiData[0] );
55594  return (volatile WalIndexHdr*)pWal->apWiData[0];
55595}
55596
55597/*
55598** The argument to this macro must be of type u32. On a little-endian
55599** architecture, it returns the u32 value that results from interpreting
55600** the 4 bytes as a big-endian value. On a big-endian architecture, it
55601** returns the value that would be produced by interpreting the 4 bytes
55602** of the input value as a little-endian integer.
55603*/
55604#define BYTESWAP32(x) ( \
55605    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
55606  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
55607)
55608
55609/*
55610** Generate or extend an 8 byte checksum based on the data in
55611** array aByte[] and the initial values of aIn[0] and aIn[1] (or
55612** initial values of 0 and 0 if aIn==NULL).
55613**
55614** The checksum is written back into aOut[] before returning.
55615**
55616** nByte must be a positive multiple of 8.
55617*/
55618static void walChecksumBytes(
55619  int nativeCksum, /* True for native byte-order, false for non-native */
55620  u8 *a,           /* Content to be checksummed */
55621  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
55622  const u32 *aIn,  /* Initial checksum value input */
55623  u32 *aOut        /* OUT: Final checksum value output */
55624){
55625  u32 s1, s2;
55626  u32 *aData = (u32 *)a;
55627  u32 *aEnd = (u32 *)&a[nByte];
55628
55629  if( aIn ){
55630    s1 = aIn[0];
55631    s2 = aIn[1];
55632  }else{
55633    s1 = s2 = 0;
55634  }
55635
55636  assert( nByte>=8 );
55637  assert( (nByte&0x00000007)==0 );
55638
55639  if( nativeCksum ){
55640    do {
55641      s1 += *aData++ + s2;
55642      s2 += *aData++ + s1;
55643    }while( aData<aEnd );
55644  }else{
55645    do {
55646      s1 += BYTESWAP32(aData[0]) + s2;
55647      s2 += BYTESWAP32(aData[1]) + s1;
55648      aData += 2;
55649    }while( aData<aEnd );
55650  }
55651
55652  aOut[0] = s1;
55653  aOut[1] = s2;
55654}
55655
55656static void walShmBarrier(Wal *pWal){
55657  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
55658    sqlite3OsShmBarrier(pWal->pDbFd);
55659  }
55660}
55661
55662/*
55663** Write the header information in pWal->hdr into the wal-index.
55664**
55665** The checksum on pWal->hdr is updated before it is written.
55666*/
55667static void walIndexWriteHdr(Wal *pWal){
55668  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
55669  const int nCksum = offsetof(WalIndexHdr, aCksum);
55670
55671  assert( pWal->writeLock );
55672  pWal->hdr.isInit = 1;
55673  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
55674  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
55675  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
55676  walShmBarrier(pWal);
55677  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
55678}
55679
55680/*
55681** This function encodes a single frame header and writes it to a buffer
55682** supplied by the caller. A frame-header is made up of a series of
55683** 4-byte big-endian integers, as follows:
55684**
55685**     0: Page number.
55686**     4: For commit records, the size of the database image in pages
55687**        after the commit. For all other records, zero.
55688**     8: Salt-1 (copied from the wal-header)
55689**    12: Salt-2 (copied from the wal-header)
55690**    16: Checksum-1.
55691**    20: Checksum-2.
55692*/
55693static void walEncodeFrame(
55694  Wal *pWal,                      /* The write-ahead log */
55695  u32 iPage,                      /* Database page number for frame */
55696  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
55697  u8 *aData,                      /* Pointer to page data */
55698  u8 *aFrame                      /* OUT: Write encoded frame here */
55699){
55700  int nativeCksum;                /* True for native byte-order checksums */
55701  u32 *aCksum = pWal->hdr.aFrameCksum;
55702  assert( WAL_FRAME_HDRSIZE==24 );
55703  sqlite3Put4byte(&aFrame[0], iPage);
55704  sqlite3Put4byte(&aFrame[4], nTruncate);
55705  if( pWal->iReCksum==0 ){
55706    memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
55707
55708    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
55709    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
55710    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
55711
55712    sqlite3Put4byte(&aFrame[16], aCksum[0]);
55713    sqlite3Put4byte(&aFrame[20], aCksum[1]);
55714  }else{
55715    memset(&aFrame[8], 0, 16);
55716  }
55717}
55718
55719/*
55720** Check to see if the frame with header in aFrame[] and content
55721** in aData[] is valid.  If it is a valid frame, fill *piPage and
55722** *pnTruncate and return true.  Return if the frame is not valid.
55723*/
55724static int walDecodeFrame(
55725  Wal *pWal,                      /* The write-ahead log */
55726  u32 *piPage,                    /* OUT: Database page number for frame */
55727  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
55728  u8 *aData,                      /* Pointer to page data (for checksum) */
55729  u8 *aFrame                      /* Frame data */
55730){
55731  int nativeCksum;                /* True for native byte-order checksums */
55732  u32 *aCksum = pWal->hdr.aFrameCksum;
55733  u32 pgno;                       /* Page number of the frame */
55734  assert( WAL_FRAME_HDRSIZE==24 );
55735
55736  /* A frame is only valid if the salt values in the frame-header
55737  ** match the salt values in the wal-header.
55738  */
55739  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
55740    return 0;
55741  }
55742
55743  /* A frame is only valid if the page number is creater than zero.
55744  */
55745  pgno = sqlite3Get4byte(&aFrame[0]);
55746  if( pgno==0 ){
55747    return 0;
55748  }
55749
55750  /* A frame is only valid if a checksum of the WAL header,
55751  ** all prior frams, the first 16 bytes of this frame-header,
55752  ** and the frame-data matches the checksum in the last 8
55753  ** bytes of this frame-header.
55754  */
55755  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
55756  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
55757  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
55758  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
55759   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
55760  ){
55761    /* Checksum failed. */
55762    return 0;
55763  }
55764
55765  /* If we reach this point, the frame is valid.  Return the page number
55766  ** and the new database size.
55767  */
55768  *piPage = pgno;
55769  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
55770  return 1;
55771}
55772
55773
55774#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
55775/*
55776** Names of locks.  This routine is used to provide debugging output and is not
55777** a part of an ordinary build.
55778*/
55779static const char *walLockName(int lockIdx){
55780  if( lockIdx==WAL_WRITE_LOCK ){
55781    return "WRITE-LOCK";
55782  }else if( lockIdx==WAL_CKPT_LOCK ){
55783    return "CKPT-LOCK";
55784  }else if( lockIdx==WAL_RECOVER_LOCK ){
55785    return "RECOVER-LOCK";
55786  }else{
55787    static char zName[15];
55788    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
55789                     lockIdx-WAL_READ_LOCK(0));
55790    return zName;
55791  }
55792}
55793#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
55794
55795
55796/*
55797** Set or release locks on the WAL.  Locks are either shared or exclusive.
55798** A lock cannot be moved directly between shared and exclusive - it must go
55799** through the unlocked state first.
55800**
55801** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
55802*/
55803static int walLockShared(Wal *pWal, int lockIdx){
55804  int rc;
55805  if( pWal->exclusiveMode ) return SQLITE_OK;
55806  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
55807                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
55808  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
55809            walLockName(lockIdx), rc ? "failed" : "ok"));
55810  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
55811  return rc;
55812}
55813static void walUnlockShared(Wal *pWal, int lockIdx){
55814  if( pWal->exclusiveMode ) return;
55815  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
55816                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
55817  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
55818}
55819static int walLockExclusive(Wal *pWal, int lockIdx, int n){
55820  int rc;
55821  if( pWal->exclusiveMode ) return SQLITE_OK;
55822  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
55823                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
55824  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
55825            walLockName(lockIdx), n, rc ? "failed" : "ok"));
55826  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
55827  return rc;
55828}
55829static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
55830  if( pWal->exclusiveMode ) return;
55831  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
55832                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
55833  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
55834             walLockName(lockIdx), n));
55835}
55836
55837/*
55838** Compute a hash on a page number.  The resulting hash value must land
55839** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
55840** the hash to the next value in the event of a collision.
55841*/
55842static int walHash(u32 iPage){
55843  assert( iPage>0 );
55844  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
55845  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
55846}
55847static int walNextHash(int iPriorHash){
55848  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
55849}
55850
55851/*
55852** Return pointers to the hash table and page number array stored on
55853** page iHash of the wal-index. The wal-index is broken into 32KB pages
55854** numbered starting from 0.
55855**
55856** Set output variable *paHash to point to the start of the hash table
55857** in the wal-index file. Set *piZero to one less than the frame
55858** number of the first frame indexed by this hash table. If a
55859** slot in the hash table is set to N, it refers to frame number
55860** (*piZero+N) in the log.
55861**
55862** Finally, set *paPgno so that *paPgno[1] is the page number of the
55863** first frame indexed by the hash table, frame (*piZero+1).
55864*/
55865static int walHashGet(
55866  Wal *pWal,                      /* WAL handle */
55867  int iHash,                      /* Find the iHash'th table */
55868  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
55869  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
55870  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
55871){
55872  int rc;                         /* Return code */
55873  volatile u32 *aPgno;
55874
55875  rc = walIndexPage(pWal, iHash, &aPgno);
55876  assert( rc==SQLITE_OK || iHash>0 );
55877
55878  if( rc==SQLITE_OK ){
55879    u32 iZero;
55880    volatile ht_slot *aHash;
55881
55882    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
55883    if( iHash==0 ){
55884      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
55885      iZero = 0;
55886    }else{
55887      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
55888    }
55889
55890    *paPgno = &aPgno[-1];
55891    *paHash = aHash;
55892    *piZero = iZero;
55893  }
55894  return rc;
55895}
55896
55897/*
55898** Return the number of the wal-index page that contains the hash-table
55899** and page-number array that contain entries corresponding to WAL frame
55900** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
55901** are numbered starting from 0.
55902*/
55903static int walFramePage(u32 iFrame){
55904  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
55905  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
55906       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
55907       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
55908       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
55909       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
55910  );
55911  return iHash;
55912}
55913
55914/*
55915** Return the page number associated with frame iFrame in this WAL.
55916*/
55917static u32 walFramePgno(Wal *pWal, u32 iFrame){
55918  int iHash = walFramePage(iFrame);
55919  if( iHash==0 ){
55920    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
55921  }
55922  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
55923}
55924
55925/*
55926** Remove entries from the hash table that point to WAL slots greater
55927** than pWal->hdr.mxFrame.
55928**
55929** This function is called whenever pWal->hdr.mxFrame is decreased due
55930** to a rollback or savepoint.
55931**
55932** At most only the hash table containing pWal->hdr.mxFrame needs to be
55933** updated.  Any later hash tables will be automatically cleared when
55934** pWal->hdr.mxFrame advances to the point where those hash tables are
55935** actually needed.
55936*/
55937static void walCleanupHash(Wal *pWal){
55938  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
55939  volatile u32 *aPgno = 0;        /* Page number array for hash table */
55940  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
55941  int iLimit = 0;                 /* Zero values greater than this */
55942  int nByte;                      /* Number of bytes to zero in aPgno[] */
55943  int i;                          /* Used to iterate through aHash[] */
55944
55945  assert( pWal->writeLock );
55946  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
55947  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
55948  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
55949
55950  if( pWal->hdr.mxFrame==0 ) return;
55951
55952  /* Obtain pointers to the hash-table and page-number array containing
55953  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
55954  ** that the page said hash-table and array reside on is already mapped.
55955  */
55956  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
55957  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
55958  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
55959
55960  /* Zero all hash-table entries that correspond to frame numbers greater
55961  ** than pWal->hdr.mxFrame.
55962  */
55963  iLimit = pWal->hdr.mxFrame - iZero;
55964  assert( iLimit>0 );
55965  for(i=0; i<HASHTABLE_NSLOT; i++){
55966    if( aHash[i]>iLimit ){
55967      aHash[i] = 0;
55968    }
55969  }
55970
55971  /* Zero the entries in the aPgno array that correspond to frames with
55972  ** frame numbers greater than pWal->hdr.mxFrame.
55973  */
55974  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
55975  memset((void *)&aPgno[iLimit+1], 0, nByte);
55976
55977#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
55978  /* Verify that the every entry in the mapping region is still reachable
55979  ** via the hash table even after the cleanup.
55980  */
55981  if( iLimit ){
55982    int j;           /* Loop counter */
55983    int iKey;        /* Hash key */
55984    for(j=1; j<=iLimit; j++){
55985      for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
55986        if( aHash[iKey]==j ) break;
55987      }
55988      assert( aHash[iKey]==j );
55989    }
55990  }
55991#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
55992}
55993
55994
55995/*
55996** Set an entry in the wal-index that will map database page number
55997** pPage into WAL frame iFrame.
55998*/
55999static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
56000  int rc;                         /* Return code */
56001  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
56002  volatile u32 *aPgno = 0;        /* Page number array */
56003  volatile ht_slot *aHash = 0;    /* Hash table */
56004
56005  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
56006
56007  /* Assuming the wal-index file was successfully mapped, populate the
56008  ** page number array and hash table entry.
56009  */
56010  if( rc==SQLITE_OK ){
56011    int iKey;                     /* Hash table key */
56012    int idx;                      /* Value to write to hash-table slot */
56013    int nCollide;                 /* Number of hash collisions */
56014
56015    idx = iFrame - iZero;
56016    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
56017
56018    /* If this is the first entry to be added to this hash-table, zero the
56019    ** entire hash table and aPgno[] array before proceeding.
56020    */
56021    if( idx==1 ){
56022      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
56023      memset((void*)&aPgno[1], 0, nByte);
56024    }
56025
56026    /* If the entry in aPgno[] is already set, then the previous writer
56027    ** must have exited unexpectedly in the middle of a transaction (after
56028    ** writing one or more dirty pages to the WAL to free up memory).
56029    ** Remove the remnants of that writers uncommitted transaction from
56030    ** the hash-table before writing any new entries.
56031    */
56032    if( aPgno[idx] ){
56033      walCleanupHash(pWal);
56034      assert( !aPgno[idx] );
56035    }
56036
56037    /* Write the aPgno[] array entry and the hash-table slot. */
56038    nCollide = idx;
56039    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
56040      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
56041    }
56042    aPgno[idx] = iPage;
56043    aHash[iKey] = (ht_slot)idx;
56044
56045#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
56046    /* Verify that the number of entries in the hash table exactly equals
56047    ** the number of entries in the mapping region.
56048    */
56049    {
56050      int i;           /* Loop counter */
56051      int nEntry = 0;  /* Number of entries in the hash table */
56052      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
56053      assert( nEntry==idx );
56054    }
56055
56056    /* Verify that the every entry in the mapping region is reachable
56057    ** via the hash table.  This turns out to be a really, really expensive
56058    ** thing to check, so only do this occasionally - not on every
56059    ** iteration.
56060    */
56061    if( (idx&0x3ff)==0 ){
56062      int i;           /* Loop counter */
56063      for(i=1; i<=idx; i++){
56064        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
56065          if( aHash[iKey]==i ) break;
56066        }
56067        assert( aHash[iKey]==i );
56068      }
56069    }
56070#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
56071  }
56072
56073
56074  return rc;
56075}
56076
56077
56078/*
56079** Recover the wal-index by reading the write-ahead log file.
56080**
56081** This routine first tries to establish an exclusive lock on the
56082** wal-index to prevent other threads/processes from doing anything
56083** with the WAL or wal-index while recovery is running.  The
56084** WAL_RECOVER_LOCK is also held so that other threads will know
56085** that this thread is running recovery.  If unable to establish
56086** the necessary locks, this routine returns SQLITE_BUSY.
56087*/
56088static int walIndexRecover(Wal *pWal){
56089  int rc;                         /* Return Code */
56090  i64 nSize;                      /* Size of log file */
56091  u32 aFrameCksum[2] = {0, 0};
56092  int iLock;                      /* Lock offset to lock for checkpoint */
56093  int nLock;                      /* Number of locks to hold */
56094
56095  /* Obtain an exclusive lock on all byte in the locking range not already
56096  ** locked by the caller. The caller is guaranteed to have locked the
56097  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
56098  ** If successful, the same bytes that are locked here are unlocked before
56099  ** this function returns.
56100  */
56101  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
56102  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
56103  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
56104  assert( pWal->writeLock );
56105  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
56106  nLock = SQLITE_SHM_NLOCK - iLock;
56107  rc = walLockExclusive(pWal, iLock, nLock);
56108  if( rc ){
56109    return rc;
56110  }
56111  WALTRACE(("WAL%p: recovery begin...\n", pWal));
56112
56113  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
56114
56115  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
56116  if( rc!=SQLITE_OK ){
56117    goto recovery_error;
56118  }
56119
56120  if( nSize>WAL_HDRSIZE ){
56121    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
56122    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
56123    int szFrame;                  /* Number of bytes in buffer aFrame[] */
56124    u8 *aData;                    /* Pointer to data part of aFrame buffer */
56125    int iFrame;                   /* Index of last frame read */
56126    i64 iOffset;                  /* Next offset to read from log file */
56127    int szPage;                   /* Page size according to the log */
56128    u32 magic;                    /* Magic value read from WAL header */
56129    u32 version;                  /* Magic value read from WAL header */
56130    int isValid;                  /* True if this frame is valid */
56131
56132    /* Read in the WAL header. */
56133    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
56134    if( rc!=SQLITE_OK ){
56135      goto recovery_error;
56136    }
56137
56138    /* If the database page size is not a power of two, or is greater than
56139    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
56140    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
56141    ** WAL file.
56142    */
56143    magic = sqlite3Get4byte(&aBuf[0]);
56144    szPage = sqlite3Get4byte(&aBuf[8]);
56145    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
56146     || szPage&(szPage-1)
56147     || szPage>SQLITE_MAX_PAGE_SIZE
56148     || szPage<512
56149    ){
56150      goto finished;
56151    }
56152    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
56153    pWal->szPage = szPage;
56154    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
56155    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
56156
56157    /* Verify that the WAL header checksum is correct */
56158    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
56159        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
56160    );
56161    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
56162     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
56163    ){
56164      goto finished;
56165    }
56166
56167    /* Verify that the version number on the WAL format is one that
56168    ** are able to understand */
56169    version = sqlite3Get4byte(&aBuf[4]);
56170    if( version!=WAL_MAX_VERSION ){
56171      rc = SQLITE_CANTOPEN_BKPT;
56172      goto finished;
56173    }
56174
56175    /* Malloc a buffer to read frames into. */
56176    szFrame = szPage + WAL_FRAME_HDRSIZE;
56177    aFrame = (u8 *)sqlite3_malloc64(szFrame);
56178    if( !aFrame ){
56179      rc = SQLITE_NOMEM_BKPT;
56180      goto recovery_error;
56181    }
56182    aData = &aFrame[WAL_FRAME_HDRSIZE];
56183
56184    /* Read all frames from the log file. */
56185    iFrame = 0;
56186    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
56187      u32 pgno;                   /* Database page number for frame */
56188      u32 nTruncate;              /* dbsize field from frame header */
56189
56190      /* Read and decode the next log frame. */
56191      iFrame++;
56192      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
56193      if( rc!=SQLITE_OK ) break;
56194      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
56195      if( !isValid ) break;
56196      rc = walIndexAppend(pWal, iFrame, pgno);
56197      if( rc!=SQLITE_OK ) break;
56198
56199      /* If nTruncate is non-zero, this is a commit record. */
56200      if( nTruncate ){
56201        pWal->hdr.mxFrame = iFrame;
56202        pWal->hdr.nPage = nTruncate;
56203        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
56204        testcase( szPage<=32768 );
56205        testcase( szPage>=65536 );
56206        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
56207        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
56208      }
56209    }
56210
56211    sqlite3_free(aFrame);
56212  }
56213
56214finished:
56215  if( rc==SQLITE_OK ){
56216    volatile WalCkptInfo *pInfo;
56217    int i;
56218    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
56219    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
56220    walIndexWriteHdr(pWal);
56221
56222    /* Reset the checkpoint-header. This is safe because this thread is
56223    ** currently holding locks that exclude all other readers, writers and
56224    ** checkpointers.
56225    */
56226    pInfo = walCkptInfo(pWal);
56227    pInfo->nBackfill = 0;
56228    pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
56229    pInfo->aReadMark[0] = 0;
56230    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
56231    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
56232
56233    /* If more than one frame was recovered from the log file, report an
56234    ** event via sqlite3_log(). This is to help with identifying performance
56235    ** problems caused by applications routinely shutting down without
56236    ** checkpointing the log file.
56237    */
56238    if( pWal->hdr.nPage ){
56239      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
56240          "recovered %d frames from WAL file %s",
56241          pWal->hdr.mxFrame, pWal->zWalName
56242      );
56243    }
56244  }
56245
56246recovery_error:
56247  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
56248  walUnlockExclusive(pWal, iLock, nLock);
56249  return rc;
56250}
56251
56252/*
56253** Close an open wal-index.
56254*/
56255static void walIndexClose(Wal *pWal, int isDelete){
56256  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
56257    int i;
56258    for(i=0; i<pWal->nWiData; i++){
56259      sqlite3_free((void *)pWal->apWiData[i]);
56260      pWal->apWiData[i] = 0;
56261    }
56262  }else{
56263    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
56264  }
56265}
56266
56267/*
56268** Open a connection to the WAL file zWalName. The database file must
56269** already be opened on connection pDbFd. The buffer that zWalName points
56270** to must remain valid for the lifetime of the returned Wal* handle.
56271**
56272** A SHARED lock should be held on the database file when this function
56273** is called. The purpose of this SHARED lock is to prevent any other
56274** client from unlinking the WAL or wal-index file. If another process
56275** were to do this just after this client opened one of these files, the
56276** system would be badly broken.
56277**
56278** If the log file is successfully opened, SQLITE_OK is returned and
56279** *ppWal is set to point to a new WAL handle. If an error occurs,
56280** an SQLite error code is returned and *ppWal is left unmodified.
56281*/
56282SQLITE_PRIVATE int sqlite3WalOpen(
56283  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
56284  sqlite3_file *pDbFd,            /* The open database file */
56285  const char *zWalName,           /* Name of the WAL file */
56286  int bNoShm,                     /* True to run in heap-memory mode */
56287  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
56288  Wal **ppWal                     /* OUT: Allocated Wal handle */
56289){
56290  int rc;                         /* Return Code */
56291  Wal *pRet;                      /* Object to allocate and return */
56292  int flags;                      /* Flags passed to OsOpen() */
56293
56294  assert( zWalName && zWalName[0] );
56295  assert( pDbFd );
56296
56297  /* In the amalgamation, the os_unix.c and os_win.c source files come before
56298  ** this source file.  Verify that the #defines of the locking byte offsets
56299  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
56300  ** For that matter, if the lock offset ever changes from its initial design
56301  ** value of 120, we need to know that so there is an assert() to check it.
56302  */
56303  assert( 120==WALINDEX_LOCK_OFFSET );
56304  assert( 136==WALINDEX_HDR_SIZE );
56305#ifdef WIN_SHM_BASE
56306  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
56307#endif
56308#ifdef UNIX_SHM_BASE
56309  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
56310#endif
56311
56312
56313  /* Allocate an instance of struct Wal to return. */
56314  *ppWal = 0;
56315  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
56316  if( !pRet ){
56317    return SQLITE_NOMEM_BKPT;
56318  }
56319
56320  pRet->pVfs = pVfs;
56321  pRet->pWalFd = (sqlite3_file *)&pRet[1];
56322  pRet->pDbFd = pDbFd;
56323  pRet->readLock = -1;
56324  pRet->mxWalSize = mxWalSize;
56325  pRet->zWalName = zWalName;
56326  pRet->syncHeader = 1;
56327  pRet->padToSectorBoundary = 1;
56328  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
56329
56330  /* Open file handle on the write-ahead log file. */
56331  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
56332  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
56333  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
56334    pRet->readOnly = WAL_RDONLY;
56335  }
56336
56337  if( rc!=SQLITE_OK ){
56338    walIndexClose(pRet, 0);
56339    sqlite3OsClose(pRet->pWalFd);
56340    sqlite3_free(pRet);
56341  }else{
56342    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
56343    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
56344    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
56345      pRet->padToSectorBoundary = 0;
56346    }
56347    *ppWal = pRet;
56348    WALTRACE(("WAL%d: opened\n", pRet));
56349  }
56350  return rc;
56351}
56352
56353/*
56354** Change the size to which the WAL file is trucated on each reset.
56355*/
56356SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
56357  if( pWal ) pWal->mxWalSize = iLimit;
56358}
56359
56360/*
56361** Find the smallest page number out of all pages held in the WAL that
56362** has not been returned by any prior invocation of this method on the
56363** same WalIterator object.   Write into *piFrame the frame index where
56364** that page was last written into the WAL.  Write into *piPage the page
56365** number.
56366**
56367** Return 0 on success.  If there are no pages in the WAL with a page
56368** number larger than *piPage, then return 1.
56369*/
56370static int walIteratorNext(
56371  WalIterator *p,               /* Iterator */
56372  u32 *piPage,                  /* OUT: The page number of the next page */
56373  u32 *piFrame                  /* OUT: Wal frame index of next page */
56374){
56375  u32 iMin;                     /* Result pgno must be greater than iMin */
56376  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
56377  int i;                        /* For looping through segments */
56378
56379  iMin = p->iPrior;
56380  assert( iMin<0xffffffff );
56381  for(i=p->nSegment-1; i>=0; i--){
56382    struct WalSegment *pSegment = &p->aSegment[i];
56383    while( pSegment->iNext<pSegment->nEntry ){
56384      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
56385      if( iPg>iMin ){
56386        if( iPg<iRet ){
56387          iRet = iPg;
56388          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
56389        }
56390        break;
56391      }
56392      pSegment->iNext++;
56393    }
56394  }
56395
56396  *piPage = p->iPrior = iRet;
56397  return (iRet==0xFFFFFFFF);
56398}
56399
56400/*
56401** This function merges two sorted lists into a single sorted list.
56402**
56403** aLeft[] and aRight[] are arrays of indices.  The sort key is
56404** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
56405** is guaranteed for all J<K:
56406**
56407**        aContent[aLeft[J]] < aContent[aLeft[K]]
56408**        aContent[aRight[J]] < aContent[aRight[K]]
56409**
56410** This routine overwrites aRight[] with a new (probably longer) sequence
56411** of indices such that the aRight[] contains every index that appears in
56412** either aLeft[] or the old aRight[] and such that the second condition
56413** above is still met.
56414**
56415** The aContent[aLeft[X]] values will be unique for all X.  And the
56416** aContent[aRight[X]] values will be unique too.  But there might be
56417** one or more combinations of X and Y such that
56418**
56419**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
56420**
56421** When that happens, omit the aLeft[X] and use the aRight[Y] index.
56422*/
56423static void walMerge(
56424  const u32 *aContent,            /* Pages in wal - keys for the sort */
56425  ht_slot *aLeft,                 /* IN: Left hand input list */
56426  int nLeft,                      /* IN: Elements in array *paLeft */
56427  ht_slot **paRight,              /* IN/OUT: Right hand input list */
56428  int *pnRight,                   /* IN/OUT: Elements in *paRight */
56429  ht_slot *aTmp                   /* Temporary buffer */
56430){
56431  int iLeft = 0;                  /* Current index in aLeft */
56432  int iRight = 0;                 /* Current index in aRight */
56433  int iOut = 0;                   /* Current index in output buffer */
56434  int nRight = *pnRight;
56435  ht_slot *aRight = *paRight;
56436
56437  assert( nLeft>0 && nRight>0 );
56438  while( iRight<nRight || iLeft<nLeft ){
56439    ht_slot logpage;
56440    Pgno dbpage;
56441
56442    if( (iLeft<nLeft)
56443     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
56444    ){
56445      logpage = aLeft[iLeft++];
56446    }else{
56447      logpage = aRight[iRight++];
56448    }
56449    dbpage = aContent[logpage];
56450
56451    aTmp[iOut++] = logpage;
56452    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
56453
56454    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
56455    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
56456  }
56457
56458  *paRight = aLeft;
56459  *pnRight = iOut;
56460  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
56461}
56462
56463/*
56464** Sort the elements in list aList using aContent[] as the sort key.
56465** Remove elements with duplicate keys, preferring to keep the
56466** larger aList[] values.
56467**
56468** The aList[] entries are indices into aContent[].  The values in
56469** aList[] are to be sorted so that for all J<K:
56470**
56471**      aContent[aList[J]] < aContent[aList[K]]
56472**
56473** For any X and Y such that
56474**
56475**      aContent[aList[X]] == aContent[aList[Y]]
56476**
56477** Keep the larger of the two values aList[X] and aList[Y] and discard
56478** the smaller.
56479*/
56480static void walMergesort(
56481  const u32 *aContent,            /* Pages in wal */
56482  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
56483  ht_slot *aList,                 /* IN/OUT: List to sort */
56484  int *pnList                     /* IN/OUT: Number of elements in aList[] */
56485){
56486  struct Sublist {
56487    int nList;                    /* Number of elements in aList */
56488    ht_slot *aList;               /* Pointer to sub-list content */
56489  };
56490
56491  const int nList = *pnList;      /* Size of input list */
56492  int nMerge = 0;                 /* Number of elements in list aMerge */
56493  ht_slot *aMerge = 0;            /* List to be merged */
56494  int iList;                      /* Index into input list */
56495  u32 iSub = 0;                   /* Index into aSub array */
56496  struct Sublist aSub[13];        /* Array of sub-lists */
56497
56498  memset(aSub, 0, sizeof(aSub));
56499  assert( nList<=HASHTABLE_NPAGE && nList>0 );
56500  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
56501
56502  for(iList=0; iList<nList; iList++){
56503    nMerge = 1;
56504    aMerge = &aList[iList];
56505    for(iSub=0; iList & (1<<iSub); iSub++){
56506      struct Sublist *p;
56507      assert( iSub<ArraySize(aSub) );
56508      p = &aSub[iSub];
56509      assert( p->aList && p->nList<=(1<<iSub) );
56510      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
56511      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
56512    }
56513    aSub[iSub].aList = aMerge;
56514    aSub[iSub].nList = nMerge;
56515  }
56516
56517  for(iSub++; iSub<ArraySize(aSub); iSub++){
56518    if( nList & (1<<iSub) ){
56519      struct Sublist *p;
56520      assert( iSub<ArraySize(aSub) );
56521      p = &aSub[iSub];
56522      assert( p->nList<=(1<<iSub) );
56523      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
56524      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
56525    }
56526  }
56527  assert( aMerge==aList );
56528  *pnList = nMerge;
56529
56530#ifdef SQLITE_DEBUG
56531  {
56532    int i;
56533    for(i=1; i<*pnList; i++){
56534      assert( aContent[aList[i]] > aContent[aList[i-1]] );
56535    }
56536  }
56537#endif
56538}
56539
56540/*
56541** Free an iterator allocated by walIteratorInit().
56542*/
56543static void walIteratorFree(WalIterator *p){
56544  sqlite3_free(p);
56545}
56546
56547/*
56548** Construct a WalInterator object that can be used to loop over all
56549** pages in the WAL in ascending order. The caller must hold the checkpoint
56550** lock.
56551**
56552** On success, make *pp point to the newly allocated WalInterator object
56553** return SQLITE_OK. Otherwise, return an error code. If this routine
56554** returns an error, the value of *pp is undefined.
56555**
56556** The calling routine should invoke walIteratorFree() to destroy the
56557** WalIterator object when it has finished with it.
56558*/
56559static int walIteratorInit(Wal *pWal, WalIterator **pp){
56560  WalIterator *p;                 /* Return value */
56561  int nSegment;                   /* Number of segments to merge */
56562  u32 iLast;                      /* Last frame in log */
56563  int nByte;                      /* Number of bytes to allocate */
56564  int i;                          /* Iterator variable */
56565  ht_slot *aTmp;                  /* Temp space used by merge-sort */
56566  int rc = SQLITE_OK;             /* Return Code */
56567
56568  /* This routine only runs while holding the checkpoint lock. And
56569  ** it only runs if there is actually content in the log (mxFrame>0).
56570  */
56571  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
56572  iLast = pWal->hdr.mxFrame;
56573
56574  /* Allocate space for the WalIterator object. */
56575  nSegment = walFramePage(iLast) + 1;
56576  nByte = sizeof(WalIterator)
56577        + (nSegment-1)*sizeof(struct WalSegment)
56578        + iLast*sizeof(ht_slot);
56579  p = (WalIterator *)sqlite3_malloc64(nByte);
56580  if( !p ){
56581    return SQLITE_NOMEM_BKPT;
56582  }
56583  memset(p, 0, nByte);
56584  p->nSegment = nSegment;
56585
56586  /* Allocate temporary space used by the merge-sort routine. This block
56587  ** of memory will be freed before this function returns.
56588  */
56589  aTmp = (ht_slot *)sqlite3_malloc64(
56590      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
56591  );
56592  if( !aTmp ){
56593    rc = SQLITE_NOMEM_BKPT;
56594  }
56595
56596  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
56597    volatile ht_slot *aHash;
56598    u32 iZero;
56599    volatile u32 *aPgno;
56600
56601    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
56602    if( rc==SQLITE_OK ){
56603      int j;                      /* Counter variable */
56604      int nEntry;                 /* Number of entries in this segment */
56605      ht_slot *aIndex;            /* Sorted index for this segment */
56606
56607      aPgno++;
56608      if( (i+1)==nSegment ){
56609        nEntry = (int)(iLast - iZero);
56610      }else{
56611        nEntry = (int)((u32*)aHash - (u32*)aPgno);
56612      }
56613      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
56614      iZero++;
56615
56616      for(j=0; j<nEntry; j++){
56617        aIndex[j] = (ht_slot)j;
56618      }
56619      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
56620      p->aSegment[i].iZero = iZero;
56621      p->aSegment[i].nEntry = nEntry;
56622      p->aSegment[i].aIndex = aIndex;
56623      p->aSegment[i].aPgno = (u32 *)aPgno;
56624    }
56625  }
56626  sqlite3_free(aTmp);
56627
56628  if( rc!=SQLITE_OK ){
56629    walIteratorFree(p);
56630  }
56631  *pp = p;
56632  return rc;
56633}
56634
56635/*
56636** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
56637** n. If the attempt fails and parameter xBusy is not NULL, then it is a
56638** busy-handler function. Invoke it and retry the lock until either the
56639** lock is successfully obtained or the busy-handler returns 0.
56640*/
56641static int walBusyLock(
56642  Wal *pWal,                      /* WAL connection */
56643  int (*xBusy)(void*),            /* Function to call when busy */
56644  void *pBusyArg,                 /* Context argument for xBusyHandler */
56645  int lockIdx,                    /* Offset of first byte to lock */
56646  int n                           /* Number of bytes to lock */
56647){
56648  int rc;
56649  do {
56650    rc = walLockExclusive(pWal, lockIdx, n);
56651  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
56652  return rc;
56653}
56654
56655/*
56656** The cache of the wal-index header must be valid to call this function.
56657** Return the page-size in bytes used by the database.
56658*/
56659static int walPagesize(Wal *pWal){
56660  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
56661}
56662
56663/*
56664** The following is guaranteed when this function is called:
56665**
56666**   a) the WRITER lock is held,
56667**   b) the entire log file has been checkpointed, and
56668**   c) any existing readers are reading exclusively from the database
56669**      file - there are no readers that may attempt to read a frame from
56670**      the log file.
56671**
56672** This function updates the shared-memory structures so that the next
56673** client to write to the database (which may be this one) does so by
56674** writing frames into the start of the log file.
56675**
56676** The value of parameter salt1 is used as the aSalt[1] value in the
56677** new wal-index header. It should be passed a pseudo-random value (i.e.
56678** one obtained from sqlite3_randomness()).
56679*/
56680static void walRestartHdr(Wal *pWal, u32 salt1){
56681  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56682  int i;                          /* Loop counter */
56683  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
56684  pWal->nCkpt++;
56685  pWal->hdr.mxFrame = 0;
56686  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
56687  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
56688  walIndexWriteHdr(pWal);
56689  pInfo->nBackfill = 0;
56690  pInfo->nBackfillAttempted = 0;
56691  pInfo->aReadMark[1] = 0;
56692  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
56693  assert( pInfo->aReadMark[0]==0 );
56694}
56695
56696/*
56697** Copy as much content as we can from the WAL back into the database file
56698** in response to an sqlite3_wal_checkpoint() request or the equivalent.
56699**
56700** The amount of information copies from WAL to database might be limited
56701** by active readers.  This routine will never overwrite a database page
56702** that a concurrent reader might be using.
56703**
56704** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
56705** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
56706** checkpoints are always run by a background thread or background
56707** process, foreground threads will never block on a lengthy fsync call.
56708**
56709** Fsync is called on the WAL before writing content out of the WAL and
56710** into the database.  This ensures that if the new content is persistent
56711** in the WAL and can be recovered following a power-loss or hard reset.
56712**
56713** Fsync is also called on the database file if (and only if) the entire
56714** WAL content is copied into the database file.  This second fsync makes
56715** it safe to delete the WAL since the new content will persist in the
56716** database file.
56717**
56718** This routine uses and updates the nBackfill field of the wal-index header.
56719** This is the only routine that will increase the value of nBackfill.
56720** (A WAL reset or recovery will revert nBackfill to zero, but not increase
56721** its value.)
56722**
56723** The caller must be holding sufficient locks to ensure that no other
56724** checkpoint is running (in any other thread or process) at the same
56725** time.
56726*/
56727static int walCheckpoint(
56728  Wal *pWal,                      /* Wal connection */
56729  sqlite3 *db,                    /* Check for interrupts on this handle */
56730  int eMode,                      /* One of PASSIVE, FULL or RESTART */
56731  int (*xBusy)(void*),            /* Function to call when busy */
56732  void *pBusyArg,                 /* Context argument for xBusyHandler */
56733  int sync_flags,                 /* Flags for OsSync() (or 0) */
56734  u8 *zBuf                        /* Temporary buffer to use */
56735){
56736  int rc = SQLITE_OK;             /* Return code */
56737  int szPage;                     /* Database page-size */
56738  WalIterator *pIter = 0;         /* Wal iterator context */
56739  u32 iDbpage = 0;                /* Next database page to write */
56740  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
56741  u32 mxSafeFrame;                /* Max frame that can be backfilled */
56742  u32 mxPage;                     /* Max database page to write */
56743  int i;                          /* Loop counter */
56744  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
56745
56746  szPage = walPagesize(pWal);
56747  testcase( szPage<=32768 );
56748  testcase( szPage>=65536 );
56749  pInfo = walCkptInfo(pWal);
56750  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
56751
56752    /* Allocate the iterator */
56753    rc = walIteratorInit(pWal, &pIter);
56754    if( rc!=SQLITE_OK ){
56755      return rc;
56756    }
56757    assert( pIter );
56758
56759    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
56760    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
56761    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
56762
56763    /* Compute in mxSafeFrame the index of the last frame of the WAL that is
56764    ** safe to write into the database.  Frames beyond mxSafeFrame might
56765    ** overwrite database pages that are in use by active readers and thus
56766    ** cannot be backfilled from the WAL.
56767    */
56768    mxSafeFrame = pWal->hdr.mxFrame;
56769    mxPage = pWal->hdr.nPage;
56770    for(i=1; i<WAL_NREADER; i++){
56771      /* Thread-sanitizer reports that the following is an unsafe read,
56772      ** as some other thread may be in the process of updating the value
56773      ** of the aReadMark[] slot. The assumption here is that if that is
56774      ** happening, the other client may only be increasing the value,
56775      ** not decreasing it. So assuming either that either the "old" or
56776      ** "new" version of the value is read, and not some arbitrary value
56777      ** that would never be written by a real client, things are still
56778      ** safe.  */
56779      u32 y = pInfo->aReadMark[i];
56780      if( mxSafeFrame>y ){
56781        assert( y<=pWal->hdr.mxFrame );
56782        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
56783        if( rc==SQLITE_OK ){
56784          pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
56785          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
56786        }else if( rc==SQLITE_BUSY ){
56787          mxSafeFrame = y;
56788          xBusy = 0;
56789        }else{
56790          goto walcheckpoint_out;
56791        }
56792      }
56793    }
56794
56795    if( pInfo->nBackfill<mxSafeFrame
56796     && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
56797    ){
56798      i64 nSize;                    /* Current size of database file */
56799      u32 nBackfill = pInfo->nBackfill;
56800
56801      pInfo->nBackfillAttempted = mxSafeFrame;
56802
56803      /* Sync the WAL to disk */
56804      if( sync_flags ){
56805        rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
56806      }
56807
56808      /* If the database may grow as a result of this checkpoint, hint
56809      ** about the eventual size of the db file to the VFS layer.
56810      */
56811      if( rc==SQLITE_OK ){
56812        i64 nReq = ((i64)mxPage * szPage);
56813        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
56814        if( rc==SQLITE_OK && nSize<nReq ){
56815          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
56816        }
56817      }
56818
56819
56820      /* Iterate through the contents of the WAL, copying data to the db file */
56821      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
56822        i64 iOffset;
56823        assert( walFramePgno(pWal, iFrame)==iDbpage );
56824        if( db->u1.isInterrupted ){
56825          rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
56826          break;
56827        }
56828        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
56829          continue;
56830        }
56831        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
56832        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
56833        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
56834        if( rc!=SQLITE_OK ) break;
56835        iOffset = (iDbpage-1)*(i64)szPage;
56836        testcase( IS_BIG_INT(iOffset) );
56837        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
56838        if( rc!=SQLITE_OK ) break;
56839      }
56840
56841      /* If work was actually accomplished... */
56842      if( rc==SQLITE_OK ){
56843        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
56844          i64 szDb = pWal->hdr.nPage*(i64)szPage;
56845          testcase( IS_BIG_INT(szDb) );
56846          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
56847          if( rc==SQLITE_OK && sync_flags ){
56848            rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
56849          }
56850        }
56851        if( rc==SQLITE_OK ){
56852          pInfo->nBackfill = mxSafeFrame;
56853        }
56854      }
56855
56856      /* Release the reader lock held while backfilling */
56857      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
56858    }
56859
56860    if( rc==SQLITE_BUSY ){
56861      /* Reset the return code so as not to report a checkpoint failure
56862      ** just because there are active readers.  */
56863      rc = SQLITE_OK;
56864    }
56865  }
56866
56867  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
56868  ** entire wal file has been copied into the database file, then block
56869  ** until all readers have finished using the wal file. This ensures that
56870  ** the next process to write to the database restarts the wal file.
56871  */
56872  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
56873    assert( pWal->writeLock );
56874    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
56875      rc = SQLITE_BUSY;
56876    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
56877      u32 salt1;
56878      sqlite3_randomness(4, &salt1);
56879      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56880      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
56881      if( rc==SQLITE_OK ){
56882        if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
56883          /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
56884          ** SQLITE_CHECKPOINT_RESTART with the addition that it also
56885          ** truncates the log file to zero bytes just prior to a
56886          ** successful return.
56887          **
56888          ** In theory, it might be safe to do this without updating the
56889          ** wal-index header in shared memory, as all subsequent reader or
56890          ** writer clients should see that the entire log file has been
56891          ** checkpointed and behave accordingly. This seems unsafe though,
56892          ** as it would leave the system in a state where the contents of
56893          ** the wal-index header do not match the contents of the
56894          ** file-system. To avoid this, update the wal-index header to
56895          ** indicate that the log file contains zero valid frames.  */
56896          walRestartHdr(pWal, salt1);
56897          rc = sqlite3OsTruncate(pWal->pWalFd, 0);
56898        }
56899        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56900      }
56901    }
56902  }
56903
56904 walcheckpoint_out:
56905  walIteratorFree(pIter);
56906  return rc;
56907}
56908
56909/*
56910** If the WAL file is currently larger than nMax bytes in size, truncate
56911** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
56912*/
56913static void walLimitSize(Wal *pWal, i64 nMax){
56914  i64 sz;
56915  int rx;
56916  sqlite3BeginBenignMalloc();
56917  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
56918  if( rx==SQLITE_OK && (sz > nMax ) ){
56919    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
56920  }
56921  sqlite3EndBenignMalloc();
56922  if( rx ){
56923    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
56924  }
56925}
56926
56927/*
56928** Close a connection to a log file.
56929*/
56930SQLITE_PRIVATE int sqlite3WalClose(
56931  Wal *pWal,                      /* Wal to close */
56932  sqlite3 *db,                    /* For interrupt flag */
56933  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
56934  int nBuf,
56935  u8 *zBuf                        /* Buffer of at least nBuf bytes */
56936){
56937  int rc = SQLITE_OK;
56938  if( pWal ){
56939    int isDelete = 0;             /* True to unlink wal and wal-index files */
56940
56941    /* If an EXCLUSIVE lock can be obtained on the database file (using the
56942    ** ordinary, rollback-mode locking methods, this guarantees that the
56943    ** connection associated with this log file is the only connection to
56944    ** the database. In this case checkpoint the database and unlink both
56945    ** the wal and wal-index files.
56946    **
56947    ** The EXCLUSIVE lock is not released before returning.
56948    */
56949    if( zBuf!=0
56950     && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
56951    ){
56952      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
56953        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
56954      }
56955      rc = sqlite3WalCheckpoint(pWal, db,
56956          SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
56957      );
56958      if( rc==SQLITE_OK ){
56959        int bPersist = -1;
56960        sqlite3OsFileControlHint(
56961            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
56962        );
56963        if( bPersist!=1 ){
56964          /* Try to delete the WAL file if the checkpoint completed and
56965          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
56966          ** mode (!bPersist) */
56967          isDelete = 1;
56968        }else if( pWal->mxWalSize>=0 ){
56969          /* Try to truncate the WAL file to zero bytes if the checkpoint
56970          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
56971          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
56972          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
56973          ** to zero bytes as truncating to the journal_size_limit might
56974          ** leave a corrupt WAL file on disk. */
56975          walLimitSize(pWal, 0);
56976        }
56977      }
56978    }
56979
56980    walIndexClose(pWal, isDelete);
56981    sqlite3OsClose(pWal->pWalFd);
56982    if( isDelete ){
56983      sqlite3BeginBenignMalloc();
56984      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
56985      sqlite3EndBenignMalloc();
56986    }
56987    WALTRACE(("WAL%p: closed\n", pWal));
56988    sqlite3_free((void *)pWal->apWiData);
56989    sqlite3_free(pWal);
56990  }
56991  return rc;
56992}
56993
56994/*
56995** Try to read the wal-index header.  Return 0 on success and 1 if
56996** there is a problem.
56997**
56998** The wal-index is in shared memory.  Another thread or process might
56999** be writing the header at the same time this procedure is trying to
57000** read it, which might result in inconsistency.  A dirty read is detected
57001** by verifying that both copies of the header are the same and also by
57002** a checksum on the header.
57003**
57004** If and only if the read is consistent and the header is different from
57005** pWal->hdr, then pWal->hdr is updated to the content of the new header
57006** and *pChanged is set to 1.
57007**
57008** If the checksum cannot be verified return non-zero. If the header
57009** is read successfully and the checksum verified, return zero.
57010*/
57011static int walIndexTryHdr(Wal *pWal, int *pChanged){
57012  u32 aCksum[2];                  /* Checksum on the header content */
57013  WalIndexHdr h1, h2;             /* Two copies of the header content */
57014  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
57015
57016  /* The first page of the wal-index must be mapped at this point. */
57017  assert( pWal->nWiData>0 && pWal->apWiData[0] );
57018
57019  /* Read the header. This might happen concurrently with a write to the
57020  ** same area of shared memory on a different CPU in a SMP,
57021  ** meaning it is possible that an inconsistent snapshot is read
57022  ** from the file. If this happens, return non-zero.
57023  **
57024  ** There are two copies of the header at the beginning of the wal-index.
57025  ** When reading, read [0] first then [1].  Writes are in the reverse order.
57026  ** Memory barriers are used to prevent the compiler or the hardware from
57027  ** reordering the reads and writes.
57028  */
57029  aHdr = walIndexHdr(pWal);
57030  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
57031  walShmBarrier(pWal);
57032  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
57033
57034  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
57035    return 1;   /* Dirty read */
57036  }
57037  if( h1.isInit==0 ){
57038    return 1;   /* Malformed header - probably all zeros */
57039  }
57040  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
57041  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
57042    return 1;   /* Checksum does not match */
57043  }
57044
57045  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
57046    *pChanged = 1;
57047    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
57048    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
57049    testcase( pWal->szPage<=32768 );
57050    testcase( pWal->szPage>=65536 );
57051  }
57052
57053  /* The header was successfully read. Return zero. */
57054  return 0;
57055}
57056
57057/*
57058** Read the wal-index header from the wal-index and into pWal->hdr.
57059** If the wal-header appears to be corrupt, try to reconstruct the
57060** wal-index from the WAL before returning.
57061**
57062** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
57063** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
57064** to 0.
57065**
57066** If the wal-index header is successfully read, return SQLITE_OK.
57067** Otherwise an SQLite error code.
57068*/
57069static int walIndexReadHdr(Wal *pWal, int *pChanged){
57070  int rc;                         /* Return code */
57071  int badHdr;                     /* True if a header read failed */
57072  volatile u32 *page0;            /* Chunk of wal-index containing header */
57073
57074  /* Ensure that page 0 of the wal-index (the page that contains the
57075  ** wal-index header) is mapped. Return early if an error occurs here.
57076  */
57077  assert( pChanged );
57078  rc = walIndexPage(pWal, 0, &page0);
57079  if( rc!=SQLITE_OK ){
57080    return rc;
57081  };
57082  assert( page0 || pWal->writeLock==0 );
57083
57084  /* If the first page of the wal-index has been mapped, try to read the
57085  ** wal-index header immediately, without holding any lock. This usually
57086  ** works, but may fail if the wal-index header is corrupt or currently
57087  ** being modified by another thread or process.
57088  */
57089  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
57090
57091  /* If the first attempt failed, it might have been due to a race
57092  ** with a writer.  So get a WRITE lock and try again.
57093  */
57094  assert( badHdr==0 || pWal->writeLock==0 );
57095  if( badHdr ){
57096    if( pWal->readOnly & WAL_SHM_RDONLY ){
57097      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
57098        walUnlockShared(pWal, WAL_WRITE_LOCK);
57099        rc = SQLITE_READONLY_RECOVERY;
57100      }
57101    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
57102      pWal->writeLock = 1;
57103      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
57104        badHdr = walIndexTryHdr(pWal, pChanged);
57105        if( badHdr ){
57106          /* If the wal-index header is still malformed even while holding
57107          ** a WRITE lock, it can only mean that the header is corrupted and
57108          ** needs to be reconstructed.  So run recovery to do exactly that.
57109          */
57110          rc = walIndexRecover(pWal);
57111          *pChanged = 1;
57112        }
57113      }
57114      pWal->writeLock = 0;
57115      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
57116    }
57117  }
57118
57119  /* If the header is read successfully, check the version number to make
57120  ** sure the wal-index was not constructed with some future format that
57121  ** this version of SQLite cannot understand.
57122  */
57123  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
57124    rc = SQLITE_CANTOPEN_BKPT;
57125  }
57126
57127  return rc;
57128}
57129
57130/*
57131** This is the value that walTryBeginRead returns when it needs to
57132** be retried.
57133*/
57134#define WAL_RETRY  (-1)
57135
57136/*
57137** Attempt to start a read transaction.  This might fail due to a race or
57138** other transient condition.  When that happens, it returns WAL_RETRY to
57139** indicate to the caller that it is safe to retry immediately.
57140**
57141** On success return SQLITE_OK.  On a permanent failure (such an
57142** I/O error or an SQLITE_BUSY because another process is running
57143** recovery) return a positive error code.
57144**
57145** The useWal parameter is true to force the use of the WAL and disable
57146** the case where the WAL is bypassed because it has been completely
57147** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
57148** to make a copy of the wal-index header into pWal->hdr.  If the
57149** wal-index header has changed, *pChanged is set to 1 (as an indication
57150** to the caller that the local paget cache is obsolete and needs to be
57151** flushed.)  When useWal==1, the wal-index header is assumed to already
57152** be loaded and the pChanged parameter is unused.
57153**
57154** The caller must set the cnt parameter to the number of prior calls to
57155** this routine during the current read attempt that returned WAL_RETRY.
57156** This routine will start taking more aggressive measures to clear the
57157** race conditions after multiple WAL_RETRY returns, and after an excessive
57158** number of errors will ultimately return SQLITE_PROTOCOL.  The
57159** SQLITE_PROTOCOL return indicates that some other process has gone rogue
57160** and is not honoring the locking protocol.  There is a vanishingly small
57161** chance that SQLITE_PROTOCOL could be returned because of a run of really
57162** bad luck when there is lots of contention for the wal-index, but that
57163** possibility is so small that it can be safely neglected, we believe.
57164**
57165** On success, this routine obtains a read lock on
57166** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
57167** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
57168** that means the Wal does not hold any read lock.  The reader must not
57169** access any database page that is modified by a WAL frame up to and
57170** including frame number aReadMark[pWal->readLock].  The reader will
57171** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
57172** Or if pWal->readLock==0, then the reader will ignore the WAL
57173** completely and get all content directly from the database file.
57174** If the useWal parameter is 1 then the WAL will never be ignored and
57175** this routine will always set pWal->readLock>0 on success.
57176** When the read transaction is completed, the caller must release the
57177** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
57178**
57179** This routine uses the nBackfill and aReadMark[] fields of the header
57180** to select a particular WAL_READ_LOCK() that strives to let the
57181** checkpoint process do as much work as possible.  This routine might
57182** update values of the aReadMark[] array in the header, but if it does
57183** so it takes care to hold an exclusive lock on the corresponding
57184** WAL_READ_LOCK() while changing values.
57185*/
57186static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
57187  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
57188  u32 mxReadMark;                 /* Largest aReadMark[] value */
57189  int mxI;                        /* Index of largest aReadMark[] value */
57190  int i;                          /* Loop counter */
57191  int rc = SQLITE_OK;             /* Return code  */
57192  u32 mxFrame;                    /* Wal frame to lock to */
57193
57194  assert( pWal->readLock<0 );     /* Not currently locked */
57195
57196  /* Take steps to avoid spinning forever if there is a protocol error.
57197  **
57198  ** Circumstances that cause a RETRY should only last for the briefest
57199  ** instances of time.  No I/O or other system calls are done while the
57200  ** locks are held, so the locks should not be held for very long. But
57201  ** if we are unlucky, another process that is holding a lock might get
57202  ** paged out or take a page-fault that is time-consuming to resolve,
57203  ** during the few nanoseconds that it is holding the lock.  In that case,
57204  ** it might take longer than normal for the lock to free.
57205  **
57206  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
57207  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
57208  ** is more of a scheduler yield than an actual delay.  But on the 10th
57209  ** an subsequent retries, the delays start becoming longer and longer,
57210  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
57211  ** The total delay time before giving up is less than 10 seconds.
57212  */
57213  if( cnt>5 ){
57214    int nDelay = 1;                      /* Pause time in microseconds */
57215    if( cnt>100 ){
57216      VVA_ONLY( pWal->lockError = 1; )
57217      return SQLITE_PROTOCOL;
57218    }
57219    if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
57220    sqlite3OsSleep(pWal->pVfs, nDelay);
57221  }
57222
57223  if( !useWal ){
57224    rc = walIndexReadHdr(pWal, pChanged);
57225    if( rc==SQLITE_BUSY ){
57226      /* If there is not a recovery running in another thread or process
57227      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
57228      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
57229      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
57230      ** would be technically correct.  But the race is benign since with
57231      ** WAL_RETRY this routine will be called again and will probably be
57232      ** right on the second iteration.
57233      */
57234      if( pWal->apWiData[0]==0 ){
57235        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
57236        ** We assume this is a transient condition, so return WAL_RETRY. The
57237        ** xShmMap() implementation used by the default unix and win32 VFS
57238        ** modules may return SQLITE_BUSY due to a race condition in the
57239        ** code that determines whether or not the shared-memory region
57240        ** must be zeroed before the requested page is returned.
57241        */
57242        rc = WAL_RETRY;
57243      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
57244        walUnlockShared(pWal, WAL_RECOVER_LOCK);
57245        rc = WAL_RETRY;
57246      }else if( rc==SQLITE_BUSY ){
57247        rc = SQLITE_BUSY_RECOVERY;
57248      }
57249    }
57250    if( rc!=SQLITE_OK ){
57251      return rc;
57252    }
57253  }
57254
57255  pInfo = walCkptInfo(pWal);
57256  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
57257#ifdef SQLITE_ENABLE_SNAPSHOT
57258   && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
57259     || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
57260#endif
57261  ){
57262    /* The WAL has been completely backfilled (or it is empty).
57263    ** and can be safely ignored.
57264    */
57265    rc = walLockShared(pWal, WAL_READ_LOCK(0));
57266    walShmBarrier(pWal);
57267    if( rc==SQLITE_OK ){
57268      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
57269        /* It is not safe to allow the reader to continue here if frames
57270        ** may have been appended to the log before READ_LOCK(0) was obtained.
57271        ** When holding READ_LOCK(0), the reader ignores the entire log file,
57272        ** which implies that the database file contains a trustworthy
57273        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
57274        ** happening, this is usually correct.
57275        **
57276        ** However, if frames have been appended to the log (or if the log
57277        ** is wrapped and written for that matter) before the READ_LOCK(0)
57278        ** is obtained, that is not necessarily true. A checkpointer may
57279        ** have started to backfill the appended frames but crashed before
57280        ** it finished. Leaving a corrupt image in the database file.
57281        */
57282        walUnlockShared(pWal, WAL_READ_LOCK(0));
57283        return WAL_RETRY;
57284      }
57285      pWal->readLock = 0;
57286      return SQLITE_OK;
57287    }else if( rc!=SQLITE_BUSY ){
57288      return rc;
57289    }
57290  }
57291
57292  /* If we get this far, it means that the reader will want to use
57293  ** the WAL to get at content from recent commits.  The job now is
57294  ** to select one of the aReadMark[] entries that is closest to
57295  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
57296  */
57297  mxReadMark = 0;
57298  mxI = 0;
57299  mxFrame = pWal->hdr.mxFrame;
57300#ifdef SQLITE_ENABLE_SNAPSHOT
57301  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
57302    mxFrame = pWal->pSnapshot->mxFrame;
57303  }
57304#endif
57305  for(i=1; i<WAL_NREADER; i++){
57306    u32 thisMark = pInfo->aReadMark[i];
57307    if( mxReadMark<=thisMark && thisMark<=mxFrame ){
57308      assert( thisMark!=READMARK_NOT_USED );
57309      mxReadMark = thisMark;
57310      mxI = i;
57311    }
57312  }
57313  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
57314   && (mxReadMark<mxFrame || mxI==0)
57315  ){
57316    for(i=1; i<WAL_NREADER; i++){
57317      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
57318      if( rc==SQLITE_OK ){
57319        mxReadMark = pInfo->aReadMark[i] = mxFrame;
57320        mxI = i;
57321        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
57322        break;
57323      }else if( rc!=SQLITE_BUSY ){
57324        return rc;
57325      }
57326    }
57327  }
57328  if( mxI==0 ){
57329    assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
57330    return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
57331  }
57332
57333  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
57334  if( rc ){
57335    return rc==SQLITE_BUSY ? WAL_RETRY : rc;
57336  }
57337  /* Now that the read-lock has been obtained, check that neither the
57338  ** value in the aReadMark[] array or the contents of the wal-index
57339  ** header have changed.
57340  **
57341  ** It is necessary to check that the wal-index header did not change
57342  ** between the time it was read and when the shared-lock was obtained
57343  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
57344  ** that the log file may have been wrapped by a writer, or that frames
57345  ** that occur later in the log than pWal->hdr.mxFrame may have been
57346  ** copied into the database by a checkpointer. If either of these things
57347  ** happened, then reading the database with the current value of
57348  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
57349  ** instead.
57350  **
57351  ** Before checking that the live wal-index header has not changed
57352  ** since it was read, set Wal.minFrame to the first frame in the wal
57353  ** file that has not yet been checkpointed. This client will not need
57354  ** to read any frames earlier than minFrame from the wal file - they
57355  ** can be safely read directly from the database file.
57356  **
57357  ** Because a ShmBarrier() call is made between taking the copy of
57358  ** nBackfill and checking that the wal-header in shared-memory still
57359  ** matches the one cached in pWal->hdr, it is guaranteed that the
57360  ** checkpointer that set nBackfill was not working with a wal-index
57361  ** header newer than that cached in pWal->hdr. If it were, that could
57362  ** cause a problem. The checkpointer could omit to checkpoint
57363  ** a version of page X that lies before pWal->minFrame (call that version
57364  ** A) on the basis that there is a newer version (version B) of the same
57365  ** page later in the wal file. But if version B happens to like past
57366  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
57367  ** that it can read version A from the database file. However, since
57368  ** we can guarantee that the checkpointer that set nBackfill could not
57369  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
57370  */
57371  pWal->minFrame = pInfo->nBackfill+1;
57372  walShmBarrier(pWal);
57373  if( pInfo->aReadMark[mxI]!=mxReadMark
57374   || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
57375  ){
57376    walUnlockShared(pWal, WAL_READ_LOCK(mxI));
57377    return WAL_RETRY;
57378  }else{
57379    assert( mxReadMark<=pWal->hdr.mxFrame );
57380    pWal->readLock = (i16)mxI;
57381  }
57382  return rc;
57383}
57384
57385#ifdef SQLITE_ENABLE_SNAPSHOT
57386/*
57387** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
57388** variable so that older snapshots can be accessed. To do this, loop
57389** through all wal frames from nBackfillAttempted to (nBackfill+1),
57390** comparing their content to the corresponding page with the database
57391** file, if any. Set nBackfillAttempted to the frame number of the
57392** first frame for which the wal file content matches the db file.
57393**
57394** This is only really safe if the file-system is such that any page
57395** writes made by earlier checkpointers were atomic operations, which
57396** is not always true. It is also possible that nBackfillAttempted
57397** may be left set to a value larger than expected, if a wal frame
57398** contains content that duplicate of an earlier version of the same
57399** page.
57400**
57401** SQLITE_OK is returned if successful, or an SQLite error code if an
57402** error occurs. It is not an error if nBackfillAttempted cannot be
57403** decreased at all.
57404*/
57405SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
57406  int rc;
57407
57408  assert( pWal->readLock>=0 );
57409  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
57410  if( rc==SQLITE_OK ){
57411    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
57412    int szPage = (int)pWal->szPage;
57413    i64 szDb;                   /* Size of db file in bytes */
57414
57415    rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
57416    if( rc==SQLITE_OK ){
57417      void *pBuf1 = sqlite3_malloc(szPage);
57418      void *pBuf2 = sqlite3_malloc(szPage);
57419      if( pBuf1==0 || pBuf2==0 ){
57420        rc = SQLITE_NOMEM;
57421      }else{
57422        u32 i = pInfo->nBackfillAttempted;
57423        for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
57424          volatile ht_slot *dummy;
57425          volatile u32 *aPgno;      /* Array of page numbers */
57426          u32 iZero;                /* Frame corresponding to aPgno[0] */
57427          u32 pgno;                 /* Page number in db file */
57428          i64 iDbOff;               /* Offset of db file entry */
57429          i64 iWalOff;              /* Offset of wal file entry */
57430
57431          rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
57432          if( rc!=SQLITE_OK ) break;
57433          pgno = aPgno[i-iZero];
57434          iDbOff = (i64)(pgno-1) * szPage;
57435
57436          if( iDbOff+szPage<=szDb ){
57437            iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
57438            rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
57439
57440            if( rc==SQLITE_OK ){
57441              rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
57442            }
57443
57444            if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
57445              break;
57446            }
57447          }
57448
57449          pInfo->nBackfillAttempted = i-1;
57450        }
57451      }
57452
57453      sqlite3_free(pBuf1);
57454      sqlite3_free(pBuf2);
57455    }
57456    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
57457  }
57458
57459  return rc;
57460}
57461#endif /* SQLITE_ENABLE_SNAPSHOT */
57462
57463/*
57464** Begin a read transaction on the database.
57465**
57466** This routine used to be called sqlite3OpenSnapshot() and with good reason:
57467** it takes a snapshot of the state of the WAL and wal-index for the current
57468** instant in time.  The current thread will continue to use this snapshot.
57469** Other threads might append new content to the WAL and wal-index but
57470** that extra content is ignored by the current thread.
57471**
57472** If the database contents have changes since the previous read
57473** transaction, then *pChanged is set to 1 before returning.  The
57474** Pager layer will use this to know that is cache is stale and
57475** needs to be flushed.
57476*/
57477SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
57478  int rc;                         /* Return code */
57479  int cnt = 0;                    /* Number of TryBeginRead attempts */
57480
57481#ifdef SQLITE_ENABLE_SNAPSHOT
57482  int bChanged = 0;
57483  WalIndexHdr *pSnapshot = pWal->pSnapshot;
57484  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
57485    bChanged = 1;
57486  }
57487#endif
57488
57489  do{
57490    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
57491  }while( rc==WAL_RETRY );
57492  testcase( (rc&0xff)==SQLITE_BUSY );
57493  testcase( (rc&0xff)==SQLITE_IOERR );
57494  testcase( rc==SQLITE_PROTOCOL );
57495  testcase( rc==SQLITE_OK );
57496
57497#ifdef SQLITE_ENABLE_SNAPSHOT
57498  if( rc==SQLITE_OK ){
57499    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
57500      /* At this point the client has a lock on an aReadMark[] slot holding
57501      ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
57502      ** is populated with the wal-index header corresponding to the head
57503      ** of the wal file. Verify that pSnapshot is still valid before
57504      ** continuing.  Reasons why pSnapshot might no longer be valid:
57505      **
57506      **    (1)  The WAL file has been reset since the snapshot was taken.
57507      **         In this case, the salt will have changed.
57508      **
57509      **    (2)  A checkpoint as been attempted that wrote frames past
57510      **         pSnapshot->mxFrame into the database file.  Note that the
57511      **         checkpoint need not have completed for this to cause problems.
57512      */
57513      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
57514
57515      assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
57516      assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
57517
57518      /* It is possible that there is a checkpointer thread running
57519      ** concurrent with this code. If this is the case, it may be that the
57520      ** checkpointer has already determined that it will checkpoint
57521      ** snapshot X, where X is later in the wal file than pSnapshot, but
57522      ** has not yet set the pInfo->nBackfillAttempted variable to indicate
57523      ** its intent. To avoid the race condition this leads to, ensure that
57524      ** there is no checkpointer process by taking a shared CKPT lock
57525      ** before checking pInfo->nBackfillAttempted.
57526      **
57527      ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
57528      **       this already?
57529      */
57530      rc = walLockShared(pWal, WAL_CKPT_LOCK);
57531
57532      if( rc==SQLITE_OK ){
57533        /* Check that the wal file has not been wrapped. Assuming that it has
57534        ** not, also check that no checkpointer has attempted to checkpoint any
57535        ** frames beyond pSnapshot->mxFrame. If either of these conditions are
57536        ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
57537        ** with *pSnapshot and set *pChanged as appropriate for opening the
57538        ** snapshot.  */
57539        if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
57540         && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
57541        ){
57542          assert( pWal->readLock>0 );
57543          memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
57544          *pChanged = bChanged;
57545        }else{
57546          rc = SQLITE_BUSY_SNAPSHOT;
57547        }
57548
57549        /* Release the shared CKPT lock obtained above. */
57550        walUnlockShared(pWal, WAL_CKPT_LOCK);
57551      }
57552
57553
57554      if( rc!=SQLITE_OK ){
57555        sqlite3WalEndReadTransaction(pWal);
57556      }
57557    }
57558  }
57559#endif
57560  return rc;
57561}
57562
57563/*
57564** Finish with a read transaction.  All this does is release the
57565** read-lock.
57566*/
57567SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
57568  sqlite3WalEndWriteTransaction(pWal);
57569  if( pWal->readLock>=0 ){
57570    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
57571    pWal->readLock = -1;
57572  }
57573}
57574
57575/*
57576** Search the wal file for page pgno. If found, set *piRead to the frame that
57577** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
57578** to zero.
57579**
57580** Return SQLITE_OK if successful, or an error code if an error occurs. If an
57581** error does occur, the final value of *piRead is undefined.
57582*/
57583SQLITE_PRIVATE int sqlite3WalFindFrame(
57584  Wal *pWal,                      /* WAL handle */
57585  Pgno pgno,                      /* Database page number to read data for */
57586  u32 *piRead                     /* OUT: Frame number (or zero) */
57587){
57588  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
57589  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
57590  int iHash;                      /* Used to loop through N hash tables */
57591  int iMinHash;
57592
57593  /* This routine is only be called from within a read transaction. */
57594  assert( pWal->readLock>=0 || pWal->lockError );
57595
57596  /* If the "last page" field of the wal-index header snapshot is 0, then
57597  ** no data will be read from the wal under any circumstances. Return early
57598  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
57599  ** then the WAL is ignored by the reader so return early, as if the
57600  ** WAL were empty.
57601  */
57602  if( iLast==0 || pWal->readLock==0 ){
57603    *piRead = 0;
57604    return SQLITE_OK;
57605  }
57606
57607  /* Search the hash table or tables for an entry matching page number
57608  ** pgno. Each iteration of the following for() loop searches one
57609  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
57610  **
57611  ** This code might run concurrently to the code in walIndexAppend()
57612  ** that adds entries to the wal-index (and possibly to this hash
57613  ** table). This means the value just read from the hash
57614  ** slot (aHash[iKey]) may have been added before or after the
57615  ** current read transaction was opened. Values added after the
57616  ** read transaction was opened may have been written incorrectly -
57617  ** i.e. these slots may contain garbage data. However, we assume
57618  ** that any slots written before the current read transaction was
57619  ** opened remain unmodified.
57620  **
57621  ** For the reasons above, the if(...) condition featured in the inner
57622  ** loop of the following block is more stringent that would be required
57623  ** if we had exclusive access to the hash-table:
57624  **
57625  **   (aPgno[iFrame]==pgno):
57626  **     This condition filters out normal hash-table collisions.
57627  **
57628  **   (iFrame<=iLast):
57629  **     This condition filters out entries that were added to the hash
57630  **     table after the current read-transaction had started.
57631  */
57632  iMinHash = walFramePage(pWal->minFrame);
57633  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
57634    volatile ht_slot *aHash;      /* Pointer to hash table */
57635    volatile u32 *aPgno;          /* Pointer to array of page numbers */
57636    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
57637    int iKey;                     /* Hash slot index */
57638    int nCollide;                 /* Number of hash collisions remaining */
57639    int rc;                       /* Error code */
57640
57641    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
57642    if( rc!=SQLITE_OK ){
57643      return rc;
57644    }
57645    nCollide = HASHTABLE_NSLOT;
57646    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
57647      u32 iFrame = aHash[iKey] + iZero;
57648      if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
57649        assert( iFrame>iRead || CORRUPT_DB );
57650        iRead = iFrame;
57651      }
57652      if( (nCollide--)==0 ){
57653        return SQLITE_CORRUPT_BKPT;
57654      }
57655    }
57656  }
57657
57658#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
57659  /* If expensive assert() statements are available, do a linear search
57660  ** of the wal-index file content. Make sure the results agree with the
57661  ** result obtained using the hash indexes above.  */
57662  {
57663    u32 iRead2 = 0;
57664    u32 iTest;
57665    assert( pWal->minFrame>0 );
57666    for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
57667      if( walFramePgno(pWal, iTest)==pgno ){
57668        iRead2 = iTest;
57669        break;
57670      }
57671    }
57672    assert( iRead==iRead2 );
57673  }
57674#endif
57675
57676  *piRead = iRead;
57677  return SQLITE_OK;
57678}
57679
57680/*
57681** Read the contents of frame iRead from the wal file into buffer pOut
57682** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
57683** error code otherwise.
57684*/
57685SQLITE_PRIVATE int sqlite3WalReadFrame(
57686  Wal *pWal,                      /* WAL handle */
57687  u32 iRead,                      /* Frame to read */
57688  int nOut,                       /* Size of buffer pOut in bytes */
57689  u8 *pOut                        /* Buffer to write page data to */
57690){
57691  int sz;
57692  i64 iOffset;
57693  sz = pWal->hdr.szPage;
57694  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
57695  testcase( sz<=32768 );
57696  testcase( sz>=65536 );
57697  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
57698  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
57699  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
57700}
57701
57702/*
57703** Return the size of the database in pages (or zero, if unknown).
57704*/
57705SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
57706  if( pWal && ALWAYS(pWal->readLock>=0) ){
57707    return pWal->hdr.nPage;
57708  }
57709  return 0;
57710}
57711
57712
57713/*
57714** This function starts a write transaction on the WAL.
57715**
57716** A read transaction must have already been started by a prior call
57717** to sqlite3WalBeginReadTransaction().
57718**
57719** If another thread or process has written into the database since
57720** the read transaction was started, then it is not possible for this
57721** thread to write as doing so would cause a fork.  So this routine
57722** returns SQLITE_BUSY in that case and no write transaction is started.
57723**
57724** There can only be a single writer active at a time.
57725*/
57726SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
57727  int rc;
57728
57729  /* Cannot start a write transaction without first holding a read
57730  ** transaction. */
57731  assert( pWal->readLock>=0 );
57732  assert( pWal->writeLock==0 && pWal->iReCksum==0 );
57733
57734  if( pWal->readOnly ){
57735    return SQLITE_READONLY;
57736  }
57737
57738  /* Only one writer allowed at a time.  Get the write lock.  Return
57739  ** SQLITE_BUSY if unable.
57740  */
57741  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
57742  if( rc ){
57743    return rc;
57744  }
57745  pWal->writeLock = 1;
57746
57747  /* If another connection has written to the database file since the
57748  ** time the read transaction on this connection was started, then
57749  ** the write is disallowed.
57750  */
57751  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
57752    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
57753    pWal->writeLock = 0;
57754    rc = SQLITE_BUSY_SNAPSHOT;
57755  }
57756
57757  return rc;
57758}
57759
57760/*
57761** End a write transaction.  The commit has already been done.  This
57762** routine merely releases the lock.
57763*/
57764SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
57765  if( pWal->writeLock ){
57766    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
57767    pWal->writeLock = 0;
57768    pWal->iReCksum = 0;
57769    pWal->truncateOnCommit = 0;
57770  }
57771  return SQLITE_OK;
57772}
57773
57774/*
57775** If any data has been written (but not committed) to the log file, this
57776** function moves the write-pointer back to the start of the transaction.
57777**
57778** Additionally, the callback function is invoked for each frame written
57779** to the WAL since the start of the transaction. If the callback returns
57780** other than SQLITE_OK, it is not invoked again and the error code is
57781** returned to the caller.
57782**
57783** Otherwise, if the callback function does not return an error, this
57784** function returns SQLITE_OK.
57785*/
57786SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
57787  int rc = SQLITE_OK;
57788  if( ALWAYS(pWal->writeLock) ){
57789    Pgno iMax = pWal->hdr.mxFrame;
57790    Pgno iFrame;
57791
57792    /* Restore the clients cache of the wal-index header to the state it
57793    ** was in before the client began writing to the database.
57794    */
57795    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
57796
57797    for(iFrame=pWal->hdr.mxFrame+1;
57798        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
57799        iFrame++
57800    ){
57801      /* This call cannot fail. Unless the page for which the page number
57802      ** is passed as the second argument is (a) in the cache and
57803      ** (b) has an outstanding reference, then xUndo is either a no-op
57804      ** (if (a) is false) or simply expels the page from the cache (if (b)
57805      ** is false).
57806      **
57807      ** If the upper layer is doing a rollback, it is guaranteed that there
57808      ** are no outstanding references to any page other than page 1. And
57809      ** page 1 is never written to the log until the transaction is
57810      ** committed. As a result, the call to xUndo may not fail.
57811      */
57812      assert( walFramePgno(pWal, iFrame)!=1 );
57813      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
57814    }
57815    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
57816  }
57817  return rc;
57818}
57819
57820/*
57821** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
57822** values. This function populates the array with values required to
57823** "rollback" the write position of the WAL handle back to the current
57824** point in the event of a savepoint rollback (via WalSavepointUndo()).
57825*/
57826SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
57827  assert( pWal->writeLock );
57828  aWalData[0] = pWal->hdr.mxFrame;
57829  aWalData[1] = pWal->hdr.aFrameCksum[0];
57830  aWalData[2] = pWal->hdr.aFrameCksum[1];
57831  aWalData[3] = pWal->nCkpt;
57832}
57833
57834/*
57835** Move the write position of the WAL back to the point identified by
57836** the values in the aWalData[] array. aWalData must point to an array
57837** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
57838** by a call to WalSavepoint().
57839*/
57840SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
57841  int rc = SQLITE_OK;
57842
57843  assert( pWal->writeLock );
57844  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
57845
57846  if( aWalData[3]!=pWal->nCkpt ){
57847    /* This savepoint was opened immediately after the write-transaction
57848    ** was started. Right after that, the writer decided to wrap around
57849    ** to the start of the log. Update the savepoint values to match.
57850    */
57851    aWalData[0] = 0;
57852    aWalData[3] = pWal->nCkpt;
57853  }
57854
57855  if( aWalData[0]<pWal->hdr.mxFrame ){
57856    pWal->hdr.mxFrame = aWalData[0];
57857    pWal->hdr.aFrameCksum[0] = aWalData[1];
57858    pWal->hdr.aFrameCksum[1] = aWalData[2];
57859    walCleanupHash(pWal);
57860  }
57861
57862  return rc;
57863}
57864
57865/*
57866** This function is called just before writing a set of frames to the log
57867** file (see sqlite3WalFrames()). It checks to see if, instead of appending
57868** to the current log file, it is possible to overwrite the start of the
57869** existing log file with the new frames (i.e. "reset" the log). If so,
57870** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
57871** unchanged.
57872**
57873** SQLITE_OK is returned if no error is encountered (regardless of whether
57874** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
57875** if an error occurs.
57876*/
57877static int walRestartLog(Wal *pWal){
57878  int rc = SQLITE_OK;
57879  int cnt;
57880
57881  if( pWal->readLock==0 ){
57882    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
57883    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
57884    if( pInfo->nBackfill>0 ){
57885      u32 salt1;
57886      sqlite3_randomness(4, &salt1);
57887      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
57888      if( rc==SQLITE_OK ){
57889        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
57890        ** readers are currently using the WAL), then the transactions
57891        ** frames will overwrite the start of the existing log. Update the
57892        ** wal-index header to reflect this.
57893        **
57894        ** In theory it would be Ok to update the cache of the header only
57895        ** at this point. But updating the actual wal-index header is also
57896        ** safe and means there is no special case for sqlite3WalUndo()
57897        ** to handle if this transaction is rolled back.  */
57898        walRestartHdr(pWal, salt1);
57899        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
57900      }else if( rc!=SQLITE_BUSY ){
57901        return rc;
57902      }
57903    }
57904    walUnlockShared(pWal, WAL_READ_LOCK(0));
57905    pWal->readLock = -1;
57906    cnt = 0;
57907    do{
57908      int notUsed;
57909      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
57910    }while( rc==WAL_RETRY );
57911    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
57912    testcase( (rc&0xff)==SQLITE_IOERR );
57913    testcase( rc==SQLITE_PROTOCOL );
57914    testcase( rc==SQLITE_OK );
57915  }
57916  return rc;
57917}
57918
57919/*
57920** Information about the current state of the WAL file and where
57921** the next fsync should occur - passed from sqlite3WalFrames() into
57922** walWriteToLog().
57923*/
57924typedef struct WalWriter {
57925  Wal *pWal;                   /* The complete WAL information */
57926  sqlite3_file *pFd;           /* The WAL file to which we write */
57927  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
57928  int syncFlags;               /* Flags for the fsync */
57929  int szPage;                  /* Size of one page */
57930} WalWriter;
57931
57932/*
57933** Write iAmt bytes of content into the WAL file beginning at iOffset.
57934** Do a sync when crossing the p->iSyncPoint boundary.
57935**
57936** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
57937** first write the part before iSyncPoint, then sync, then write the
57938** rest.
57939*/
57940static int walWriteToLog(
57941  WalWriter *p,              /* WAL to write to */
57942  void *pContent,            /* Content to be written */
57943  int iAmt,                  /* Number of bytes to write */
57944  sqlite3_int64 iOffset      /* Start writing at this offset */
57945){
57946  int rc;
57947  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
57948    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
57949    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
57950    if( rc ) return rc;
57951    iOffset += iFirstAmt;
57952    iAmt -= iFirstAmt;
57953    pContent = (void*)(iFirstAmt + (char*)pContent);
57954    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
57955    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
57956    if( iAmt==0 || rc ) return rc;
57957  }
57958  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
57959  return rc;
57960}
57961
57962/*
57963** Write out a single frame of the WAL
57964*/
57965static int walWriteOneFrame(
57966  WalWriter *p,               /* Where to write the frame */
57967  PgHdr *pPage,               /* The page of the frame to be written */
57968  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
57969  sqlite3_int64 iOffset       /* Byte offset at which to write */
57970){
57971  int rc;                         /* Result code from subfunctions */
57972  void *pData;                    /* Data actually written */
57973  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
57974#if defined(SQLITE_HAS_CODEC)
57975  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
57976#else
57977  pData = pPage->pData;
57978#endif
57979  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
57980  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
57981  if( rc ) return rc;
57982  /* Write the page data */
57983  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
57984  return rc;
57985}
57986
57987/*
57988** This function is called as part of committing a transaction within which
57989** one or more frames have been overwritten. It updates the checksums for
57990** all frames written to the wal file by the current transaction starting
57991** with the earliest to have been overwritten.
57992**
57993** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
57994*/
57995static int walRewriteChecksums(Wal *pWal, u32 iLast){
57996  const int szPage = pWal->szPage;/* Database page size */
57997  int rc = SQLITE_OK;             /* Return code */
57998  u8 *aBuf;                       /* Buffer to load data from wal file into */
57999  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
58000  u32 iRead;                      /* Next frame to read from wal file */
58001  i64 iCksumOff;
58002
58003  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
58004  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
58005
58006  /* Find the checksum values to use as input for the recalculating the
58007  ** first checksum. If the first frame is frame 1 (implying that the current
58008  ** transaction restarted the wal file), these values must be read from the
58009  ** wal-file header. Otherwise, read them from the frame header of the
58010  ** previous frame.  */
58011  assert( pWal->iReCksum>0 );
58012  if( pWal->iReCksum==1 ){
58013    iCksumOff = 24;
58014  }else{
58015    iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
58016  }
58017  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
58018  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
58019  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
58020
58021  iRead = pWal->iReCksum;
58022  pWal->iReCksum = 0;
58023  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
58024    i64 iOff = walFrameOffset(iRead, szPage);
58025    rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
58026    if( rc==SQLITE_OK ){
58027      u32 iPgno, nDbSize;
58028      iPgno = sqlite3Get4byte(aBuf);
58029      nDbSize = sqlite3Get4byte(&aBuf[4]);
58030
58031      walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
58032      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
58033    }
58034  }
58035
58036  sqlite3_free(aBuf);
58037  return rc;
58038}
58039
58040/*
58041** Write a set of frames to the log. The caller must hold the write-lock
58042** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
58043*/
58044SQLITE_PRIVATE int sqlite3WalFrames(
58045  Wal *pWal,                      /* Wal handle to write to */
58046  int szPage,                     /* Database page-size in bytes */
58047  PgHdr *pList,                   /* List of dirty pages to write */
58048  Pgno nTruncate,                 /* Database size after this commit */
58049  int isCommit,                   /* True if this is a commit */
58050  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
58051){
58052  int rc;                         /* Used to catch return codes */
58053  u32 iFrame;                     /* Next frame address */
58054  PgHdr *p;                       /* Iterator to run through pList with. */
58055  PgHdr *pLast = 0;               /* Last frame in list */
58056  int nExtra = 0;                 /* Number of extra copies of last page */
58057  int szFrame;                    /* The size of a single frame */
58058  i64 iOffset;                    /* Next byte to write in WAL file */
58059  WalWriter w;                    /* The writer */
58060  u32 iFirst = 0;                 /* First frame that may be overwritten */
58061  WalIndexHdr *pLive;             /* Pointer to shared header */
58062
58063  assert( pList );
58064  assert( pWal->writeLock );
58065
58066  /* If this frame set completes a transaction, then nTruncate>0.  If
58067  ** nTruncate==0 then this frame set does not complete the transaction. */
58068  assert( (isCommit!=0)==(nTruncate!=0) );
58069
58070#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
58071  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
58072    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
58073              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
58074  }
58075#endif
58076
58077  pLive = (WalIndexHdr*)walIndexHdr(pWal);
58078  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
58079    iFirst = pLive->mxFrame+1;
58080  }
58081
58082  /* See if it is possible to write these frames into the start of the
58083  ** log file, instead of appending to it at pWal->hdr.mxFrame.
58084  */
58085  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
58086    return rc;
58087  }
58088
58089  /* If this is the first frame written into the log, write the WAL
58090  ** header to the start of the WAL file. See comments at the top of
58091  ** this source file for a description of the WAL header format.
58092  */
58093  iFrame = pWal->hdr.mxFrame;
58094  if( iFrame==0 ){
58095    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
58096    u32 aCksum[2];                /* Checksum for wal-header */
58097
58098    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
58099    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
58100    sqlite3Put4byte(&aWalHdr[8], szPage);
58101    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
58102    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
58103    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
58104    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
58105    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
58106    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
58107
58108    pWal->szPage = szPage;
58109    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
58110    pWal->hdr.aFrameCksum[0] = aCksum[0];
58111    pWal->hdr.aFrameCksum[1] = aCksum[1];
58112    pWal->truncateOnCommit = 1;
58113
58114    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
58115    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
58116    if( rc!=SQLITE_OK ){
58117      return rc;
58118    }
58119
58120    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
58121    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
58122    ** an out-of-order write following a WAL restart could result in
58123    ** database corruption.  See the ticket:
58124    **
58125    **     http://localhost:591/sqlite/info/ff5be73dee
58126    */
58127    if( pWal->syncHeader && sync_flags ){
58128      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
58129      if( rc ) return rc;
58130    }
58131  }
58132  assert( (int)pWal->szPage==szPage );
58133
58134  /* Setup information needed to write frames into the WAL */
58135  w.pWal = pWal;
58136  w.pFd = pWal->pWalFd;
58137  w.iSyncPoint = 0;
58138  w.syncFlags = sync_flags;
58139  w.szPage = szPage;
58140  iOffset = walFrameOffset(iFrame+1, szPage);
58141  szFrame = szPage + WAL_FRAME_HDRSIZE;
58142
58143  /* Write all frames into the log file exactly once */
58144  for(p=pList; p; p=p->pDirty){
58145    int nDbSize;   /* 0 normally.  Positive == commit flag */
58146
58147    /* Check if this page has already been written into the wal file by
58148    ** the current transaction. If so, overwrite the existing frame and
58149    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
58150    ** checksums must be recomputed when the transaction is committed.  */
58151    if( iFirst && (p->pDirty || isCommit==0) ){
58152      u32 iWrite = 0;
58153      VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
58154      assert( rc==SQLITE_OK || iWrite==0 );
58155      if( iWrite>=iFirst ){
58156        i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
58157        void *pData;
58158        if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
58159          pWal->iReCksum = iWrite;
58160        }
58161#if defined(SQLITE_HAS_CODEC)
58162        if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
58163#else
58164        pData = p->pData;
58165#endif
58166        rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
58167        if( rc ) return rc;
58168        p->flags &= ~PGHDR_WAL_APPEND;
58169        continue;
58170      }
58171    }
58172
58173    iFrame++;
58174    assert( iOffset==walFrameOffset(iFrame, szPage) );
58175    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
58176    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
58177    if( rc ) return rc;
58178    pLast = p;
58179    iOffset += szFrame;
58180    p->flags |= PGHDR_WAL_APPEND;
58181  }
58182
58183  /* Recalculate checksums within the wal file if required. */
58184  if( isCommit && pWal->iReCksum ){
58185    rc = walRewriteChecksums(pWal, iFrame);
58186    if( rc ) return rc;
58187  }
58188
58189  /* If this is the end of a transaction, then we might need to pad
58190  ** the transaction and/or sync the WAL file.
58191  **
58192  ** Padding and syncing only occur if this set of frames complete a
58193  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
58194  ** or synchronous==OFF, then no padding or syncing are needed.
58195  **
58196  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
58197  ** needed and only the sync is done.  If padding is needed, then the
58198  ** final frame is repeated (with its commit mark) until the next sector
58199  ** boundary is crossed.  Only the part of the WAL prior to the last
58200  ** sector boundary is synced; the part of the last frame that extends
58201  ** past the sector boundary is written after the sync.
58202  */
58203  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
58204    int bSync = 1;
58205    if( pWal->padToSectorBoundary ){
58206      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
58207      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
58208      bSync = (w.iSyncPoint==iOffset);
58209      testcase( bSync );
58210      while( iOffset<w.iSyncPoint ){
58211        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
58212        if( rc ) return rc;
58213        iOffset += szFrame;
58214        nExtra++;
58215      }
58216    }
58217    if( bSync ){
58218      assert( rc==SQLITE_OK );
58219      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
58220    }
58221  }
58222
58223  /* If this frame set completes the first transaction in the WAL and
58224  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
58225  ** journal size limit, if possible.
58226  */
58227  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
58228    i64 sz = pWal->mxWalSize;
58229    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
58230      sz = walFrameOffset(iFrame+nExtra+1, szPage);
58231    }
58232    walLimitSize(pWal, sz);
58233    pWal->truncateOnCommit = 0;
58234  }
58235
58236  /* Append data to the wal-index. It is not necessary to lock the
58237  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
58238  ** guarantees that there are no other writers, and no data that may
58239  ** be in use by existing readers is being overwritten.
58240  */
58241  iFrame = pWal->hdr.mxFrame;
58242  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
58243    if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
58244    iFrame++;
58245    rc = walIndexAppend(pWal, iFrame, p->pgno);
58246  }
58247  while( rc==SQLITE_OK && nExtra>0 ){
58248    iFrame++;
58249    nExtra--;
58250    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
58251  }
58252
58253  if( rc==SQLITE_OK ){
58254    /* Update the private copy of the header. */
58255    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
58256    testcase( szPage<=32768 );
58257    testcase( szPage>=65536 );
58258    pWal->hdr.mxFrame = iFrame;
58259    if( isCommit ){
58260      pWal->hdr.iChange++;
58261      pWal->hdr.nPage = nTruncate;
58262    }
58263    /* If this is a commit, update the wal-index header too. */
58264    if( isCommit ){
58265      walIndexWriteHdr(pWal);
58266      pWal->iCallback = iFrame;
58267    }
58268  }
58269
58270  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
58271  return rc;
58272}
58273
58274/*
58275** This routine is called to implement sqlite3_wal_checkpoint() and
58276** related interfaces.
58277**
58278** Obtain a CHECKPOINT lock and then backfill as much information as
58279** we can from WAL into the database.
58280**
58281** If parameter xBusy is not NULL, it is a pointer to a busy-handler
58282** callback. In this case this function runs a blocking checkpoint.
58283*/
58284SQLITE_PRIVATE int sqlite3WalCheckpoint(
58285  Wal *pWal,                      /* Wal connection */
58286  sqlite3 *db,                    /* Check this handle's interrupt flag */
58287  int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
58288  int (*xBusy)(void*),            /* Function to call when busy */
58289  void *pBusyArg,                 /* Context argument for xBusyHandler */
58290  int sync_flags,                 /* Flags to sync db file with (or 0) */
58291  int nBuf,                       /* Size of temporary buffer */
58292  u8 *zBuf,                       /* Temporary buffer to use */
58293  int *pnLog,                     /* OUT: Number of frames in WAL */
58294  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
58295){
58296  int rc;                         /* Return code */
58297  int isChanged = 0;              /* True if a new wal-index header is loaded */
58298  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
58299  int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
58300
58301  assert( pWal->ckptLock==0 );
58302  assert( pWal->writeLock==0 );
58303
58304  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
58305  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
58306  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
58307
58308  if( pWal->readOnly ) return SQLITE_READONLY;
58309  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
58310
58311  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
58312  ** "checkpoint" lock on the database file. */
58313  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
58314  if( rc ){
58315    /* EVIDENCE-OF: R-10421-19736 If any other process is running a
58316    ** checkpoint operation at the same time, the lock cannot be obtained and
58317    ** SQLITE_BUSY is returned.
58318    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
58319    ** it will not be invoked in this case.
58320    */
58321    testcase( rc==SQLITE_BUSY );
58322    testcase( xBusy!=0 );
58323    return rc;
58324  }
58325  pWal->ckptLock = 1;
58326
58327  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
58328  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
58329  ** file.
58330  **
58331  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
58332  ** immediately, and a busy-handler is configured, it is invoked and the
58333  ** writer lock retried until either the busy-handler returns 0 or the
58334  ** lock is successfully obtained.
58335  */
58336  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
58337    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
58338    if( rc==SQLITE_OK ){
58339      pWal->writeLock = 1;
58340    }else if( rc==SQLITE_BUSY ){
58341      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
58342      xBusy2 = 0;
58343      rc = SQLITE_OK;
58344    }
58345  }
58346
58347  /* Read the wal-index header. */
58348  if( rc==SQLITE_OK ){
58349    rc = walIndexReadHdr(pWal, &isChanged);
58350    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
58351      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
58352    }
58353  }
58354
58355  /* Copy data from the log to the database file. */
58356  if( rc==SQLITE_OK ){
58357
58358    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
58359      rc = SQLITE_CORRUPT_BKPT;
58360    }else{
58361      rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
58362    }
58363
58364    /* If no error occurred, set the output variables. */
58365    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
58366      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
58367      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
58368    }
58369  }
58370
58371  if( isChanged ){
58372    /* If a new wal-index header was loaded before the checkpoint was
58373    ** performed, then the pager-cache associated with pWal is now
58374    ** out of date. So zero the cached wal-index header to ensure that
58375    ** next time the pager opens a snapshot on this database it knows that
58376    ** the cache needs to be reset.
58377    */
58378    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
58379  }
58380
58381  /* Release the locks. */
58382  sqlite3WalEndWriteTransaction(pWal);
58383  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
58384  pWal->ckptLock = 0;
58385  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
58386  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
58387}
58388
58389/* Return the value to pass to a sqlite3_wal_hook callback, the
58390** number of frames in the WAL at the point of the last commit since
58391** sqlite3WalCallback() was called.  If no commits have occurred since
58392** the last call, then return 0.
58393*/
58394SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
58395  u32 ret = 0;
58396  if( pWal ){
58397    ret = pWal->iCallback;
58398    pWal->iCallback = 0;
58399  }
58400  return (int)ret;
58401}
58402
58403/*
58404** This function is called to change the WAL subsystem into or out
58405** of locking_mode=EXCLUSIVE.
58406**
58407** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
58408** into locking_mode=NORMAL.  This means that we must acquire a lock
58409** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
58410** or if the acquisition of the lock fails, then return 0.  If the
58411** transition out of exclusive-mode is successful, return 1.  This
58412** operation must occur while the pager is still holding the exclusive
58413** lock on the main database file.
58414**
58415** If op is one, then change from locking_mode=NORMAL into
58416** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
58417** be released.  Return 1 if the transition is made and 0 if the
58418** WAL is already in exclusive-locking mode - meaning that this
58419** routine is a no-op.  The pager must already hold the exclusive lock
58420** on the main database file before invoking this operation.
58421**
58422** If op is negative, then do a dry-run of the op==1 case but do
58423** not actually change anything. The pager uses this to see if it
58424** should acquire the database exclusive lock prior to invoking
58425** the op==1 case.
58426*/
58427SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
58428  int rc;
58429  assert( pWal->writeLock==0 );
58430  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
58431
58432  /* pWal->readLock is usually set, but might be -1 if there was a
58433  ** prior error while attempting to acquire are read-lock. This cannot
58434  ** happen if the connection is actually in exclusive mode (as no xShmLock
58435  ** locks are taken in this case). Nor should the pager attempt to
58436  ** upgrade to exclusive-mode following such an error.
58437  */
58438  assert( pWal->readLock>=0 || pWal->lockError );
58439  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
58440
58441  if( op==0 ){
58442    if( pWal->exclusiveMode ){
58443      pWal->exclusiveMode = 0;
58444      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
58445        pWal->exclusiveMode = 1;
58446      }
58447      rc = pWal->exclusiveMode==0;
58448    }else{
58449      /* Already in locking_mode=NORMAL */
58450      rc = 0;
58451    }
58452  }else if( op>0 ){
58453    assert( pWal->exclusiveMode==0 );
58454    assert( pWal->readLock>=0 );
58455    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
58456    pWal->exclusiveMode = 1;
58457    rc = 1;
58458  }else{
58459    rc = pWal->exclusiveMode==0;
58460  }
58461  return rc;
58462}
58463
58464/*
58465** Return true if the argument is non-NULL and the WAL module is using
58466** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
58467** WAL module is using shared-memory, return false.
58468*/
58469SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
58470  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
58471}
58472
58473#ifdef SQLITE_ENABLE_SNAPSHOT
58474/* Create a snapshot object.  The content of a snapshot is opaque to
58475** every other subsystem, so the WAL module can put whatever it needs
58476** in the object.
58477*/
58478SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
58479  int rc = SQLITE_OK;
58480  WalIndexHdr *pRet;
58481  static const u32 aZero[4] = { 0, 0, 0, 0 };
58482
58483  assert( pWal->readLock>=0 && pWal->writeLock==0 );
58484
58485  if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
58486    *ppSnapshot = 0;
58487    return SQLITE_ERROR;
58488  }
58489  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
58490  if( pRet==0 ){
58491    rc = SQLITE_NOMEM_BKPT;
58492  }else{
58493    memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
58494    *ppSnapshot = (sqlite3_snapshot*)pRet;
58495  }
58496
58497  return rc;
58498}
58499
58500/* Try to open on pSnapshot when the next read-transaction starts
58501*/
58502SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
58503  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
58504}
58505
58506/*
58507** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
58508** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
58509*/
58510SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
58511  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
58512  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
58513
58514  /* aSalt[0] is a copy of the value stored in the wal file header. It
58515  ** is incremented each time the wal file is restarted.  */
58516  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
58517  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
58518  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
58519  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
58520  return 0;
58521}
58522#endif /* SQLITE_ENABLE_SNAPSHOT */
58523
58524#ifdef SQLITE_ENABLE_ZIPVFS
58525/*
58526** If the argument is not NULL, it points to a Wal object that holds a
58527** read-lock. This function returns the database page-size if it is known,
58528** or zero if it is not (or if pWal is NULL).
58529*/
58530SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
58531  assert( pWal==0 || pWal->readLock>=0 );
58532  return (pWal ? pWal->szPage : 0);
58533}
58534#endif
58535
58536/* Return the sqlite3_file object for the WAL file
58537*/
58538SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
58539  return pWal->pWalFd;
58540}
58541
58542#endif /* #ifndef SQLITE_OMIT_WAL */
58543
58544/************** End of wal.c *************************************************/
58545/************** Begin file btmutex.c *****************************************/
58546/*
58547** 2007 August 27
58548**
58549** The author disclaims copyright to this source code.  In place of
58550** a legal notice, here is a blessing:
58551**
58552**    May you do good and not evil.
58553**    May you find forgiveness for yourself and forgive others.
58554**    May you share freely, never taking more than you give.
58555**
58556*************************************************************************
58557**
58558** This file contains code used to implement mutexes on Btree objects.
58559** This code really belongs in btree.c.  But btree.c is getting too
58560** big and we want to break it down some.  This packaged seemed like
58561** a good breakout.
58562*/
58563/************** Include btreeInt.h in the middle of btmutex.c ****************/
58564/************** Begin file btreeInt.h ****************************************/
58565/*
58566** 2004 April 6
58567**
58568** The author disclaims copyright to this source code.  In place of
58569** a legal notice, here is a blessing:
58570**
58571**    May you do good and not evil.
58572**    May you find forgiveness for yourself and forgive others.
58573**    May you share freely, never taking more than you give.
58574**
58575*************************************************************************
58576** This file implements an external (disk-based) database using BTrees.
58577** For a detailed discussion of BTrees, refer to
58578**
58579**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
58580**     "Sorting And Searching", pages 473-480. Addison-Wesley
58581**     Publishing Company, Reading, Massachusetts.
58582**
58583** The basic idea is that each page of the file contains N database
58584** entries and N+1 pointers to subpages.
58585**
58586**   ----------------------------------------------------------------
58587**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
58588**   ----------------------------------------------------------------
58589**
58590** All of the keys on the page that Ptr(0) points to have values less
58591** than Key(0).  All of the keys on page Ptr(1) and its subpages have
58592** values greater than Key(0) and less than Key(1).  All of the keys
58593** on Ptr(N) and its subpages have values greater than Key(N-1).  And
58594** so forth.
58595**
58596** Finding a particular key requires reading O(log(M)) pages from the
58597** disk where M is the number of entries in the tree.
58598**
58599** In this implementation, a single file can hold one or more separate
58600** BTrees.  Each BTree is identified by the index of its root page.  The
58601** key and data for any entry are combined to form the "payload".  A
58602** fixed amount of payload can be carried directly on the database
58603** page.  If the payload is larger than the preset amount then surplus
58604** bytes are stored on overflow pages.  The payload for an entry
58605** and the preceding pointer are combined to form a "Cell".  Each
58606** page has a small header which contains the Ptr(N) pointer and other
58607** information such as the size of key and data.
58608**
58609** FORMAT DETAILS
58610**
58611** The file is divided into pages.  The first page is called page 1,
58612** the second is page 2, and so forth.  A page number of zero indicates
58613** "no such page".  The page size can be any power of 2 between 512 and 65536.
58614** Each page can be either a btree page, a freelist page, an overflow
58615** page, or a pointer-map page.
58616**
58617** The first page is always a btree page.  The first 100 bytes of the first
58618** page contain a special header (the "file header") that describes the file.
58619** The format of the file header is as follows:
58620**
58621**   OFFSET   SIZE    DESCRIPTION
58622**      0      16     Header string: "SQLite format 3\000"
58623**     16       2     Page size in bytes.  (1 means 65536)
58624**     18       1     File format write version
58625**     19       1     File format read version
58626**     20       1     Bytes of unused space at the end of each page
58627**     21       1     Max embedded payload fraction (must be 64)
58628**     22       1     Min embedded payload fraction (must be 32)
58629**     23       1     Min leaf payload fraction (must be 32)
58630**     24       4     File change counter
58631**     28       4     Reserved for future use
58632**     32       4     First freelist page
58633**     36       4     Number of freelist pages in the file
58634**     40      60     15 4-byte meta values passed to higher layers
58635**
58636**     40       4     Schema cookie
58637**     44       4     File format of schema layer
58638**     48       4     Size of page cache
58639**     52       4     Largest root-page (auto/incr_vacuum)
58640**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
58641**     60       4     User version
58642**     64       4     Incremental vacuum mode
58643**     68       4     Application-ID
58644**     72      20     unused
58645**     92       4     The version-valid-for number
58646**     96       4     SQLITE_VERSION_NUMBER
58647**
58648** All of the integer values are big-endian (most significant byte first).
58649**
58650** The file change counter is incremented when the database is changed
58651** This counter allows other processes to know when the file has changed
58652** and thus when they need to flush their cache.
58653**
58654** The max embedded payload fraction is the amount of the total usable
58655** space in a page that can be consumed by a single cell for standard
58656** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
58657** is to limit the maximum cell size so that at least 4 cells will fit
58658** on one page.  Thus the default max embedded payload fraction is 64.
58659**
58660** If the payload for a cell is larger than the max payload, then extra
58661** payload is spilled to overflow pages.  Once an overflow page is allocated,
58662** as many bytes as possible are moved into the overflow pages without letting
58663** the cell size drop below the min embedded payload fraction.
58664**
58665** The min leaf payload fraction is like the min embedded payload fraction
58666** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
58667** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
58668** not specified in the header.
58669**
58670** Each btree pages is divided into three sections:  The header, the
58671** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
58672** file header that occurs before the page header.
58673**
58674**      |----------------|
58675**      | file header    |   100 bytes.  Page 1 only.
58676**      |----------------|
58677**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
58678**      |----------------|
58679**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
58680**      | array          |   |  Grows downward
58681**      |                |   v
58682**      |----------------|
58683**      | unallocated    |
58684**      | space          |
58685**      |----------------|   ^  Grows upwards
58686**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
58687**      | area           |   |  and free space fragments.
58688**      |----------------|
58689**
58690** The page headers looks like this:
58691**
58692**   OFFSET   SIZE     DESCRIPTION
58693**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
58694**      1       2      byte offset to the first freeblock
58695**      3       2      number of cells on this page
58696**      5       2      first byte of the cell content area
58697**      7       1      number of fragmented free bytes
58698**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
58699**
58700** The flags define the format of this btree page.  The leaf flag means that
58701** this page has no children.  The zerodata flag means that this page carries
58702** only keys and no data.  The intkey flag means that the key is an integer
58703** which is stored in the key size entry of the cell header rather than in
58704** the payload area.
58705**
58706** The cell pointer array begins on the first byte after the page header.
58707** The cell pointer array contains zero or more 2-byte numbers which are
58708** offsets from the beginning of the page to the cell content in the cell
58709** content area.  The cell pointers occur in sorted order.  The system strives
58710** to keep free space after the last cell pointer so that new cells can
58711** be easily added without having to defragment the page.
58712**
58713** Cell content is stored at the very end of the page and grows toward the
58714** beginning of the page.
58715**
58716** Unused space within the cell content area is collected into a linked list of
58717** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
58718** to the first freeblock is given in the header.  Freeblocks occur in
58719** increasing order.  Because a freeblock must be at least 4 bytes in size,
58720** any group of 3 or fewer unused bytes in the cell content area cannot
58721** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
58722** a fragment.  The total number of bytes in all fragments is recorded.
58723** in the page header at offset 7.
58724**
58725**    SIZE    DESCRIPTION
58726**      2     Byte offset of the next freeblock
58727**      2     Bytes in this freeblock
58728**
58729** Cells are of variable length.  Cells are stored in the cell content area at
58730** the end of the page.  Pointers to the cells are in the cell pointer array
58731** that immediately follows the page header.  Cells is not necessarily
58732** contiguous or in order, but cell pointers are contiguous and in order.
58733**
58734** Cell content makes use of variable length integers.  A variable
58735** length integer is 1 to 9 bytes where the lower 7 bits of each
58736** byte are used.  The integer consists of all bytes that have bit 8 set and
58737** the first byte with bit 8 clear.  The most significant byte of the integer
58738** appears first.  A variable-length integer may not be more than 9 bytes long.
58739** As a special case, all 8 bytes of the 9th byte are used as data.  This
58740** allows a 64-bit integer to be encoded in 9 bytes.
58741**
58742**    0x00                      becomes  0x00000000
58743**    0x7f                      becomes  0x0000007f
58744**    0x81 0x00                 becomes  0x00000080
58745**    0x82 0x00                 becomes  0x00000100
58746**    0x80 0x7f                 becomes  0x0000007f
58747**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
58748**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
58749**
58750** Variable length integers are used for rowids and to hold the number of
58751** bytes of key and data in a btree cell.
58752**
58753** The content of a cell looks like this:
58754**
58755**    SIZE    DESCRIPTION
58756**      4     Page number of the left child. Omitted if leaf flag is set.
58757**     var    Number of bytes of data. Omitted if the zerodata flag is set.
58758**     var    Number of bytes of key. Or the key itself if intkey flag is set.
58759**      *     Payload
58760**      4     First page of the overflow chain.  Omitted if no overflow
58761**
58762** Overflow pages form a linked list.  Each page except the last is completely
58763** filled with data (pagesize - 4 bytes).  The last page can have as little
58764** as 1 byte of data.
58765**
58766**    SIZE    DESCRIPTION
58767**      4     Page number of next overflow page
58768**      *     Data
58769**
58770** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
58771** file header points to the first in a linked list of trunk page.  Each trunk
58772** page points to multiple leaf pages.  The content of a leaf page is
58773** unspecified.  A trunk page looks like this:
58774**
58775**    SIZE    DESCRIPTION
58776**      4     Page number of next trunk page
58777**      4     Number of leaf pointers on this page
58778**      *     zero or more pages numbers of leaves
58779*/
58780/* #include "sqliteInt.h" */
58781
58782
58783/* The following value is the maximum cell size assuming a maximum page
58784** size give above.
58785*/
58786#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
58787
58788/* The maximum number of cells on a single page of the database.  This
58789** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
58790** plus 2 bytes for the index to the cell in the page header).  Such
58791** small cells will be rare, but they are possible.
58792*/
58793#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
58794
58795/* Forward declarations */
58796typedef struct MemPage MemPage;
58797typedef struct BtLock BtLock;
58798typedef struct CellInfo CellInfo;
58799
58800/*
58801** This is a magic string that appears at the beginning of every
58802** SQLite database in order to identify the file as a real database.
58803**
58804** You can change this value at compile-time by specifying a
58805** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
58806** header must be exactly 16 bytes including the zero-terminator so
58807** the string itself should be 15 characters long.  If you change
58808** the header, then your custom library will not be able to read
58809** databases generated by the standard tools and the standard tools
58810** will not be able to read databases created by your custom library.
58811*/
58812#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
58813#  define SQLITE_FILE_HEADER "SQLite format 3"
58814#endif
58815
58816/*
58817** Page type flags.  An ORed combination of these flags appear as the
58818** first byte of on-disk image of every BTree page.
58819*/
58820#define PTF_INTKEY    0x01
58821#define PTF_ZERODATA  0x02
58822#define PTF_LEAFDATA  0x04
58823#define PTF_LEAF      0x08
58824
58825/*
58826** An instance of this object stores information about each a single database
58827** page that has been loaded into memory.  The information in this object
58828** is derived from the raw on-disk page content.
58829**
58830** As each database page is loaded into memory, the pager allocats an
58831** instance of this object and zeros the first 8 bytes.  (This is the
58832** "extra" information associated with each page of the pager.)
58833**
58834** Access to all fields of this structure is controlled by the mutex
58835** stored in MemPage.pBt->mutex.
58836*/
58837struct MemPage {
58838  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
58839  u8 bBusy;            /* Prevent endless loops on corrupt database files */
58840  u8 intKey;           /* True if table b-trees.  False for index b-trees */
58841  u8 intKeyLeaf;       /* True if the leaf of an intKey table */
58842  Pgno pgno;           /* Page number for this page */
58843  /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
58844  ** is allocated. All fields that follow must be initialized before use */
58845  u8 leaf;             /* True if a leaf page */
58846  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
58847  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
58848  u8 max1bytePayload;  /* min(maxLocal,127) */
58849  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
58850  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
58851  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
58852  u16 cellOffset;      /* Index in aData of first cell pointer */
58853  u16 nFree;           /* Number of free bytes on the page */
58854  u16 nCell;           /* Number of cells on this page, local and ovfl */
58855  u16 maskPage;        /* Mask for page offset */
58856  u16 aiOvfl[4];       /* Insert the i-th overflow cell before the aiOvfl-th
58857                       ** non-overflow cell */
58858  u8 *apOvfl[4];       /* Pointers to the body of overflow cells */
58859  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
58860  u8 *aData;           /* Pointer to disk image of the page data */
58861  u8 *aDataEnd;        /* One byte past the end of usable data */
58862  u8 *aCellIdx;        /* The cell index area */
58863  u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
58864  DbPage *pDbPage;     /* Pager page handle */
58865  u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
58866  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
58867};
58868
58869/*
58870** A linked list of the following structures is stored at BtShared.pLock.
58871** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
58872** is opened on the table with root page BtShared.iTable. Locks are removed
58873** from this list when a transaction is committed or rolled back, or when
58874** a btree handle is closed.
58875*/
58876struct BtLock {
58877  Btree *pBtree;        /* Btree handle holding this lock */
58878  Pgno iTable;          /* Root page of table */
58879  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
58880  BtLock *pNext;        /* Next in BtShared.pLock list */
58881};
58882
58883/* Candidate values for BtLock.eLock */
58884#define READ_LOCK     1
58885#define WRITE_LOCK    2
58886
58887/* A Btree handle
58888**
58889** A database connection contains a pointer to an instance of
58890** this object for every database file that it has open.  This structure
58891** is opaque to the database connection.  The database connection cannot
58892** see the internals of this structure and only deals with pointers to
58893** this structure.
58894**
58895** For some database files, the same underlying database cache might be
58896** shared between multiple connections.  In that case, each connection
58897** has it own instance of this object.  But each instance of this object
58898** points to the same BtShared object.  The database cache and the
58899** schema associated with the database file are all contained within
58900** the BtShared object.
58901**
58902** All fields in this structure are accessed under sqlite3.mutex.
58903** The pBt pointer itself may not be changed while there exists cursors
58904** in the referenced BtShared that point back to this Btree since those
58905** cursors have to go through this Btree to find their BtShared and
58906** they often do so without holding sqlite3.mutex.
58907*/
58908struct Btree {
58909  sqlite3 *db;       /* The database connection holding this btree */
58910  BtShared *pBt;     /* Sharable content of this btree */
58911  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
58912  u8 sharable;       /* True if we can share pBt with another db */
58913  u8 locked;         /* True if db currently has pBt locked */
58914  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
58915  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
58916  int nBackup;       /* Number of backup operations reading this btree */
58917  u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
58918  Btree *pNext;      /* List of other sharable Btrees from the same db */
58919  Btree *pPrev;      /* Back pointer of the same list */
58920#ifndef SQLITE_OMIT_SHARED_CACHE
58921  BtLock lock;       /* Object used to lock page 1 */
58922#endif
58923};
58924
58925/*
58926** Btree.inTrans may take one of the following values.
58927**
58928** If the shared-data extension is enabled, there may be multiple users
58929** of the Btree structure. At most one of these may open a write transaction,
58930** but any number may have active read transactions.
58931*/
58932#define TRANS_NONE  0
58933#define TRANS_READ  1
58934#define TRANS_WRITE 2
58935
58936/*
58937** An instance of this object represents a single database file.
58938**
58939** A single database file can be in use at the same time by two
58940** or more database connections.  When two or more connections are
58941** sharing the same database file, each connection has it own
58942** private Btree object for the file and each of those Btrees points
58943** to this one BtShared object.  BtShared.nRef is the number of
58944** connections currently sharing this database file.
58945**
58946** Fields in this structure are accessed under the BtShared.mutex
58947** mutex, except for nRef and pNext which are accessed under the
58948** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
58949** may not be modified once it is initially set as long as nRef>0.
58950** The pSchema field may be set once under BtShared.mutex and
58951** thereafter is unchanged as long as nRef>0.
58952**
58953** isPending:
58954**
58955**   If a BtShared client fails to obtain a write-lock on a database
58956**   table (because there exists one or more read-locks on the table),
58957**   the shared-cache enters 'pending-lock' state and isPending is
58958**   set to true.
58959**
58960**   The shared-cache leaves the 'pending lock' state when either of
58961**   the following occur:
58962**
58963**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
58964**     2) The number of locks held by other connections drops to zero.
58965**
58966**   while in the 'pending-lock' state, no connection may start a new
58967**   transaction.
58968**
58969**   This feature is included to help prevent writer-starvation.
58970*/
58971struct BtShared {
58972  Pager *pPager;        /* The page cache */
58973  sqlite3 *db;          /* Database connection currently using this Btree */
58974  BtCursor *pCursor;    /* A list of all open cursors */
58975  MemPage *pPage1;      /* First page of the database */
58976  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
58977#ifndef SQLITE_OMIT_AUTOVACUUM
58978  u8 autoVacuum;        /* True if auto-vacuum is enabled */
58979  u8 incrVacuum;        /* True if incr-vacuum is enabled */
58980  u8 bDoTruncate;       /* True to truncate db on commit */
58981#endif
58982  u8 inTransaction;     /* Transaction state */
58983  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
58984#ifdef SQLITE_HAS_CODEC
58985  u8 optimalReserve;    /* Desired amount of reserved space per page */
58986#endif
58987  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
58988  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
58989  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
58990  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
58991  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
58992  u32 pageSize;         /* Total number of bytes on a page */
58993  u32 usableSize;       /* Number of usable bytes on each page */
58994  int nTransaction;     /* Number of open transactions (read + write) */
58995  u32 nPage;            /* Number of pages in the database */
58996  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
58997  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
58998  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
58999  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
59000#ifndef SQLITE_OMIT_SHARED_CACHE
59001  int nRef;             /* Number of references to this structure */
59002  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
59003  BtLock *pLock;        /* List of locks held on this shared-btree struct */
59004  Btree *pWriter;       /* Btree with currently open write transaction */
59005#endif
59006  u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
59007};
59008
59009/*
59010** Allowed values for BtShared.btsFlags
59011*/
59012#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
59013#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
59014#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
59015#define BTS_OVERWRITE        0x0008   /* Overwrite deleted content with zeros */
59016#define BTS_FAST_SECURE      0x000c   /* Combination of the previous two */
59017#define BTS_INITIALLY_EMPTY  0x0010   /* Database was empty at trans start */
59018#define BTS_NO_WAL           0x0020   /* Do not open write-ahead-log files */
59019#define BTS_EXCLUSIVE        0x0040   /* pWriter has an exclusive lock */
59020#define BTS_PENDING          0x0080   /* Waiting for read-locks to clear */
59021
59022/*
59023** An instance of the following structure is used to hold information
59024** about a cell.  The parseCellPtr() function fills in this structure
59025** based on information extract from the raw disk page.
59026*/
59027struct CellInfo {
59028  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
59029  u8 *pPayload;  /* Pointer to the start of payload */
59030  u32 nPayload;  /* Bytes of payload */
59031  u16 nLocal;    /* Amount of payload held locally, not on overflow */
59032  u16 nSize;     /* Size of the cell content on the main b-tree page */
59033};
59034
59035/*
59036** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
59037** this will be declared corrupt. This value is calculated based on a
59038** maximum database size of 2^31 pages a minimum fanout of 2 for a
59039** root-node and 3 for all other internal nodes.
59040**
59041** If a tree that appears to be taller than this is encountered, it is
59042** assumed that the database is corrupt.
59043*/
59044#define BTCURSOR_MAX_DEPTH 20
59045
59046/*
59047** A cursor is a pointer to a particular entry within a particular
59048** b-tree within a database file.
59049**
59050** The entry is identified by its MemPage and the index in
59051** MemPage.aCell[] of the entry.
59052**
59053** A single database file can be shared by two more database connections,
59054** but cursors cannot be shared.  Each cursor is associated with a
59055** particular database connection identified BtCursor.pBtree.db.
59056**
59057** Fields in this structure are accessed under the BtShared.mutex
59058** found at self->pBt->mutex.
59059**
59060** skipNext meaning:
59061**    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
59062**    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
59063**    eState==FAULT:                   Cursor fault with skipNext as error code.
59064*/
59065struct BtCursor {
59066  Btree *pBtree;            /* The Btree to which this cursor belongs */
59067  BtShared *pBt;            /* The BtShared this cursor points to */
59068  BtCursor *pNext;          /* Forms a linked list of all cursors */
59069  Pgno *aOverflow;          /* Cache of overflow page locations */
59070  CellInfo info;            /* A parse of the cell we are pointing at */
59071  i64 nKey;                 /* Size of pKey, or last integer key */
59072  void *pKey;               /* Saved key that was cursor last known position */
59073  Pgno pgnoRoot;            /* The root page of this tree */
59074  int nOvflAlloc;           /* Allocated size of aOverflow[] array */
59075  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
59076                   ** Error code if eState==CURSOR_FAULT */
59077  u8 curFlags;              /* zero or more BTCF_* flags defined below */
59078  u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
59079  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
59080  u8 hints;                 /* As configured by CursorSetHints() */
59081  /* All fields above are zeroed when the cursor is allocated.  See
59082  ** sqlite3BtreeCursorZero().  Fields that follow must be manually
59083  ** initialized. */
59084  i8 iPage;                 /* Index of current page in apPage */
59085  u8 curIntKey;             /* Value of apPage[0]->intKey */
59086  u16 ix;                   /* Current index for apPage[iPage] */
59087  u16 aiIdx[BTCURSOR_MAX_DEPTH-1];     /* Current index in apPage[i] */
59088  struct KeyInfo *pKeyInfo;            /* Arg passed to comparison function */
59089  MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
59090};
59091
59092/*
59093** Legal values for BtCursor.curFlags
59094*/
59095#define BTCF_WriteFlag    0x01   /* True if a write cursor */
59096#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
59097#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
59098#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
59099#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
59100#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
59101
59102/*
59103** Potential values for BtCursor.eState.
59104**
59105** CURSOR_INVALID:
59106**   Cursor does not point to a valid entry. This can happen (for example)
59107**   because the table is empty or because BtreeCursorFirst() has not been
59108**   called.
59109**
59110** CURSOR_VALID:
59111**   Cursor points to a valid entry. getPayload() etc. may be called.
59112**
59113** CURSOR_SKIPNEXT:
59114**   Cursor is valid except that the Cursor.skipNext field is non-zero
59115**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
59116**   operation should be a no-op.
59117**
59118** CURSOR_REQUIRESEEK:
59119**   The table that this cursor was opened on still exists, but has been
59120**   modified since the cursor was last used. The cursor position is saved
59121**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
59122**   this state, restoreCursorPosition() can be called to attempt to
59123**   seek the cursor to the saved position.
59124**
59125** CURSOR_FAULT:
59126**   An unrecoverable error (an I/O error or a malloc failure) has occurred
59127**   on a different connection that shares the BtShared cache with this
59128**   cursor.  The error has left the cache in an inconsistent state.
59129**   Do nothing else with this cursor.  Any attempt to use the cursor
59130**   should return the error code stored in BtCursor.skipNext
59131*/
59132#define CURSOR_INVALID           0
59133#define CURSOR_VALID             1
59134#define CURSOR_SKIPNEXT          2
59135#define CURSOR_REQUIRESEEK       3
59136#define CURSOR_FAULT             4
59137
59138/*
59139** The database page the PENDING_BYTE occupies. This page is never used.
59140*/
59141# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
59142
59143/*
59144** These macros define the location of the pointer-map entry for a
59145** database page. The first argument to each is the number of usable
59146** bytes on each page of the database (often 1024). The second is the
59147** page number to look up in the pointer map.
59148**
59149** PTRMAP_PAGENO returns the database page number of the pointer-map
59150** page that stores the required pointer. PTRMAP_PTROFFSET returns
59151** the offset of the requested map entry.
59152**
59153** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
59154** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
59155** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
59156** this test.
59157*/
59158#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
59159#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
59160#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
59161
59162/*
59163** The pointer map is a lookup table that identifies the parent page for
59164** each child page in the database file.  The parent page is the page that
59165** contains a pointer to the child.  Every page in the database contains
59166** 0 or 1 parent pages.  (In this context 'database page' refers
59167** to any page that is not part of the pointer map itself.)  Each pointer map
59168** entry consists of a single byte 'type' and a 4 byte parent page number.
59169** The PTRMAP_XXX identifiers below are the valid types.
59170**
59171** The purpose of the pointer map is to facility moving pages from one
59172** position in the file to another as part of autovacuum.  When a page
59173** is moved, the pointer in its parent must be updated to point to the
59174** new location.  The pointer map is used to locate the parent page quickly.
59175**
59176** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
59177**                  used in this case.
59178**
59179** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
59180**                  is not used in this case.
59181**
59182** PTRMAP_OVERFLOW1: The database page is the first page in a list of
59183**                   overflow pages. The page number identifies the page that
59184**                   contains the cell with a pointer to this overflow page.
59185**
59186** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
59187**                   overflow pages. The page-number identifies the previous
59188**                   page in the overflow page list.
59189**
59190** PTRMAP_BTREE: The database page is a non-root btree page. The page number
59191**               identifies the parent page in the btree.
59192*/
59193#define PTRMAP_ROOTPAGE 1
59194#define PTRMAP_FREEPAGE 2
59195#define PTRMAP_OVERFLOW1 3
59196#define PTRMAP_OVERFLOW2 4
59197#define PTRMAP_BTREE 5
59198
59199/* A bunch of assert() statements to check the transaction state variables
59200** of handle p (type Btree*) are internally consistent.
59201*/
59202#define btreeIntegrity(p) \
59203  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
59204  assert( p->pBt->inTransaction>=p->inTrans );
59205
59206
59207/*
59208** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
59209** if the database supports auto-vacuum or not. Because it is used
59210** within an expression that is an argument to another macro
59211** (sqliteMallocRaw), it is not possible to use conditional compilation.
59212** So, this macro is defined instead.
59213*/
59214#ifndef SQLITE_OMIT_AUTOVACUUM
59215#define ISAUTOVACUUM (pBt->autoVacuum)
59216#else
59217#define ISAUTOVACUUM 0
59218#endif
59219
59220
59221/*
59222** This structure is passed around through all the sanity checking routines
59223** in order to keep track of some global state information.
59224**
59225** The aRef[] array is allocated so that there is 1 bit for each page in
59226** the database. As the integrity-check proceeds, for each page used in
59227** the database the corresponding bit is set. This allows integrity-check to
59228** detect pages that are used twice and orphaned pages (both of which
59229** indicate corruption).
59230*/
59231typedef struct IntegrityCk IntegrityCk;
59232struct IntegrityCk {
59233  BtShared *pBt;    /* The tree being checked out */
59234  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
59235  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
59236  Pgno nPage;       /* Number of pages in the database */
59237  int mxErr;        /* Stop accumulating errors when this reaches zero */
59238  int nErr;         /* Number of messages written to zErrMsg so far */
59239  int mallocFailed; /* A memory allocation error has occurred */
59240  const char *zPfx; /* Error message prefix */
59241  int v1, v2;       /* Values for up to two %d fields in zPfx */
59242  StrAccum errMsg;  /* Accumulate the error message text here */
59243  u32 *heap;        /* Min-heap used for analyzing cell coverage */
59244};
59245
59246/*
59247** Routines to read or write a two- and four-byte big-endian integer values.
59248*/
59249#define get2byte(x)   ((x)[0]<<8 | (x)[1])
59250#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
59251#define get4byte sqlite3Get4byte
59252#define put4byte sqlite3Put4byte
59253
59254/*
59255** get2byteAligned(), unlike get2byte(), requires that its argument point to a
59256** two-byte aligned address.  get2bytea() is only used for accessing the
59257** cell addresses in a btree header.
59258*/
59259#if SQLITE_BYTEORDER==4321
59260# define get2byteAligned(x)  (*(u16*)(x))
59261#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
59262# define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
59263#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
59264# define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
59265#else
59266# define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
59267#endif
59268
59269/************** End of btreeInt.h ********************************************/
59270/************** Continuing where we left off in btmutex.c ********************/
59271#ifndef SQLITE_OMIT_SHARED_CACHE
59272#if SQLITE_THREADSAFE
59273
59274/*
59275** Obtain the BtShared mutex associated with B-Tree handle p. Also,
59276** set BtShared.db to the database handle associated with p and the
59277** p->locked boolean to true.
59278*/
59279static void lockBtreeMutex(Btree *p){
59280  assert( p->locked==0 );
59281  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
59282  assert( sqlite3_mutex_held(p->db->mutex) );
59283
59284  sqlite3_mutex_enter(p->pBt->mutex);
59285  p->pBt->db = p->db;
59286  p->locked = 1;
59287}
59288
59289/*
59290** Release the BtShared mutex associated with B-Tree handle p and
59291** clear the p->locked boolean.
59292*/
59293static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
59294  BtShared *pBt = p->pBt;
59295  assert( p->locked==1 );
59296  assert( sqlite3_mutex_held(pBt->mutex) );
59297  assert( sqlite3_mutex_held(p->db->mutex) );
59298  assert( p->db==pBt->db );
59299
59300  sqlite3_mutex_leave(pBt->mutex);
59301  p->locked = 0;
59302}
59303
59304/* Forward reference */
59305static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
59306
59307/*
59308** Enter a mutex on the given BTree object.
59309**
59310** If the object is not sharable, then no mutex is ever required
59311** and this routine is a no-op.  The underlying mutex is non-recursive.
59312** But we keep a reference count in Btree.wantToLock so the behavior
59313** of this interface is recursive.
59314**
59315** To avoid deadlocks, multiple Btrees are locked in the same order
59316** by all database connections.  The p->pNext is a list of other
59317** Btrees belonging to the same database connection as the p Btree
59318** which need to be locked after p.  If we cannot get a lock on
59319** p, then first unlock all of the others on p->pNext, then wait
59320** for the lock to become available on p, then relock all of the
59321** subsequent Btrees that desire a lock.
59322*/
59323SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
59324  /* Some basic sanity checking on the Btree.  The list of Btrees
59325  ** connected by pNext and pPrev should be in sorted order by
59326  ** Btree.pBt value. All elements of the list should belong to
59327  ** the same connection. Only shared Btrees are on the list. */
59328  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
59329  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
59330  assert( p->pNext==0 || p->pNext->db==p->db );
59331  assert( p->pPrev==0 || p->pPrev->db==p->db );
59332  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
59333
59334  /* Check for locking consistency */
59335  assert( !p->locked || p->wantToLock>0 );
59336  assert( p->sharable || p->wantToLock==0 );
59337
59338  /* We should already hold a lock on the database connection */
59339  assert( sqlite3_mutex_held(p->db->mutex) );
59340
59341  /* Unless the database is sharable and unlocked, then BtShared.db
59342  ** should already be set correctly. */
59343  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
59344
59345  if( !p->sharable ) return;
59346  p->wantToLock++;
59347  if( p->locked ) return;
59348  btreeLockCarefully(p);
59349}
59350
59351/* This is a helper function for sqlite3BtreeLock(). By moving
59352** complex, but seldom used logic, out of sqlite3BtreeLock() and
59353** into this routine, we avoid unnecessary stack pointer changes
59354** and thus help the sqlite3BtreeLock() routine to run much faster
59355** in the common case.
59356*/
59357static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
59358  Btree *pLater;
59359
59360  /* In most cases, we should be able to acquire the lock we
59361  ** want without having to go through the ascending lock
59362  ** procedure that follows.  Just be sure not to block.
59363  */
59364  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
59365    p->pBt->db = p->db;
59366    p->locked = 1;
59367    return;
59368  }
59369
59370  /* To avoid deadlock, first release all locks with a larger
59371  ** BtShared address.  Then acquire our lock.  Then reacquire
59372  ** the other BtShared locks that we used to hold in ascending
59373  ** order.
59374  */
59375  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
59376    assert( pLater->sharable );
59377    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
59378    assert( !pLater->locked || pLater->wantToLock>0 );
59379    if( pLater->locked ){
59380      unlockBtreeMutex(pLater);
59381    }
59382  }
59383  lockBtreeMutex(p);
59384  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
59385    if( pLater->wantToLock ){
59386      lockBtreeMutex(pLater);
59387    }
59388  }
59389}
59390
59391
59392/*
59393** Exit the recursive mutex on a Btree.
59394*/
59395SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
59396  assert( sqlite3_mutex_held(p->db->mutex) );
59397  if( p->sharable ){
59398    assert( p->wantToLock>0 );
59399    p->wantToLock--;
59400    if( p->wantToLock==0 ){
59401      unlockBtreeMutex(p);
59402    }
59403  }
59404}
59405
59406#ifndef NDEBUG
59407/*
59408** Return true if the BtShared mutex is held on the btree, or if the
59409** B-Tree is not marked as sharable.
59410**
59411** This routine is used only from within assert() statements.
59412*/
59413SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
59414  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
59415  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
59416  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
59417  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
59418
59419  return (p->sharable==0 || p->locked);
59420}
59421#endif
59422
59423
59424/*
59425** Enter the mutex on every Btree associated with a database
59426** connection.  This is needed (for example) prior to parsing
59427** a statement since we will be comparing table and column names
59428** against all schemas and we do not want those schemas being
59429** reset out from under us.
59430**
59431** There is a corresponding leave-all procedures.
59432**
59433** Enter the mutexes in accending order by BtShared pointer address
59434** to avoid the possibility of deadlock when two threads with
59435** two or more btrees in common both try to lock all their btrees
59436** at the same instant.
59437*/
59438static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
59439  int i;
59440  int skipOk = 1;
59441  Btree *p;
59442  assert( sqlite3_mutex_held(db->mutex) );
59443  for(i=0; i<db->nDb; i++){
59444    p = db->aDb[i].pBt;
59445    if( p && p->sharable ){
59446      sqlite3BtreeEnter(p);
59447      skipOk = 0;
59448    }
59449  }
59450  db->skipBtreeMutex = skipOk;
59451}
59452SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
59453  if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
59454}
59455static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
59456  int i;
59457  Btree *p;
59458  assert( sqlite3_mutex_held(db->mutex) );
59459  for(i=0; i<db->nDb; i++){
59460    p = db->aDb[i].pBt;
59461    if( p ) sqlite3BtreeLeave(p);
59462  }
59463}
59464SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
59465  if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
59466}
59467
59468#ifndef NDEBUG
59469/*
59470** Return true if the current thread holds the database connection
59471** mutex and all required BtShared mutexes.
59472**
59473** This routine is used inside assert() statements only.
59474*/
59475SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
59476  int i;
59477  if( !sqlite3_mutex_held(db->mutex) ){
59478    return 0;
59479  }
59480  for(i=0; i<db->nDb; i++){
59481    Btree *p;
59482    p = db->aDb[i].pBt;
59483    if( p && p->sharable &&
59484         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
59485      return 0;
59486    }
59487  }
59488  return 1;
59489}
59490#endif /* NDEBUG */
59491
59492#ifndef NDEBUG
59493/*
59494** Return true if the correct mutexes are held for accessing the
59495** db->aDb[iDb].pSchema structure.  The mutexes required for schema
59496** access are:
59497**
59498**   (1) The mutex on db
59499**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
59500**
59501** If pSchema is not NULL, then iDb is computed from pSchema and
59502** db using sqlite3SchemaToIndex().
59503*/
59504SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
59505  Btree *p;
59506  assert( db!=0 );
59507  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
59508  assert( iDb>=0 && iDb<db->nDb );
59509  if( !sqlite3_mutex_held(db->mutex) ) return 0;
59510  if( iDb==1 ) return 1;
59511  p = db->aDb[iDb].pBt;
59512  assert( p!=0 );
59513  return p->sharable==0 || p->locked==1;
59514}
59515#endif /* NDEBUG */
59516
59517#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
59518/*
59519** The following are special cases for mutex enter routines for use
59520** in single threaded applications that use shared cache.  Except for
59521** these two routines, all mutex operations are no-ops in that case and
59522** are null #defines in btree.h.
59523**
59524** If shared cache is disabled, then all btree mutex routines, including
59525** the ones below, are no-ops and are null #defines in btree.h.
59526*/
59527
59528SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
59529  p->pBt->db = p->db;
59530}
59531SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
59532  int i;
59533  for(i=0; i<db->nDb; i++){
59534    Btree *p = db->aDb[i].pBt;
59535    if( p ){
59536      p->pBt->db = p->db;
59537    }
59538  }
59539}
59540#endif /* if SQLITE_THREADSAFE */
59541
59542#ifndef SQLITE_OMIT_INCRBLOB
59543/*
59544** Enter a mutex on a Btree given a cursor owned by that Btree.
59545**
59546** These entry points are used by incremental I/O only. Enter() is required
59547** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
59548** the build is threadsafe. Leave() is only required by threadsafe builds.
59549*/
59550SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
59551  sqlite3BtreeEnter(pCur->pBtree);
59552}
59553# if SQLITE_THREADSAFE
59554SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
59555  sqlite3BtreeLeave(pCur->pBtree);
59556}
59557# endif
59558#endif /* ifndef SQLITE_OMIT_INCRBLOB */
59559
59560#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
59561
59562/************** End of btmutex.c *********************************************/
59563/************** Begin file btree.c *******************************************/
59564/*
59565** 2004 April 6
59566**
59567** The author disclaims copyright to this source code.  In place of
59568** a legal notice, here is a blessing:
59569**
59570**    May you do good and not evil.
59571**    May you find forgiveness for yourself and forgive others.
59572**    May you share freely, never taking more than you give.
59573**
59574*************************************************************************
59575** This file implements an external (disk-based) database using BTrees.
59576** See the header comment on "btreeInt.h" for additional information.
59577** Including a description of file format and an overview of operation.
59578*/
59579/* #include "btreeInt.h" */
59580
59581/*
59582** The header string that appears at the beginning of every
59583** SQLite database.
59584*/
59585static const char zMagicHeader[] = SQLITE_FILE_HEADER;
59586
59587/*
59588** Set this global variable to 1 to enable tracing using the TRACE
59589** macro.
59590*/
59591#if 0
59592int sqlite3BtreeTrace=1;  /* True to enable tracing */
59593# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
59594#else
59595# define TRACE(X)
59596#endif
59597
59598/*
59599** Extract a 2-byte big-endian integer from an array of unsigned bytes.
59600** But if the value is zero, make it 65536.
59601**
59602** This routine is used to extract the "offset to cell content area" value
59603** from the header of a btree page.  If the page size is 65536 and the page
59604** is empty, the offset should be 65536, but the 2-byte value stores zero.
59605** This routine makes the necessary adjustment to 65536.
59606*/
59607#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
59608
59609/*
59610** Values passed as the 5th argument to allocateBtreePage()
59611*/
59612#define BTALLOC_ANY   0           /* Allocate any page */
59613#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
59614#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
59615
59616/*
59617** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
59618** defined, or 0 if it is. For example:
59619**
59620**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
59621*/
59622#ifndef SQLITE_OMIT_AUTOVACUUM
59623#define IfNotOmitAV(expr) (expr)
59624#else
59625#define IfNotOmitAV(expr) 0
59626#endif
59627
59628#ifndef SQLITE_OMIT_SHARED_CACHE
59629/*
59630** A list of BtShared objects that are eligible for participation
59631** in shared cache.  This variable has file scope during normal builds,
59632** but the test harness needs to access it so we make it global for
59633** test builds.
59634**
59635** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
59636*/
59637#ifdef SQLITE_TEST
59638SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
59639#else
59640static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
59641#endif
59642#endif /* SQLITE_OMIT_SHARED_CACHE */
59643
59644#ifndef SQLITE_OMIT_SHARED_CACHE
59645/*
59646** Enable or disable the shared pager and schema features.
59647**
59648** This routine has no effect on existing database connections.
59649** The shared cache setting effects only future calls to
59650** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
59651*/
59652SQLITE_API int sqlite3_enable_shared_cache(int enable){
59653  sqlite3GlobalConfig.sharedCacheEnabled = enable;
59654  return SQLITE_OK;
59655}
59656#endif
59657
59658
59659
59660#ifdef SQLITE_OMIT_SHARED_CACHE
59661  /*
59662  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
59663  ** and clearAllSharedCacheTableLocks()
59664  ** manipulate entries in the BtShared.pLock linked list used to store
59665  ** shared-cache table level locks. If the library is compiled with the
59666  ** shared-cache feature disabled, then there is only ever one user
59667  ** of each BtShared structure and so this locking is not necessary.
59668  ** So define the lock related functions as no-ops.
59669  */
59670  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
59671  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
59672  #define clearAllSharedCacheTableLocks(a)
59673  #define downgradeAllSharedCacheTableLocks(a)
59674  #define hasSharedCacheTableLock(a,b,c,d) 1
59675  #define hasReadConflicts(a, b) 0
59676#endif
59677
59678#ifndef SQLITE_OMIT_SHARED_CACHE
59679
59680#ifdef SQLITE_DEBUG
59681/*
59682**** This function is only used as part of an assert() statement. ***
59683**
59684** Check to see if pBtree holds the required locks to read or write to the
59685** table with root page iRoot.   Return 1 if it does and 0 if not.
59686**
59687** For example, when writing to a table with root-page iRoot via
59688** Btree connection pBtree:
59689**
59690**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
59691**
59692** When writing to an index that resides in a sharable database, the
59693** caller should have first obtained a lock specifying the root page of
59694** the corresponding table. This makes things a bit more complicated,
59695** as this module treats each table as a separate structure. To determine
59696** the table corresponding to the index being written, this
59697** function has to search through the database schema.
59698**
59699** Instead of a lock on the table/index rooted at page iRoot, the caller may
59700** hold a write-lock on the schema table (root page 1). This is also
59701** acceptable.
59702*/
59703static int hasSharedCacheTableLock(
59704  Btree *pBtree,         /* Handle that must hold lock */
59705  Pgno iRoot,            /* Root page of b-tree */
59706  int isIndex,           /* True if iRoot is the root of an index b-tree */
59707  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
59708){
59709  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
59710  Pgno iTab = 0;
59711  BtLock *pLock;
59712
59713  /* If this database is not shareable, or if the client is reading
59714  ** and has the read-uncommitted flag set, then no lock is required.
59715  ** Return true immediately.
59716  */
59717  if( (pBtree->sharable==0)
59718   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
59719  ){
59720    return 1;
59721  }
59722
59723  /* If the client is reading  or writing an index and the schema is
59724  ** not loaded, then it is too difficult to actually check to see if
59725  ** the correct locks are held.  So do not bother - just return true.
59726  ** This case does not come up very often anyhow.
59727  */
59728  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
59729    return 1;
59730  }
59731
59732  /* Figure out the root-page that the lock should be held on. For table
59733  ** b-trees, this is just the root page of the b-tree being read or
59734  ** written. For index b-trees, it is the root page of the associated
59735  ** table.  */
59736  if( isIndex ){
59737    HashElem *p;
59738    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
59739      Index *pIdx = (Index *)sqliteHashData(p);
59740      if( pIdx->tnum==(int)iRoot ){
59741        if( iTab ){
59742          /* Two or more indexes share the same root page.  There must
59743          ** be imposter tables.  So just return true.  The assert is not
59744          ** useful in that case. */
59745          return 1;
59746        }
59747        iTab = pIdx->pTable->tnum;
59748      }
59749    }
59750  }else{
59751    iTab = iRoot;
59752  }
59753
59754  /* Search for the required lock. Either a write-lock on root-page iTab, a
59755  ** write-lock on the schema table, or (if the client is reading) a
59756  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
59757  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
59758    if( pLock->pBtree==pBtree
59759     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
59760     && pLock->eLock>=eLockType
59761    ){
59762      return 1;
59763    }
59764  }
59765
59766  /* Failed to find the required lock. */
59767  return 0;
59768}
59769#endif /* SQLITE_DEBUG */
59770
59771#ifdef SQLITE_DEBUG
59772/*
59773**** This function may be used as part of assert() statements only. ****
59774**
59775** Return true if it would be illegal for pBtree to write into the
59776** table or index rooted at iRoot because other shared connections are
59777** simultaneously reading that same table or index.
59778**
59779** It is illegal for pBtree to write if some other Btree object that
59780** shares the same BtShared object is currently reading or writing
59781** the iRoot table.  Except, if the other Btree object has the
59782** read-uncommitted flag set, then it is OK for the other object to
59783** have a read cursor.
59784**
59785** For example, before writing to any part of the table or index
59786** rooted at page iRoot, one should call:
59787**
59788**    assert( !hasReadConflicts(pBtree, iRoot) );
59789*/
59790static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
59791  BtCursor *p;
59792  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
59793    if( p->pgnoRoot==iRoot
59794     && p->pBtree!=pBtree
59795     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
59796    ){
59797      return 1;
59798    }
59799  }
59800  return 0;
59801}
59802#endif    /* #ifdef SQLITE_DEBUG */
59803
59804/*
59805** Query to see if Btree handle p may obtain a lock of type eLock
59806** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
59807** SQLITE_OK if the lock may be obtained (by calling
59808** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
59809*/
59810static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
59811  BtShared *pBt = p->pBt;
59812  BtLock *pIter;
59813
59814  assert( sqlite3BtreeHoldsMutex(p) );
59815  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
59816  assert( p->db!=0 );
59817  assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
59818
59819  /* If requesting a write-lock, then the Btree must have an open write
59820  ** transaction on this file. And, obviously, for this to be so there
59821  ** must be an open write transaction on the file itself.
59822  */
59823  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
59824  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
59825
59826  /* This routine is a no-op if the shared-cache is not enabled */
59827  if( !p->sharable ){
59828    return SQLITE_OK;
59829  }
59830
59831  /* If some other connection is holding an exclusive lock, the
59832  ** requested lock may not be obtained.
59833  */
59834  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
59835    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
59836    return SQLITE_LOCKED_SHAREDCACHE;
59837  }
59838
59839  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
59840    /* The condition (pIter->eLock!=eLock) in the following if(...)
59841    ** statement is a simplification of:
59842    **
59843    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
59844    **
59845    ** since we know that if eLock==WRITE_LOCK, then no other connection
59846    ** may hold a WRITE_LOCK on any table in this file (since there can
59847    ** only be a single writer).
59848    */
59849    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
59850    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
59851    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
59852      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
59853      if( eLock==WRITE_LOCK ){
59854        assert( p==pBt->pWriter );
59855        pBt->btsFlags |= BTS_PENDING;
59856      }
59857      return SQLITE_LOCKED_SHAREDCACHE;
59858    }
59859  }
59860  return SQLITE_OK;
59861}
59862#endif /* !SQLITE_OMIT_SHARED_CACHE */
59863
59864#ifndef SQLITE_OMIT_SHARED_CACHE
59865/*
59866** Add a lock on the table with root-page iTable to the shared-btree used
59867** by Btree handle p. Parameter eLock must be either READ_LOCK or
59868** WRITE_LOCK.
59869**
59870** This function assumes the following:
59871**
59872**   (a) The specified Btree object p is connected to a sharable
59873**       database (one with the BtShared.sharable flag set), and
59874**
59875**   (b) No other Btree objects hold a lock that conflicts
59876**       with the requested lock (i.e. querySharedCacheTableLock() has
59877**       already been called and returned SQLITE_OK).
59878**
59879** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
59880** is returned if a malloc attempt fails.
59881*/
59882static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
59883  BtShared *pBt = p->pBt;
59884  BtLock *pLock = 0;
59885  BtLock *pIter;
59886
59887  assert( sqlite3BtreeHoldsMutex(p) );
59888  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
59889  assert( p->db!=0 );
59890
59891  /* A connection with the read-uncommitted flag set will never try to
59892  ** obtain a read-lock using this function. The only read-lock obtained
59893  ** by a connection in read-uncommitted mode is on the sqlite_master
59894  ** table, and that lock is obtained in BtreeBeginTrans().  */
59895  assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
59896
59897  /* This function should only be called on a sharable b-tree after it
59898  ** has been determined that no other b-tree holds a conflicting lock.  */
59899  assert( p->sharable );
59900  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
59901
59902  /* First search the list for an existing lock on this table. */
59903  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
59904    if( pIter->iTable==iTable && pIter->pBtree==p ){
59905      pLock = pIter;
59906      break;
59907    }
59908  }
59909
59910  /* If the above search did not find a BtLock struct associating Btree p
59911  ** with table iTable, allocate one and link it into the list.
59912  */
59913  if( !pLock ){
59914    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
59915    if( !pLock ){
59916      return SQLITE_NOMEM_BKPT;
59917    }
59918    pLock->iTable = iTable;
59919    pLock->pBtree = p;
59920    pLock->pNext = pBt->pLock;
59921    pBt->pLock = pLock;
59922  }
59923
59924  /* Set the BtLock.eLock variable to the maximum of the current lock
59925  ** and the requested lock. This means if a write-lock was already held
59926  ** and a read-lock requested, we don't incorrectly downgrade the lock.
59927  */
59928  assert( WRITE_LOCK>READ_LOCK );
59929  if( eLock>pLock->eLock ){
59930    pLock->eLock = eLock;
59931  }
59932
59933  return SQLITE_OK;
59934}
59935#endif /* !SQLITE_OMIT_SHARED_CACHE */
59936
59937#ifndef SQLITE_OMIT_SHARED_CACHE
59938/*
59939** Release all the table locks (locks obtained via calls to
59940** the setSharedCacheTableLock() procedure) held by Btree object p.
59941**
59942** This function assumes that Btree p has an open read or write
59943** transaction. If it does not, then the BTS_PENDING flag
59944** may be incorrectly cleared.
59945*/
59946static void clearAllSharedCacheTableLocks(Btree *p){
59947  BtShared *pBt = p->pBt;
59948  BtLock **ppIter = &pBt->pLock;
59949
59950  assert( sqlite3BtreeHoldsMutex(p) );
59951  assert( p->sharable || 0==*ppIter );
59952  assert( p->inTrans>0 );
59953
59954  while( *ppIter ){
59955    BtLock *pLock = *ppIter;
59956    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
59957    assert( pLock->pBtree->inTrans>=pLock->eLock );
59958    if( pLock->pBtree==p ){
59959      *ppIter = pLock->pNext;
59960      assert( pLock->iTable!=1 || pLock==&p->lock );
59961      if( pLock->iTable!=1 ){
59962        sqlite3_free(pLock);
59963      }
59964    }else{
59965      ppIter = &pLock->pNext;
59966    }
59967  }
59968
59969  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
59970  if( pBt->pWriter==p ){
59971    pBt->pWriter = 0;
59972    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
59973  }else if( pBt->nTransaction==2 ){
59974    /* This function is called when Btree p is concluding its
59975    ** transaction. If there currently exists a writer, and p is not
59976    ** that writer, then the number of locks held by connections other
59977    ** than the writer must be about to drop to zero. In this case
59978    ** set the BTS_PENDING flag to 0.
59979    **
59980    ** If there is not currently a writer, then BTS_PENDING must
59981    ** be zero already. So this next line is harmless in that case.
59982    */
59983    pBt->btsFlags &= ~BTS_PENDING;
59984  }
59985}
59986
59987/*
59988** This function changes all write-locks held by Btree p into read-locks.
59989*/
59990static void downgradeAllSharedCacheTableLocks(Btree *p){
59991  BtShared *pBt = p->pBt;
59992  if( pBt->pWriter==p ){
59993    BtLock *pLock;
59994    pBt->pWriter = 0;
59995    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
59996    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
59997      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
59998      pLock->eLock = READ_LOCK;
59999    }
60000  }
60001}
60002
60003#endif /* SQLITE_OMIT_SHARED_CACHE */
60004
60005static void releasePage(MemPage *pPage);  /* Forward reference */
60006
60007/*
60008***** This routine is used inside of assert() only ****
60009**
60010** Verify that the cursor holds the mutex on its BtShared
60011*/
60012#ifdef SQLITE_DEBUG
60013static int cursorHoldsMutex(BtCursor *p){
60014  return sqlite3_mutex_held(p->pBt->mutex);
60015}
60016
60017/* Verify that the cursor and the BtShared agree about what is the current
60018** database connetion. This is important in shared-cache mode. If the database
60019** connection pointers get out-of-sync, it is possible for routines like
60020** btreeInitPage() to reference an stale connection pointer that references a
60021** a connection that has already closed.  This routine is used inside assert()
60022** statements only and for the purpose of double-checking that the btree code
60023** does keep the database connection pointers up-to-date.
60024*/
60025static int cursorOwnsBtShared(BtCursor *p){
60026  assert( cursorHoldsMutex(p) );
60027  return (p->pBtree->db==p->pBt->db);
60028}
60029#endif
60030
60031/*
60032** Invalidate the overflow cache of the cursor passed as the first argument.
60033** on the shared btree structure pBt.
60034*/
60035#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
60036
60037/*
60038** Invalidate the overflow page-list cache for all cursors opened
60039** on the shared btree structure pBt.
60040*/
60041static void invalidateAllOverflowCache(BtShared *pBt){
60042  BtCursor *p;
60043  assert( sqlite3_mutex_held(pBt->mutex) );
60044  for(p=pBt->pCursor; p; p=p->pNext){
60045    invalidateOverflowCache(p);
60046  }
60047}
60048
60049#ifndef SQLITE_OMIT_INCRBLOB
60050/*
60051** This function is called before modifying the contents of a table
60052** to invalidate any incrblob cursors that are open on the
60053** row or one of the rows being modified.
60054**
60055** If argument isClearTable is true, then the entire contents of the
60056** table is about to be deleted. In this case invalidate all incrblob
60057** cursors open on any row within the table with root-page pgnoRoot.
60058**
60059** Otherwise, if argument isClearTable is false, then the row with
60060** rowid iRow is being replaced or deleted. In this case invalidate
60061** only those incrblob cursors open on that specific row.
60062*/
60063static void invalidateIncrblobCursors(
60064  Btree *pBtree,          /* The database file to check */
60065  Pgno pgnoRoot,          /* The table that might be changing */
60066  i64 iRow,               /* The rowid that might be changing */
60067  int isClearTable        /* True if all rows are being deleted */
60068){
60069  BtCursor *p;
60070  if( pBtree->hasIncrblobCur==0 ) return;
60071  assert( sqlite3BtreeHoldsMutex(pBtree) );
60072  pBtree->hasIncrblobCur = 0;
60073  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
60074    if( (p->curFlags & BTCF_Incrblob)!=0 ){
60075      pBtree->hasIncrblobCur = 1;
60076      if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
60077        p->eState = CURSOR_INVALID;
60078      }
60079    }
60080  }
60081}
60082
60083#else
60084  /* Stub function when INCRBLOB is omitted */
60085  #define invalidateIncrblobCursors(w,x,y,z)
60086#endif /* SQLITE_OMIT_INCRBLOB */
60087
60088/*
60089** Set bit pgno of the BtShared.pHasContent bitvec. This is called
60090** when a page that previously contained data becomes a free-list leaf
60091** page.
60092**
60093** The BtShared.pHasContent bitvec exists to work around an obscure
60094** bug caused by the interaction of two useful IO optimizations surrounding
60095** free-list leaf pages:
60096**
60097**   1) When all data is deleted from a page and the page becomes
60098**      a free-list leaf page, the page is not written to the database
60099**      (as free-list leaf pages contain no meaningful data). Sometimes
60100**      such a page is not even journalled (as it will not be modified,
60101**      why bother journalling it?).
60102**
60103**   2) When a free-list leaf page is reused, its content is not read
60104**      from the database or written to the journal file (why should it
60105**      be, if it is not at all meaningful?).
60106**
60107** By themselves, these optimizations work fine and provide a handy
60108** performance boost to bulk delete or insert operations. However, if
60109** a page is moved to the free-list and then reused within the same
60110** transaction, a problem comes up. If the page is not journalled when
60111** it is moved to the free-list and it is also not journalled when it
60112** is extracted from the free-list and reused, then the original data
60113** may be lost. In the event of a rollback, it may not be possible
60114** to restore the database to its original configuration.
60115**
60116** The solution is the BtShared.pHasContent bitvec. Whenever a page is
60117** moved to become a free-list leaf page, the corresponding bit is
60118** set in the bitvec. Whenever a leaf page is extracted from the free-list,
60119** optimization 2 above is omitted if the corresponding bit is already
60120** set in BtShared.pHasContent. The contents of the bitvec are cleared
60121** at the end of every transaction.
60122*/
60123static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
60124  int rc = SQLITE_OK;
60125  if( !pBt->pHasContent ){
60126    assert( pgno<=pBt->nPage );
60127    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
60128    if( !pBt->pHasContent ){
60129      rc = SQLITE_NOMEM_BKPT;
60130    }
60131  }
60132  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
60133    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
60134  }
60135  return rc;
60136}
60137
60138/*
60139** Query the BtShared.pHasContent vector.
60140**
60141** This function is called when a free-list leaf page is removed from the
60142** free-list for reuse. It returns false if it is safe to retrieve the
60143** page from the pager layer with the 'no-content' flag set. True otherwise.
60144*/
60145static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
60146  Bitvec *p = pBt->pHasContent;
60147  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
60148}
60149
60150/*
60151** Clear (destroy) the BtShared.pHasContent bitvec. This should be
60152** invoked at the conclusion of each write-transaction.
60153*/
60154static void btreeClearHasContent(BtShared *pBt){
60155  sqlite3BitvecDestroy(pBt->pHasContent);
60156  pBt->pHasContent = 0;
60157}
60158
60159/*
60160** Release all of the apPage[] pages for a cursor.
60161*/
60162static void btreeReleaseAllCursorPages(BtCursor *pCur){
60163  int i;
60164  for(i=0; i<=pCur->iPage; i++){
60165    releasePage(pCur->apPage[i]);
60166    pCur->apPage[i] = 0;
60167  }
60168  pCur->iPage = -1;
60169}
60170
60171/*
60172** The cursor passed as the only argument must point to a valid entry
60173** when this function is called (i.e. have eState==CURSOR_VALID). This
60174** function saves the current cursor key in variables pCur->nKey and
60175** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
60176** code otherwise.
60177**
60178** If the cursor is open on an intkey table, then the integer key
60179** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
60180** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
60181** set to point to a malloced buffer pCur->nKey bytes in size containing
60182** the key.
60183*/
60184static int saveCursorKey(BtCursor *pCur){
60185  int rc = SQLITE_OK;
60186  assert( CURSOR_VALID==pCur->eState );
60187  assert( 0==pCur->pKey );
60188  assert( cursorHoldsMutex(pCur) );
60189
60190  if( pCur->curIntKey ){
60191    /* Only the rowid is required for a table btree */
60192    pCur->nKey = sqlite3BtreeIntegerKey(pCur);
60193  }else{
60194    /* For an index btree, save the complete key content */
60195    void *pKey;
60196    pCur->nKey = sqlite3BtreePayloadSize(pCur);
60197    pKey = sqlite3Malloc( pCur->nKey );
60198    if( pKey ){
60199      rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
60200      if( rc==SQLITE_OK ){
60201        pCur->pKey = pKey;
60202      }else{
60203        sqlite3_free(pKey);
60204      }
60205    }else{
60206      rc = SQLITE_NOMEM_BKPT;
60207    }
60208  }
60209  assert( !pCur->curIntKey || !pCur->pKey );
60210  return rc;
60211}
60212
60213/*
60214** Save the current cursor position in the variables BtCursor.nKey
60215** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
60216**
60217** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
60218** prior to calling this routine.
60219*/
60220static int saveCursorPosition(BtCursor *pCur){
60221  int rc;
60222
60223  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
60224  assert( 0==pCur->pKey );
60225  assert( cursorHoldsMutex(pCur) );
60226
60227  if( pCur->eState==CURSOR_SKIPNEXT ){
60228    pCur->eState = CURSOR_VALID;
60229  }else{
60230    pCur->skipNext = 0;
60231  }
60232
60233  rc = saveCursorKey(pCur);
60234  if( rc==SQLITE_OK ){
60235    btreeReleaseAllCursorPages(pCur);
60236    pCur->eState = CURSOR_REQUIRESEEK;
60237  }
60238
60239  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
60240  return rc;
60241}
60242
60243/* Forward reference */
60244static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
60245
60246/*
60247** Save the positions of all cursors (except pExcept) that are open on
60248** the table with root-page iRoot.  "Saving the cursor position" means that
60249** the location in the btree is remembered in such a way that it can be
60250** moved back to the same spot after the btree has been modified.  This
60251** routine is called just before cursor pExcept is used to modify the
60252** table, for example in BtreeDelete() or BtreeInsert().
60253**
60254** If there are two or more cursors on the same btree, then all such
60255** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
60256** routine enforces that rule.  This routine only needs to be called in
60257** the uncommon case when pExpect has the BTCF_Multiple flag set.
60258**
60259** If pExpect!=NULL and if no other cursors are found on the same root-page,
60260** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
60261** pointless call to this routine.
60262**
60263** Implementation note:  This routine merely checks to see if any cursors
60264** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
60265** event that cursors are in need to being saved.
60266*/
60267static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
60268  BtCursor *p;
60269  assert( sqlite3_mutex_held(pBt->mutex) );
60270  assert( pExcept==0 || pExcept->pBt==pBt );
60271  for(p=pBt->pCursor; p; p=p->pNext){
60272    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
60273  }
60274  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
60275  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
60276  return SQLITE_OK;
60277}
60278
60279/* This helper routine to saveAllCursors does the actual work of saving
60280** the cursors if and when a cursor is found that actually requires saving.
60281** The common case is that no cursors need to be saved, so this routine is
60282** broken out from its caller to avoid unnecessary stack pointer movement.
60283*/
60284static int SQLITE_NOINLINE saveCursorsOnList(
60285  BtCursor *p,         /* The first cursor that needs saving */
60286  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
60287  BtCursor *pExcept    /* Do not save this cursor */
60288){
60289  do{
60290    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
60291      if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
60292        int rc = saveCursorPosition(p);
60293        if( SQLITE_OK!=rc ){
60294          return rc;
60295        }
60296      }else{
60297        testcase( p->iPage>0 );
60298        btreeReleaseAllCursorPages(p);
60299      }
60300    }
60301    p = p->pNext;
60302  }while( p );
60303  return SQLITE_OK;
60304}
60305
60306/*
60307** Clear the current cursor position.
60308*/
60309SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
60310  assert( cursorHoldsMutex(pCur) );
60311  sqlite3_free(pCur->pKey);
60312  pCur->pKey = 0;
60313  pCur->eState = CURSOR_INVALID;
60314}
60315
60316/*
60317** In this version of BtreeMoveto, pKey is a packed index record
60318** such as is generated by the OP_MakeRecord opcode.  Unpack the
60319** record and then call BtreeMovetoUnpacked() to do the work.
60320*/
60321static int btreeMoveto(
60322  BtCursor *pCur,     /* Cursor open on the btree to be searched */
60323  const void *pKey,   /* Packed key if the btree is an index */
60324  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
60325  int bias,           /* Bias search to the high end */
60326  int *pRes           /* Write search results here */
60327){
60328  int rc;                    /* Status code */
60329  UnpackedRecord *pIdxKey;   /* Unpacked index key */
60330
60331  if( pKey ){
60332    assert( nKey==(i64)(int)nKey );
60333    pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
60334    if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
60335    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
60336    if( pIdxKey->nField==0 ){
60337      rc = SQLITE_CORRUPT_PGNO(pCur->apPage[pCur->iPage]->pgno);
60338      goto moveto_done;
60339    }
60340  }else{
60341    pIdxKey = 0;
60342  }
60343  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
60344moveto_done:
60345  if( pIdxKey ){
60346    sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
60347  }
60348  return rc;
60349}
60350
60351/*
60352** Restore the cursor to the position it was in (or as close to as possible)
60353** when saveCursorPosition() was called. Note that this call deletes the
60354** saved position info stored by saveCursorPosition(), so there can be
60355** at most one effective restoreCursorPosition() call after each
60356** saveCursorPosition().
60357*/
60358static int btreeRestoreCursorPosition(BtCursor *pCur){
60359  int rc;
60360  int skipNext;
60361  assert( cursorOwnsBtShared(pCur) );
60362  assert( pCur->eState>=CURSOR_REQUIRESEEK );
60363  if( pCur->eState==CURSOR_FAULT ){
60364    return pCur->skipNext;
60365  }
60366  pCur->eState = CURSOR_INVALID;
60367  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
60368  if( rc==SQLITE_OK ){
60369    sqlite3_free(pCur->pKey);
60370    pCur->pKey = 0;
60371    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
60372    pCur->skipNext |= skipNext;
60373    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
60374      pCur->eState = CURSOR_SKIPNEXT;
60375    }
60376  }
60377  return rc;
60378}
60379
60380#define restoreCursorPosition(p) \
60381  (p->eState>=CURSOR_REQUIRESEEK ? \
60382         btreeRestoreCursorPosition(p) : \
60383         SQLITE_OK)
60384
60385/*
60386** Determine whether or not a cursor has moved from the position where
60387** it was last placed, or has been invalidated for any other reason.
60388** Cursors can move when the row they are pointing at is deleted out
60389** from under them, for example.  Cursor might also move if a btree
60390** is rebalanced.
60391**
60392** Calling this routine with a NULL cursor pointer returns false.
60393**
60394** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
60395** back to where it ought to be if this routine returns true.
60396*/
60397SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
60398  return pCur->eState!=CURSOR_VALID;
60399}
60400
60401/*
60402** This routine restores a cursor back to its original position after it
60403** has been moved by some outside activity (such as a btree rebalance or
60404** a row having been deleted out from under the cursor).
60405**
60406** On success, the *pDifferentRow parameter is false if the cursor is left
60407** pointing at exactly the same row.  *pDifferntRow is the row the cursor
60408** was pointing to has been deleted, forcing the cursor to point to some
60409** nearby row.
60410**
60411** This routine should only be called for a cursor that just returned
60412** TRUE from sqlite3BtreeCursorHasMoved().
60413*/
60414SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
60415  int rc;
60416
60417  assert( pCur!=0 );
60418  assert( pCur->eState!=CURSOR_VALID );
60419  rc = restoreCursorPosition(pCur);
60420  if( rc ){
60421    *pDifferentRow = 1;
60422    return rc;
60423  }
60424  if( pCur->eState!=CURSOR_VALID ){
60425    *pDifferentRow = 1;
60426  }else{
60427    assert( pCur->skipNext==0 );
60428    *pDifferentRow = 0;
60429  }
60430  return SQLITE_OK;
60431}
60432
60433#ifdef SQLITE_ENABLE_CURSOR_HINTS
60434/*
60435** Provide hints to the cursor.  The particular hint given (and the type
60436** and number of the varargs parameters) is determined by the eHintType
60437** parameter.  See the definitions of the BTREE_HINT_* macros for details.
60438*/
60439SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
60440  /* Used only by system that substitute their own storage engine */
60441}
60442#endif
60443
60444/*
60445** Provide flag hints to the cursor.
60446*/
60447SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
60448  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
60449  pCur->hints = x;
60450}
60451
60452
60453#ifndef SQLITE_OMIT_AUTOVACUUM
60454/*
60455** Given a page number of a regular database page, return the page
60456** number for the pointer-map page that contains the entry for the
60457** input page number.
60458**
60459** Return 0 (not a valid page) for pgno==1 since there is
60460** no pointer map associated with page 1.  The integrity_check logic
60461** requires that ptrmapPageno(*,1)!=1.
60462*/
60463static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
60464  int nPagesPerMapPage;
60465  Pgno iPtrMap, ret;
60466  assert( sqlite3_mutex_held(pBt->mutex) );
60467  if( pgno<2 ) return 0;
60468  nPagesPerMapPage = (pBt->usableSize/5)+1;
60469  iPtrMap = (pgno-2)/nPagesPerMapPage;
60470  ret = (iPtrMap*nPagesPerMapPage) + 2;
60471  if( ret==PENDING_BYTE_PAGE(pBt) ){
60472    ret++;
60473  }
60474  return ret;
60475}
60476
60477/*
60478** Write an entry into the pointer map.
60479**
60480** This routine updates the pointer map entry for page number 'key'
60481** so that it maps to type 'eType' and parent page number 'pgno'.
60482**
60483** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
60484** a no-op.  If an error occurs, the appropriate error code is written
60485** into *pRC.
60486*/
60487static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
60488  DbPage *pDbPage;  /* The pointer map page */
60489  u8 *pPtrmap;      /* The pointer map data */
60490  Pgno iPtrmap;     /* The pointer map page number */
60491  int offset;       /* Offset in pointer map page */
60492  int rc;           /* Return code from subfunctions */
60493
60494  if( *pRC ) return;
60495
60496  assert( sqlite3_mutex_held(pBt->mutex) );
60497  /* The master-journal page number must never be used as a pointer map page */
60498  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
60499
60500  assert( pBt->autoVacuum );
60501  if( key==0 ){
60502    *pRC = SQLITE_CORRUPT_BKPT;
60503    return;
60504  }
60505  iPtrmap = PTRMAP_PAGENO(pBt, key);
60506  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
60507  if( rc!=SQLITE_OK ){
60508    *pRC = rc;
60509    return;
60510  }
60511  offset = PTRMAP_PTROFFSET(iPtrmap, key);
60512  if( offset<0 ){
60513    *pRC = SQLITE_CORRUPT_BKPT;
60514    goto ptrmap_exit;
60515  }
60516  assert( offset <= (int)pBt->usableSize-5 );
60517  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
60518
60519  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
60520    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
60521    *pRC= rc = sqlite3PagerWrite(pDbPage);
60522    if( rc==SQLITE_OK ){
60523      pPtrmap[offset] = eType;
60524      put4byte(&pPtrmap[offset+1], parent);
60525    }
60526  }
60527
60528ptrmap_exit:
60529  sqlite3PagerUnref(pDbPage);
60530}
60531
60532/*
60533** Read an entry from the pointer map.
60534**
60535** This routine retrieves the pointer map entry for page 'key', writing
60536** the type and parent page number to *pEType and *pPgno respectively.
60537** An error code is returned if something goes wrong, otherwise SQLITE_OK.
60538*/
60539static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
60540  DbPage *pDbPage;   /* The pointer map page */
60541  int iPtrmap;       /* Pointer map page index */
60542  u8 *pPtrmap;       /* Pointer map page data */
60543  int offset;        /* Offset of entry in pointer map */
60544  int rc;
60545
60546  assert( sqlite3_mutex_held(pBt->mutex) );
60547
60548  iPtrmap = PTRMAP_PAGENO(pBt, key);
60549  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
60550  if( rc!=0 ){
60551    return rc;
60552  }
60553  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
60554
60555  offset = PTRMAP_PTROFFSET(iPtrmap, key);
60556  if( offset<0 ){
60557    sqlite3PagerUnref(pDbPage);
60558    return SQLITE_CORRUPT_BKPT;
60559  }
60560  assert( offset <= (int)pBt->usableSize-5 );
60561  assert( pEType!=0 );
60562  *pEType = pPtrmap[offset];
60563  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
60564
60565  sqlite3PagerUnref(pDbPage);
60566  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
60567  return SQLITE_OK;
60568}
60569
60570#else /* if defined SQLITE_OMIT_AUTOVACUUM */
60571  #define ptrmapPut(w,x,y,z,rc)
60572  #define ptrmapGet(w,x,y,z) SQLITE_OK
60573  #define ptrmapPutOvflPtr(x, y, rc)
60574#endif
60575
60576/*
60577** Given a btree page and a cell index (0 means the first cell on
60578** the page, 1 means the second cell, and so forth) return a pointer
60579** to the cell content.
60580**
60581** findCellPastPtr() does the same except it skips past the initial
60582** 4-byte child pointer found on interior pages, if there is one.
60583**
60584** This routine works only for pages that do not contain overflow cells.
60585*/
60586#define findCell(P,I) \
60587  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
60588#define findCellPastPtr(P,I) \
60589  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
60590
60591
60592/*
60593** This is common tail processing for btreeParseCellPtr() and
60594** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
60595** on a single B-tree page.  Make necessary adjustments to the CellInfo
60596** structure.
60597*/
60598static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
60599  MemPage *pPage,         /* Page containing the cell */
60600  u8 *pCell,              /* Pointer to the cell text. */
60601  CellInfo *pInfo         /* Fill in this structure */
60602){
60603  /* If the payload will not fit completely on the local page, we have
60604  ** to decide how much to store locally and how much to spill onto
60605  ** overflow pages.  The strategy is to minimize the amount of unused
60606  ** space on overflow pages while keeping the amount of local storage
60607  ** in between minLocal and maxLocal.
60608  **
60609  ** Warning:  changing the way overflow payload is distributed in any
60610  ** way will result in an incompatible file format.
60611  */
60612  int minLocal;  /* Minimum amount of payload held locally */
60613  int maxLocal;  /* Maximum amount of payload held locally */
60614  int surplus;   /* Overflow payload available for local storage */
60615
60616  minLocal = pPage->minLocal;
60617  maxLocal = pPage->maxLocal;
60618  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
60619  testcase( surplus==maxLocal );
60620  testcase( surplus==maxLocal+1 );
60621  if( surplus <= maxLocal ){
60622    pInfo->nLocal = (u16)surplus;
60623  }else{
60624    pInfo->nLocal = (u16)minLocal;
60625  }
60626  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
60627}
60628
60629/*
60630** The following routines are implementations of the MemPage.xParseCell()
60631** method.
60632**
60633** Parse a cell content block and fill in the CellInfo structure.
60634**
60635** btreeParseCellPtr()        =>   table btree leaf nodes
60636** btreeParseCellNoPayload()  =>   table btree internal nodes
60637** btreeParseCellPtrIndex()   =>   index btree nodes
60638**
60639** There is also a wrapper function btreeParseCell() that works for
60640** all MemPage types and that references the cell by index rather than
60641** by pointer.
60642*/
60643static void btreeParseCellPtrNoPayload(
60644  MemPage *pPage,         /* Page containing the cell */
60645  u8 *pCell,              /* Pointer to the cell text. */
60646  CellInfo *pInfo         /* Fill in this structure */
60647){
60648  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60649  assert( pPage->leaf==0 );
60650  assert( pPage->childPtrSize==4 );
60651#ifndef SQLITE_DEBUG
60652  UNUSED_PARAMETER(pPage);
60653#endif
60654  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
60655  pInfo->nPayload = 0;
60656  pInfo->nLocal = 0;
60657  pInfo->pPayload = 0;
60658  return;
60659}
60660static void btreeParseCellPtr(
60661  MemPage *pPage,         /* Page containing the cell */
60662  u8 *pCell,              /* Pointer to the cell text. */
60663  CellInfo *pInfo         /* Fill in this structure */
60664){
60665  u8 *pIter;              /* For scanning through pCell */
60666  u32 nPayload;           /* Number of bytes of cell payload */
60667  u64 iKey;               /* Extracted Key value */
60668
60669  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60670  assert( pPage->leaf==0 || pPage->leaf==1 );
60671  assert( pPage->intKeyLeaf );
60672  assert( pPage->childPtrSize==0 );
60673  pIter = pCell;
60674
60675  /* The next block of code is equivalent to:
60676  **
60677  **     pIter += getVarint32(pIter, nPayload);
60678  **
60679  ** The code is inlined to avoid a function call.
60680  */
60681  nPayload = *pIter;
60682  if( nPayload>=0x80 ){
60683    u8 *pEnd = &pIter[8];
60684    nPayload &= 0x7f;
60685    do{
60686      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
60687    }while( (*pIter)>=0x80 && pIter<pEnd );
60688  }
60689  pIter++;
60690
60691  /* The next block of code is equivalent to:
60692  **
60693  **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
60694  **
60695  ** The code is inlined to avoid a function call.
60696  */
60697  iKey = *pIter;
60698  if( iKey>=0x80 ){
60699    u8 *pEnd = &pIter[7];
60700    iKey &= 0x7f;
60701    while(1){
60702      iKey = (iKey<<7) | (*++pIter & 0x7f);
60703      if( (*pIter)<0x80 ) break;
60704      if( pIter>=pEnd ){
60705        iKey = (iKey<<8) | *++pIter;
60706        break;
60707      }
60708    }
60709  }
60710  pIter++;
60711
60712  pInfo->nKey = *(i64*)&iKey;
60713  pInfo->nPayload = nPayload;
60714  pInfo->pPayload = pIter;
60715  testcase( nPayload==pPage->maxLocal );
60716  testcase( nPayload==pPage->maxLocal+1 );
60717  if( nPayload<=pPage->maxLocal ){
60718    /* This is the (easy) common case where the entire payload fits
60719    ** on the local page.  No overflow is required.
60720    */
60721    pInfo->nSize = nPayload + (u16)(pIter - pCell);
60722    if( pInfo->nSize<4 ) pInfo->nSize = 4;
60723    pInfo->nLocal = (u16)nPayload;
60724  }else{
60725    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
60726  }
60727}
60728static void btreeParseCellPtrIndex(
60729  MemPage *pPage,         /* Page containing the cell */
60730  u8 *pCell,              /* Pointer to the cell text. */
60731  CellInfo *pInfo         /* Fill in this structure */
60732){
60733  u8 *pIter;              /* For scanning through pCell */
60734  u32 nPayload;           /* Number of bytes of cell payload */
60735
60736  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60737  assert( pPage->leaf==0 || pPage->leaf==1 );
60738  assert( pPage->intKeyLeaf==0 );
60739  pIter = pCell + pPage->childPtrSize;
60740  nPayload = *pIter;
60741  if( nPayload>=0x80 ){
60742    u8 *pEnd = &pIter[8];
60743    nPayload &= 0x7f;
60744    do{
60745      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
60746    }while( *(pIter)>=0x80 && pIter<pEnd );
60747  }
60748  pIter++;
60749  pInfo->nKey = nPayload;
60750  pInfo->nPayload = nPayload;
60751  pInfo->pPayload = pIter;
60752  testcase( nPayload==pPage->maxLocal );
60753  testcase( nPayload==pPage->maxLocal+1 );
60754  if( nPayload<=pPage->maxLocal ){
60755    /* This is the (easy) common case where the entire payload fits
60756    ** on the local page.  No overflow is required.
60757    */
60758    pInfo->nSize = nPayload + (u16)(pIter - pCell);
60759    if( pInfo->nSize<4 ) pInfo->nSize = 4;
60760    pInfo->nLocal = (u16)nPayload;
60761  }else{
60762    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
60763  }
60764}
60765static void btreeParseCell(
60766  MemPage *pPage,         /* Page containing the cell */
60767  int iCell,              /* The cell index.  First cell is 0 */
60768  CellInfo *pInfo         /* Fill in this structure */
60769){
60770  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
60771}
60772
60773/*
60774** The following routines are implementations of the MemPage.xCellSize
60775** method.
60776**
60777** Compute the total number of bytes that a Cell needs in the cell
60778** data area of the btree-page.  The return number includes the cell
60779** data header and the local payload, but not any overflow page or
60780** the space used by the cell pointer.
60781**
60782** cellSizePtrNoPayload()    =>   table internal nodes
60783** cellSizePtr()             =>   all index nodes & table leaf nodes
60784*/
60785static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
60786  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
60787  u8 *pEnd;                                /* End mark for a varint */
60788  u32 nSize;                               /* Size value to return */
60789
60790#ifdef SQLITE_DEBUG
60791  /* The value returned by this function should always be the same as
60792  ** the (CellInfo.nSize) value found by doing a full parse of the
60793  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
60794  ** this function verifies that this invariant is not violated. */
60795  CellInfo debuginfo;
60796  pPage->xParseCell(pPage, pCell, &debuginfo);
60797#endif
60798
60799  nSize = *pIter;
60800  if( nSize>=0x80 ){
60801    pEnd = &pIter[8];
60802    nSize &= 0x7f;
60803    do{
60804      nSize = (nSize<<7) | (*++pIter & 0x7f);
60805    }while( *(pIter)>=0x80 && pIter<pEnd );
60806  }
60807  pIter++;
60808  if( pPage->intKey ){
60809    /* pIter now points at the 64-bit integer key value, a variable length
60810    ** integer. The following block moves pIter to point at the first byte
60811    ** past the end of the key value. */
60812    pEnd = &pIter[9];
60813    while( (*pIter++)&0x80 && pIter<pEnd );
60814  }
60815  testcase( nSize==pPage->maxLocal );
60816  testcase( nSize==pPage->maxLocal+1 );
60817  if( nSize<=pPage->maxLocal ){
60818    nSize += (u32)(pIter - pCell);
60819    if( nSize<4 ) nSize = 4;
60820  }else{
60821    int minLocal = pPage->minLocal;
60822    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
60823    testcase( nSize==pPage->maxLocal );
60824    testcase( nSize==pPage->maxLocal+1 );
60825    if( nSize>pPage->maxLocal ){
60826      nSize = minLocal;
60827    }
60828    nSize += 4 + (u16)(pIter - pCell);
60829  }
60830  assert( nSize==debuginfo.nSize || CORRUPT_DB );
60831  return (u16)nSize;
60832}
60833static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
60834  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
60835  u8 *pEnd;              /* End mark for a varint */
60836
60837#ifdef SQLITE_DEBUG
60838  /* The value returned by this function should always be the same as
60839  ** the (CellInfo.nSize) value found by doing a full parse of the
60840  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
60841  ** this function verifies that this invariant is not violated. */
60842  CellInfo debuginfo;
60843  pPage->xParseCell(pPage, pCell, &debuginfo);
60844#else
60845  UNUSED_PARAMETER(pPage);
60846#endif
60847
60848  assert( pPage->childPtrSize==4 );
60849  pEnd = pIter + 9;
60850  while( (*pIter++)&0x80 && pIter<pEnd );
60851  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
60852  return (u16)(pIter - pCell);
60853}
60854
60855
60856#ifdef SQLITE_DEBUG
60857/* This variation on cellSizePtr() is used inside of assert() statements
60858** only. */
60859static u16 cellSize(MemPage *pPage, int iCell){
60860  return pPage->xCellSize(pPage, findCell(pPage, iCell));
60861}
60862#endif
60863
60864#ifndef SQLITE_OMIT_AUTOVACUUM
60865/*
60866** If the cell pCell, part of page pPage contains a pointer
60867** to an overflow page, insert an entry into the pointer-map
60868** for the overflow page.
60869*/
60870static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
60871  CellInfo info;
60872  if( *pRC ) return;
60873  assert( pCell!=0 );
60874  pPage->xParseCell(pPage, pCell, &info);
60875  if( info.nLocal<info.nPayload ){
60876    Pgno ovfl = get4byte(&pCell[info.nSize-4]);
60877    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
60878  }
60879}
60880#endif
60881
60882
60883/*
60884** Defragment the page given. This routine reorganizes cells within the
60885** page so that there are no free-blocks on the free-block list.
60886**
60887** Parameter nMaxFrag is the maximum amount of fragmented space that may be
60888** present in the page after this routine returns.
60889**
60890** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
60891** b-tree page so that there are no freeblocks or fragment bytes, all
60892** unused bytes are contained in the unallocated space region, and all
60893** cells are packed tightly at the end of the page.
60894*/
60895static int defragmentPage(MemPage *pPage, int nMaxFrag){
60896  int i;                     /* Loop counter */
60897  int pc;                    /* Address of the i-th cell */
60898  int hdr;                   /* Offset to the page header */
60899  int size;                  /* Size of a cell */
60900  int usableSize;            /* Number of usable bytes on a page */
60901  int cellOffset;            /* Offset to the cell pointer array */
60902  int cbrk;                  /* Offset to the cell content area */
60903  int nCell;                 /* Number of cells on the page */
60904  unsigned char *data;       /* The page data */
60905  unsigned char *temp;       /* Temp area for cell content */
60906  unsigned char *src;        /* Source of content */
60907  int iCellFirst;            /* First allowable cell index */
60908  int iCellLast;             /* Last possible cell index */
60909
60910  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60911  assert( pPage->pBt!=0 );
60912  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
60913  assert( pPage->nOverflow==0 );
60914  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60915  temp = 0;
60916  src = data = pPage->aData;
60917  hdr = pPage->hdrOffset;
60918  cellOffset = pPage->cellOffset;
60919  nCell = pPage->nCell;
60920  assert( nCell==get2byte(&data[hdr+3]) );
60921  iCellFirst = cellOffset + 2*nCell;
60922  usableSize = pPage->pBt->usableSize;
60923
60924  /* This block handles pages with two or fewer free blocks and nMaxFrag
60925  ** or fewer fragmented bytes. In this case it is faster to move the
60926  ** two (or one) blocks of cells using memmove() and add the required
60927  ** offsets to each pointer in the cell-pointer array than it is to
60928  ** reconstruct the entire page.  */
60929  if( (int)data[hdr+7]<=nMaxFrag ){
60930    int iFree = get2byte(&data[hdr+1]);
60931    if( iFree ){
60932      int iFree2 = get2byte(&data[iFree]);
60933
60934      /* pageFindSlot() has already verified that free blocks are sorted
60935      ** in order of offset within the page, and that no block extends
60936      ** past the end of the page. Provided the two free slots do not
60937      ** overlap, this guarantees that the memmove() calls below will not
60938      ** overwrite the usableSize byte buffer, even if the database page
60939      ** is corrupt.  */
60940      assert( iFree2==0 || iFree2>iFree );
60941      assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
60942      assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
60943
60944      if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
60945        u8 *pEnd = &data[cellOffset + nCell*2];
60946        u8 *pAddr;
60947        int sz2 = 0;
60948        int sz = get2byte(&data[iFree+2]);
60949        int top = get2byte(&data[hdr+5]);
60950        if( iFree2 ){
60951          if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
60952          sz2 = get2byte(&data[iFree2+2]);
60953          assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
60954          memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
60955          sz += sz2;
60956        }
60957        cbrk = top+sz;
60958        assert( cbrk+(iFree-top) <= usableSize );
60959        memmove(&data[cbrk], &data[top], iFree-top);
60960        for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
60961          pc = get2byte(pAddr);
60962          if( pc<iFree ){ put2byte(pAddr, pc+sz); }
60963          else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
60964        }
60965        goto defragment_out;
60966      }
60967    }
60968  }
60969
60970  cbrk = usableSize;
60971  iCellLast = usableSize - 4;
60972  for(i=0; i<nCell; i++){
60973    u8 *pAddr;     /* The i-th cell pointer */
60974    pAddr = &data[cellOffset + i*2];
60975    pc = get2byte(pAddr);
60976    testcase( pc==iCellFirst );
60977    testcase( pc==iCellLast );
60978    /* These conditions have already been verified in btreeInitPage()
60979    ** if PRAGMA cell_size_check=ON.
60980    */
60981    if( pc<iCellFirst || pc>iCellLast ){
60982      return SQLITE_CORRUPT_PGNO(pPage->pgno);
60983    }
60984    assert( pc>=iCellFirst && pc<=iCellLast );
60985    size = pPage->xCellSize(pPage, &src[pc]);
60986    cbrk -= size;
60987    if( cbrk<iCellFirst || pc+size>usableSize ){
60988      return SQLITE_CORRUPT_PGNO(pPage->pgno);
60989    }
60990    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
60991    testcase( cbrk+size==usableSize );
60992    testcase( pc+size==usableSize );
60993    put2byte(pAddr, cbrk);
60994    if( temp==0 ){
60995      int x;
60996      if( cbrk==pc ) continue;
60997      temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
60998      x = get2byte(&data[hdr+5]);
60999      memcpy(&temp[x], &data[x], (cbrk+size) - x);
61000      src = temp;
61001    }
61002    memcpy(&data[cbrk], &src[pc], size);
61003  }
61004  data[hdr+7] = 0;
61005
61006 defragment_out:
61007  if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
61008    return SQLITE_CORRUPT_PGNO(pPage->pgno);
61009  }
61010  assert( cbrk>=iCellFirst );
61011  put2byte(&data[hdr+5], cbrk);
61012  data[hdr+1] = 0;
61013  data[hdr+2] = 0;
61014  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
61015  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61016  return SQLITE_OK;
61017}
61018
61019/*
61020** Search the free-list on page pPg for space to store a cell nByte bytes in
61021** size. If one can be found, return a pointer to the space and remove it
61022** from the free-list.
61023**
61024** If no suitable space can be found on the free-list, return NULL.
61025**
61026** This function may detect corruption within pPg.  If corruption is
61027** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
61028**
61029** Slots on the free list that are between 1 and 3 bytes larger than nByte
61030** will be ignored if adding the extra space to the fragmentation count
61031** causes the fragmentation count to exceed 60.
61032*/
61033static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
61034  const int hdr = pPg->hdrOffset;
61035  u8 * const aData = pPg->aData;
61036  int iAddr = hdr + 1;
61037  int pc = get2byte(&aData[iAddr]);
61038  int x;
61039  int usableSize = pPg->pBt->usableSize;
61040
61041  assert( pc>0 );
61042  do{
61043    int size;            /* Size of the free slot */
61044    /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
61045    ** increasing offset. */
61046    if( pc>usableSize-4 || pc<iAddr+4 ){
61047      *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
61048      return 0;
61049    }
61050    /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
61051    ** freeblock form a big-endian integer which is the size of the freeblock
61052    ** in bytes, including the 4-byte header. */
61053    size = get2byte(&aData[pc+2]);
61054    if( (x = size - nByte)>=0 ){
61055      testcase( x==4 );
61056      testcase( x==3 );
61057      if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
61058        *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno);
61059        return 0;
61060      }else if( x<4 ){
61061        /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
61062        ** number of bytes in fragments may not exceed 60. */
61063        if( aData[hdr+7]>57 ) return 0;
61064
61065        /* Remove the slot from the free-list. Update the number of
61066        ** fragmented bytes within the page. */
61067        memcpy(&aData[iAddr], &aData[pc], 2);
61068        aData[hdr+7] += (u8)x;
61069      }else{
61070        /* The slot remains on the free-list. Reduce its size to account
61071         ** for the portion used by the new allocation. */
61072        put2byte(&aData[pc+2], x);
61073      }
61074      return &aData[pc + x];
61075    }
61076    iAddr = pc;
61077    pc = get2byte(&aData[pc]);
61078  }while( pc );
61079
61080  return 0;
61081}
61082
61083/*
61084** Allocate nByte bytes of space from within the B-Tree page passed
61085** as the first argument. Write into *pIdx the index into pPage->aData[]
61086** of the first byte of allocated space. Return either SQLITE_OK or
61087** an error code (usually SQLITE_CORRUPT).
61088**
61089** The caller guarantees that there is sufficient space to make the
61090** allocation.  This routine might need to defragment in order to bring
61091** all the space together, however.  This routine will avoid using
61092** the first two bytes past the cell pointer area since presumably this
61093** allocation is being made in order to insert a new cell, so we will
61094** also end up needing a new cell pointer.
61095*/
61096static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
61097  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
61098  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
61099  int top;                             /* First byte of cell content area */
61100  int rc = SQLITE_OK;                  /* Integer return code */
61101  int gap;        /* First byte of gap between cell pointers and cell content */
61102
61103  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61104  assert( pPage->pBt );
61105  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61106  assert( nByte>=0 );  /* Minimum cell size is 4 */
61107  assert( pPage->nFree>=nByte );
61108  assert( pPage->nOverflow==0 );
61109  assert( nByte < (int)(pPage->pBt->usableSize-8) );
61110
61111  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
61112  gap = pPage->cellOffset + 2*pPage->nCell;
61113  assert( gap<=65536 );
61114  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
61115  ** and the reserved space is zero (the usual value for reserved space)
61116  ** then the cell content offset of an empty page wants to be 65536.
61117  ** However, that integer is too large to be stored in a 2-byte unsigned
61118  ** integer, so a value of 0 is used in its place. */
61119  top = get2byte(&data[hdr+5]);
61120  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
61121  if( gap>top ){
61122    if( top==0 && pPage->pBt->usableSize==65536 ){
61123      top = 65536;
61124    }else{
61125      return SQLITE_CORRUPT_PGNO(pPage->pgno);
61126    }
61127  }
61128
61129  /* If there is enough space between gap and top for one more cell pointer
61130  ** array entry offset, and if the freelist is not empty, then search the
61131  ** freelist looking for a free slot big enough to satisfy the request.
61132  */
61133  testcase( gap+2==top );
61134  testcase( gap+1==top );
61135  testcase( gap==top );
61136  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
61137    u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
61138    if( pSpace ){
61139      assert( pSpace>=data && (pSpace - data)<65536 );
61140      *pIdx = (int)(pSpace - data);
61141      return SQLITE_OK;
61142    }else if( rc ){
61143      return rc;
61144    }
61145  }
61146
61147  /* The request could not be fulfilled using a freelist slot.  Check
61148  ** to see if defragmentation is necessary.
61149  */
61150  testcase( gap+2+nByte==top );
61151  if( gap+2+nByte>top ){
61152    assert( pPage->nCell>0 || CORRUPT_DB );
61153    rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
61154    if( rc ) return rc;
61155    top = get2byteNotZero(&data[hdr+5]);
61156    assert( gap+2+nByte<=top );
61157  }
61158
61159
61160  /* Allocate memory from the gap in between the cell pointer array
61161  ** and the cell content area.  The btreeInitPage() call has already
61162  ** validated the freelist.  Given that the freelist is valid, there
61163  ** is no way that the allocation can extend off the end of the page.
61164  ** The assert() below verifies the previous sentence.
61165  */
61166  top -= nByte;
61167  put2byte(&data[hdr+5], top);
61168  assert( top+nByte <= (int)pPage->pBt->usableSize );
61169  *pIdx = top;
61170  return SQLITE_OK;
61171}
61172
61173/*
61174** Return a section of the pPage->aData to the freelist.
61175** The first byte of the new free block is pPage->aData[iStart]
61176** and the size of the block is iSize bytes.
61177**
61178** Adjacent freeblocks are coalesced.
61179**
61180** Note that even though the freeblock list was checked by btreeInitPage(),
61181** that routine will not detect overlap between cells or freeblocks.  Nor
61182** does it detect cells or freeblocks that encrouch into the reserved bytes
61183** at the end of the page.  So do additional corruption checks inside this
61184** routine and return SQLITE_CORRUPT if any problems are found.
61185*/
61186static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
61187  u16 iPtr;                             /* Address of ptr to next freeblock */
61188  u16 iFreeBlk;                         /* Address of the next freeblock */
61189  u8 hdr;                               /* Page header size.  0 or 100 */
61190  u8 nFrag = 0;                         /* Reduction in fragmentation */
61191  u16 iOrigSize = iSize;                /* Original value of iSize */
61192  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
61193  u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
61194  unsigned char *data = pPage->aData;   /* Page content */
61195
61196  assert( pPage->pBt!=0 );
61197  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61198  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
61199  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
61200  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61201  assert( iSize>=4 );   /* Minimum cell size is 4 */
61202  assert( iStart<=iLast );
61203
61204  /* Overwrite deleted information with zeros when the secure_delete
61205  ** option is enabled */
61206  if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
61207    memset(&data[iStart], 0, iSize);
61208  }
61209
61210  /* The list of freeblocks must be in ascending order.  Find the
61211  ** spot on the list where iStart should be inserted.
61212  */
61213  hdr = pPage->hdrOffset;
61214  iPtr = hdr + 1;
61215  if( data[iPtr+1]==0 && data[iPtr]==0 ){
61216    iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
61217  }else{
61218    while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
61219      if( iFreeBlk<iPtr+4 ){
61220        if( iFreeBlk==0 ) break;
61221        return SQLITE_CORRUPT_PGNO(pPage->pgno);
61222      }
61223      iPtr = iFreeBlk;
61224    }
61225    if( iFreeBlk>iLast ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61226    assert( iFreeBlk>iPtr || iFreeBlk==0 );
61227
61228    /* At this point:
61229    **    iFreeBlk:   First freeblock after iStart, or zero if none
61230    **    iPtr:       The address of a pointer to iFreeBlk
61231    **
61232    ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
61233    */
61234    if( iFreeBlk && iEnd+3>=iFreeBlk ){
61235      nFrag = iFreeBlk - iEnd;
61236      if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61237      iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
61238      if( iEnd > pPage->pBt->usableSize ){
61239        return SQLITE_CORRUPT_PGNO(pPage->pgno);
61240      }
61241      iSize = iEnd - iStart;
61242      iFreeBlk = get2byte(&data[iFreeBlk]);
61243    }
61244
61245    /* If iPtr is another freeblock (that is, if iPtr is not the freelist
61246    ** pointer in the page header) then check to see if iStart should be
61247    ** coalesced onto the end of iPtr.
61248    */
61249    if( iPtr>hdr+1 ){
61250      int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
61251      if( iPtrEnd+3>=iStart ){
61252        if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61253        nFrag += iStart - iPtrEnd;
61254        iSize = iEnd - iPtr;
61255        iStart = iPtr;
61256      }
61257    }
61258    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61259    data[hdr+7] -= nFrag;
61260  }
61261  if( iStart==get2byte(&data[hdr+5]) ){
61262    /* The new freeblock is at the beginning of the cell content area,
61263    ** so just extend the cell content area rather than create another
61264    ** freelist entry */
61265    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PGNO(pPage->pgno);
61266    put2byte(&data[hdr+1], iFreeBlk);
61267    put2byte(&data[hdr+5], iEnd);
61268  }else{
61269    /* Insert the new freeblock into the freelist */
61270    put2byte(&data[iPtr], iStart);
61271    put2byte(&data[iStart], iFreeBlk);
61272    put2byte(&data[iStart+2], iSize);
61273  }
61274  pPage->nFree += iOrigSize;
61275  return SQLITE_OK;
61276}
61277
61278/*
61279** Decode the flags byte (the first byte of the header) for a page
61280** and initialize fields of the MemPage structure accordingly.
61281**
61282** Only the following combinations are supported.  Anything different
61283** indicates a corrupt database files:
61284**
61285**         PTF_ZERODATA
61286**         PTF_ZERODATA | PTF_LEAF
61287**         PTF_LEAFDATA | PTF_INTKEY
61288**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
61289*/
61290static int decodeFlags(MemPage *pPage, int flagByte){
61291  BtShared *pBt;     /* A copy of pPage->pBt */
61292
61293  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
61294  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61295  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
61296  flagByte &= ~PTF_LEAF;
61297  pPage->childPtrSize = 4-4*pPage->leaf;
61298  pPage->xCellSize = cellSizePtr;
61299  pBt = pPage->pBt;
61300  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
61301    /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
61302    ** interior table b-tree page. */
61303    assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
61304    /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
61305    ** leaf table b-tree page. */
61306    assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
61307    pPage->intKey = 1;
61308    if( pPage->leaf ){
61309      pPage->intKeyLeaf = 1;
61310      pPage->xParseCell = btreeParseCellPtr;
61311    }else{
61312      pPage->intKeyLeaf = 0;
61313      pPage->xCellSize = cellSizePtrNoPayload;
61314      pPage->xParseCell = btreeParseCellPtrNoPayload;
61315    }
61316    pPage->maxLocal = pBt->maxLeaf;
61317    pPage->minLocal = pBt->minLeaf;
61318  }else if( flagByte==PTF_ZERODATA ){
61319    /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
61320    ** interior index b-tree page. */
61321    assert( (PTF_ZERODATA)==2 );
61322    /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
61323    ** leaf index b-tree page. */
61324    assert( (PTF_ZERODATA|PTF_LEAF)==10 );
61325    pPage->intKey = 0;
61326    pPage->intKeyLeaf = 0;
61327    pPage->xParseCell = btreeParseCellPtrIndex;
61328    pPage->maxLocal = pBt->maxLocal;
61329    pPage->minLocal = pBt->minLocal;
61330  }else{
61331    /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
61332    ** an error. */
61333    return SQLITE_CORRUPT_PGNO(pPage->pgno);
61334  }
61335  pPage->max1bytePayload = pBt->max1bytePayload;
61336  return SQLITE_OK;
61337}
61338
61339/*
61340** Initialize the auxiliary information for a disk block.
61341**
61342** Return SQLITE_OK on success.  If we see that the page does
61343** not contain a well-formed database page, then return
61344** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
61345** guarantee that the page is well-formed.  It only shows that
61346** we failed to detect any corruption.
61347*/
61348static int btreeInitPage(MemPage *pPage){
61349  int pc;            /* Address of a freeblock within pPage->aData[] */
61350  u8 hdr;            /* Offset to beginning of page header */
61351  u8 *data;          /* Equal to pPage->aData */
61352  BtShared *pBt;        /* The main btree structure */
61353  int usableSize;    /* Amount of usable space on each page */
61354  u16 cellOffset;    /* Offset from start of page to first cell pointer */
61355  int nFree;         /* Number of unused bytes on the page */
61356  int top;           /* First byte of the cell content area */
61357  int iCellFirst;    /* First allowable cell or freeblock offset */
61358  int iCellLast;     /* Last possible cell or freeblock offset */
61359
61360  assert( pPage->pBt!=0 );
61361  assert( pPage->pBt->db!=0 );
61362  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61363  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
61364  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
61365  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
61366  assert( pPage->isInit==0 );
61367
61368  pBt = pPage->pBt;
61369  hdr = pPage->hdrOffset;
61370  data = pPage->aData;
61371  /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
61372  ** the b-tree page type. */
61373  if( decodeFlags(pPage, data[hdr]) ){
61374    return SQLITE_CORRUPT_PGNO(pPage->pgno);
61375  }
61376  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
61377  pPage->maskPage = (u16)(pBt->pageSize - 1);
61378  pPage->nOverflow = 0;
61379  usableSize = pBt->usableSize;
61380  pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
61381  pPage->aDataEnd = &data[usableSize];
61382  pPage->aCellIdx = &data[cellOffset];
61383  pPage->aDataOfst = &data[pPage->childPtrSize];
61384  /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
61385  ** the start of the cell content area. A zero value for this integer is
61386  ** interpreted as 65536. */
61387  top = get2byteNotZero(&data[hdr+5]);
61388  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
61389  ** number of cells on the page. */
61390  pPage->nCell = get2byte(&data[hdr+3]);
61391  if( pPage->nCell>MX_CELL(pBt) ){
61392    /* To many cells for a single page.  The page must be corrupt */
61393    return SQLITE_CORRUPT_PGNO(pPage->pgno);
61394  }
61395  testcase( pPage->nCell==MX_CELL(pBt) );
61396  /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
61397  ** possible for a root page of a table that contains no rows) then the
61398  ** offset to the cell content area will equal the page size minus the
61399  ** bytes of reserved space. */
61400  assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
61401
61402  /* A malformed database page might cause us to read past the end
61403  ** of page when parsing a cell.
61404  **
61405  ** The following block of code checks early to see if a cell extends
61406  ** past the end of a page boundary and causes SQLITE_CORRUPT to be
61407  ** returned if it does.
61408  */
61409  iCellFirst = cellOffset + 2*pPage->nCell;
61410  iCellLast = usableSize - 4;
61411  if( pBt->db->flags & SQLITE_CellSizeCk ){
61412    int i;            /* Index into the cell pointer array */
61413    int sz;           /* Size of a cell */
61414
61415    if( !pPage->leaf ) iCellLast--;
61416    for(i=0; i<pPage->nCell; i++){
61417      pc = get2byteAligned(&data[cellOffset+i*2]);
61418      testcase( pc==iCellFirst );
61419      testcase( pc==iCellLast );
61420      if( pc<iCellFirst || pc>iCellLast ){
61421        return SQLITE_CORRUPT_PGNO(pPage->pgno);
61422      }
61423      sz = pPage->xCellSize(pPage, &data[pc]);
61424      testcase( pc+sz==usableSize );
61425      if( pc+sz>usableSize ){
61426        return SQLITE_CORRUPT_PGNO(pPage->pgno);
61427      }
61428    }
61429    if( !pPage->leaf ) iCellLast++;
61430  }
61431
61432  /* Compute the total free space on the page
61433  ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
61434  ** start of the first freeblock on the page, or is zero if there are no
61435  ** freeblocks. */
61436  pc = get2byte(&data[hdr+1]);
61437  nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
61438  if( pc>0 ){
61439    u32 next, size;
61440    if( pc<iCellFirst ){
61441      /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
61442      ** always be at least one cell before the first freeblock.
61443      */
61444      return SQLITE_CORRUPT_PGNO(pPage->pgno);
61445    }
61446    while( 1 ){
61447      if( pc>iCellLast ){
61448        /* Freeblock off the end of the page */
61449        return SQLITE_CORRUPT_PGNO(pPage->pgno);
61450      }
61451      next = get2byte(&data[pc]);
61452      size = get2byte(&data[pc+2]);
61453      nFree = nFree + size;
61454      if( next<=pc+size+3 ) break;
61455      pc = next;
61456    }
61457    if( next>0 ){
61458      /* Freeblock not in ascending order */
61459      return SQLITE_CORRUPT_PGNO(pPage->pgno);
61460    }
61461    if( pc+size>(unsigned int)usableSize ){
61462      /* Last freeblock extends past page end */
61463      return SQLITE_CORRUPT_PGNO(pPage->pgno);
61464    }
61465  }
61466
61467  /* At this point, nFree contains the sum of the offset to the start
61468  ** of the cell-content area plus the number of free bytes within
61469  ** the cell-content area. If this is greater than the usable-size
61470  ** of the page, then the page must be corrupted. This check also
61471  ** serves to verify that the offset to the start of the cell-content
61472  ** area, according to the page header, lies within the page.
61473  */
61474  if( nFree>usableSize ){
61475    return SQLITE_CORRUPT_PGNO(pPage->pgno);
61476  }
61477  pPage->nFree = (u16)(nFree - iCellFirst);
61478  pPage->isInit = 1;
61479  return SQLITE_OK;
61480}
61481
61482/*
61483** Set up a raw page so that it looks like a database page holding
61484** no entries.
61485*/
61486static void zeroPage(MemPage *pPage, int flags){
61487  unsigned char *data = pPage->aData;
61488  BtShared *pBt = pPage->pBt;
61489  u8 hdr = pPage->hdrOffset;
61490  u16 first;
61491
61492  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
61493  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
61494  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
61495  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61496  assert( sqlite3_mutex_held(pBt->mutex) );
61497  if( pBt->btsFlags & BTS_FAST_SECURE ){
61498    memset(&data[hdr], 0, pBt->usableSize - hdr);
61499  }
61500  data[hdr] = (char)flags;
61501  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
61502  memset(&data[hdr+1], 0, 4);
61503  data[hdr+7] = 0;
61504  put2byte(&data[hdr+5], pBt->usableSize);
61505  pPage->nFree = (u16)(pBt->usableSize - first);
61506  decodeFlags(pPage, flags);
61507  pPage->cellOffset = first;
61508  pPage->aDataEnd = &data[pBt->usableSize];
61509  pPage->aCellIdx = &data[first];
61510  pPage->aDataOfst = &data[pPage->childPtrSize];
61511  pPage->nOverflow = 0;
61512  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
61513  pPage->maskPage = (u16)(pBt->pageSize - 1);
61514  pPage->nCell = 0;
61515  pPage->isInit = 1;
61516}
61517
61518
61519/*
61520** Convert a DbPage obtained from the pager into a MemPage used by
61521** the btree layer.
61522*/
61523static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
61524  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
61525  if( pgno!=pPage->pgno ){
61526    pPage->aData = sqlite3PagerGetData(pDbPage);
61527    pPage->pDbPage = pDbPage;
61528    pPage->pBt = pBt;
61529    pPage->pgno = pgno;
61530    pPage->hdrOffset = pgno==1 ? 100 : 0;
61531  }
61532  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
61533  return pPage;
61534}
61535
61536/*
61537** Get a page from the pager.  Initialize the MemPage.pBt and
61538** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
61539**
61540** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
61541** about the content of the page at this time.  So do not go to the disk
61542** to fetch the content.  Just fill in the content with zeros for now.
61543** If in the future we call sqlite3PagerWrite() on this page, that
61544** means we have started to be concerned about content and the disk
61545** read should occur at that point.
61546*/
61547static int btreeGetPage(
61548  BtShared *pBt,       /* The btree */
61549  Pgno pgno,           /* Number of the page to fetch */
61550  MemPage **ppPage,    /* Return the page in this parameter */
61551  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
61552){
61553  int rc;
61554  DbPage *pDbPage;
61555
61556  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
61557  assert( sqlite3_mutex_held(pBt->mutex) );
61558  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
61559  if( rc ) return rc;
61560  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
61561  return SQLITE_OK;
61562}
61563
61564/*
61565** Retrieve a page from the pager cache. If the requested page is not
61566** already in the pager cache return NULL. Initialize the MemPage.pBt and
61567** MemPage.aData elements if needed.
61568*/
61569static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
61570  DbPage *pDbPage;
61571  assert( sqlite3_mutex_held(pBt->mutex) );
61572  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
61573  if( pDbPage ){
61574    return btreePageFromDbPage(pDbPage, pgno, pBt);
61575  }
61576  return 0;
61577}
61578
61579/*
61580** Return the size of the database file in pages. If there is any kind of
61581** error, return ((unsigned int)-1).
61582*/
61583static Pgno btreePagecount(BtShared *pBt){
61584  return pBt->nPage;
61585}
61586SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
61587  assert( sqlite3BtreeHoldsMutex(p) );
61588  assert( ((p->pBt->nPage)&0x8000000)==0 );
61589  return btreePagecount(p->pBt);
61590}
61591
61592/*
61593** Get a page from the pager and initialize it.
61594**
61595** If pCur!=0 then the page is being fetched as part of a moveToChild()
61596** call.  Do additional sanity checking on the page in this case.
61597** And if the fetch fails, this routine must decrement pCur->iPage.
61598**
61599** The page is fetched as read-write unless pCur is not NULL and is
61600** a read-only cursor.
61601**
61602** If an error occurs, then *ppPage is undefined. It
61603** may remain unchanged, or it may be set to an invalid value.
61604*/
61605static int getAndInitPage(
61606  BtShared *pBt,                  /* The database file */
61607  Pgno pgno,                      /* Number of the page to get */
61608  MemPage **ppPage,               /* Write the page pointer here */
61609  BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
61610  int bReadOnly                   /* True for a read-only page */
61611){
61612  int rc;
61613  DbPage *pDbPage;
61614  assert( sqlite3_mutex_held(pBt->mutex) );
61615  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
61616  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
61617  assert( pCur==0 || pCur->iPage>0 );
61618
61619  if( pgno>btreePagecount(pBt) ){
61620    rc = SQLITE_CORRUPT_BKPT;
61621    goto getAndInitPage_error;
61622  }
61623  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
61624  if( rc ){
61625    goto getAndInitPage_error;
61626  }
61627  *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
61628  if( (*ppPage)->isInit==0 ){
61629    btreePageFromDbPage(pDbPage, pgno, pBt);
61630    rc = btreeInitPage(*ppPage);
61631    if( rc!=SQLITE_OK ){
61632      releasePage(*ppPage);
61633      goto getAndInitPage_error;
61634    }
61635  }
61636  assert( (*ppPage)->pgno==pgno );
61637  assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
61638
61639  /* If obtaining a child page for a cursor, we must verify that the page is
61640  ** compatible with the root page. */
61641  if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
61642    rc = SQLITE_CORRUPT_PGNO(pgno);
61643    releasePage(*ppPage);
61644    goto getAndInitPage_error;
61645  }
61646  return SQLITE_OK;
61647
61648getAndInitPage_error:
61649  if( pCur ) pCur->iPage--;
61650  testcase( pgno==0 );
61651  assert( pgno!=0 || rc==SQLITE_CORRUPT );
61652  return rc;
61653}
61654
61655/*
61656** Release a MemPage.  This should be called once for each prior
61657** call to btreeGetPage.
61658*/
61659static void releasePageNotNull(MemPage *pPage){
61660  assert( pPage->aData );
61661  assert( pPage->pBt );
61662  assert( pPage->pDbPage!=0 );
61663  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
61664  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
61665  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61666  sqlite3PagerUnrefNotNull(pPage->pDbPage);
61667}
61668static void releasePage(MemPage *pPage){
61669  if( pPage ) releasePageNotNull(pPage);
61670}
61671
61672/*
61673** Get an unused page.
61674**
61675** This works just like btreeGetPage() with the addition:
61676**
61677**   *  If the page is already in use for some other purpose, immediately
61678**      release it and return an SQLITE_CURRUPT error.
61679**   *  Make sure the isInit flag is clear
61680*/
61681static int btreeGetUnusedPage(
61682  BtShared *pBt,       /* The btree */
61683  Pgno pgno,           /* Number of the page to fetch */
61684  MemPage **ppPage,    /* Return the page in this parameter */
61685  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
61686){
61687  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
61688  if( rc==SQLITE_OK ){
61689    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
61690      releasePage(*ppPage);
61691      *ppPage = 0;
61692      return SQLITE_CORRUPT_BKPT;
61693    }
61694    (*ppPage)->isInit = 0;
61695  }else{
61696    *ppPage = 0;
61697  }
61698  return rc;
61699}
61700
61701
61702/*
61703** During a rollback, when the pager reloads information into the cache
61704** so that the cache is restored to its original state at the start of
61705** the transaction, for each page restored this routine is called.
61706**
61707** This routine needs to reset the extra data section at the end of the
61708** page to agree with the restored data.
61709*/
61710static void pageReinit(DbPage *pData){
61711  MemPage *pPage;
61712  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
61713  assert( sqlite3PagerPageRefcount(pData)>0 );
61714  if( pPage->isInit ){
61715    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61716    pPage->isInit = 0;
61717    if( sqlite3PagerPageRefcount(pData)>1 ){
61718      /* pPage might not be a btree page;  it might be an overflow page
61719      ** or ptrmap page or a free page.  In those cases, the following
61720      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
61721      ** But no harm is done by this.  And it is very important that
61722      ** btreeInitPage() be called on every btree page so we make
61723      ** the call for every page that comes in for re-initing. */
61724      btreeInitPage(pPage);
61725    }
61726  }
61727}
61728
61729/*
61730** Invoke the busy handler for a btree.
61731*/
61732static int btreeInvokeBusyHandler(void *pArg){
61733  BtShared *pBt = (BtShared*)pArg;
61734  assert( pBt->db );
61735  assert( sqlite3_mutex_held(pBt->db->mutex) );
61736  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
61737}
61738
61739/*
61740** Open a database file.
61741**
61742** zFilename is the name of the database file.  If zFilename is NULL
61743** then an ephemeral database is created.  The ephemeral database might
61744** be exclusively in memory, or it might use a disk-based memory cache.
61745** Either way, the ephemeral database will be automatically deleted
61746** when sqlite3BtreeClose() is called.
61747**
61748** If zFilename is ":memory:" then an in-memory database is created
61749** that is automatically destroyed when it is closed.
61750**
61751** The "flags" parameter is a bitmask that might contain bits like
61752** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
61753**
61754** If the database is already opened in the same database connection
61755** and we are in shared cache mode, then the open will fail with an
61756** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
61757** objects in the same database connection since doing so will lead
61758** to problems with locking.
61759*/
61760SQLITE_PRIVATE int sqlite3BtreeOpen(
61761  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
61762  const char *zFilename,  /* Name of the file containing the BTree database */
61763  sqlite3 *db,            /* Associated database handle */
61764  Btree **ppBtree,        /* Pointer to new Btree object written here */
61765  int flags,              /* Options */
61766  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
61767){
61768  BtShared *pBt = 0;             /* Shared part of btree structure */
61769  Btree *p;                      /* Handle to return */
61770  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
61771  int rc = SQLITE_OK;            /* Result code from this function */
61772  u8 nReserve;                   /* Byte of unused space on each page */
61773  unsigned char zDbHeader[100];  /* Database header content */
61774
61775  /* True if opening an ephemeral, temporary database */
61776  const int isTempDb = zFilename==0 || zFilename[0]==0;
61777
61778  /* Set the variable isMemdb to true for an in-memory database, or
61779  ** false for a file-based database.
61780  */
61781#ifdef SQLITE_OMIT_MEMORYDB
61782  const int isMemdb = 0;
61783#else
61784  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
61785                       || (isTempDb && sqlite3TempInMemory(db))
61786                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
61787#endif
61788
61789  assert( db!=0 );
61790  assert( pVfs!=0 );
61791  assert( sqlite3_mutex_held(db->mutex) );
61792  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
61793
61794  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
61795  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
61796
61797  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
61798  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
61799
61800  if( isMemdb ){
61801    flags |= BTREE_MEMORY;
61802  }
61803  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
61804    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
61805  }
61806  p = sqlite3MallocZero(sizeof(Btree));
61807  if( !p ){
61808    return SQLITE_NOMEM_BKPT;
61809  }
61810  p->inTrans = TRANS_NONE;
61811  p->db = db;
61812#ifndef SQLITE_OMIT_SHARED_CACHE
61813  p->lock.pBtree = p;
61814  p->lock.iTable = 1;
61815#endif
61816
61817#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
61818  /*
61819  ** If this Btree is a candidate for shared cache, try to find an
61820  ** existing BtShared object that we can share with
61821  */
61822  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
61823    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
61824      int nFilename = sqlite3Strlen30(zFilename)+1;
61825      int nFullPathname = pVfs->mxPathname+1;
61826      char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
61827      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
61828
61829      p->sharable = 1;
61830      if( !zFullPathname ){
61831        sqlite3_free(p);
61832        return SQLITE_NOMEM_BKPT;
61833      }
61834      if( isMemdb ){
61835        memcpy(zFullPathname, zFilename, nFilename);
61836      }else{
61837        rc = sqlite3OsFullPathname(pVfs, zFilename,
61838                                   nFullPathname, zFullPathname);
61839        if( rc ){
61840          sqlite3_free(zFullPathname);
61841          sqlite3_free(p);
61842          return rc;
61843        }
61844      }
61845#if SQLITE_THREADSAFE
61846      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
61847      sqlite3_mutex_enter(mutexOpen);
61848      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
61849      sqlite3_mutex_enter(mutexShared);
61850#endif
61851      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
61852        assert( pBt->nRef>0 );
61853        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
61854                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
61855          int iDb;
61856          for(iDb=db->nDb-1; iDb>=0; iDb--){
61857            Btree *pExisting = db->aDb[iDb].pBt;
61858            if( pExisting && pExisting->pBt==pBt ){
61859              sqlite3_mutex_leave(mutexShared);
61860              sqlite3_mutex_leave(mutexOpen);
61861              sqlite3_free(zFullPathname);
61862              sqlite3_free(p);
61863              return SQLITE_CONSTRAINT;
61864            }
61865          }
61866          p->pBt = pBt;
61867          pBt->nRef++;
61868          break;
61869        }
61870      }
61871      sqlite3_mutex_leave(mutexShared);
61872      sqlite3_free(zFullPathname);
61873    }
61874#ifdef SQLITE_DEBUG
61875    else{
61876      /* In debug mode, we mark all persistent databases as sharable
61877      ** even when they are not.  This exercises the locking code and
61878      ** gives more opportunity for asserts(sqlite3_mutex_held())
61879      ** statements to find locking problems.
61880      */
61881      p->sharable = 1;
61882    }
61883#endif
61884  }
61885#endif
61886  if( pBt==0 ){
61887    /*
61888    ** The following asserts make sure that structures used by the btree are
61889    ** the right size.  This is to guard against size changes that result
61890    ** when compiling on a different architecture.
61891    */
61892    assert( sizeof(i64)==8 );
61893    assert( sizeof(u64)==8 );
61894    assert( sizeof(u32)==4 );
61895    assert( sizeof(u16)==2 );
61896    assert( sizeof(Pgno)==4 );
61897
61898    pBt = sqlite3MallocZero( sizeof(*pBt) );
61899    if( pBt==0 ){
61900      rc = SQLITE_NOMEM_BKPT;
61901      goto btree_open_out;
61902    }
61903    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
61904                          sizeof(MemPage), flags, vfsFlags, pageReinit);
61905    if( rc==SQLITE_OK ){
61906      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
61907      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
61908    }
61909    if( rc!=SQLITE_OK ){
61910      goto btree_open_out;
61911    }
61912    pBt->openFlags = (u8)flags;
61913    pBt->db = db;
61914    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
61915    p->pBt = pBt;
61916
61917    pBt->pCursor = 0;
61918    pBt->pPage1 = 0;
61919    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
61920#if defined(SQLITE_SECURE_DELETE)
61921    pBt->btsFlags |= BTS_SECURE_DELETE;
61922#elif defined(SQLITE_FAST_SECURE_DELETE)
61923    pBt->btsFlags |= BTS_OVERWRITE;
61924#endif
61925    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
61926    ** determined by the 2-byte integer located at an offset of 16 bytes from
61927    ** the beginning of the database file. */
61928    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
61929    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
61930         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
61931      pBt->pageSize = 0;
61932#ifndef SQLITE_OMIT_AUTOVACUUM
61933      /* If the magic name ":memory:" will create an in-memory database, then
61934      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
61935      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
61936      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
61937      ** regular file-name. In this case the auto-vacuum applies as per normal.
61938      */
61939      if( zFilename && !isMemdb ){
61940        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
61941        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
61942      }
61943#endif
61944      nReserve = 0;
61945    }else{
61946      /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
61947      ** determined by the one-byte unsigned integer found at an offset of 20
61948      ** into the database file header. */
61949      nReserve = zDbHeader[20];
61950      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
61951#ifndef SQLITE_OMIT_AUTOVACUUM
61952      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
61953      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
61954#endif
61955    }
61956    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
61957    if( rc ) goto btree_open_out;
61958    pBt->usableSize = pBt->pageSize - nReserve;
61959    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
61960
61961#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
61962    /* Add the new BtShared object to the linked list sharable BtShareds.
61963    */
61964    pBt->nRef = 1;
61965    if( p->sharable ){
61966      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
61967      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
61968      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
61969        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
61970        if( pBt->mutex==0 ){
61971          rc = SQLITE_NOMEM_BKPT;
61972          goto btree_open_out;
61973        }
61974      }
61975      sqlite3_mutex_enter(mutexShared);
61976      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
61977      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
61978      sqlite3_mutex_leave(mutexShared);
61979    }
61980#endif
61981  }
61982
61983#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
61984  /* If the new Btree uses a sharable pBtShared, then link the new
61985  ** Btree into the list of all sharable Btrees for the same connection.
61986  ** The list is kept in ascending order by pBt address.
61987  */
61988  if( p->sharable ){
61989    int i;
61990    Btree *pSib;
61991    for(i=0; i<db->nDb; i++){
61992      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
61993        while( pSib->pPrev ){ pSib = pSib->pPrev; }
61994        if( (uptr)p->pBt<(uptr)pSib->pBt ){
61995          p->pNext = pSib;
61996          p->pPrev = 0;
61997          pSib->pPrev = p;
61998        }else{
61999          while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
62000            pSib = pSib->pNext;
62001          }
62002          p->pNext = pSib->pNext;
62003          p->pPrev = pSib;
62004          if( p->pNext ){
62005            p->pNext->pPrev = p;
62006          }
62007          pSib->pNext = p;
62008        }
62009        break;
62010      }
62011    }
62012  }
62013#endif
62014  *ppBtree = p;
62015
62016btree_open_out:
62017  if( rc!=SQLITE_OK ){
62018    if( pBt && pBt->pPager ){
62019      sqlite3PagerClose(pBt->pPager, 0);
62020    }
62021    sqlite3_free(pBt);
62022    sqlite3_free(p);
62023    *ppBtree = 0;
62024  }else{
62025    sqlite3_file *pFile;
62026
62027    /* If the B-Tree was successfully opened, set the pager-cache size to the
62028    ** default value. Except, when opening on an existing shared pager-cache,
62029    ** do not change the pager-cache size.
62030    */
62031    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
62032      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
62033    }
62034
62035    pFile = sqlite3PagerFile(pBt->pPager);
62036    if( pFile->pMethods ){
62037      sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
62038    }
62039  }
62040  if( mutexOpen ){
62041    assert( sqlite3_mutex_held(mutexOpen) );
62042    sqlite3_mutex_leave(mutexOpen);
62043  }
62044  assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
62045  return rc;
62046}
62047
62048/*
62049** Decrement the BtShared.nRef counter.  When it reaches zero,
62050** remove the BtShared structure from the sharing list.  Return
62051** true if the BtShared.nRef counter reaches zero and return
62052** false if it is still positive.
62053*/
62054static int removeFromSharingList(BtShared *pBt){
62055#ifndef SQLITE_OMIT_SHARED_CACHE
62056  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
62057  BtShared *pList;
62058  int removed = 0;
62059
62060  assert( sqlite3_mutex_notheld(pBt->mutex) );
62061  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
62062  sqlite3_mutex_enter(pMaster);
62063  pBt->nRef--;
62064  if( pBt->nRef<=0 ){
62065    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
62066      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
62067    }else{
62068      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
62069      while( ALWAYS(pList) && pList->pNext!=pBt ){
62070        pList=pList->pNext;
62071      }
62072      if( ALWAYS(pList) ){
62073        pList->pNext = pBt->pNext;
62074      }
62075    }
62076    if( SQLITE_THREADSAFE ){
62077      sqlite3_mutex_free(pBt->mutex);
62078    }
62079    removed = 1;
62080  }
62081  sqlite3_mutex_leave(pMaster);
62082  return removed;
62083#else
62084  return 1;
62085#endif
62086}
62087
62088/*
62089** Make sure pBt->pTmpSpace points to an allocation of
62090** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
62091** pointer.
62092*/
62093static void allocateTempSpace(BtShared *pBt){
62094  if( !pBt->pTmpSpace ){
62095    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
62096
62097    /* One of the uses of pBt->pTmpSpace is to format cells before
62098    ** inserting them into a leaf page (function fillInCell()). If
62099    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
62100    ** by the various routines that manipulate binary cells. Which
62101    ** can mean that fillInCell() only initializes the first 2 or 3
62102    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
62103    ** it into a database page. This is not actually a problem, but it
62104    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
62105    ** data is passed to system call write(). So to avoid this error,
62106    ** zero the first 4 bytes of temp space here.
62107    **
62108    ** Also:  Provide four bytes of initialized space before the
62109    ** beginning of pTmpSpace as an area available to prepend the
62110    ** left-child pointer to the beginning of a cell.
62111    */
62112    if( pBt->pTmpSpace ){
62113      memset(pBt->pTmpSpace, 0, 8);
62114      pBt->pTmpSpace += 4;
62115    }
62116  }
62117}
62118
62119/*
62120** Free the pBt->pTmpSpace allocation
62121*/
62122static void freeTempSpace(BtShared *pBt){
62123  if( pBt->pTmpSpace ){
62124    pBt->pTmpSpace -= 4;
62125    sqlite3PageFree(pBt->pTmpSpace);
62126    pBt->pTmpSpace = 0;
62127  }
62128}
62129
62130/*
62131** Close an open database and invalidate all cursors.
62132*/
62133SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
62134  BtShared *pBt = p->pBt;
62135  BtCursor *pCur;
62136
62137  /* Close all cursors opened via this handle.  */
62138  assert( sqlite3_mutex_held(p->db->mutex) );
62139  sqlite3BtreeEnter(p);
62140  pCur = pBt->pCursor;
62141  while( pCur ){
62142    BtCursor *pTmp = pCur;
62143    pCur = pCur->pNext;
62144    if( pTmp->pBtree==p ){
62145      sqlite3BtreeCloseCursor(pTmp);
62146    }
62147  }
62148
62149  /* Rollback any active transaction and free the handle structure.
62150  ** The call to sqlite3BtreeRollback() drops any table-locks held by
62151  ** this handle.
62152  */
62153  sqlite3BtreeRollback(p, SQLITE_OK, 0);
62154  sqlite3BtreeLeave(p);
62155
62156  /* If there are still other outstanding references to the shared-btree
62157  ** structure, return now. The remainder of this procedure cleans
62158  ** up the shared-btree.
62159  */
62160  assert( p->wantToLock==0 && p->locked==0 );
62161  if( !p->sharable || removeFromSharingList(pBt) ){
62162    /* The pBt is no longer on the sharing list, so we can access
62163    ** it without having to hold the mutex.
62164    **
62165    ** Clean out and delete the BtShared object.
62166    */
62167    assert( !pBt->pCursor );
62168    sqlite3PagerClose(pBt->pPager, p->db);
62169    if( pBt->xFreeSchema && pBt->pSchema ){
62170      pBt->xFreeSchema(pBt->pSchema);
62171    }
62172    sqlite3DbFree(0, pBt->pSchema);
62173    freeTempSpace(pBt);
62174    sqlite3_free(pBt);
62175  }
62176
62177#ifndef SQLITE_OMIT_SHARED_CACHE
62178  assert( p->wantToLock==0 );
62179  assert( p->locked==0 );
62180  if( p->pPrev ) p->pPrev->pNext = p->pNext;
62181  if( p->pNext ) p->pNext->pPrev = p->pPrev;
62182#endif
62183
62184  sqlite3_free(p);
62185  return SQLITE_OK;
62186}
62187
62188/*
62189** Change the "soft" limit on the number of pages in the cache.
62190** Unused and unmodified pages will be recycled when the number of
62191** pages in the cache exceeds this soft limit.  But the size of the
62192** cache is allowed to grow larger than this limit if it contains
62193** dirty pages or pages still in active use.
62194*/
62195SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
62196  BtShared *pBt = p->pBt;
62197  assert( sqlite3_mutex_held(p->db->mutex) );
62198  sqlite3BtreeEnter(p);
62199  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
62200  sqlite3BtreeLeave(p);
62201  return SQLITE_OK;
62202}
62203
62204/*
62205** Change the "spill" limit on the number of pages in the cache.
62206** If the number of pages exceeds this limit during a write transaction,
62207** the pager might attempt to "spill" pages to the journal early in
62208** order to free up memory.
62209**
62210** The value returned is the current spill size.  If zero is passed
62211** as an argument, no changes are made to the spill size setting, so
62212** using mxPage of 0 is a way to query the current spill size.
62213*/
62214SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
62215  BtShared *pBt = p->pBt;
62216  int res;
62217  assert( sqlite3_mutex_held(p->db->mutex) );
62218  sqlite3BtreeEnter(p);
62219  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
62220  sqlite3BtreeLeave(p);
62221  return res;
62222}
62223
62224#if SQLITE_MAX_MMAP_SIZE>0
62225/*
62226** Change the limit on the amount of the database file that may be
62227** memory mapped.
62228*/
62229SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
62230  BtShared *pBt = p->pBt;
62231  assert( sqlite3_mutex_held(p->db->mutex) );
62232  sqlite3BtreeEnter(p);
62233  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
62234  sqlite3BtreeLeave(p);
62235  return SQLITE_OK;
62236}
62237#endif /* SQLITE_MAX_MMAP_SIZE>0 */
62238
62239/*
62240** Change the way data is synced to disk in order to increase or decrease
62241** how well the database resists damage due to OS crashes and power
62242** failures.  Level 1 is the same as asynchronous (no syncs() occur and
62243** there is a high probability of damage)  Level 2 is the default.  There
62244** is a very low but non-zero probability of damage.  Level 3 reduces the
62245** probability of damage to near zero but with a write performance reduction.
62246*/
62247#ifndef SQLITE_OMIT_PAGER_PRAGMAS
62248SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
62249  Btree *p,              /* The btree to set the safety level on */
62250  unsigned pgFlags       /* Various PAGER_* flags */
62251){
62252  BtShared *pBt = p->pBt;
62253  assert( sqlite3_mutex_held(p->db->mutex) );
62254  sqlite3BtreeEnter(p);
62255  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
62256  sqlite3BtreeLeave(p);
62257  return SQLITE_OK;
62258}
62259#endif
62260
62261/*
62262** Change the default pages size and the number of reserved bytes per page.
62263** Or, if the page size has already been fixed, return SQLITE_READONLY
62264** without changing anything.
62265**
62266** The page size must be a power of 2 between 512 and 65536.  If the page
62267** size supplied does not meet this constraint then the page size is not
62268** changed.
62269**
62270** Page sizes are constrained to be a power of two so that the region
62271** of the database file used for locking (beginning at PENDING_BYTE,
62272** the first byte past the 1GB boundary, 0x40000000) needs to occur
62273** at the beginning of a page.
62274**
62275** If parameter nReserve is less than zero, then the number of reserved
62276** bytes per page is left unchanged.
62277**
62278** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
62279** and autovacuum mode can no longer be changed.
62280*/
62281SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
62282  int rc = SQLITE_OK;
62283  BtShared *pBt = p->pBt;
62284  assert( nReserve>=-1 && nReserve<=255 );
62285  sqlite3BtreeEnter(p);
62286#if SQLITE_HAS_CODEC
62287  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
62288#endif
62289  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
62290    sqlite3BtreeLeave(p);
62291    return SQLITE_READONLY;
62292  }
62293  if( nReserve<0 ){
62294    nReserve = pBt->pageSize - pBt->usableSize;
62295  }
62296  assert( nReserve>=0 && nReserve<=255 );
62297  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
62298        ((pageSize-1)&pageSize)==0 ){
62299    assert( (pageSize & 7)==0 );
62300    assert( !pBt->pCursor );
62301    pBt->pageSize = (u32)pageSize;
62302    freeTempSpace(pBt);
62303  }
62304  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
62305  pBt->usableSize = pBt->pageSize - (u16)nReserve;
62306  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
62307  sqlite3BtreeLeave(p);
62308  return rc;
62309}
62310
62311/*
62312** Return the currently defined page size
62313*/
62314SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
62315  return p->pBt->pageSize;
62316}
62317
62318/*
62319** This function is similar to sqlite3BtreeGetReserve(), except that it
62320** may only be called if it is guaranteed that the b-tree mutex is already
62321** held.
62322**
62323** This is useful in one special case in the backup API code where it is
62324** known that the shared b-tree mutex is held, but the mutex on the
62325** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
62326** were to be called, it might collide with some other operation on the
62327** database handle that owns *p, causing undefined behavior.
62328*/
62329SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
62330  int n;
62331  assert( sqlite3_mutex_held(p->pBt->mutex) );
62332  n = p->pBt->pageSize - p->pBt->usableSize;
62333  return n;
62334}
62335
62336/*
62337** Return the number of bytes of space at the end of every page that
62338** are intentually left unused.  This is the "reserved" space that is
62339** sometimes used by extensions.
62340**
62341** If SQLITE_HAS_MUTEX is defined then the number returned is the
62342** greater of the current reserved space and the maximum requested
62343** reserve space.
62344*/
62345SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
62346  int n;
62347  sqlite3BtreeEnter(p);
62348  n = sqlite3BtreeGetReserveNoMutex(p);
62349#ifdef SQLITE_HAS_CODEC
62350  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
62351#endif
62352  sqlite3BtreeLeave(p);
62353  return n;
62354}
62355
62356
62357/*
62358** Set the maximum page count for a database if mxPage is positive.
62359** No changes are made if mxPage is 0 or negative.
62360** Regardless of the value of mxPage, return the maximum page count.
62361*/
62362SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
62363  int n;
62364  sqlite3BtreeEnter(p);
62365  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
62366  sqlite3BtreeLeave(p);
62367  return n;
62368}
62369
62370/*
62371** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
62372**
62373**    newFlag==0       Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
62374**    newFlag==1       BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
62375**    newFlag==2       BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
62376**    newFlag==(-1)    No changes
62377**
62378** This routine acts as a query if newFlag is less than zero
62379**
62380** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
62381** freelist leaf pages are not written back to the database.  Thus in-page
62382** deleted content is cleared, but freelist deleted content is not.
62383**
62384** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
62385** that freelist leaf pages are written back into the database, increasing
62386** the amount of disk I/O.
62387*/
62388SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
62389  int b;
62390  if( p==0 ) return 0;
62391  sqlite3BtreeEnter(p);
62392  assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
62393  assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
62394  if( newFlag>=0 ){
62395    p->pBt->btsFlags &= ~BTS_FAST_SECURE;
62396    p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
62397  }
62398  b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
62399  sqlite3BtreeLeave(p);
62400  return b;
62401}
62402
62403/*
62404** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
62405** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
62406** is disabled. The default value for the auto-vacuum property is
62407** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
62408*/
62409SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
62410#ifdef SQLITE_OMIT_AUTOVACUUM
62411  return SQLITE_READONLY;
62412#else
62413  BtShared *pBt = p->pBt;
62414  int rc = SQLITE_OK;
62415  u8 av = (u8)autoVacuum;
62416
62417  sqlite3BtreeEnter(p);
62418  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
62419    rc = SQLITE_READONLY;
62420  }else{
62421    pBt->autoVacuum = av ?1:0;
62422    pBt->incrVacuum = av==2 ?1:0;
62423  }
62424  sqlite3BtreeLeave(p);
62425  return rc;
62426#endif
62427}
62428
62429/*
62430** Return the value of the 'auto-vacuum' property. If auto-vacuum is
62431** enabled 1 is returned. Otherwise 0.
62432*/
62433SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
62434#ifdef SQLITE_OMIT_AUTOVACUUM
62435  return BTREE_AUTOVACUUM_NONE;
62436#else
62437  int rc;
62438  sqlite3BtreeEnter(p);
62439  rc = (
62440    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
62441    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
62442    BTREE_AUTOVACUUM_INCR
62443  );
62444  sqlite3BtreeLeave(p);
62445  return rc;
62446#endif
62447}
62448
62449/*
62450** If the user has not set the safety-level for this database connection
62451** using "PRAGMA synchronous", and if the safety-level is not already
62452** set to the value passed to this function as the second parameter,
62453** set it so.
62454*/
62455#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
62456static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
62457  sqlite3 *db;
62458  Db *pDb;
62459  if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
62460    while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
62461    if( pDb->bSyncSet==0
62462     && pDb->safety_level!=safety_level
62463     && pDb!=&db->aDb[1]
62464    ){
62465      pDb->safety_level = safety_level;
62466      sqlite3PagerSetFlags(pBt->pPager,
62467          pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
62468    }
62469  }
62470}
62471#else
62472# define setDefaultSyncFlag(pBt,safety_level)
62473#endif
62474
62475/*
62476** Get a reference to pPage1 of the database file.  This will
62477** also acquire a readlock on that file.
62478**
62479** SQLITE_OK is returned on success.  If the file is not a
62480** well-formed database file, then SQLITE_CORRUPT is returned.
62481** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
62482** is returned if we run out of memory.
62483*/
62484static int lockBtree(BtShared *pBt){
62485  int rc;              /* Result code from subfunctions */
62486  MemPage *pPage1;     /* Page 1 of the database file */
62487  int nPage;           /* Number of pages in the database */
62488  int nPageFile = 0;   /* Number of pages in the database file */
62489  int nPageHeader;     /* Number of pages in the database according to hdr */
62490
62491  assert( sqlite3_mutex_held(pBt->mutex) );
62492  assert( pBt->pPage1==0 );
62493  rc = sqlite3PagerSharedLock(pBt->pPager);
62494  if( rc!=SQLITE_OK ) return rc;
62495  rc = btreeGetPage(pBt, 1, &pPage1, 0);
62496  if( rc!=SQLITE_OK ) return rc;
62497
62498  /* Do some checking to help insure the file we opened really is
62499  ** a valid database file.
62500  */
62501  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
62502  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
62503  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
62504    nPage = nPageFile;
62505  }
62506  if( nPage>0 ){
62507    u32 pageSize;
62508    u32 usableSize;
62509    u8 *page1 = pPage1->aData;
62510    rc = SQLITE_NOTADB;
62511    /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
62512    ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
62513    ** 61 74 20 33 00. */
62514    if( memcmp(page1, zMagicHeader, 16)!=0 ){
62515      goto page1_init_failed;
62516    }
62517
62518#ifdef SQLITE_OMIT_WAL
62519    if( page1[18]>1 ){
62520      pBt->btsFlags |= BTS_READ_ONLY;
62521    }
62522    if( page1[19]>1 ){
62523      goto page1_init_failed;
62524    }
62525#else
62526    if( page1[18]>2 ){
62527      pBt->btsFlags |= BTS_READ_ONLY;
62528    }
62529    if( page1[19]>2 ){
62530      goto page1_init_failed;
62531    }
62532
62533    /* If the write version is set to 2, this database should be accessed
62534    ** in WAL mode. If the log is not already open, open it now. Then
62535    ** return SQLITE_OK and return without populating BtShared.pPage1.
62536    ** The caller detects this and calls this function again. This is
62537    ** required as the version of page 1 currently in the page1 buffer
62538    ** may not be the latest version - there may be a newer one in the log
62539    ** file.
62540    */
62541    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
62542      int isOpen = 0;
62543      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
62544      if( rc!=SQLITE_OK ){
62545        goto page1_init_failed;
62546      }else{
62547        setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
62548        if( isOpen==0 ){
62549          releasePage(pPage1);
62550          return SQLITE_OK;
62551        }
62552      }
62553      rc = SQLITE_NOTADB;
62554    }else{
62555      setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
62556    }
62557#endif
62558
62559    /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
62560    ** fractions and the leaf payload fraction values must be 64, 32, and 32.
62561    **
62562    ** The original design allowed these amounts to vary, but as of
62563    ** version 3.6.0, we require them to be fixed.
62564    */
62565    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
62566      goto page1_init_failed;
62567    }
62568    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
62569    ** determined by the 2-byte integer located at an offset of 16 bytes from
62570    ** the beginning of the database file. */
62571    pageSize = (page1[16]<<8) | (page1[17]<<16);
62572    /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
62573    ** between 512 and 65536 inclusive. */
62574    if( ((pageSize-1)&pageSize)!=0
62575     || pageSize>SQLITE_MAX_PAGE_SIZE
62576     || pageSize<=256
62577    ){
62578      goto page1_init_failed;
62579    }
62580    assert( (pageSize & 7)==0 );
62581    /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
62582    ** integer at offset 20 is the number of bytes of space at the end of
62583    ** each page to reserve for extensions.
62584    **
62585    ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
62586    ** determined by the one-byte unsigned integer found at an offset of 20
62587    ** into the database file header. */
62588    usableSize = pageSize - page1[20];
62589    if( (u32)pageSize!=pBt->pageSize ){
62590      /* After reading the first page of the database assuming a page size
62591      ** of BtShared.pageSize, we have discovered that the page-size is
62592      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
62593      ** zero and return SQLITE_OK. The caller will call this function
62594      ** again with the correct page-size.
62595      */
62596      releasePage(pPage1);
62597      pBt->usableSize = usableSize;
62598      pBt->pageSize = pageSize;
62599      freeTempSpace(pBt);
62600      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
62601                                   pageSize-usableSize);
62602      return rc;
62603    }
62604    if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
62605      rc = SQLITE_CORRUPT_BKPT;
62606      goto page1_init_failed;
62607    }
62608    /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
62609    ** be less than 480. In other words, if the page size is 512, then the
62610    ** reserved space size cannot exceed 32. */
62611    if( usableSize<480 ){
62612      goto page1_init_failed;
62613    }
62614    pBt->pageSize = pageSize;
62615    pBt->usableSize = usableSize;
62616#ifndef SQLITE_OMIT_AUTOVACUUM
62617    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
62618    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
62619#endif
62620  }
62621
62622  /* maxLocal is the maximum amount of payload to store locally for
62623  ** a cell.  Make sure it is small enough so that at least minFanout
62624  ** cells can will fit on one page.  We assume a 10-byte page header.
62625  ** Besides the payload, the cell must store:
62626  **     2-byte pointer to the cell
62627  **     4-byte child pointer
62628  **     9-byte nKey value
62629  **     4-byte nData value
62630  **     4-byte overflow page pointer
62631  ** So a cell consists of a 2-byte pointer, a header which is as much as
62632  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
62633  ** page pointer.
62634  */
62635  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
62636  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
62637  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
62638  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
62639  if( pBt->maxLocal>127 ){
62640    pBt->max1bytePayload = 127;
62641  }else{
62642    pBt->max1bytePayload = (u8)pBt->maxLocal;
62643  }
62644  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
62645  pBt->pPage1 = pPage1;
62646  pBt->nPage = nPage;
62647  return SQLITE_OK;
62648
62649page1_init_failed:
62650  releasePage(pPage1);
62651  pBt->pPage1 = 0;
62652  return rc;
62653}
62654
62655#ifndef NDEBUG
62656/*
62657** Return the number of cursors open on pBt. This is for use
62658** in assert() expressions, so it is only compiled if NDEBUG is not
62659** defined.
62660**
62661** Only write cursors are counted if wrOnly is true.  If wrOnly is
62662** false then all cursors are counted.
62663**
62664** For the purposes of this routine, a cursor is any cursor that
62665** is capable of reading or writing to the database.  Cursors that
62666** have been tripped into the CURSOR_FAULT state are not counted.
62667*/
62668static int countValidCursors(BtShared *pBt, int wrOnly){
62669  BtCursor *pCur;
62670  int r = 0;
62671  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
62672    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
62673     && pCur->eState!=CURSOR_FAULT ) r++;
62674  }
62675  return r;
62676}
62677#endif
62678
62679/*
62680** If there are no outstanding cursors and we are not in the middle
62681** of a transaction but there is a read lock on the database, then
62682** this routine unrefs the first page of the database file which
62683** has the effect of releasing the read lock.
62684**
62685** If there is a transaction in progress, this routine is a no-op.
62686*/
62687static void unlockBtreeIfUnused(BtShared *pBt){
62688  assert( sqlite3_mutex_held(pBt->mutex) );
62689  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
62690  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
62691    MemPage *pPage1 = pBt->pPage1;
62692    assert( pPage1->aData );
62693    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
62694    pBt->pPage1 = 0;
62695    releasePageNotNull(pPage1);
62696  }
62697}
62698
62699/*
62700** If pBt points to an empty file then convert that empty file
62701** into a new empty database by initializing the first page of
62702** the database.
62703*/
62704static int newDatabase(BtShared *pBt){
62705  MemPage *pP1;
62706  unsigned char *data;
62707  int rc;
62708
62709  assert( sqlite3_mutex_held(pBt->mutex) );
62710  if( pBt->nPage>0 ){
62711    return SQLITE_OK;
62712  }
62713  pP1 = pBt->pPage1;
62714  assert( pP1!=0 );
62715  data = pP1->aData;
62716  rc = sqlite3PagerWrite(pP1->pDbPage);
62717  if( rc ) return rc;
62718  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
62719  assert( sizeof(zMagicHeader)==16 );
62720  data[16] = (u8)((pBt->pageSize>>8)&0xff);
62721  data[17] = (u8)((pBt->pageSize>>16)&0xff);
62722  data[18] = 1;
62723  data[19] = 1;
62724  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
62725  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
62726  data[21] = 64;
62727  data[22] = 32;
62728  data[23] = 32;
62729  memset(&data[24], 0, 100-24);
62730  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
62731  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
62732#ifndef SQLITE_OMIT_AUTOVACUUM
62733  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
62734  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
62735  put4byte(&data[36 + 4*4], pBt->autoVacuum);
62736  put4byte(&data[36 + 7*4], pBt->incrVacuum);
62737#endif
62738  pBt->nPage = 1;
62739  data[31] = 1;
62740  return SQLITE_OK;
62741}
62742
62743/*
62744** Initialize the first page of the database file (creating a database
62745** consisting of a single page and no schema objects). Return SQLITE_OK
62746** if successful, or an SQLite error code otherwise.
62747*/
62748SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
62749  int rc;
62750  sqlite3BtreeEnter(p);
62751  p->pBt->nPage = 0;
62752  rc = newDatabase(p->pBt);
62753  sqlite3BtreeLeave(p);
62754  return rc;
62755}
62756
62757/*
62758** Attempt to start a new transaction. A write-transaction
62759** is started if the second argument is nonzero, otherwise a read-
62760** transaction.  If the second argument is 2 or more and exclusive
62761** transaction is started, meaning that no other process is allowed
62762** to access the database.  A preexisting transaction may not be
62763** upgraded to exclusive by calling this routine a second time - the
62764** exclusivity flag only works for a new transaction.
62765**
62766** A write-transaction must be started before attempting any
62767** changes to the database.  None of the following routines
62768** will work unless a transaction is started first:
62769**
62770**      sqlite3BtreeCreateTable()
62771**      sqlite3BtreeCreateIndex()
62772**      sqlite3BtreeClearTable()
62773**      sqlite3BtreeDropTable()
62774**      sqlite3BtreeInsert()
62775**      sqlite3BtreeDelete()
62776**      sqlite3BtreeUpdateMeta()
62777**
62778** If an initial attempt to acquire the lock fails because of lock contention
62779** and the database was previously unlocked, then invoke the busy handler
62780** if there is one.  But if there was previously a read-lock, do not
62781** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
62782** returned when there is already a read-lock in order to avoid a deadlock.
62783**
62784** Suppose there are two processes A and B.  A has a read lock and B has
62785** a reserved lock.  B tries to promote to exclusive but is blocked because
62786** of A's read lock.  A tries to promote to reserved but is blocked by B.
62787** One or the other of the two processes must give way or there can be
62788** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
62789** when A already has a read lock, we encourage A to give up and let B
62790** proceed.
62791*/
62792SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
62793  BtShared *pBt = p->pBt;
62794  int rc = SQLITE_OK;
62795
62796  sqlite3BtreeEnter(p);
62797  btreeIntegrity(p);
62798
62799  /* If the btree is already in a write-transaction, or it
62800  ** is already in a read-transaction and a read-transaction
62801  ** is requested, this is a no-op.
62802  */
62803  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
62804    goto trans_begun;
62805  }
62806  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
62807
62808  /* Write transactions are not possible on a read-only database */
62809  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
62810    rc = SQLITE_READONLY;
62811    goto trans_begun;
62812  }
62813
62814#ifndef SQLITE_OMIT_SHARED_CACHE
62815  {
62816    sqlite3 *pBlock = 0;
62817    /* If another database handle has already opened a write transaction
62818    ** on this shared-btree structure and a second write transaction is
62819    ** requested, return SQLITE_LOCKED.
62820    */
62821    if( (wrflag && pBt->inTransaction==TRANS_WRITE)
62822     || (pBt->btsFlags & BTS_PENDING)!=0
62823    ){
62824      pBlock = pBt->pWriter->db;
62825    }else if( wrflag>1 ){
62826      BtLock *pIter;
62827      for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
62828        if( pIter->pBtree!=p ){
62829          pBlock = pIter->pBtree->db;
62830          break;
62831        }
62832      }
62833    }
62834    if( pBlock ){
62835      sqlite3ConnectionBlocked(p->db, pBlock);
62836      rc = SQLITE_LOCKED_SHAREDCACHE;
62837      goto trans_begun;
62838    }
62839  }
62840#endif
62841
62842  /* Any read-only or read-write transaction implies a read-lock on
62843  ** page 1. So if some other shared-cache client already has a write-lock
62844  ** on page 1, the transaction cannot be opened. */
62845  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
62846  if( SQLITE_OK!=rc ) goto trans_begun;
62847
62848  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
62849  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
62850  do {
62851    /* Call lockBtree() until either pBt->pPage1 is populated or
62852    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
62853    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
62854    ** reading page 1 it discovers that the page-size of the database
62855    ** file is not pBt->pageSize. In this case lockBtree() will update
62856    ** pBt->pageSize to the page-size of the file on disk.
62857    */
62858    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
62859
62860    if( rc==SQLITE_OK && wrflag ){
62861      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
62862        rc = SQLITE_READONLY;
62863      }else{
62864        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
62865        if( rc==SQLITE_OK ){
62866          rc = newDatabase(pBt);
62867        }
62868      }
62869    }
62870
62871    if( rc!=SQLITE_OK ){
62872      unlockBtreeIfUnused(pBt);
62873    }
62874  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
62875          btreeInvokeBusyHandler(pBt) );
62876
62877  if( rc==SQLITE_OK ){
62878    if( p->inTrans==TRANS_NONE ){
62879      pBt->nTransaction++;
62880#ifndef SQLITE_OMIT_SHARED_CACHE
62881      if( p->sharable ){
62882        assert( p->lock.pBtree==p && p->lock.iTable==1 );
62883        p->lock.eLock = READ_LOCK;
62884        p->lock.pNext = pBt->pLock;
62885        pBt->pLock = &p->lock;
62886      }
62887#endif
62888    }
62889    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
62890    if( p->inTrans>pBt->inTransaction ){
62891      pBt->inTransaction = p->inTrans;
62892    }
62893    if( wrflag ){
62894      MemPage *pPage1 = pBt->pPage1;
62895#ifndef SQLITE_OMIT_SHARED_CACHE
62896      assert( !pBt->pWriter );
62897      pBt->pWriter = p;
62898      pBt->btsFlags &= ~BTS_EXCLUSIVE;
62899      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
62900#endif
62901
62902      /* If the db-size header field is incorrect (as it may be if an old
62903      ** client has been writing the database file), update it now. Doing
62904      ** this sooner rather than later means the database size can safely
62905      ** re-read the database size from page 1 if a savepoint or transaction
62906      ** rollback occurs within the transaction.
62907      */
62908      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
62909        rc = sqlite3PagerWrite(pPage1->pDbPage);
62910        if( rc==SQLITE_OK ){
62911          put4byte(&pPage1->aData[28], pBt->nPage);
62912        }
62913      }
62914    }
62915  }
62916
62917
62918trans_begun:
62919  if( rc==SQLITE_OK && wrflag ){
62920    /* This call makes sure that the pager has the correct number of
62921    ** open savepoints. If the second parameter is greater than 0 and
62922    ** the sub-journal is not already open, then it will be opened here.
62923    */
62924    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
62925  }
62926
62927  btreeIntegrity(p);
62928  sqlite3BtreeLeave(p);
62929  return rc;
62930}
62931
62932#ifndef SQLITE_OMIT_AUTOVACUUM
62933
62934/*
62935** Set the pointer-map entries for all children of page pPage. Also, if
62936** pPage contains cells that point to overflow pages, set the pointer
62937** map entries for the overflow pages as well.
62938*/
62939static int setChildPtrmaps(MemPage *pPage){
62940  int i;                             /* Counter variable */
62941  int nCell;                         /* Number of cells in page pPage */
62942  int rc;                            /* Return code */
62943  BtShared *pBt = pPage->pBt;
62944  Pgno pgno = pPage->pgno;
62945
62946  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
62947  rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
62948  if( rc!=SQLITE_OK ) return rc;
62949  nCell = pPage->nCell;
62950
62951  for(i=0; i<nCell; i++){
62952    u8 *pCell = findCell(pPage, i);
62953
62954    ptrmapPutOvflPtr(pPage, pCell, &rc);
62955
62956    if( !pPage->leaf ){
62957      Pgno childPgno = get4byte(pCell);
62958      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
62959    }
62960  }
62961
62962  if( !pPage->leaf ){
62963    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
62964    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
62965  }
62966
62967  return rc;
62968}
62969
62970/*
62971** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
62972** that it points to iTo. Parameter eType describes the type of pointer to
62973** be modified, as  follows:
62974**
62975** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
62976**                   page of pPage.
62977**
62978** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
62979**                   page pointed to by one of the cells on pPage.
62980**
62981** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
62982**                   overflow page in the list.
62983*/
62984static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
62985  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
62986  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
62987  if( eType==PTRMAP_OVERFLOW2 ){
62988    /* The pointer is always the first 4 bytes of the page in this case.  */
62989    if( get4byte(pPage->aData)!=iFrom ){
62990      return SQLITE_CORRUPT_PGNO(pPage->pgno);
62991    }
62992    put4byte(pPage->aData, iTo);
62993  }else{
62994    int i;
62995    int nCell;
62996    int rc;
62997
62998    rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
62999    if( rc ) return rc;
63000    nCell = pPage->nCell;
63001
63002    for(i=0; i<nCell; i++){
63003      u8 *pCell = findCell(pPage, i);
63004      if( eType==PTRMAP_OVERFLOW1 ){
63005        CellInfo info;
63006        pPage->xParseCell(pPage, pCell, &info);
63007        if( info.nLocal<info.nPayload ){
63008          if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
63009            return SQLITE_CORRUPT_PGNO(pPage->pgno);
63010          }
63011          if( iFrom==get4byte(pCell+info.nSize-4) ){
63012            put4byte(pCell+info.nSize-4, iTo);
63013            break;
63014          }
63015        }
63016      }else{
63017        if( get4byte(pCell)==iFrom ){
63018          put4byte(pCell, iTo);
63019          break;
63020        }
63021      }
63022    }
63023
63024    if( i==nCell ){
63025      if( eType!=PTRMAP_BTREE ||
63026          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
63027        return SQLITE_CORRUPT_PGNO(pPage->pgno);
63028      }
63029      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
63030    }
63031  }
63032  return SQLITE_OK;
63033}
63034
63035
63036/*
63037** Move the open database page pDbPage to location iFreePage in the
63038** database. The pDbPage reference remains valid.
63039**
63040** The isCommit flag indicates that there is no need to remember that
63041** the journal needs to be sync()ed before database page pDbPage->pgno
63042** can be written to. The caller has already promised not to write to that
63043** page.
63044*/
63045static int relocatePage(
63046  BtShared *pBt,           /* Btree */
63047  MemPage *pDbPage,        /* Open page to move */
63048  u8 eType,                /* Pointer map 'type' entry for pDbPage */
63049  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
63050  Pgno iFreePage,          /* The location to move pDbPage to */
63051  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
63052){
63053  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
63054  Pgno iDbPage = pDbPage->pgno;
63055  Pager *pPager = pBt->pPager;
63056  int rc;
63057
63058  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
63059      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
63060  assert( sqlite3_mutex_held(pBt->mutex) );
63061  assert( pDbPage->pBt==pBt );
63062
63063  /* Move page iDbPage from its current location to page number iFreePage */
63064  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
63065      iDbPage, iFreePage, iPtrPage, eType));
63066  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
63067  if( rc!=SQLITE_OK ){
63068    return rc;
63069  }
63070  pDbPage->pgno = iFreePage;
63071
63072  /* If pDbPage was a btree-page, then it may have child pages and/or cells
63073  ** that point to overflow pages. The pointer map entries for all these
63074  ** pages need to be changed.
63075  **
63076  ** If pDbPage is an overflow page, then the first 4 bytes may store a
63077  ** pointer to a subsequent overflow page. If this is the case, then
63078  ** the pointer map needs to be updated for the subsequent overflow page.
63079  */
63080  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
63081    rc = setChildPtrmaps(pDbPage);
63082    if( rc!=SQLITE_OK ){
63083      return rc;
63084    }
63085  }else{
63086    Pgno nextOvfl = get4byte(pDbPage->aData);
63087    if( nextOvfl!=0 ){
63088      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
63089      if( rc!=SQLITE_OK ){
63090        return rc;
63091      }
63092    }
63093  }
63094
63095  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
63096  ** that it points at iFreePage. Also fix the pointer map entry for
63097  ** iPtrPage.
63098  */
63099  if( eType!=PTRMAP_ROOTPAGE ){
63100    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
63101    if( rc!=SQLITE_OK ){
63102      return rc;
63103    }
63104    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
63105    if( rc!=SQLITE_OK ){
63106      releasePage(pPtrPage);
63107      return rc;
63108    }
63109    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
63110    releasePage(pPtrPage);
63111    if( rc==SQLITE_OK ){
63112      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
63113    }
63114  }
63115  return rc;
63116}
63117
63118/* Forward declaration required by incrVacuumStep(). */
63119static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
63120
63121/*
63122** Perform a single step of an incremental-vacuum. If successful, return
63123** SQLITE_OK. If there is no work to do (and therefore no point in
63124** calling this function again), return SQLITE_DONE. Or, if an error
63125** occurs, return some other error code.
63126**
63127** More specifically, this function attempts to re-organize the database so
63128** that the last page of the file currently in use is no longer in use.
63129**
63130** Parameter nFin is the number of pages that this database would contain
63131** were this function called until it returns SQLITE_DONE.
63132**
63133** If the bCommit parameter is non-zero, this function assumes that the
63134** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
63135** or an error. bCommit is passed true for an auto-vacuum-on-commit
63136** operation, or false for an incremental vacuum.
63137*/
63138static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
63139  Pgno nFreeList;           /* Number of pages still on the free-list */
63140  int rc;
63141
63142  assert( sqlite3_mutex_held(pBt->mutex) );
63143  assert( iLastPg>nFin );
63144
63145  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
63146    u8 eType;
63147    Pgno iPtrPage;
63148
63149    nFreeList = get4byte(&pBt->pPage1->aData[36]);
63150    if( nFreeList==0 ){
63151      return SQLITE_DONE;
63152    }
63153
63154    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
63155    if( rc!=SQLITE_OK ){
63156      return rc;
63157    }
63158    if( eType==PTRMAP_ROOTPAGE ){
63159      return SQLITE_CORRUPT_BKPT;
63160    }
63161
63162    if( eType==PTRMAP_FREEPAGE ){
63163      if( bCommit==0 ){
63164        /* Remove the page from the files free-list. This is not required
63165        ** if bCommit is non-zero. In that case, the free-list will be
63166        ** truncated to zero after this function returns, so it doesn't
63167        ** matter if it still contains some garbage entries.
63168        */
63169        Pgno iFreePg;
63170        MemPage *pFreePg;
63171        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
63172        if( rc!=SQLITE_OK ){
63173          return rc;
63174        }
63175        assert( iFreePg==iLastPg );
63176        releasePage(pFreePg);
63177      }
63178    } else {
63179      Pgno iFreePg;             /* Index of free page to move pLastPg to */
63180      MemPage *pLastPg;
63181      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
63182      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
63183
63184      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
63185      if( rc!=SQLITE_OK ){
63186        return rc;
63187      }
63188
63189      /* If bCommit is zero, this loop runs exactly once and page pLastPg
63190      ** is swapped with the first free page pulled off the free list.
63191      **
63192      ** On the other hand, if bCommit is greater than zero, then keep
63193      ** looping until a free-page located within the first nFin pages
63194      ** of the file is found.
63195      */
63196      if( bCommit==0 ){
63197        eMode = BTALLOC_LE;
63198        iNear = nFin;
63199      }
63200      do {
63201        MemPage *pFreePg;
63202        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
63203        if( rc!=SQLITE_OK ){
63204          releasePage(pLastPg);
63205          return rc;
63206        }
63207        releasePage(pFreePg);
63208      }while( bCommit && iFreePg>nFin );
63209      assert( iFreePg<iLastPg );
63210
63211      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
63212      releasePage(pLastPg);
63213      if( rc!=SQLITE_OK ){
63214        return rc;
63215      }
63216    }
63217  }
63218
63219  if( bCommit==0 ){
63220    do {
63221      iLastPg--;
63222    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
63223    pBt->bDoTruncate = 1;
63224    pBt->nPage = iLastPg;
63225  }
63226  return SQLITE_OK;
63227}
63228
63229/*
63230** The database opened by the first argument is an auto-vacuum database
63231** nOrig pages in size containing nFree free pages. Return the expected
63232** size of the database in pages following an auto-vacuum operation.
63233*/
63234static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
63235  int nEntry;                     /* Number of entries on one ptrmap page */
63236  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
63237  Pgno nFin;                      /* Return value */
63238
63239  nEntry = pBt->usableSize/5;
63240  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
63241  nFin = nOrig - nFree - nPtrmap;
63242  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
63243    nFin--;
63244  }
63245  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
63246    nFin--;
63247  }
63248
63249  return nFin;
63250}
63251
63252/*
63253** A write-transaction must be opened before calling this function.
63254** It performs a single unit of work towards an incremental vacuum.
63255**
63256** If the incremental vacuum is finished after this function has run,
63257** SQLITE_DONE is returned. If it is not finished, but no error occurred,
63258** SQLITE_OK is returned. Otherwise an SQLite error code.
63259*/
63260SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
63261  int rc;
63262  BtShared *pBt = p->pBt;
63263
63264  sqlite3BtreeEnter(p);
63265  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
63266  if( !pBt->autoVacuum ){
63267    rc = SQLITE_DONE;
63268  }else{
63269    Pgno nOrig = btreePagecount(pBt);
63270    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
63271    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
63272
63273    if( nOrig<nFin ){
63274      rc = SQLITE_CORRUPT_BKPT;
63275    }else if( nFree>0 ){
63276      rc = saveAllCursors(pBt, 0, 0);
63277      if( rc==SQLITE_OK ){
63278        invalidateAllOverflowCache(pBt);
63279        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
63280      }
63281      if( rc==SQLITE_OK ){
63282        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63283        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
63284      }
63285    }else{
63286      rc = SQLITE_DONE;
63287    }
63288  }
63289  sqlite3BtreeLeave(p);
63290  return rc;
63291}
63292
63293/*
63294** This routine is called prior to sqlite3PagerCommit when a transaction
63295** is committed for an auto-vacuum database.
63296**
63297** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
63298** the database file should be truncated to during the commit process.
63299** i.e. the database has been reorganized so that only the first *pnTrunc
63300** pages are in use.
63301*/
63302static int autoVacuumCommit(BtShared *pBt){
63303  int rc = SQLITE_OK;
63304  Pager *pPager = pBt->pPager;
63305  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
63306
63307  assert( sqlite3_mutex_held(pBt->mutex) );
63308  invalidateAllOverflowCache(pBt);
63309  assert(pBt->autoVacuum);
63310  if( !pBt->incrVacuum ){
63311    Pgno nFin;         /* Number of pages in database after autovacuuming */
63312    Pgno nFree;        /* Number of pages on the freelist initially */
63313    Pgno iFree;        /* The next page to be freed */
63314    Pgno nOrig;        /* Database size before freeing */
63315
63316    nOrig = btreePagecount(pBt);
63317    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
63318      /* It is not possible to create a database for which the final page
63319      ** is either a pointer-map page or the pending-byte page. If one
63320      ** is encountered, this indicates corruption.
63321      */
63322      return SQLITE_CORRUPT_BKPT;
63323    }
63324
63325    nFree = get4byte(&pBt->pPage1->aData[36]);
63326    nFin = finalDbSize(pBt, nOrig, nFree);
63327    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
63328    if( nFin<nOrig ){
63329      rc = saveAllCursors(pBt, 0, 0);
63330    }
63331    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
63332      rc = incrVacuumStep(pBt, nFin, iFree, 1);
63333    }
63334    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
63335      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63336      put4byte(&pBt->pPage1->aData[32], 0);
63337      put4byte(&pBt->pPage1->aData[36], 0);
63338      put4byte(&pBt->pPage1->aData[28], nFin);
63339      pBt->bDoTruncate = 1;
63340      pBt->nPage = nFin;
63341    }
63342    if( rc!=SQLITE_OK ){
63343      sqlite3PagerRollback(pPager);
63344    }
63345  }
63346
63347  assert( nRef>=sqlite3PagerRefcount(pPager) );
63348  return rc;
63349}
63350
63351#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
63352# define setChildPtrmaps(x) SQLITE_OK
63353#endif
63354
63355/*
63356** This routine does the first phase of a two-phase commit.  This routine
63357** causes a rollback journal to be created (if it does not already exist)
63358** and populated with enough information so that if a power loss occurs
63359** the database can be restored to its original state by playing back
63360** the journal.  Then the contents of the journal are flushed out to
63361** the disk.  After the journal is safely on oxide, the changes to the
63362** database are written into the database file and flushed to oxide.
63363** At the end of this call, the rollback journal still exists on the
63364** disk and we are still holding all locks, so the transaction has not
63365** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
63366** commit process.
63367**
63368** This call is a no-op if no write-transaction is currently active on pBt.
63369**
63370** Otherwise, sync the database file for the btree pBt. zMaster points to
63371** the name of a master journal file that should be written into the
63372** individual journal file, or is NULL, indicating no master journal file
63373** (single database transaction).
63374**
63375** When this is called, the master journal should already have been
63376** created, populated with this journal pointer and synced to disk.
63377**
63378** Once this is routine has returned, the only thing required to commit
63379** the write-transaction for this database file is to delete the journal.
63380*/
63381SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
63382  int rc = SQLITE_OK;
63383  if( p->inTrans==TRANS_WRITE ){
63384    BtShared *pBt = p->pBt;
63385    sqlite3BtreeEnter(p);
63386#ifndef SQLITE_OMIT_AUTOVACUUM
63387    if( pBt->autoVacuum ){
63388      rc = autoVacuumCommit(pBt);
63389      if( rc!=SQLITE_OK ){
63390        sqlite3BtreeLeave(p);
63391        return rc;
63392      }
63393    }
63394    if( pBt->bDoTruncate ){
63395      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
63396    }
63397#endif
63398    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
63399    sqlite3BtreeLeave(p);
63400  }
63401  return rc;
63402}
63403
63404/*
63405** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
63406** at the conclusion of a transaction.
63407*/
63408static void btreeEndTransaction(Btree *p){
63409  BtShared *pBt = p->pBt;
63410  sqlite3 *db = p->db;
63411  assert( sqlite3BtreeHoldsMutex(p) );
63412
63413#ifndef SQLITE_OMIT_AUTOVACUUM
63414  pBt->bDoTruncate = 0;
63415#endif
63416  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
63417    /* If there are other active statements that belong to this database
63418    ** handle, downgrade to a read-only transaction. The other statements
63419    ** may still be reading from the database.  */
63420    downgradeAllSharedCacheTableLocks(p);
63421    p->inTrans = TRANS_READ;
63422  }else{
63423    /* If the handle had any kind of transaction open, decrement the
63424    ** transaction count of the shared btree. If the transaction count
63425    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
63426    ** call below will unlock the pager.  */
63427    if( p->inTrans!=TRANS_NONE ){
63428      clearAllSharedCacheTableLocks(p);
63429      pBt->nTransaction--;
63430      if( 0==pBt->nTransaction ){
63431        pBt->inTransaction = TRANS_NONE;
63432      }
63433    }
63434
63435    /* Set the current transaction state to TRANS_NONE and unlock the
63436    ** pager if this call closed the only read or write transaction.  */
63437    p->inTrans = TRANS_NONE;
63438    unlockBtreeIfUnused(pBt);
63439  }
63440
63441  btreeIntegrity(p);
63442}
63443
63444/*
63445** Commit the transaction currently in progress.
63446**
63447** This routine implements the second phase of a 2-phase commit.  The
63448** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
63449** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
63450** routine did all the work of writing information out to disk and flushing the
63451** contents so that they are written onto the disk platter.  All this
63452** routine has to do is delete or truncate or zero the header in the
63453** the rollback journal (which causes the transaction to commit) and
63454** drop locks.
63455**
63456** Normally, if an error occurs while the pager layer is attempting to
63457** finalize the underlying journal file, this function returns an error and
63458** the upper layer will attempt a rollback. However, if the second argument
63459** is non-zero then this b-tree transaction is part of a multi-file
63460** transaction. In this case, the transaction has already been committed
63461** (by deleting a master journal file) and the caller will ignore this
63462** functions return code. So, even if an error occurs in the pager layer,
63463** reset the b-tree objects internal state to indicate that the write
63464** transaction has been closed. This is quite safe, as the pager will have
63465** transitioned to the error state.
63466**
63467** This will release the write lock on the database file.  If there
63468** are no active cursors, it also releases the read lock.
63469*/
63470SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
63471
63472  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
63473  sqlite3BtreeEnter(p);
63474  btreeIntegrity(p);
63475
63476  /* If the handle has a write-transaction open, commit the shared-btrees
63477  ** transaction and set the shared state to TRANS_READ.
63478  */
63479  if( p->inTrans==TRANS_WRITE ){
63480    int rc;
63481    BtShared *pBt = p->pBt;
63482    assert( pBt->inTransaction==TRANS_WRITE );
63483    assert( pBt->nTransaction>0 );
63484    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
63485    if( rc!=SQLITE_OK && bCleanup==0 ){
63486      sqlite3BtreeLeave(p);
63487      return rc;
63488    }
63489    p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
63490    pBt->inTransaction = TRANS_READ;
63491    btreeClearHasContent(pBt);
63492  }
63493
63494  btreeEndTransaction(p);
63495  sqlite3BtreeLeave(p);
63496  return SQLITE_OK;
63497}
63498
63499/*
63500** Do both phases of a commit.
63501*/
63502SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
63503  int rc;
63504  sqlite3BtreeEnter(p);
63505  rc = sqlite3BtreeCommitPhaseOne(p, 0);
63506  if( rc==SQLITE_OK ){
63507    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
63508  }
63509  sqlite3BtreeLeave(p);
63510  return rc;
63511}
63512
63513/*
63514** This routine sets the state to CURSOR_FAULT and the error
63515** code to errCode for every cursor on any BtShared that pBtree
63516** references.  Or if the writeOnly flag is set to 1, then only
63517** trip write cursors and leave read cursors unchanged.
63518**
63519** Every cursor is a candidate to be tripped, including cursors
63520** that belong to other database connections that happen to be
63521** sharing the cache with pBtree.
63522**
63523** This routine gets called when a rollback occurs. If the writeOnly
63524** flag is true, then only write-cursors need be tripped - read-only
63525** cursors save their current positions so that they may continue
63526** following the rollback. Or, if writeOnly is false, all cursors are
63527** tripped. In general, writeOnly is false if the transaction being
63528** rolled back modified the database schema. In this case b-tree root
63529** pages may be moved or deleted from the database altogether, making
63530** it unsafe for read cursors to continue.
63531**
63532** If the writeOnly flag is true and an error is encountered while
63533** saving the current position of a read-only cursor, all cursors,
63534** including all read-cursors are tripped.
63535**
63536** SQLITE_OK is returned if successful, or if an error occurs while
63537** saving a cursor position, an SQLite error code.
63538*/
63539SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
63540  BtCursor *p;
63541  int rc = SQLITE_OK;
63542
63543  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
63544  if( pBtree ){
63545    sqlite3BtreeEnter(pBtree);
63546    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
63547      int i;
63548      if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
63549        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
63550          rc = saveCursorPosition(p);
63551          if( rc!=SQLITE_OK ){
63552            (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
63553            break;
63554          }
63555        }
63556      }else{
63557        sqlite3BtreeClearCursor(p);
63558        p->eState = CURSOR_FAULT;
63559        p->skipNext = errCode;
63560      }
63561      for(i=0; i<=p->iPage; i++){
63562        releasePage(p->apPage[i]);
63563        p->apPage[i] = 0;
63564      }
63565    }
63566    sqlite3BtreeLeave(pBtree);
63567  }
63568  return rc;
63569}
63570
63571/*
63572** Rollback the transaction in progress.
63573**
63574** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
63575** Only write cursors are tripped if writeOnly is true but all cursors are
63576** tripped if writeOnly is false.  Any attempt to use
63577** a tripped cursor will result in an error.
63578**
63579** This will release the write lock on the database file.  If there
63580** are no active cursors, it also releases the read lock.
63581*/
63582SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
63583  int rc;
63584  BtShared *pBt = p->pBt;
63585  MemPage *pPage1;
63586
63587  assert( writeOnly==1 || writeOnly==0 );
63588  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
63589  sqlite3BtreeEnter(p);
63590  if( tripCode==SQLITE_OK ){
63591    rc = tripCode = saveAllCursors(pBt, 0, 0);
63592    if( rc ) writeOnly = 0;
63593  }else{
63594    rc = SQLITE_OK;
63595  }
63596  if( tripCode ){
63597    int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
63598    assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
63599    if( rc2!=SQLITE_OK ) rc = rc2;
63600  }
63601  btreeIntegrity(p);
63602
63603  if( p->inTrans==TRANS_WRITE ){
63604    int rc2;
63605
63606    assert( TRANS_WRITE==pBt->inTransaction );
63607    rc2 = sqlite3PagerRollback(pBt->pPager);
63608    if( rc2!=SQLITE_OK ){
63609      rc = rc2;
63610    }
63611
63612    /* The rollback may have destroyed the pPage1->aData value.  So
63613    ** call btreeGetPage() on page 1 again to make
63614    ** sure pPage1->aData is set correctly. */
63615    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
63616      int nPage = get4byte(28+(u8*)pPage1->aData);
63617      testcase( nPage==0 );
63618      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
63619      testcase( pBt->nPage!=nPage );
63620      pBt->nPage = nPage;
63621      releasePage(pPage1);
63622    }
63623    assert( countValidCursors(pBt, 1)==0 );
63624    pBt->inTransaction = TRANS_READ;
63625    btreeClearHasContent(pBt);
63626  }
63627
63628  btreeEndTransaction(p);
63629  sqlite3BtreeLeave(p);
63630  return rc;
63631}
63632
63633/*
63634** Start a statement subtransaction. The subtransaction can be rolled
63635** back independently of the main transaction. You must start a transaction
63636** before starting a subtransaction. The subtransaction is ended automatically
63637** if the main transaction commits or rolls back.
63638**
63639** Statement subtransactions are used around individual SQL statements
63640** that are contained within a BEGIN...COMMIT block.  If a constraint
63641** error occurs within the statement, the effect of that one statement
63642** can be rolled back without having to rollback the entire transaction.
63643**
63644** A statement sub-transaction is implemented as an anonymous savepoint. The
63645** value passed as the second parameter is the total number of savepoints,
63646** including the new anonymous savepoint, open on the B-Tree. i.e. if there
63647** are no active savepoints and no other statement-transactions open,
63648** iStatement is 1. This anonymous savepoint can be released or rolled back
63649** using the sqlite3BtreeSavepoint() function.
63650*/
63651SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
63652  int rc;
63653  BtShared *pBt = p->pBt;
63654  sqlite3BtreeEnter(p);
63655  assert( p->inTrans==TRANS_WRITE );
63656  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
63657  assert( iStatement>0 );
63658  assert( iStatement>p->db->nSavepoint );
63659  assert( pBt->inTransaction==TRANS_WRITE );
63660  /* At the pager level, a statement transaction is a savepoint with
63661  ** an index greater than all savepoints created explicitly using
63662  ** SQL statements. It is illegal to open, release or rollback any
63663  ** such savepoints while the statement transaction savepoint is active.
63664  */
63665  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
63666  sqlite3BtreeLeave(p);
63667  return rc;
63668}
63669
63670/*
63671** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
63672** or SAVEPOINT_RELEASE. This function either releases or rolls back the
63673** savepoint identified by parameter iSavepoint, depending on the value
63674** of op.
63675**
63676** Normally, iSavepoint is greater than or equal to zero. However, if op is
63677** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
63678** contents of the entire transaction are rolled back. This is different
63679** from a normal transaction rollback, as no locks are released and the
63680** transaction remains open.
63681*/
63682SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
63683  int rc = SQLITE_OK;
63684  if( p && p->inTrans==TRANS_WRITE ){
63685    BtShared *pBt = p->pBt;
63686    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
63687    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
63688    sqlite3BtreeEnter(p);
63689    if( op==SAVEPOINT_ROLLBACK ){
63690      rc = saveAllCursors(pBt, 0, 0);
63691    }
63692    if( rc==SQLITE_OK ){
63693      rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
63694    }
63695    if( rc==SQLITE_OK ){
63696      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
63697        pBt->nPage = 0;
63698      }
63699      rc = newDatabase(pBt);
63700      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
63701
63702      /* The database size was written into the offset 28 of the header
63703      ** when the transaction started, so we know that the value at offset
63704      ** 28 is nonzero. */
63705      assert( pBt->nPage>0 );
63706    }
63707    sqlite3BtreeLeave(p);
63708  }
63709  return rc;
63710}
63711
63712/*
63713** Create a new cursor for the BTree whose root is on the page
63714** iTable. If a read-only cursor is requested, it is assumed that
63715** the caller already has at least a read-only transaction open
63716** on the database already. If a write-cursor is requested, then
63717** the caller is assumed to have an open write transaction.
63718**
63719** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
63720** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
63721** can be used for reading or for writing if other conditions for writing
63722** are also met.  These are the conditions that must be met in order
63723** for writing to be allowed:
63724**
63725** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
63726**
63727** 2:  Other database connections that share the same pager cache
63728**     but which are not in the READ_UNCOMMITTED state may not have
63729**     cursors open with wrFlag==0 on the same table.  Otherwise
63730**     the changes made by this write cursor would be visible to
63731**     the read cursors in the other database connection.
63732**
63733** 3:  The database must be writable (not on read-only media)
63734**
63735** 4:  There must be an active transaction.
63736**
63737** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
63738** is set.  If FORDELETE is set, that is a hint to the implementation that
63739** this cursor will only be used to seek to and delete entries of an index
63740** as part of a larger DELETE statement.  The FORDELETE hint is not used by
63741** this implementation.  But in a hypothetical alternative storage engine
63742** in which index entries are automatically deleted when corresponding table
63743** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
63744** operations on this cursor can be no-ops and all READ operations can
63745** return a null row (2-bytes: 0x01 0x00).
63746**
63747** No checking is done to make sure that page iTable really is the
63748** root page of a b-tree.  If it is not, then the cursor acquired
63749** will not work correctly.
63750**
63751** It is assumed that the sqlite3BtreeCursorZero() has been called
63752** on pCur to initialize the memory space prior to invoking this routine.
63753*/
63754static int btreeCursor(
63755  Btree *p,                              /* The btree */
63756  int iTable,                            /* Root page of table to open */
63757  int wrFlag,                            /* 1 to write. 0 read-only */
63758  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
63759  BtCursor *pCur                         /* Space for new cursor */
63760){
63761  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
63762  BtCursor *pX;                          /* Looping over other all cursors */
63763
63764  assert( sqlite3BtreeHoldsMutex(p) );
63765  assert( wrFlag==0
63766       || wrFlag==BTREE_WRCSR
63767       || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
63768  );
63769
63770  /* The following assert statements verify that if this is a sharable
63771  ** b-tree database, the connection is holding the required table locks,
63772  ** and that no other connection has any open cursor that conflicts with
63773  ** this lock.  */
63774  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
63775  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
63776
63777  /* Assert that the caller has opened the required transaction. */
63778  assert( p->inTrans>TRANS_NONE );
63779  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
63780  assert( pBt->pPage1 && pBt->pPage1->aData );
63781  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
63782
63783  if( wrFlag ){
63784    allocateTempSpace(pBt);
63785    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
63786  }
63787  if( iTable==1 && btreePagecount(pBt)==0 ){
63788    assert( wrFlag==0 );
63789    iTable = 0;
63790  }
63791
63792  /* Now that no other errors can occur, finish filling in the BtCursor
63793  ** variables and link the cursor into the BtShared list.  */
63794  pCur->pgnoRoot = (Pgno)iTable;
63795  pCur->iPage = -1;
63796  pCur->pKeyInfo = pKeyInfo;
63797  pCur->pBtree = p;
63798  pCur->pBt = pBt;
63799  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
63800  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
63801  /* If there are two or more cursors on the same btree, then all such
63802  ** cursors *must* have the BTCF_Multiple flag set. */
63803  for(pX=pBt->pCursor; pX; pX=pX->pNext){
63804    if( pX->pgnoRoot==(Pgno)iTable ){
63805      pX->curFlags |= BTCF_Multiple;
63806      pCur->curFlags |= BTCF_Multiple;
63807    }
63808  }
63809  pCur->pNext = pBt->pCursor;
63810  pBt->pCursor = pCur;
63811  pCur->eState = CURSOR_INVALID;
63812  return SQLITE_OK;
63813}
63814SQLITE_PRIVATE int sqlite3BtreeCursor(
63815  Btree *p,                                   /* The btree */
63816  int iTable,                                 /* Root page of table to open */
63817  int wrFlag,                                 /* 1 to write. 0 read-only */
63818  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
63819  BtCursor *pCur                              /* Write new cursor here */
63820){
63821  int rc;
63822  if( iTable<1 ){
63823    rc = SQLITE_CORRUPT_BKPT;
63824  }else{
63825    sqlite3BtreeEnter(p);
63826    rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
63827    sqlite3BtreeLeave(p);
63828  }
63829  return rc;
63830}
63831
63832/*
63833** Return the size of a BtCursor object in bytes.
63834**
63835** This interfaces is needed so that users of cursors can preallocate
63836** sufficient storage to hold a cursor.  The BtCursor object is opaque
63837** to users so they cannot do the sizeof() themselves - they must call
63838** this routine.
63839*/
63840SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
63841  return ROUND8(sizeof(BtCursor));
63842}
63843
63844/*
63845** Initialize memory that will be converted into a BtCursor object.
63846**
63847** The simple approach here would be to memset() the entire object
63848** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
63849** do not need to be zeroed and they are large, so we can save a lot
63850** of run-time by skipping the initialization of those elements.
63851*/
63852SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
63853  memset(p, 0, offsetof(BtCursor, iPage));
63854}
63855
63856/*
63857** Close a cursor.  The read lock on the database file is released
63858** when the last cursor is closed.
63859*/
63860SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
63861  Btree *pBtree = pCur->pBtree;
63862  if( pBtree ){
63863    int i;
63864    BtShared *pBt = pCur->pBt;
63865    sqlite3BtreeEnter(pBtree);
63866    sqlite3BtreeClearCursor(pCur);
63867    assert( pBt->pCursor!=0 );
63868    if( pBt->pCursor==pCur ){
63869      pBt->pCursor = pCur->pNext;
63870    }else{
63871      BtCursor *pPrev = pBt->pCursor;
63872      do{
63873        if( pPrev->pNext==pCur ){
63874          pPrev->pNext = pCur->pNext;
63875          break;
63876        }
63877        pPrev = pPrev->pNext;
63878      }while( ALWAYS(pPrev) );
63879    }
63880    for(i=0; i<=pCur->iPage; i++){
63881      releasePage(pCur->apPage[i]);
63882    }
63883    unlockBtreeIfUnused(pBt);
63884    sqlite3_free(pCur->aOverflow);
63885    /* sqlite3_free(pCur); */
63886    sqlite3BtreeLeave(pBtree);
63887  }
63888  return SQLITE_OK;
63889}
63890
63891/*
63892** Make sure the BtCursor* given in the argument has a valid
63893** BtCursor.info structure.  If it is not already valid, call
63894** btreeParseCell() to fill it in.
63895**
63896** BtCursor.info is a cache of the information in the current cell.
63897** Using this cache reduces the number of calls to btreeParseCell().
63898*/
63899#ifndef NDEBUG
63900  static void assertCellInfo(BtCursor *pCur){
63901    CellInfo info;
63902    int iPage = pCur->iPage;
63903    memset(&info, 0, sizeof(info));
63904    btreeParseCell(pCur->apPage[iPage], pCur->ix, &info);
63905    assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
63906  }
63907#else
63908  #define assertCellInfo(x)
63909#endif
63910static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
63911  if( pCur->info.nSize==0 ){
63912    int iPage = pCur->iPage;
63913    pCur->curFlags |= BTCF_ValidNKey;
63914    btreeParseCell(pCur->apPage[iPage],pCur->ix,&pCur->info);
63915  }else{
63916    assertCellInfo(pCur);
63917  }
63918}
63919
63920#ifndef NDEBUG  /* The next routine used only within assert() statements */
63921/*
63922** Return true if the given BtCursor is valid.  A valid cursor is one
63923** that is currently pointing to a row in a (non-empty) table.
63924** This is a verification routine is used only within assert() statements.
63925*/
63926SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
63927  return pCur && pCur->eState==CURSOR_VALID;
63928}
63929#endif /* NDEBUG */
63930SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
63931  assert( pCur!=0 );
63932  return pCur->eState==CURSOR_VALID;
63933}
63934
63935/*
63936** Return the value of the integer key or "rowid" for a table btree.
63937** This routine is only valid for a cursor that is pointing into a
63938** ordinary table btree.  If the cursor points to an index btree or
63939** is invalid, the result of this routine is undefined.
63940*/
63941SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
63942  assert( cursorHoldsMutex(pCur) );
63943  assert( pCur->eState==CURSOR_VALID );
63944  assert( pCur->curIntKey );
63945  getCellInfo(pCur);
63946  return pCur->info.nKey;
63947}
63948
63949/*
63950** Return the number of bytes of payload for the entry that pCur is
63951** currently pointing to.  For table btrees, this will be the amount
63952** of data.  For index btrees, this will be the size of the key.
63953**
63954** The caller must guarantee that the cursor is pointing to a non-NULL
63955** valid entry.  In other words, the calling procedure must guarantee
63956** that the cursor has Cursor.eState==CURSOR_VALID.
63957*/
63958SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
63959  assert( cursorHoldsMutex(pCur) );
63960  assert( pCur->eState==CURSOR_VALID );
63961  getCellInfo(pCur);
63962  return pCur->info.nPayload;
63963}
63964
63965/*
63966** Given the page number of an overflow page in the database (parameter
63967** ovfl), this function finds the page number of the next page in the
63968** linked list of overflow pages. If possible, it uses the auto-vacuum
63969** pointer-map data instead of reading the content of page ovfl to do so.
63970**
63971** If an error occurs an SQLite error code is returned. Otherwise:
63972**
63973** The page number of the next overflow page in the linked list is
63974** written to *pPgnoNext. If page ovfl is the last page in its linked
63975** list, *pPgnoNext is set to zero.
63976**
63977** If ppPage is not NULL, and a reference to the MemPage object corresponding
63978** to page number pOvfl was obtained, then *ppPage is set to point to that
63979** reference. It is the responsibility of the caller to call releasePage()
63980** on *ppPage to free the reference. In no reference was obtained (because
63981** the pointer-map was used to obtain the value for *pPgnoNext), then
63982** *ppPage is set to zero.
63983*/
63984static int getOverflowPage(
63985  BtShared *pBt,               /* The database file */
63986  Pgno ovfl,                   /* Current overflow page number */
63987  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
63988  Pgno *pPgnoNext              /* OUT: Next overflow page number */
63989){
63990  Pgno next = 0;
63991  MemPage *pPage = 0;
63992  int rc = SQLITE_OK;
63993
63994  assert( sqlite3_mutex_held(pBt->mutex) );
63995  assert(pPgnoNext);
63996
63997#ifndef SQLITE_OMIT_AUTOVACUUM
63998  /* Try to find the next page in the overflow list using the
63999  ** autovacuum pointer-map pages. Guess that the next page in
64000  ** the overflow list is page number (ovfl+1). If that guess turns
64001  ** out to be wrong, fall back to loading the data of page
64002  ** number ovfl to determine the next page number.
64003  */
64004  if( pBt->autoVacuum ){
64005    Pgno pgno;
64006    Pgno iGuess = ovfl+1;
64007    u8 eType;
64008
64009    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
64010      iGuess++;
64011    }
64012
64013    if( iGuess<=btreePagecount(pBt) ){
64014      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
64015      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
64016        next = iGuess;
64017        rc = SQLITE_DONE;
64018      }
64019    }
64020  }
64021#endif
64022
64023  assert( next==0 || rc==SQLITE_DONE );
64024  if( rc==SQLITE_OK ){
64025    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
64026    assert( rc==SQLITE_OK || pPage==0 );
64027    if( rc==SQLITE_OK ){
64028      next = get4byte(pPage->aData);
64029    }
64030  }
64031
64032  *pPgnoNext = next;
64033  if( ppPage ){
64034    *ppPage = pPage;
64035  }else{
64036    releasePage(pPage);
64037  }
64038  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
64039}
64040
64041/*
64042** Copy data from a buffer to a page, or from a page to a buffer.
64043**
64044** pPayload is a pointer to data stored on database page pDbPage.
64045** If argument eOp is false, then nByte bytes of data are copied
64046** from pPayload to the buffer pointed at by pBuf. If eOp is true,
64047** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
64048** of data are copied from the buffer pBuf to pPayload.
64049**
64050** SQLITE_OK is returned on success, otherwise an error code.
64051*/
64052static int copyPayload(
64053  void *pPayload,           /* Pointer to page data */
64054  void *pBuf,               /* Pointer to buffer */
64055  int nByte,                /* Number of bytes to copy */
64056  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
64057  DbPage *pDbPage           /* Page containing pPayload */
64058){
64059  if( eOp ){
64060    /* Copy data from buffer to page (a write operation) */
64061    int rc = sqlite3PagerWrite(pDbPage);
64062    if( rc!=SQLITE_OK ){
64063      return rc;
64064    }
64065    memcpy(pPayload, pBuf, nByte);
64066  }else{
64067    /* Copy data from page to buffer (a read operation) */
64068    memcpy(pBuf, pPayload, nByte);
64069  }
64070  return SQLITE_OK;
64071}
64072
64073/*
64074** This function is used to read or overwrite payload information
64075** for the entry that the pCur cursor is pointing to. The eOp
64076** argument is interpreted as follows:
64077**
64078**   0: The operation is a read. Populate the overflow cache.
64079**   1: The operation is a write. Populate the overflow cache.
64080**
64081** A total of "amt" bytes are read or written beginning at "offset".
64082** Data is read to or from the buffer pBuf.
64083**
64084** The content being read or written might appear on the main page
64085** or be scattered out on multiple overflow pages.
64086**
64087** If the current cursor entry uses one or more overflow pages
64088** this function may allocate space for and lazily populate
64089** the overflow page-list cache array (BtCursor.aOverflow).
64090** Subsequent calls use this cache to make seeking to the supplied offset
64091** more efficient.
64092**
64093** Once an overflow page-list cache has been allocated, it must be
64094** invalidated if some other cursor writes to the same table, or if
64095** the cursor is moved to a different row. Additionally, in auto-vacuum
64096** mode, the following events may invalidate an overflow page-list cache.
64097**
64098**   * An incremental vacuum,
64099**   * A commit in auto_vacuum="full" mode,
64100**   * Creating a table (may require moving an overflow page).
64101*/
64102static int accessPayload(
64103  BtCursor *pCur,      /* Cursor pointing to entry to read from */
64104  u32 offset,          /* Begin reading this far into payload */
64105  u32 amt,             /* Read this many bytes */
64106  unsigned char *pBuf, /* Write the bytes into this buffer */
64107  int eOp              /* zero to read. non-zero to write. */
64108){
64109  unsigned char *aPayload;
64110  int rc = SQLITE_OK;
64111  int iIdx = 0;
64112  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
64113  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
64114#ifdef SQLITE_DIRECT_OVERFLOW_READ
64115  unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
64116#endif
64117
64118  assert( pPage );
64119  assert( eOp==0 || eOp==1 );
64120  assert( pCur->eState==CURSOR_VALID );
64121  assert( pCur->ix<pPage->nCell );
64122  assert( cursorHoldsMutex(pCur) );
64123
64124  getCellInfo(pCur);
64125  aPayload = pCur->info.pPayload;
64126  assert( offset+amt <= pCur->info.nPayload );
64127
64128  assert( aPayload > pPage->aData );
64129  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
64130    /* Trying to read or write past the end of the data is an error.  The
64131    ** conditional above is really:
64132    **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
64133    ** but is recast into its current form to avoid integer overflow problems
64134    */
64135    return SQLITE_CORRUPT_PGNO(pPage->pgno);
64136  }
64137
64138  /* Check if data must be read/written to/from the btree page itself. */
64139  if( offset<pCur->info.nLocal ){
64140    int a = amt;
64141    if( a+offset>pCur->info.nLocal ){
64142      a = pCur->info.nLocal - offset;
64143    }
64144    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
64145    offset = 0;
64146    pBuf += a;
64147    amt -= a;
64148  }else{
64149    offset -= pCur->info.nLocal;
64150  }
64151
64152
64153  if( rc==SQLITE_OK && amt>0 ){
64154    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
64155    Pgno nextPage;
64156
64157    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
64158
64159    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
64160    **
64161    ** The aOverflow[] array is sized at one entry for each overflow page
64162    ** in the overflow chain. The page number of the first overflow page is
64163    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
64164    ** means "not yet known" (the cache is lazily populated).
64165    */
64166    if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
64167      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
64168      if( nOvfl>pCur->nOvflAlloc ){
64169        Pgno *aNew = (Pgno*)sqlite3Realloc(
64170            pCur->aOverflow, nOvfl*2*sizeof(Pgno)
64171        );
64172        if( aNew==0 ){
64173          return SQLITE_NOMEM_BKPT;
64174        }else{
64175          pCur->nOvflAlloc = nOvfl*2;
64176          pCur->aOverflow = aNew;
64177        }
64178      }
64179      memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
64180      pCur->curFlags |= BTCF_ValidOvfl;
64181    }else{
64182      /* If the overflow page-list cache has been allocated and the
64183      ** entry for the first required overflow page is valid, skip
64184      ** directly to it.
64185      */
64186      if( pCur->aOverflow[offset/ovflSize] ){
64187        iIdx = (offset/ovflSize);
64188        nextPage = pCur->aOverflow[iIdx];
64189        offset = (offset%ovflSize);
64190      }
64191    }
64192
64193    assert( rc==SQLITE_OK && amt>0 );
64194    while( nextPage ){
64195      /* If required, populate the overflow page-list cache. */
64196      assert( pCur->aOverflow[iIdx]==0
64197              || pCur->aOverflow[iIdx]==nextPage
64198              || CORRUPT_DB );
64199      pCur->aOverflow[iIdx] = nextPage;
64200
64201      if( offset>=ovflSize ){
64202        /* The only reason to read this page is to obtain the page
64203        ** number for the next page in the overflow chain. The page
64204        ** data is not required. So first try to lookup the overflow
64205        ** page-list cache, if any, then fall back to the getOverflowPage()
64206        ** function.
64207        */
64208        assert( pCur->curFlags & BTCF_ValidOvfl );
64209        assert( pCur->pBtree->db==pBt->db );
64210        if( pCur->aOverflow[iIdx+1] ){
64211          nextPage = pCur->aOverflow[iIdx+1];
64212        }else{
64213          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
64214        }
64215        offset -= ovflSize;
64216      }else{
64217        /* Need to read this page properly. It contains some of the
64218        ** range of data that is being read (eOp==0) or written (eOp!=0).
64219        */
64220#ifdef SQLITE_DIRECT_OVERFLOW_READ
64221        sqlite3_file *fd;      /* File from which to do direct overflow read */
64222#endif
64223        int a = amt;
64224        if( a + offset > ovflSize ){
64225          a = ovflSize - offset;
64226        }
64227
64228#ifdef SQLITE_DIRECT_OVERFLOW_READ
64229        /* If all the following are true:
64230        **
64231        **   1) this is a read operation, and
64232        **   2) data is required from the start of this overflow page, and
64233        **   3) there is no open write-transaction, and
64234        **   4) the database is file-backed, and
64235        **   5) the page is not in the WAL file
64236        **   6) at least 4 bytes have already been read into the output buffer
64237        **
64238        ** then data can be read directly from the database file into the
64239        ** output buffer, bypassing the page-cache altogether. This speeds
64240        ** up loading large records that span many overflow pages.
64241        */
64242        if( eOp==0                                             /* (1) */
64243         && offset==0                                          /* (2) */
64244         && pBt->inTransaction==TRANS_READ                     /* (3) */
64245         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (4) */
64246         && 0==sqlite3PagerUseWal(pBt->pPager, nextPage)       /* (5) */
64247         && &pBuf[-4]>=pBufStart                               /* (6) */
64248        ){
64249          u8 aSave[4];
64250          u8 *aWrite = &pBuf[-4];
64251          assert( aWrite>=pBufStart );                         /* due to (6) */
64252          memcpy(aSave, aWrite, 4);
64253          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
64254          nextPage = get4byte(aWrite);
64255          memcpy(aWrite, aSave, 4);
64256        }else
64257#endif
64258
64259        {
64260          DbPage *pDbPage;
64261          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
64262              (eOp==0 ? PAGER_GET_READONLY : 0)
64263          );
64264          if( rc==SQLITE_OK ){
64265            aPayload = sqlite3PagerGetData(pDbPage);
64266            nextPage = get4byte(aPayload);
64267            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
64268            sqlite3PagerUnref(pDbPage);
64269            offset = 0;
64270          }
64271        }
64272        amt -= a;
64273        if( amt==0 ) return rc;
64274        pBuf += a;
64275      }
64276      if( rc ) break;
64277      iIdx++;
64278    }
64279  }
64280
64281  if( rc==SQLITE_OK && amt>0 ){
64282    /* Overflow chain ends prematurely */
64283    return SQLITE_CORRUPT_PGNO(pPage->pgno);
64284  }
64285  return rc;
64286}
64287
64288/*
64289** Read part of the payload for the row at which that cursor pCur is currently
64290** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
64291** begins at "offset".
64292**
64293** pCur can be pointing to either a table or an index b-tree.
64294** If pointing to a table btree, then the content section is read.  If
64295** pCur is pointing to an index b-tree then the key section is read.
64296**
64297** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
64298** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
64299** cursor might be invalid or might need to be restored before being read.
64300**
64301** Return SQLITE_OK on success or an error code if anything goes
64302** wrong.  An error is returned if "offset+amt" is larger than
64303** the available payload.
64304*/
64305SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
64306  assert( cursorHoldsMutex(pCur) );
64307  assert( pCur->eState==CURSOR_VALID );
64308  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
64309  assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
64310  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
64311}
64312
64313/*
64314** This variant of sqlite3BtreePayload() works even if the cursor has not
64315** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
64316** interface.
64317*/
64318#ifndef SQLITE_OMIT_INCRBLOB
64319static SQLITE_NOINLINE int accessPayloadChecked(
64320  BtCursor *pCur,
64321  u32 offset,
64322  u32 amt,
64323  void *pBuf
64324){
64325  int rc;
64326  if ( pCur->eState==CURSOR_INVALID ){
64327    return SQLITE_ABORT;
64328  }
64329  assert( cursorOwnsBtShared(pCur) );
64330  rc = btreeRestoreCursorPosition(pCur);
64331  return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
64332}
64333SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
64334  if( pCur->eState==CURSOR_VALID ){
64335    assert( cursorOwnsBtShared(pCur) );
64336    return accessPayload(pCur, offset, amt, pBuf, 0);
64337  }else{
64338    return accessPayloadChecked(pCur, offset, amt, pBuf);
64339  }
64340}
64341#endif /* SQLITE_OMIT_INCRBLOB */
64342
64343/*
64344** Return a pointer to payload information from the entry that the
64345** pCur cursor is pointing to.  The pointer is to the beginning of
64346** the key if index btrees (pPage->intKey==0) and is the data for
64347** table btrees (pPage->intKey==1). The number of bytes of available
64348** key/data is written into *pAmt.  If *pAmt==0, then the value
64349** returned will not be a valid pointer.
64350**
64351** This routine is an optimization.  It is common for the entire key
64352** and data to fit on the local page and for there to be no overflow
64353** pages.  When that is so, this routine can be used to access the
64354** key and data without making a copy.  If the key and/or data spills
64355** onto overflow pages, then accessPayload() must be used to reassemble
64356** the key/data and copy it into a preallocated buffer.
64357**
64358** The pointer returned by this routine looks directly into the cached
64359** page of the database.  The data might change or move the next time
64360** any btree routine is called.
64361*/
64362static const void *fetchPayload(
64363  BtCursor *pCur,      /* Cursor pointing to entry to read from */
64364  u32 *pAmt            /* Write the number of available bytes here */
64365){
64366  u32 amt;
64367  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
64368  assert( pCur->eState==CURSOR_VALID );
64369  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64370  assert( cursorOwnsBtShared(pCur) );
64371  assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
64372  assert( pCur->info.nSize>0 );
64373  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
64374  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
64375  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
64376  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
64377  *pAmt = amt;
64378  return (void*)pCur->info.pPayload;
64379}
64380
64381
64382/*
64383** For the entry that cursor pCur is point to, return as
64384** many bytes of the key or data as are available on the local
64385** b-tree page.  Write the number of available bytes into *pAmt.
64386**
64387** The pointer returned is ephemeral.  The key/data may move
64388** or be destroyed on the next call to any Btree routine,
64389** including calls from other threads against the same cache.
64390** Hence, a mutex on the BtShared should be held prior to calling
64391** this routine.
64392**
64393** These routines is used to get quick access to key and data
64394** in the common case where no overflow pages are used.
64395*/
64396SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
64397  return fetchPayload(pCur, pAmt);
64398}
64399
64400
64401/*
64402** Move the cursor down to a new child page.  The newPgno argument is the
64403** page number of the child page to move to.
64404**
64405** This function returns SQLITE_CORRUPT if the page-header flags field of
64406** the new child page does not match the flags field of the parent (i.e.
64407** if an intkey page appears to be the parent of a non-intkey page, or
64408** vice-versa).
64409*/
64410static int moveToChild(BtCursor *pCur, u32 newPgno){
64411  BtShared *pBt = pCur->pBt;
64412
64413  assert( cursorOwnsBtShared(pCur) );
64414  assert( pCur->eState==CURSOR_VALID );
64415  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
64416  assert( pCur->iPage>=0 );
64417  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
64418    return SQLITE_CORRUPT_BKPT;
64419  }
64420  pCur->info.nSize = 0;
64421  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
64422  pCur->aiIdx[pCur->iPage++] = pCur->ix;
64423  pCur->ix = 0;
64424  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
64425                        pCur, pCur->curPagerFlags);
64426}
64427
64428#ifdef SQLITE_DEBUG
64429/*
64430** Page pParent is an internal (non-leaf) tree page. This function
64431** asserts that page number iChild is the left-child if the iIdx'th
64432** cell in page pParent. Or, if iIdx is equal to the total number of
64433** cells in pParent, that page number iChild is the right-child of
64434** the page.
64435*/
64436static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
64437  if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
64438                            ** in a corrupt database */
64439  assert( iIdx<=pParent->nCell );
64440  if( iIdx==pParent->nCell ){
64441    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
64442  }else{
64443    assert( get4byte(findCell(pParent, iIdx))==iChild );
64444  }
64445}
64446#else
64447#  define assertParentIndex(x,y,z)
64448#endif
64449
64450/*
64451** Move the cursor up to the parent page.
64452**
64453** pCur->idx is set to the cell index that contains the pointer
64454** to the page we are coming from.  If we are coming from the
64455** right-most child page then pCur->idx is set to one more than
64456** the largest cell index.
64457*/
64458static void moveToParent(BtCursor *pCur){
64459  assert( cursorOwnsBtShared(pCur) );
64460  assert( pCur->eState==CURSOR_VALID );
64461  assert( pCur->iPage>0 );
64462  assert( pCur->apPage[pCur->iPage] );
64463  assertParentIndex(
64464    pCur->apPage[pCur->iPage-1],
64465    pCur->aiIdx[pCur->iPage-1],
64466    pCur->apPage[pCur->iPage]->pgno
64467  );
64468  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
64469  pCur->info.nSize = 0;
64470  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
64471  pCur->ix = pCur->aiIdx[pCur->iPage-1];
64472  releasePageNotNull(pCur->apPage[pCur->iPage--]);
64473}
64474
64475/*
64476** Move the cursor to point to the root page of its b-tree structure.
64477**
64478** If the table has a virtual root page, then the cursor is moved to point
64479** to the virtual root page instead of the actual root page. A table has a
64480** virtual root page when the actual root page contains no cells and a
64481** single child page. This can only happen with the table rooted at page 1.
64482**
64483** If the b-tree structure is empty, the cursor state is set to
64484** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
64485** cell located on the root (or virtual root) page and the cursor state
64486** is set to CURSOR_VALID.
64487**
64488** If this function returns successfully, it may be assumed that the
64489** page-header flags indicate that the [virtual] root-page is the expected
64490** kind of b-tree page (i.e. if when opening the cursor the caller did not
64491** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
64492** indicating a table b-tree, or if the caller did specify a KeyInfo
64493** structure the flags byte is set to 0x02 or 0x0A, indicating an index
64494** b-tree).
64495*/
64496static int moveToRoot(BtCursor *pCur){
64497  MemPage *pRoot;
64498  int rc = SQLITE_OK;
64499
64500  assert( cursorOwnsBtShared(pCur) );
64501  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
64502  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
64503  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
64504  if( pCur->eState>=CURSOR_REQUIRESEEK ){
64505    if( pCur->eState==CURSOR_FAULT ){
64506      assert( pCur->skipNext!=SQLITE_OK );
64507      return pCur->skipNext;
64508    }
64509    sqlite3BtreeClearCursor(pCur);
64510  }
64511
64512  if( pCur->iPage>=0 ){
64513    if( pCur->iPage ){
64514      do{
64515        assert( pCur->apPage[pCur->iPage]!=0 );
64516        releasePageNotNull(pCur->apPage[pCur->iPage--]);
64517      }while( pCur->iPage);
64518      goto skip_init;
64519    }
64520  }else if( pCur->pgnoRoot==0 ){
64521    pCur->eState = CURSOR_INVALID;
64522    return SQLITE_OK;
64523  }else{
64524    assert( pCur->iPage==(-1) );
64525    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
64526                        0, pCur->curPagerFlags);
64527    if( rc!=SQLITE_OK ){
64528      pCur->eState = CURSOR_INVALID;
64529       return rc;
64530    }
64531    pCur->iPage = 0;
64532    pCur->curIntKey = pCur->apPage[0]->intKey;
64533  }
64534  pRoot = pCur->apPage[0];
64535  assert( pRoot->pgno==pCur->pgnoRoot );
64536
64537  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
64538  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
64539  ** NULL, the caller expects a table b-tree. If this is not the case,
64540  ** return an SQLITE_CORRUPT error.
64541  **
64542  ** Earlier versions of SQLite assumed that this test could not fail
64543  ** if the root page was already loaded when this function was called (i.e.
64544  ** if pCur->iPage>=0). But this is not so if the database is corrupted
64545  ** in such a way that page pRoot is linked into a second b-tree table
64546  ** (or the freelist).  */
64547  assert( pRoot->intKey==1 || pRoot->intKey==0 );
64548  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
64549    return SQLITE_CORRUPT_PGNO(pCur->apPage[pCur->iPage]->pgno);
64550  }
64551
64552skip_init:
64553  pCur->ix = 0;
64554  pCur->info.nSize = 0;
64555  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
64556
64557  pRoot = pCur->apPage[0];
64558  if( pRoot->nCell>0 ){
64559    pCur->eState = CURSOR_VALID;
64560  }else if( !pRoot->leaf ){
64561    Pgno subpage;
64562    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
64563    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
64564    pCur->eState = CURSOR_VALID;
64565    rc = moveToChild(pCur, subpage);
64566  }else{
64567    pCur->eState = CURSOR_INVALID;
64568  }
64569  return rc;
64570}
64571
64572/*
64573** Move the cursor down to the left-most leaf entry beneath the
64574** entry to which it is currently pointing.
64575**
64576** The left-most leaf is the one with the smallest key - the first
64577** in ascending order.
64578*/
64579static int moveToLeftmost(BtCursor *pCur){
64580  Pgno pgno;
64581  int rc = SQLITE_OK;
64582  MemPage *pPage;
64583
64584  assert( cursorOwnsBtShared(pCur) );
64585  assert( pCur->eState==CURSOR_VALID );
64586  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
64587    assert( pCur->ix<pPage->nCell );
64588    pgno = get4byte(findCell(pPage, pCur->ix));
64589    rc = moveToChild(pCur, pgno);
64590  }
64591  return rc;
64592}
64593
64594/*
64595** Move the cursor down to the right-most leaf entry beneath the
64596** page to which it is currently pointing.  Notice the difference
64597** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
64598** finds the left-most entry beneath the *entry* whereas moveToRightmost()
64599** finds the right-most entry beneath the *page*.
64600**
64601** The right-most entry is the one with the largest key - the last
64602** key in ascending order.
64603*/
64604static int moveToRightmost(BtCursor *pCur){
64605  Pgno pgno;
64606  int rc = SQLITE_OK;
64607  MemPage *pPage = 0;
64608
64609  assert( cursorOwnsBtShared(pCur) );
64610  assert( pCur->eState==CURSOR_VALID );
64611  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
64612    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
64613    pCur->ix = pPage->nCell;
64614    rc = moveToChild(pCur, pgno);
64615    if( rc ) return rc;
64616  }
64617  pCur->ix = pPage->nCell-1;
64618  assert( pCur->info.nSize==0 );
64619  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
64620  return SQLITE_OK;
64621}
64622
64623/* Move the cursor to the first entry in the table.  Return SQLITE_OK
64624** on success.  Set *pRes to 0 if the cursor actually points to something
64625** or set *pRes to 1 if the table is empty.
64626*/
64627SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
64628  int rc;
64629
64630  assert( cursorOwnsBtShared(pCur) );
64631  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64632  rc = moveToRoot(pCur);
64633  if( rc==SQLITE_OK ){
64634    if( pCur->eState==CURSOR_INVALID ){
64635      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
64636      *pRes = 1;
64637    }else{
64638      assert( pCur->apPage[pCur->iPage]->nCell>0 );
64639      *pRes = 0;
64640      rc = moveToLeftmost(pCur);
64641    }
64642  }
64643  return rc;
64644}
64645
64646/* Move the cursor to the last entry in the table.  Return SQLITE_OK
64647** on success.  Set *pRes to 0 if the cursor actually points to something
64648** or set *pRes to 1 if the table is empty.
64649*/
64650SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
64651  int rc;
64652
64653  assert( cursorOwnsBtShared(pCur) );
64654  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64655
64656  /* If the cursor already points to the last entry, this is a no-op. */
64657  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
64658#ifdef SQLITE_DEBUG
64659    /* This block serves to assert() that the cursor really does point
64660    ** to the last entry in the b-tree. */
64661    int ii;
64662    for(ii=0; ii<pCur->iPage; ii++){
64663      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
64664    }
64665    assert( pCur->ix==pCur->apPage[pCur->iPage]->nCell-1 );
64666    assert( pCur->apPage[pCur->iPage]->leaf );
64667#endif
64668    return SQLITE_OK;
64669  }
64670
64671  rc = moveToRoot(pCur);
64672  if( rc==SQLITE_OK ){
64673    if( CURSOR_INVALID==pCur->eState ){
64674      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
64675      *pRes = 1;
64676    }else{
64677      assert( pCur->eState==CURSOR_VALID );
64678      *pRes = 0;
64679      rc = moveToRightmost(pCur);
64680      if( rc==SQLITE_OK ){
64681        pCur->curFlags |= BTCF_AtLast;
64682      }else{
64683        pCur->curFlags &= ~BTCF_AtLast;
64684      }
64685
64686    }
64687  }
64688  return rc;
64689}
64690
64691/* Move the cursor so that it points to an entry near the key
64692** specified by pIdxKey or intKey.   Return a success code.
64693**
64694** For INTKEY tables, the intKey parameter is used.  pIdxKey
64695** must be NULL.  For index tables, pIdxKey is used and intKey
64696** is ignored.
64697**
64698** If an exact match is not found, then the cursor is always
64699** left pointing at a leaf page which would hold the entry if it
64700** were present.  The cursor might point to an entry that comes
64701** before or after the key.
64702**
64703** An integer is written into *pRes which is the result of
64704** comparing the key with the entry to which the cursor is
64705** pointing.  The meaning of the integer written into
64706** *pRes is as follows:
64707**
64708**     *pRes<0      The cursor is left pointing at an entry that
64709**                  is smaller than intKey/pIdxKey or if the table is empty
64710**                  and the cursor is therefore left point to nothing.
64711**
64712**     *pRes==0     The cursor is left pointing at an entry that
64713**                  exactly matches intKey/pIdxKey.
64714**
64715**     *pRes>0      The cursor is left pointing at an entry that
64716**                  is larger than intKey/pIdxKey.
64717**
64718** For index tables, the pIdxKey->eqSeen field is set to 1 if there
64719** exists an entry in the table that exactly matches pIdxKey.
64720*/
64721SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
64722  BtCursor *pCur,          /* The cursor to be moved */
64723  UnpackedRecord *pIdxKey, /* Unpacked index key */
64724  i64 intKey,              /* The table key */
64725  int biasRight,           /* If true, bias the search to the high end */
64726  int *pRes                /* Write search results here */
64727){
64728  int rc;
64729  RecordCompare xRecordCompare;
64730
64731  assert( cursorOwnsBtShared(pCur) );
64732  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64733  assert( pRes );
64734  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
64735  assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
64736
64737  /* If the cursor is already positioned at the point we are trying
64738  ** to move to, then just return without doing any work */
64739  if( pIdxKey==0
64740   && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
64741  ){
64742    if( pCur->info.nKey==intKey ){
64743      *pRes = 0;
64744      return SQLITE_OK;
64745    }
64746    if( pCur->info.nKey<intKey ){
64747      if( (pCur->curFlags & BTCF_AtLast)!=0 ){
64748        *pRes = -1;
64749        return SQLITE_OK;
64750      }
64751      /* If the requested key is one more than the previous key, then
64752      ** try to get there using sqlite3BtreeNext() rather than a full
64753      ** binary search.  This is an optimization only.  The correct answer
64754      ** is still obtained without this case, only a little more slowely */
64755      if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
64756        *pRes = 0;
64757        rc = sqlite3BtreeNext(pCur, 0);
64758        if( rc==SQLITE_OK ){
64759          getCellInfo(pCur);
64760          if( pCur->info.nKey==intKey ){
64761            return SQLITE_OK;
64762          }
64763        }else if( rc==SQLITE_DONE ){
64764          rc = SQLITE_OK;
64765        }else{
64766          return rc;
64767        }
64768      }
64769    }
64770  }
64771
64772  if( pIdxKey ){
64773    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
64774    pIdxKey->errCode = 0;
64775    assert( pIdxKey->default_rc==1
64776         || pIdxKey->default_rc==0
64777         || pIdxKey->default_rc==-1
64778    );
64779  }else{
64780    xRecordCompare = 0; /* All keys are integers */
64781  }
64782
64783  rc = moveToRoot(pCur);
64784  if( rc ){
64785    return rc;
64786  }
64787  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
64788  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
64789  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
64790  if( pCur->eState==CURSOR_INVALID ){
64791    *pRes = -1;
64792    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
64793    return SQLITE_OK;
64794  }
64795  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
64796  assert( pCur->curIntKey || pIdxKey );
64797  for(;;){
64798    int lwr, upr, idx, c;
64799    Pgno chldPg;
64800    MemPage *pPage = pCur->apPage[pCur->iPage];
64801    u8 *pCell;                          /* Pointer to current cell in pPage */
64802
64803    /* pPage->nCell must be greater than zero. If this is the root-page
64804    ** the cursor would have been INVALID above and this for(;;) loop
64805    ** not run. If this is not the root-page, then the moveToChild() routine
64806    ** would have already detected db corruption. Similarly, pPage must
64807    ** be the right kind (index or table) of b-tree page. Otherwise
64808    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
64809    assert( pPage->nCell>0 );
64810    assert( pPage->intKey==(pIdxKey==0) );
64811    lwr = 0;
64812    upr = pPage->nCell-1;
64813    assert( biasRight==0 || biasRight==1 );
64814    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
64815    pCur->ix = (u16)idx;
64816    if( xRecordCompare==0 ){
64817      for(;;){
64818        i64 nCellKey;
64819        pCell = findCellPastPtr(pPage, idx);
64820        if( pPage->intKeyLeaf ){
64821          while( 0x80 <= *(pCell++) ){
64822            if( pCell>=pPage->aDataEnd ){
64823              return SQLITE_CORRUPT_PGNO(pPage->pgno);
64824            }
64825          }
64826        }
64827        getVarint(pCell, (u64*)&nCellKey);
64828        if( nCellKey<intKey ){
64829          lwr = idx+1;
64830          if( lwr>upr ){ c = -1; break; }
64831        }else if( nCellKey>intKey ){
64832          upr = idx-1;
64833          if( lwr>upr ){ c = +1; break; }
64834        }else{
64835          assert( nCellKey==intKey );
64836          pCur->ix = (u16)idx;
64837          if( !pPage->leaf ){
64838            lwr = idx;
64839            goto moveto_next_layer;
64840          }else{
64841            pCur->curFlags |= BTCF_ValidNKey;
64842            pCur->info.nKey = nCellKey;
64843            pCur->info.nSize = 0;
64844            *pRes = 0;
64845            return SQLITE_OK;
64846          }
64847        }
64848        assert( lwr+upr>=0 );
64849        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
64850      }
64851    }else{
64852      for(;;){
64853        int nCell;  /* Size of the pCell cell in bytes */
64854        pCell = findCellPastPtr(pPage, idx);
64855
64856        /* The maximum supported page-size is 65536 bytes. This means that
64857        ** the maximum number of record bytes stored on an index B-Tree
64858        ** page is less than 16384 bytes and may be stored as a 2-byte
64859        ** varint. This information is used to attempt to avoid parsing
64860        ** the entire cell by checking for the cases where the record is
64861        ** stored entirely within the b-tree page by inspecting the first
64862        ** 2 bytes of the cell.
64863        */
64864        nCell = pCell[0];
64865        if( nCell<=pPage->max1bytePayload ){
64866          /* This branch runs if the record-size field of the cell is a
64867          ** single byte varint and the record fits entirely on the main
64868          ** b-tree page.  */
64869          testcase( pCell+nCell+1==pPage->aDataEnd );
64870          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
64871        }else if( !(pCell[1] & 0x80)
64872          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
64873        ){
64874          /* The record-size field is a 2 byte varint and the record
64875          ** fits entirely on the main b-tree page.  */
64876          testcase( pCell+nCell+2==pPage->aDataEnd );
64877          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
64878        }else{
64879          /* The record flows over onto one or more overflow pages. In
64880          ** this case the whole cell needs to be parsed, a buffer allocated
64881          ** and accessPayload() used to retrieve the record into the
64882          ** buffer before VdbeRecordCompare() can be called.
64883          **
64884          ** If the record is corrupt, the xRecordCompare routine may read
64885          ** up to two varints past the end of the buffer. An extra 18
64886          ** bytes of padding is allocated at the end of the buffer in
64887          ** case this happens.  */
64888          void *pCellKey;
64889          u8 * const pCellBody = pCell - pPage->childPtrSize;
64890          pPage->xParseCell(pPage, pCellBody, &pCur->info);
64891          nCell = (int)pCur->info.nKey;
64892          testcase( nCell<0 );   /* True if key size is 2^32 or more */
64893          testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
64894          testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
64895          testcase( nCell==2 );  /* Minimum legal index key size */
64896          if( nCell<2 ){
64897            rc = SQLITE_CORRUPT_PGNO(pPage->pgno);
64898            goto moveto_finish;
64899          }
64900          pCellKey = sqlite3Malloc( nCell+18 );
64901          if( pCellKey==0 ){
64902            rc = SQLITE_NOMEM_BKPT;
64903            goto moveto_finish;
64904          }
64905          pCur->ix = (u16)idx;
64906          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
64907          pCur->curFlags &= ~BTCF_ValidOvfl;
64908          if( rc ){
64909            sqlite3_free(pCellKey);
64910            goto moveto_finish;
64911          }
64912          c = xRecordCompare(nCell, pCellKey, pIdxKey);
64913          sqlite3_free(pCellKey);
64914        }
64915        assert(
64916            (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
64917         && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
64918        );
64919        if( c<0 ){
64920          lwr = idx+1;
64921        }else if( c>0 ){
64922          upr = idx-1;
64923        }else{
64924          assert( c==0 );
64925          *pRes = 0;
64926          rc = SQLITE_OK;
64927          pCur->ix = (u16)idx;
64928          if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
64929          goto moveto_finish;
64930        }
64931        if( lwr>upr ) break;
64932        assert( lwr+upr>=0 );
64933        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
64934      }
64935    }
64936    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
64937    assert( pPage->isInit );
64938    if( pPage->leaf ){
64939      assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
64940      pCur->ix = (u16)idx;
64941      *pRes = c;
64942      rc = SQLITE_OK;
64943      goto moveto_finish;
64944    }
64945moveto_next_layer:
64946    if( lwr>=pPage->nCell ){
64947      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
64948    }else{
64949      chldPg = get4byte(findCell(pPage, lwr));
64950    }
64951    pCur->ix = (u16)lwr;
64952    rc = moveToChild(pCur, chldPg);
64953    if( rc ) break;
64954  }
64955moveto_finish:
64956  pCur->info.nSize = 0;
64957  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
64958  return rc;
64959}
64960
64961
64962/*
64963** Return TRUE if the cursor is not pointing at an entry of the table.
64964**
64965** TRUE will be returned after a call to sqlite3BtreeNext() moves
64966** past the last entry in the table or sqlite3BtreePrev() moves past
64967** the first entry.  TRUE is also returned if the table is empty.
64968*/
64969SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
64970  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
64971  ** have been deleted? This API will need to change to return an error code
64972  ** as well as the boolean result value.
64973  */
64974  return (CURSOR_VALID!=pCur->eState);
64975}
64976
64977/*
64978** Return an estimate for the number of rows in the table that pCur is
64979** pointing to.  Return a negative number if no estimate is currently
64980** available.
64981*/
64982SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
64983  i64 n;
64984  u8 i;
64985
64986  assert( cursorOwnsBtShared(pCur) );
64987  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
64988
64989  /* Currently this interface is only called by the OP_IfSmaller
64990  ** opcode, and it that case the cursor will always be valid and
64991  ** will always point to a leaf node. */
64992  if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
64993  if( NEVER(pCur->apPage[pCur->iPage]->leaf==0) ) return -1;
64994
64995  for(n=1, i=0; i<=pCur->iPage; i++){
64996    n *= pCur->apPage[i]->nCell;
64997  }
64998  return n;
64999}
65000
65001/*
65002** Advance the cursor to the next entry in the database.
65003** Return value:
65004**
65005**    SQLITE_OK        success
65006**    SQLITE_DONE      cursor is already pointing at the last element
65007**    otherwise        some kind of error occurred
65008**
65009** The main entry point is sqlite3BtreeNext().  That routine is optimized
65010** for the common case of merely incrementing the cell counter BtCursor.aiIdx
65011** to the next cell on the current page.  The (slower) btreeNext() helper
65012** routine is called when it is necessary to move to a different page or
65013** to restore the cursor.
65014**
65015** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
65016** cursor corresponds to an SQL index and this routine could have been
65017** skipped if the SQL index had been a unique index.  The F argument
65018** is a hint to the implement.  SQLite btree implementation does not use
65019** this hint, but COMDB2 does.
65020*/
65021static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
65022  int rc;
65023  int idx;
65024  MemPage *pPage;
65025
65026  assert( cursorOwnsBtShared(pCur) );
65027  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
65028  if( pCur->eState!=CURSOR_VALID ){
65029    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
65030    rc = restoreCursorPosition(pCur);
65031    if( rc!=SQLITE_OK ){
65032      return rc;
65033    }
65034    if( CURSOR_INVALID==pCur->eState ){
65035      return SQLITE_DONE;
65036    }
65037    if( pCur->skipNext ){
65038      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
65039      pCur->eState = CURSOR_VALID;
65040      if( pCur->skipNext>0 ){
65041        pCur->skipNext = 0;
65042        return SQLITE_OK;
65043      }
65044      pCur->skipNext = 0;
65045    }
65046  }
65047
65048  pPage = pCur->apPage[pCur->iPage];
65049  idx = ++pCur->ix;
65050  assert( pPage->isInit );
65051
65052  /* If the database file is corrupt, it is possible for the value of idx
65053  ** to be invalid here. This can only occur if a second cursor modifies
65054  ** the page while cursor pCur is holding a reference to it. Which can
65055  ** only happen if the database is corrupt in such a way as to link the
65056  ** page into more than one b-tree structure. */
65057  testcase( idx>pPage->nCell );
65058
65059  if( idx>=pPage->nCell ){
65060    if( !pPage->leaf ){
65061      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
65062      if( rc ) return rc;
65063      return moveToLeftmost(pCur);
65064    }
65065    do{
65066      if( pCur->iPage==0 ){
65067        pCur->eState = CURSOR_INVALID;
65068        return SQLITE_DONE;
65069      }
65070      moveToParent(pCur);
65071      pPage = pCur->apPage[pCur->iPage];
65072    }while( pCur->ix>=pPage->nCell );
65073    if( pPage->intKey ){
65074      return sqlite3BtreeNext(pCur, 0);
65075    }else{
65076      return SQLITE_OK;
65077    }
65078  }
65079  if( pPage->leaf ){
65080    return SQLITE_OK;
65081  }else{
65082    return moveToLeftmost(pCur);
65083  }
65084}
65085SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
65086  MemPage *pPage;
65087  UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
65088  assert( cursorOwnsBtShared(pCur) );
65089  assert( flags==0 || flags==1 );
65090  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
65091  pCur->info.nSize = 0;
65092  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
65093  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
65094  pPage = pCur->apPage[pCur->iPage];
65095  if( (++pCur->ix)>=pPage->nCell ){
65096    pCur->ix--;
65097    return btreeNext(pCur);
65098  }
65099  if( pPage->leaf ){
65100    return SQLITE_OK;
65101  }else{
65102    return moveToLeftmost(pCur);
65103  }
65104}
65105
65106/*
65107** Step the cursor to the back to the previous entry in the database.
65108** Return values:
65109**
65110**     SQLITE_OK     success
65111**     SQLITE_DONE   the cursor is already on the first element of the table
65112**     otherwise     some kind of error occurred
65113**
65114** The main entry point is sqlite3BtreePrevious().  That routine is optimized
65115** for the common case of merely decrementing the cell counter BtCursor.aiIdx
65116** to the previous cell on the current page.  The (slower) btreePrevious()
65117** helper routine is called when it is necessary to move to a different page
65118** or to restore the cursor.
65119**
65120** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
65121** the cursor corresponds to an SQL index and this routine could have been
65122** skipped if the SQL index had been a unique index.  The F argument is a
65123** hint to the implement.  The native SQLite btree implementation does not
65124** use this hint, but COMDB2 does.
65125*/
65126static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
65127  int rc;
65128  MemPage *pPage;
65129
65130  assert( cursorOwnsBtShared(pCur) );
65131  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
65132  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
65133  assert( pCur->info.nSize==0 );
65134  if( pCur->eState!=CURSOR_VALID ){
65135    rc = restoreCursorPosition(pCur);
65136    if( rc!=SQLITE_OK ){
65137      return rc;
65138    }
65139    if( CURSOR_INVALID==pCur->eState ){
65140      return SQLITE_DONE;
65141    }
65142    if( pCur->skipNext ){
65143      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
65144      pCur->eState = CURSOR_VALID;
65145      if( pCur->skipNext<0 ){
65146        pCur->skipNext = 0;
65147        return SQLITE_OK;
65148      }
65149      pCur->skipNext = 0;
65150    }
65151  }
65152
65153  pPage = pCur->apPage[pCur->iPage];
65154  assert( pPage->isInit );
65155  if( !pPage->leaf ){
65156    int idx = pCur->ix;
65157    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
65158    if( rc ) return rc;
65159    rc = moveToRightmost(pCur);
65160  }else{
65161    while( pCur->ix==0 ){
65162      if( pCur->iPage==0 ){
65163        pCur->eState = CURSOR_INVALID;
65164        return SQLITE_DONE;
65165      }
65166      moveToParent(pCur);
65167    }
65168    assert( pCur->info.nSize==0 );
65169    assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
65170
65171    pCur->ix--;
65172    pPage = pCur->apPage[pCur->iPage];
65173    if( pPage->intKey && !pPage->leaf ){
65174      rc = sqlite3BtreePrevious(pCur, 0);
65175    }else{
65176      rc = SQLITE_OK;
65177    }
65178  }
65179  return rc;
65180}
65181SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
65182  assert( cursorOwnsBtShared(pCur) );
65183  assert( flags==0 || flags==1 );
65184  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
65185  UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
65186  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
65187  pCur->info.nSize = 0;
65188  if( pCur->eState!=CURSOR_VALID
65189   || pCur->ix==0
65190   || pCur->apPage[pCur->iPage]->leaf==0
65191  ){
65192    return btreePrevious(pCur);
65193  }
65194  pCur->ix--;
65195  return SQLITE_OK;
65196}
65197
65198/*
65199** Allocate a new page from the database file.
65200**
65201** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
65202** has already been called on the new page.)  The new page has also
65203** been referenced and the calling routine is responsible for calling
65204** sqlite3PagerUnref() on the new page when it is done.
65205**
65206** SQLITE_OK is returned on success.  Any other return value indicates
65207** an error.  *ppPage is set to NULL in the event of an error.
65208**
65209** If the "nearby" parameter is not 0, then an effort is made to
65210** locate a page close to the page number "nearby".  This can be used in an
65211** attempt to keep related pages close to each other in the database file,
65212** which in turn can make database access faster.
65213**
65214** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
65215** anywhere on the free-list, then it is guaranteed to be returned.  If
65216** eMode is BTALLOC_LT then the page returned will be less than or equal
65217** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
65218** are no restrictions on which page is returned.
65219*/
65220static int allocateBtreePage(
65221  BtShared *pBt,         /* The btree */
65222  MemPage **ppPage,      /* Store pointer to the allocated page here */
65223  Pgno *pPgno,           /* Store the page number here */
65224  Pgno nearby,           /* Search for a page near this one */
65225  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
65226){
65227  MemPage *pPage1;
65228  int rc;
65229  u32 n;     /* Number of pages on the freelist */
65230  u32 k;     /* Number of leaves on the trunk of the freelist */
65231  MemPage *pTrunk = 0;
65232  MemPage *pPrevTrunk = 0;
65233  Pgno mxPage;     /* Total size of the database file */
65234
65235  assert( sqlite3_mutex_held(pBt->mutex) );
65236  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
65237  pPage1 = pBt->pPage1;
65238  mxPage = btreePagecount(pBt);
65239  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
65240  ** stores stores the total number of pages on the freelist. */
65241  n = get4byte(&pPage1->aData[36]);
65242  testcase( n==mxPage-1 );
65243  if( n>=mxPage ){
65244    return SQLITE_CORRUPT_BKPT;
65245  }
65246  if( n>0 ){
65247    /* There are pages on the freelist.  Reuse one of those pages. */
65248    Pgno iTrunk;
65249    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
65250    u32 nSearch = 0;   /* Count of the number of search attempts */
65251
65252    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
65253    ** shows that the page 'nearby' is somewhere on the free-list, then
65254    ** the entire-list will be searched for that page.
65255    */
65256#ifndef SQLITE_OMIT_AUTOVACUUM
65257    if( eMode==BTALLOC_EXACT ){
65258      if( nearby<=mxPage ){
65259        u8 eType;
65260        assert( nearby>0 );
65261        assert( pBt->autoVacuum );
65262        rc = ptrmapGet(pBt, nearby, &eType, 0);
65263        if( rc ) return rc;
65264        if( eType==PTRMAP_FREEPAGE ){
65265          searchList = 1;
65266        }
65267      }
65268    }else if( eMode==BTALLOC_LE ){
65269      searchList = 1;
65270    }
65271#endif
65272
65273    /* Decrement the free-list count by 1. Set iTrunk to the index of the
65274    ** first free-list trunk page. iPrevTrunk is initially 1.
65275    */
65276    rc = sqlite3PagerWrite(pPage1->pDbPage);
65277    if( rc ) return rc;
65278    put4byte(&pPage1->aData[36], n-1);
65279
65280    /* The code within this loop is run only once if the 'searchList' variable
65281    ** is not true. Otherwise, it runs once for each trunk-page on the
65282    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
65283    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
65284    */
65285    do {
65286      pPrevTrunk = pTrunk;
65287      if( pPrevTrunk ){
65288        /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
65289        ** is the page number of the next freelist trunk page in the list or
65290        ** zero if this is the last freelist trunk page. */
65291        iTrunk = get4byte(&pPrevTrunk->aData[0]);
65292      }else{
65293        /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
65294        ** stores the page number of the first page of the freelist, or zero if
65295        ** the freelist is empty. */
65296        iTrunk = get4byte(&pPage1->aData[32]);
65297      }
65298      testcase( iTrunk==mxPage );
65299      if( iTrunk>mxPage || nSearch++ > n ){
65300        rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
65301      }else{
65302        rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
65303      }
65304      if( rc ){
65305        pTrunk = 0;
65306        goto end_allocate_page;
65307      }
65308      assert( pTrunk!=0 );
65309      assert( pTrunk->aData!=0 );
65310      /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
65311      ** is the number of leaf page pointers to follow. */
65312      k = get4byte(&pTrunk->aData[4]);
65313      if( k==0 && !searchList ){
65314        /* The trunk has no leaves and the list is not being searched.
65315        ** So extract the trunk page itself and use it as the newly
65316        ** allocated page */
65317        assert( pPrevTrunk==0 );
65318        rc = sqlite3PagerWrite(pTrunk->pDbPage);
65319        if( rc ){
65320          goto end_allocate_page;
65321        }
65322        *pPgno = iTrunk;
65323        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
65324        *ppPage = pTrunk;
65325        pTrunk = 0;
65326        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
65327      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
65328        /* Value of k is out of range.  Database corruption */
65329        rc = SQLITE_CORRUPT_PGNO(iTrunk);
65330        goto end_allocate_page;
65331#ifndef SQLITE_OMIT_AUTOVACUUM
65332      }else if( searchList
65333            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
65334      ){
65335        /* The list is being searched and this trunk page is the page
65336        ** to allocate, regardless of whether it has leaves.
65337        */
65338        *pPgno = iTrunk;
65339        *ppPage = pTrunk;
65340        searchList = 0;
65341        rc = sqlite3PagerWrite(pTrunk->pDbPage);
65342        if( rc ){
65343          goto end_allocate_page;
65344        }
65345        if( k==0 ){
65346          if( !pPrevTrunk ){
65347            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
65348          }else{
65349            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
65350            if( rc!=SQLITE_OK ){
65351              goto end_allocate_page;
65352            }
65353            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
65354          }
65355        }else{
65356          /* The trunk page is required by the caller but it contains
65357          ** pointers to free-list leaves. The first leaf becomes a trunk
65358          ** page in this case.
65359          */
65360          MemPage *pNewTrunk;
65361          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
65362          if( iNewTrunk>mxPage ){
65363            rc = SQLITE_CORRUPT_PGNO(iTrunk);
65364            goto end_allocate_page;
65365          }
65366          testcase( iNewTrunk==mxPage );
65367          rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
65368          if( rc!=SQLITE_OK ){
65369            goto end_allocate_page;
65370          }
65371          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
65372          if( rc!=SQLITE_OK ){
65373            releasePage(pNewTrunk);
65374            goto end_allocate_page;
65375          }
65376          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
65377          put4byte(&pNewTrunk->aData[4], k-1);
65378          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
65379          releasePage(pNewTrunk);
65380          if( !pPrevTrunk ){
65381            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
65382            put4byte(&pPage1->aData[32], iNewTrunk);
65383          }else{
65384            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
65385            if( rc ){
65386              goto end_allocate_page;
65387            }
65388            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
65389          }
65390        }
65391        pTrunk = 0;
65392        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
65393#endif
65394      }else if( k>0 ){
65395        /* Extract a leaf from the trunk */
65396        u32 closest;
65397        Pgno iPage;
65398        unsigned char *aData = pTrunk->aData;
65399        if( nearby>0 ){
65400          u32 i;
65401          closest = 0;
65402          if( eMode==BTALLOC_LE ){
65403            for(i=0; i<k; i++){
65404              iPage = get4byte(&aData[8+i*4]);
65405              if( iPage<=nearby ){
65406                closest = i;
65407                break;
65408              }
65409            }
65410          }else{
65411            int dist;
65412            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
65413            for(i=1; i<k; i++){
65414              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
65415              if( d2<dist ){
65416                closest = i;
65417                dist = d2;
65418              }
65419            }
65420          }
65421        }else{
65422          closest = 0;
65423        }
65424
65425        iPage = get4byte(&aData[8+closest*4]);
65426        testcase( iPage==mxPage );
65427        if( iPage>mxPage ){
65428          rc = SQLITE_CORRUPT_PGNO(iTrunk);
65429          goto end_allocate_page;
65430        }
65431        testcase( iPage==mxPage );
65432        if( !searchList
65433         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
65434        ){
65435          int noContent;
65436          *pPgno = iPage;
65437          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
65438                 ": %d more free pages\n",
65439                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
65440          rc = sqlite3PagerWrite(pTrunk->pDbPage);
65441          if( rc ) goto end_allocate_page;
65442          if( closest<k-1 ){
65443            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
65444          }
65445          put4byte(&aData[4], k-1);
65446          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
65447          rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
65448          if( rc==SQLITE_OK ){
65449            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
65450            if( rc!=SQLITE_OK ){
65451              releasePage(*ppPage);
65452              *ppPage = 0;
65453            }
65454          }
65455          searchList = 0;
65456        }
65457      }
65458      releasePage(pPrevTrunk);
65459      pPrevTrunk = 0;
65460    }while( searchList );
65461  }else{
65462    /* There are no pages on the freelist, so append a new page to the
65463    ** database image.
65464    **
65465    ** Normally, new pages allocated by this block can be requested from the
65466    ** pager layer with the 'no-content' flag set. This prevents the pager
65467    ** from trying to read the pages content from disk. However, if the
65468    ** current transaction has already run one or more incremental-vacuum
65469    ** steps, then the page we are about to allocate may contain content
65470    ** that is required in the event of a rollback. In this case, do
65471    ** not set the no-content flag. This causes the pager to load and journal
65472    ** the current page content before overwriting it.
65473    **
65474    ** Note that the pager will not actually attempt to load or journal
65475    ** content for any page that really does lie past the end of the database
65476    ** file on disk. So the effects of disabling the no-content optimization
65477    ** here are confined to those pages that lie between the end of the
65478    ** database image and the end of the database file.
65479    */
65480    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
65481
65482    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
65483    if( rc ) return rc;
65484    pBt->nPage++;
65485    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
65486
65487#ifndef SQLITE_OMIT_AUTOVACUUM
65488    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
65489      /* If *pPgno refers to a pointer-map page, allocate two new pages
65490      ** at the end of the file instead of one. The first allocated page
65491      ** becomes a new pointer-map page, the second is used by the caller.
65492      */
65493      MemPage *pPg = 0;
65494      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
65495      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
65496      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
65497      if( rc==SQLITE_OK ){
65498        rc = sqlite3PagerWrite(pPg->pDbPage);
65499        releasePage(pPg);
65500      }
65501      if( rc ) return rc;
65502      pBt->nPage++;
65503      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
65504    }
65505#endif
65506    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
65507    *pPgno = pBt->nPage;
65508
65509    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
65510    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
65511    if( rc ) return rc;
65512    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
65513    if( rc!=SQLITE_OK ){
65514      releasePage(*ppPage);
65515      *ppPage = 0;
65516    }
65517    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
65518  }
65519
65520  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
65521
65522end_allocate_page:
65523  releasePage(pTrunk);
65524  releasePage(pPrevTrunk);
65525  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
65526  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
65527  return rc;
65528}
65529
65530/*
65531** This function is used to add page iPage to the database file free-list.
65532** It is assumed that the page is not already a part of the free-list.
65533**
65534** The value passed as the second argument to this function is optional.
65535** If the caller happens to have a pointer to the MemPage object
65536** corresponding to page iPage handy, it may pass it as the second value.
65537** Otherwise, it may pass NULL.
65538**
65539** If a pointer to a MemPage object is passed as the second argument,
65540** its reference count is not altered by this function.
65541*/
65542static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
65543  MemPage *pTrunk = 0;                /* Free-list trunk page */
65544  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
65545  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
65546  MemPage *pPage;                     /* Page being freed. May be NULL. */
65547  int rc;                             /* Return Code */
65548  int nFree;                          /* Initial number of pages on free-list */
65549
65550  assert( sqlite3_mutex_held(pBt->mutex) );
65551  assert( CORRUPT_DB || iPage>1 );
65552  assert( !pMemPage || pMemPage->pgno==iPage );
65553
65554  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
65555  if( pMemPage ){
65556    pPage = pMemPage;
65557    sqlite3PagerRef(pPage->pDbPage);
65558  }else{
65559    pPage = btreePageLookup(pBt, iPage);
65560  }
65561
65562  /* Increment the free page count on pPage1 */
65563  rc = sqlite3PagerWrite(pPage1->pDbPage);
65564  if( rc ) goto freepage_out;
65565  nFree = get4byte(&pPage1->aData[36]);
65566  put4byte(&pPage1->aData[36], nFree+1);
65567
65568  if( pBt->btsFlags & BTS_SECURE_DELETE ){
65569    /* If the secure_delete option is enabled, then
65570    ** always fully overwrite deleted information with zeros.
65571    */
65572    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
65573     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
65574    ){
65575      goto freepage_out;
65576    }
65577    memset(pPage->aData, 0, pPage->pBt->pageSize);
65578  }
65579
65580  /* If the database supports auto-vacuum, write an entry in the pointer-map
65581  ** to indicate that the page is free.
65582  */
65583  if( ISAUTOVACUUM ){
65584    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
65585    if( rc ) goto freepage_out;
65586  }
65587
65588  /* Now manipulate the actual database free-list structure. There are two
65589  ** possibilities. If the free-list is currently empty, or if the first
65590  ** trunk page in the free-list is full, then this page will become a
65591  ** new free-list trunk page. Otherwise, it will become a leaf of the
65592  ** first trunk page in the current free-list. This block tests if it
65593  ** is possible to add the page as a new free-list leaf.
65594  */
65595  if( nFree!=0 ){
65596    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
65597
65598    iTrunk = get4byte(&pPage1->aData[32]);
65599    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
65600    if( rc!=SQLITE_OK ){
65601      goto freepage_out;
65602    }
65603
65604    nLeaf = get4byte(&pTrunk->aData[4]);
65605    assert( pBt->usableSize>32 );
65606    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
65607      rc = SQLITE_CORRUPT_BKPT;
65608      goto freepage_out;
65609    }
65610    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
65611      /* In this case there is room on the trunk page to insert the page
65612      ** being freed as a new leaf.
65613      **
65614      ** Note that the trunk page is not really full until it contains
65615      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
65616      ** coded.  But due to a coding error in versions of SQLite prior to
65617      ** 3.6.0, databases with freelist trunk pages holding more than
65618      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
65619      ** to maintain backwards compatibility with older versions of SQLite,
65620      ** we will continue to restrict the number of entries to usableSize/4 - 8
65621      ** for now.  At some point in the future (once everyone has upgraded
65622      ** to 3.6.0 or later) we should consider fixing the conditional above
65623      ** to read "usableSize/4-2" instead of "usableSize/4-8".
65624      **
65625      ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
65626      ** avoid using the last six entries in the freelist trunk page array in
65627      ** order that database files created by newer versions of SQLite can be
65628      ** read by older versions of SQLite.
65629      */
65630      rc = sqlite3PagerWrite(pTrunk->pDbPage);
65631      if( rc==SQLITE_OK ){
65632        put4byte(&pTrunk->aData[4], nLeaf+1);
65633        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
65634        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
65635          sqlite3PagerDontWrite(pPage->pDbPage);
65636        }
65637        rc = btreeSetHasContent(pBt, iPage);
65638      }
65639      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
65640      goto freepage_out;
65641    }
65642  }
65643
65644  /* If control flows to this point, then it was not possible to add the
65645  ** the page being freed as a leaf page of the first trunk in the free-list.
65646  ** Possibly because the free-list is empty, or possibly because the
65647  ** first trunk in the free-list is full. Either way, the page being freed
65648  ** will become the new first trunk page in the free-list.
65649  */
65650  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
65651    goto freepage_out;
65652  }
65653  rc = sqlite3PagerWrite(pPage->pDbPage);
65654  if( rc!=SQLITE_OK ){
65655    goto freepage_out;
65656  }
65657  put4byte(pPage->aData, iTrunk);
65658  put4byte(&pPage->aData[4], 0);
65659  put4byte(&pPage1->aData[32], iPage);
65660  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
65661
65662freepage_out:
65663  if( pPage ){
65664    pPage->isInit = 0;
65665  }
65666  releasePage(pPage);
65667  releasePage(pTrunk);
65668  return rc;
65669}
65670static void freePage(MemPage *pPage, int *pRC){
65671  if( (*pRC)==SQLITE_OK ){
65672    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
65673  }
65674}
65675
65676/*
65677** Free any overflow pages associated with the given Cell.  Write the
65678** local Cell size (the number of bytes on the original page, omitting
65679** overflow) into *pnSize.
65680*/
65681static int clearCell(
65682  MemPage *pPage,          /* The page that contains the Cell */
65683  unsigned char *pCell,    /* First byte of the Cell */
65684  CellInfo *pInfo          /* Size information about the cell */
65685){
65686  BtShared *pBt = pPage->pBt;
65687  Pgno ovflPgno;
65688  int rc;
65689  int nOvfl;
65690  u32 ovflPageSize;
65691
65692  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65693  pPage->xParseCell(pPage, pCell, pInfo);
65694  if( pInfo->nLocal==pInfo->nPayload ){
65695    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
65696  }
65697  if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
65698    /* Cell extends past end of page */
65699    return SQLITE_CORRUPT_PGNO(pPage->pgno);
65700  }
65701  ovflPgno = get4byte(pCell + pInfo->nSize - 4);
65702  assert( pBt->usableSize > 4 );
65703  ovflPageSize = pBt->usableSize - 4;
65704  nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
65705  assert( nOvfl>0 ||
65706    (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
65707  );
65708  while( nOvfl-- ){
65709    Pgno iNext = 0;
65710    MemPage *pOvfl = 0;
65711    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
65712      /* 0 is not a legal page number and page 1 cannot be an
65713      ** overflow page. Therefore if ovflPgno<2 or past the end of the
65714      ** file the database must be corrupt. */
65715      return SQLITE_CORRUPT_BKPT;
65716    }
65717    if( nOvfl ){
65718      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
65719      if( rc ) return rc;
65720    }
65721
65722    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
65723     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
65724    ){
65725      /* There is no reason any cursor should have an outstanding reference
65726      ** to an overflow page belonging to a cell that is being deleted/updated.
65727      ** So if there exists more than one reference to this page, then it
65728      ** must not really be an overflow page and the database must be corrupt.
65729      ** It is helpful to detect this before calling freePage2(), as
65730      ** freePage2() may zero the page contents if secure-delete mode is
65731      ** enabled. If this 'overflow' page happens to be a page that the
65732      ** caller is iterating through or using in some other way, this
65733      ** can be problematic.
65734      */
65735      rc = SQLITE_CORRUPT_BKPT;
65736    }else{
65737      rc = freePage2(pBt, pOvfl, ovflPgno);
65738    }
65739
65740    if( pOvfl ){
65741      sqlite3PagerUnref(pOvfl->pDbPage);
65742    }
65743    if( rc ) return rc;
65744    ovflPgno = iNext;
65745  }
65746  return SQLITE_OK;
65747}
65748
65749/*
65750** Create the byte sequence used to represent a cell on page pPage
65751** and write that byte sequence into pCell[].  Overflow pages are
65752** allocated and filled in as necessary.  The calling procedure
65753** is responsible for making sure sufficient space has been allocated
65754** for pCell[].
65755**
65756** Note that pCell does not necessary need to point to the pPage->aData
65757** area.  pCell might point to some temporary storage.  The cell will
65758** be constructed in this temporary area then copied into pPage->aData
65759** later.
65760*/
65761static int fillInCell(
65762  MemPage *pPage,                /* The page that contains the cell */
65763  unsigned char *pCell,          /* Complete text of the cell */
65764  const BtreePayload *pX,        /* Payload with which to construct the cell */
65765  int *pnSize                    /* Write cell size here */
65766){
65767  int nPayload;
65768  const u8 *pSrc;
65769  int nSrc, n, rc;
65770  int spaceLeft;
65771  MemPage *pOvfl = 0;
65772  MemPage *pToRelease = 0;
65773  unsigned char *pPrior;
65774  unsigned char *pPayload;
65775  BtShared *pBt = pPage->pBt;
65776  Pgno pgnoOvfl = 0;
65777  int nHeader;
65778
65779  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65780
65781  /* pPage is not necessarily writeable since pCell might be auxiliary
65782  ** buffer space that is separate from the pPage buffer area */
65783  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
65784            || sqlite3PagerIswriteable(pPage->pDbPage) );
65785
65786  /* Fill in the header. */
65787  nHeader = pPage->childPtrSize;
65788  if( pPage->intKey ){
65789    nPayload = pX->nData + pX->nZero;
65790    pSrc = pX->pData;
65791    nSrc = pX->nData;
65792    assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
65793    nHeader += putVarint32(&pCell[nHeader], nPayload);
65794    nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
65795  }else{
65796    assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
65797    nSrc = nPayload = (int)pX->nKey;
65798    pSrc = pX->pKey;
65799    nHeader += putVarint32(&pCell[nHeader], nPayload);
65800  }
65801
65802  /* Fill in the payload */
65803  if( nPayload<=pPage->maxLocal ){
65804    n = nHeader + nPayload;
65805    testcase( n==3 );
65806    testcase( n==4 );
65807    if( n<4 ) n = 4;
65808    *pnSize = n;
65809    spaceLeft = nPayload;
65810    pPrior = pCell;
65811  }else{
65812    int mn = pPage->minLocal;
65813    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
65814    testcase( n==pPage->maxLocal );
65815    testcase( n==pPage->maxLocal+1 );
65816    if( n > pPage->maxLocal ) n = mn;
65817    spaceLeft = n;
65818    *pnSize = n + nHeader + 4;
65819    pPrior = &pCell[nHeader+n];
65820  }
65821  pPayload = &pCell[nHeader];
65822
65823  /* At this point variables should be set as follows:
65824  **
65825  **   nPayload           Total payload size in bytes
65826  **   pPayload           Begin writing payload here
65827  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
65828  **                      that means content must spill into overflow pages.
65829  **   *pnSize            Size of the local cell (not counting overflow pages)
65830  **   pPrior             Where to write the pgno of the first overflow page
65831  **
65832  ** Use a call to btreeParseCellPtr() to verify that the values above
65833  ** were computed correctly.
65834  */
65835#ifdef SQLITE_DEBUG
65836  {
65837    CellInfo info;
65838    pPage->xParseCell(pPage, pCell, &info);
65839    assert( nHeader==(int)(info.pPayload - pCell) );
65840    assert( info.nKey==pX->nKey );
65841    assert( *pnSize == info.nSize );
65842    assert( spaceLeft == info.nLocal );
65843  }
65844#endif
65845
65846  /* Write the payload into the local Cell and any extra into overflow pages */
65847  while( nPayload>0 ){
65848    if( spaceLeft==0 ){
65849#ifndef SQLITE_OMIT_AUTOVACUUM
65850      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
65851      if( pBt->autoVacuum ){
65852        do{
65853          pgnoOvfl++;
65854        } while(
65855          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
65856        );
65857      }
65858#endif
65859      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
65860#ifndef SQLITE_OMIT_AUTOVACUUM
65861      /* If the database supports auto-vacuum, and the second or subsequent
65862      ** overflow page is being allocated, add an entry to the pointer-map
65863      ** for that page now.
65864      **
65865      ** If this is the first overflow page, then write a partial entry
65866      ** to the pointer-map. If we write nothing to this pointer-map slot,
65867      ** then the optimistic overflow chain processing in clearCell()
65868      ** may misinterpret the uninitialized values and delete the
65869      ** wrong pages from the database.
65870      */
65871      if( pBt->autoVacuum && rc==SQLITE_OK ){
65872        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
65873        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
65874        if( rc ){
65875          releasePage(pOvfl);
65876        }
65877      }
65878#endif
65879      if( rc ){
65880        releasePage(pToRelease);
65881        return rc;
65882      }
65883
65884      /* If pToRelease is not zero than pPrior points into the data area
65885      ** of pToRelease.  Make sure pToRelease is still writeable. */
65886      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
65887
65888      /* If pPrior is part of the data area of pPage, then make sure pPage
65889      ** is still writeable */
65890      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
65891            || sqlite3PagerIswriteable(pPage->pDbPage) );
65892
65893      put4byte(pPrior, pgnoOvfl);
65894      releasePage(pToRelease);
65895      pToRelease = pOvfl;
65896      pPrior = pOvfl->aData;
65897      put4byte(pPrior, 0);
65898      pPayload = &pOvfl->aData[4];
65899      spaceLeft = pBt->usableSize - 4;
65900    }
65901    n = nPayload;
65902    if( n>spaceLeft ) n = spaceLeft;
65903
65904    /* If pToRelease is not zero than pPayload points into the data area
65905    ** of pToRelease.  Make sure pToRelease is still writeable. */
65906    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
65907
65908    /* If pPayload is part of the data area of pPage, then make sure pPage
65909    ** is still writeable */
65910    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
65911            || sqlite3PagerIswriteable(pPage->pDbPage) );
65912
65913    if( nSrc>0 ){
65914      if( n>nSrc ) n = nSrc;
65915      assert( pSrc );
65916      memcpy(pPayload, pSrc, n);
65917    }else{
65918      memset(pPayload, 0, n);
65919    }
65920    nPayload -= n;
65921    pPayload += n;
65922    pSrc += n;
65923    nSrc -= n;
65924    spaceLeft -= n;
65925  }
65926  releasePage(pToRelease);
65927  return SQLITE_OK;
65928}
65929
65930/*
65931** Remove the i-th cell from pPage.  This routine effects pPage only.
65932** The cell content is not freed or deallocated.  It is assumed that
65933** the cell content has been copied someplace else.  This routine just
65934** removes the reference to the cell from pPage.
65935**
65936** "sz" must be the number of bytes in the cell.
65937*/
65938static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
65939  u32 pc;         /* Offset to cell content of cell being deleted */
65940  u8 *data;       /* pPage->aData */
65941  u8 *ptr;        /* Used to move bytes around within data[] */
65942  int rc;         /* The return code */
65943  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
65944
65945  if( *pRC ) return;
65946  assert( idx>=0 && idx<pPage->nCell );
65947  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
65948  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
65949  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65950  data = pPage->aData;
65951  ptr = &pPage->aCellIdx[2*idx];
65952  pc = get2byte(ptr);
65953  hdr = pPage->hdrOffset;
65954  testcase( pc==get2byte(&data[hdr+5]) );
65955  testcase( pc+sz==pPage->pBt->usableSize );
65956  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
65957    *pRC = SQLITE_CORRUPT_BKPT;
65958    return;
65959  }
65960  rc = freeSpace(pPage, pc, sz);
65961  if( rc ){
65962    *pRC = rc;
65963    return;
65964  }
65965  pPage->nCell--;
65966  if( pPage->nCell==0 ){
65967    memset(&data[hdr+1], 0, 4);
65968    data[hdr+7] = 0;
65969    put2byte(&data[hdr+5], pPage->pBt->usableSize);
65970    pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
65971                       - pPage->childPtrSize - 8;
65972  }else{
65973    memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
65974    put2byte(&data[hdr+3], pPage->nCell);
65975    pPage->nFree += 2;
65976  }
65977}
65978
65979/*
65980** Insert a new cell on pPage at cell index "i".  pCell points to the
65981** content of the cell.
65982**
65983** If the cell content will fit on the page, then put it there.  If it
65984** will not fit, then make a copy of the cell content into pTemp if
65985** pTemp is not null.  Regardless of pTemp, allocate a new entry
65986** in pPage->apOvfl[] and make it point to the cell content (either
65987** in pTemp or the original pCell) and also record its index.
65988** Allocating a new entry in pPage->aCell[] implies that
65989** pPage->nOverflow is incremented.
65990**
65991** *pRC must be SQLITE_OK when this routine is called.
65992*/
65993static void insertCell(
65994  MemPage *pPage,   /* Page into which we are copying */
65995  int i,            /* New cell becomes the i-th cell of the page */
65996  u8 *pCell,        /* Content of the new cell */
65997  int sz,           /* Bytes of content in pCell */
65998  u8 *pTemp,        /* Temp storage space for pCell, if needed */
65999  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
66000  int *pRC          /* Read and write return code from here */
66001){
66002  int idx = 0;      /* Where to write new cell content in data[] */
66003  int j;            /* Loop counter */
66004  u8 *data;         /* The content of the whole page */
66005  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
66006
66007  assert( *pRC==SQLITE_OK );
66008  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
66009  assert( MX_CELL(pPage->pBt)<=10921 );
66010  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
66011  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
66012  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
66013  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
66014  /* The cell should normally be sized correctly.  However, when moving a
66015  ** malformed cell from a leaf page to an interior page, if the cell size
66016  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
66017  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
66018  ** the term after the || in the following assert(). */
66019  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
66020  if( pPage->nOverflow || sz+2>pPage->nFree ){
66021    if( pTemp ){
66022      memcpy(pTemp, pCell, sz);
66023      pCell = pTemp;
66024    }
66025    if( iChild ){
66026      put4byte(pCell, iChild);
66027    }
66028    j = pPage->nOverflow++;
66029    /* Comparison against ArraySize-1 since we hold back one extra slot
66030    ** as a contingency.  In other words, never need more than 3 overflow
66031    ** slots but 4 are allocated, just to be safe. */
66032    assert( j < ArraySize(pPage->apOvfl)-1 );
66033    pPage->apOvfl[j] = pCell;
66034    pPage->aiOvfl[j] = (u16)i;
66035
66036    /* When multiple overflows occur, they are always sequential and in
66037    ** sorted order.  This invariants arise because multiple overflows can
66038    ** only occur when inserting divider cells into the parent page during
66039    ** balancing, and the dividers are adjacent and sorted.
66040    */
66041    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
66042    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
66043  }else{
66044    int rc = sqlite3PagerWrite(pPage->pDbPage);
66045    if( rc!=SQLITE_OK ){
66046      *pRC = rc;
66047      return;
66048    }
66049    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
66050    data = pPage->aData;
66051    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
66052    rc = allocateSpace(pPage, sz, &idx);
66053    if( rc ){ *pRC = rc; return; }
66054    /* The allocateSpace() routine guarantees the following properties
66055    ** if it returns successfully */
66056    assert( idx >= 0 );
66057    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
66058    assert( idx+sz <= (int)pPage->pBt->usableSize );
66059    pPage->nFree -= (u16)(2 + sz);
66060    memcpy(&data[idx], pCell, sz);
66061    if( iChild ){
66062      put4byte(&data[idx], iChild);
66063    }
66064    pIns = pPage->aCellIdx + i*2;
66065    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
66066    put2byte(pIns, idx);
66067    pPage->nCell++;
66068    /* increment the cell count */
66069    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
66070    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
66071#ifndef SQLITE_OMIT_AUTOVACUUM
66072    if( pPage->pBt->autoVacuum ){
66073      /* The cell may contain a pointer to an overflow page. If so, write
66074      ** the entry for the overflow page into the pointer map.
66075      */
66076      ptrmapPutOvflPtr(pPage, pCell, pRC);
66077    }
66078#endif
66079  }
66080}
66081
66082/*
66083** A CellArray object contains a cache of pointers and sizes for a
66084** consecutive sequence of cells that might be held on multiple pages.
66085*/
66086typedef struct CellArray CellArray;
66087struct CellArray {
66088  int nCell;              /* Number of cells in apCell[] */
66089  MemPage *pRef;          /* Reference page */
66090  u8 **apCell;            /* All cells begin balanced */
66091  u16 *szCell;            /* Local size of all cells in apCell[] */
66092};
66093
66094/*
66095** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
66096** computed.
66097*/
66098static void populateCellCache(CellArray *p, int idx, int N){
66099  assert( idx>=0 && idx+N<=p->nCell );
66100  while( N>0 ){
66101    assert( p->apCell[idx]!=0 );
66102    if( p->szCell[idx]==0 ){
66103      p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
66104    }else{
66105      assert( CORRUPT_DB ||
66106              p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
66107    }
66108    idx++;
66109    N--;
66110  }
66111}
66112
66113/*
66114** Return the size of the Nth element of the cell array
66115*/
66116static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
66117  assert( N>=0 && N<p->nCell );
66118  assert( p->szCell[N]==0 );
66119  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
66120  return p->szCell[N];
66121}
66122static u16 cachedCellSize(CellArray *p, int N){
66123  assert( N>=0 && N<p->nCell );
66124  if( p->szCell[N] ) return p->szCell[N];
66125  return computeCellSize(p, N);
66126}
66127
66128/*
66129** Array apCell[] contains pointers to nCell b-tree page cells. The
66130** szCell[] array contains the size in bytes of each cell. This function
66131** replaces the current contents of page pPg with the contents of the cell
66132** array.
66133**
66134** Some of the cells in apCell[] may currently be stored in pPg. This
66135** function works around problems caused by this by making a copy of any
66136** such cells before overwriting the page data.
66137**
66138** The MemPage.nFree field is invalidated by this function. It is the
66139** responsibility of the caller to set it correctly.
66140*/
66141static int rebuildPage(
66142  MemPage *pPg,                   /* Edit this page */
66143  int nCell,                      /* Final number of cells on page */
66144  u8 **apCell,                    /* Array of cells */
66145  u16 *szCell                     /* Array of cell sizes */
66146){
66147  const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
66148  u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
66149  const int usableSize = pPg->pBt->usableSize;
66150  u8 * const pEnd = &aData[usableSize];
66151  int i;
66152  u8 *pCellptr = pPg->aCellIdx;
66153  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
66154  u8 *pData;
66155
66156  i = get2byte(&aData[hdr+5]);
66157  memcpy(&pTmp[i], &aData[i], usableSize - i);
66158
66159  pData = pEnd;
66160  for(i=0; i<nCell; i++){
66161    u8 *pCell = apCell[i];
66162    if( SQLITE_WITHIN(pCell,aData,pEnd) ){
66163      pCell = &pTmp[pCell - aData];
66164    }
66165    pData -= szCell[i];
66166    put2byte(pCellptr, (pData - aData));
66167    pCellptr += 2;
66168    if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
66169    memcpy(pData, pCell, szCell[i]);
66170    assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
66171    testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
66172  }
66173
66174  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
66175  pPg->nCell = nCell;
66176  pPg->nOverflow = 0;
66177
66178  put2byte(&aData[hdr+1], 0);
66179  put2byte(&aData[hdr+3], pPg->nCell);
66180  put2byte(&aData[hdr+5], pData - aData);
66181  aData[hdr+7] = 0x00;
66182  return SQLITE_OK;
66183}
66184
66185/*
66186** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
66187** contains the size in bytes of each such cell. This function attempts to
66188** add the cells stored in the array to page pPg. If it cannot (because
66189** the page needs to be defragmented before the cells will fit), non-zero
66190** is returned. Otherwise, if the cells are added successfully, zero is
66191** returned.
66192**
66193** Argument pCellptr points to the first entry in the cell-pointer array
66194** (part of page pPg) to populate. After cell apCell[0] is written to the
66195** page body, a 16-bit offset is written to pCellptr. And so on, for each
66196** cell in the array. It is the responsibility of the caller to ensure
66197** that it is safe to overwrite this part of the cell-pointer array.
66198**
66199** When this function is called, *ppData points to the start of the
66200** content area on page pPg. If the size of the content area is extended,
66201** *ppData is updated to point to the new start of the content area
66202** before returning.
66203**
66204** Finally, argument pBegin points to the byte immediately following the
66205** end of the space required by this page for the cell-pointer area (for
66206** all cells - not just those inserted by the current call). If the content
66207** area must be extended to before this point in order to accomodate all
66208** cells in apCell[], then the cells do not fit and non-zero is returned.
66209*/
66210static int pageInsertArray(
66211  MemPage *pPg,                   /* Page to add cells to */
66212  u8 *pBegin,                     /* End of cell-pointer array */
66213  u8 **ppData,                    /* IN/OUT: Page content -area pointer */
66214  u8 *pCellptr,                   /* Pointer to cell-pointer area */
66215  int iFirst,                     /* Index of first cell to add */
66216  int nCell,                      /* Number of cells to add to pPg */
66217  CellArray *pCArray              /* Array of cells */
66218){
66219  int i;
66220  u8 *aData = pPg->aData;
66221  u8 *pData = *ppData;
66222  int iEnd = iFirst + nCell;
66223  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
66224  for(i=iFirst; i<iEnd; i++){
66225    int sz, rc;
66226    u8 *pSlot;
66227    sz = cachedCellSize(pCArray, i);
66228    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
66229      if( (pData - pBegin)<sz ) return 1;
66230      pData -= sz;
66231      pSlot = pData;
66232    }
66233    /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
66234    ** database.  But they might for a corrupt database.  Hence use memmove()
66235    ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
66236    assert( (pSlot+sz)<=pCArray->apCell[i]
66237         || pSlot>=(pCArray->apCell[i]+sz)
66238         || CORRUPT_DB );
66239    memmove(pSlot, pCArray->apCell[i], sz);
66240    put2byte(pCellptr, (pSlot - aData));
66241    pCellptr += 2;
66242  }
66243  *ppData = pData;
66244  return 0;
66245}
66246
66247/*
66248** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
66249** contains the size in bytes of each such cell. This function adds the
66250** space associated with each cell in the array that is currently stored
66251** within the body of pPg to the pPg free-list. The cell-pointers and other
66252** fields of the page are not updated.
66253**
66254** This function returns the total number of cells added to the free-list.
66255*/
66256static int pageFreeArray(
66257  MemPage *pPg,                   /* Page to edit */
66258  int iFirst,                     /* First cell to delete */
66259  int nCell,                      /* Cells to delete */
66260  CellArray *pCArray              /* Array of cells */
66261){
66262  u8 * const aData = pPg->aData;
66263  u8 * const pEnd = &aData[pPg->pBt->usableSize];
66264  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
66265  int nRet = 0;
66266  int i;
66267  int iEnd = iFirst + nCell;
66268  u8 *pFree = 0;
66269  int szFree = 0;
66270
66271  for(i=iFirst; i<iEnd; i++){
66272    u8 *pCell = pCArray->apCell[i];
66273    if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
66274      int sz;
66275      /* No need to use cachedCellSize() here.  The sizes of all cells that
66276      ** are to be freed have already been computing while deciding which
66277      ** cells need freeing */
66278      sz = pCArray->szCell[i];  assert( sz>0 );
66279      if( pFree!=(pCell + sz) ){
66280        if( pFree ){
66281          assert( pFree>aData && (pFree - aData)<65536 );
66282          freeSpace(pPg, (u16)(pFree - aData), szFree);
66283        }
66284        pFree = pCell;
66285        szFree = sz;
66286        if( pFree+sz>pEnd ) return 0;
66287      }else{
66288        pFree = pCell;
66289        szFree += sz;
66290      }
66291      nRet++;
66292    }
66293  }
66294  if( pFree ){
66295    assert( pFree>aData && (pFree - aData)<65536 );
66296    freeSpace(pPg, (u16)(pFree - aData), szFree);
66297  }
66298  return nRet;
66299}
66300
66301/*
66302** apCell[] and szCell[] contains pointers to and sizes of all cells in the
66303** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
66304** with apCell[iOld].  After balancing, this page should hold nNew cells
66305** starting at apCell[iNew].
66306**
66307** This routine makes the necessary adjustments to pPg so that it contains
66308** the correct cells after being balanced.
66309**
66310** The pPg->nFree field is invalid when this function returns. It is the
66311** responsibility of the caller to set it correctly.
66312*/
66313static int editPage(
66314  MemPage *pPg,                   /* Edit this page */
66315  int iOld,                       /* Index of first cell currently on page */
66316  int iNew,                       /* Index of new first cell on page */
66317  int nNew,                       /* Final number of cells on page */
66318  CellArray *pCArray              /* Array of cells and sizes */
66319){
66320  u8 * const aData = pPg->aData;
66321  const int hdr = pPg->hdrOffset;
66322  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
66323  int nCell = pPg->nCell;       /* Cells stored on pPg */
66324  u8 *pData;
66325  u8 *pCellptr;
66326  int i;
66327  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
66328  int iNewEnd = iNew + nNew;
66329
66330#ifdef SQLITE_DEBUG
66331  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
66332  memcpy(pTmp, aData, pPg->pBt->usableSize);
66333#endif
66334
66335  /* Remove cells from the start and end of the page */
66336  if( iOld<iNew ){
66337    int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
66338    memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
66339    nCell -= nShift;
66340  }
66341  if( iNewEnd < iOldEnd ){
66342    nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
66343  }
66344
66345  pData = &aData[get2byteNotZero(&aData[hdr+5])];
66346  if( pData<pBegin ) goto editpage_fail;
66347
66348  /* Add cells to the start of the page */
66349  if( iNew<iOld ){
66350    int nAdd = MIN(nNew,iOld-iNew);
66351    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
66352    pCellptr = pPg->aCellIdx;
66353    memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
66354    if( pageInsertArray(
66355          pPg, pBegin, &pData, pCellptr,
66356          iNew, nAdd, pCArray
66357    ) ) goto editpage_fail;
66358    nCell += nAdd;
66359  }
66360
66361  /* Add any overflow cells */
66362  for(i=0; i<pPg->nOverflow; i++){
66363    int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
66364    if( iCell>=0 && iCell<nNew ){
66365      pCellptr = &pPg->aCellIdx[iCell * 2];
66366      memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
66367      nCell++;
66368      if( pageInsertArray(
66369            pPg, pBegin, &pData, pCellptr,
66370            iCell+iNew, 1, pCArray
66371      ) ) goto editpage_fail;
66372    }
66373  }
66374
66375  /* Append cells to the end of the page */
66376  pCellptr = &pPg->aCellIdx[nCell*2];
66377  if( pageInsertArray(
66378        pPg, pBegin, &pData, pCellptr,
66379        iNew+nCell, nNew-nCell, pCArray
66380  ) ) goto editpage_fail;
66381
66382  pPg->nCell = nNew;
66383  pPg->nOverflow = 0;
66384
66385  put2byte(&aData[hdr+3], pPg->nCell);
66386  put2byte(&aData[hdr+5], pData - aData);
66387
66388#ifdef SQLITE_DEBUG
66389  for(i=0; i<nNew && !CORRUPT_DB; i++){
66390    u8 *pCell = pCArray->apCell[i+iNew];
66391    int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
66392    if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
66393      pCell = &pTmp[pCell - aData];
66394    }
66395    assert( 0==memcmp(pCell, &aData[iOff],
66396            pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
66397  }
66398#endif
66399
66400  return SQLITE_OK;
66401 editpage_fail:
66402  /* Unable to edit this page. Rebuild it from scratch instead. */
66403  populateCellCache(pCArray, iNew, nNew);
66404  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
66405}
66406
66407/*
66408** The following parameters determine how many adjacent pages get involved
66409** in a balancing operation.  NN is the number of neighbors on either side
66410** of the page that participate in the balancing operation.  NB is the
66411** total number of pages that participate, including the target page and
66412** NN neighbors on either side.
66413**
66414** The minimum value of NN is 1 (of course).  Increasing NN above 1
66415** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
66416** in exchange for a larger degradation in INSERT and UPDATE performance.
66417** The value of NN appears to give the best results overall.
66418*/
66419#define NN 1             /* Number of neighbors on either side of pPage */
66420#define NB (NN*2+1)      /* Total pages involved in the balance */
66421
66422
66423#ifndef SQLITE_OMIT_QUICKBALANCE
66424/*
66425** This version of balance() handles the common special case where
66426** a new entry is being inserted on the extreme right-end of the
66427** tree, in other words, when the new entry will become the largest
66428** entry in the tree.
66429**
66430** Instead of trying to balance the 3 right-most leaf pages, just add
66431** a new page to the right-hand side and put the one new entry in
66432** that page.  This leaves the right side of the tree somewhat
66433** unbalanced.  But odds are that we will be inserting new entries
66434** at the end soon afterwards so the nearly empty page will quickly
66435** fill up.  On average.
66436**
66437** pPage is the leaf page which is the right-most page in the tree.
66438** pParent is its parent.  pPage must have a single overflow entry
66439** which is also the right-most entry on the page.
66440**
66441** The pSpace buffer is used to store a temporary copy of the divider
66442** cell that will be inserted into pParent. Such a cell consists of a 4
66443** byte page number followed by a variable length integer. In other
66444** words, at most 13 bytes. Hence the pSpace buffer must be at
66445** least 13 bytes in size.
66446*/
66447static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
66448  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
66449  MemPage *pNew;                       /* Newly allocated page */
66450  int rc;                              /* Return Code */
66451  Pgno pgnoNew;                        /* Page number of pNew */
66452
66453  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
66454  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
66455  assert( pPage->nOverflow==1 );
66456
66457  /* This error condition is now caught prior to reaching this function */
66458  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
66459
66460  /* Allocate a new page. This page will become the right-sibling of
66461  ** pPage. Make the parent page writable, so that the new divider cell
66462  ** may be inserted. If both these operations are successful, proceed.
66463  */
66464  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
66465
66466  if( rc==SQLITE_OK ){
66467
66468    u8 *pOut = &pSpace[4];
66469    u8 *pCell = pPage->apOvfl[0];
66470    u16 szCell = pPage->xCellSize(pPage, pCell);
66471    u8 *pStop;
66472
66473    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
66474    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
66475    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
66476    rc = rebuildPage(pNew, 1, &pCell, &szCell);
66477    if( NEVER(rc) ) return rc;
66478    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
66479
66480    /* If this is an auto-vacuum database, update the pointer map
66481    ** with entries for the new page, and any pointer from the
66482    ** cell on the page to an overflow page. If either of these
66483    ** operations fails, the return code is set, but the contents
66484    ** of the parent page are still manipulated by thh code below.
66485    ** That is Ok, at this point the parent page is guaranteed to
66486    ** be marked as dirty. Returning an error code will cause a
66487    ** rollback, undoing any changes made to the parent page.
66488    */
66489    if( ISAUTOVACUUM ){
66490      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
66491      if( szCell>pNew->minLocal ){
66492        ptrmapPutOvflPtr(pNew, pCell, &rc);
66493      }
66494    }
66495
66496    /* Create a divider cell to insert into pParent. The divider cell
66497    ** consists of a 4-byte page number (the page number of pPage) and
66498    ** a variable length key value (which must be the same value as the
66499    ** largest key on pPage).
66500    **
66501    ** To find the largest key value on pPage, first find the right-most
66502    ** cell on pPage. The first two fields of this cell are the
66503    ** record-length (a variable length integer at most 32-bits in size)
66504    ** and the key value (a variable length integer, may have any value).
66505    ** The first of the while(...) loops below skips over the record-length
66506    ** field. The second while(...) loop copies the key value from the
66507    ** cell on pPage into the pSpace buffer.
66508    */
66509    pCell = findCell(pPage, pPage->nCell-1);
66510    pStop = &pCell[9];
66511    while( (*(pCell++)&0x80) && pCell<pStop );
66512    pStop = &pCell[9];
66513    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
66514
66515    /* Insert the new divider cell into pParent. */
66516    if( rc==SQLITE_OK ){
66517      insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
66518                   0, pPage->pgno, &rc);
66519    }
66520
66521    /* Set the right-child pointer of pParent to point to the new page. */
66522    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
66523
66524    /* Release the reference to the new page. */
66525    releasePage(pNew);
66526  }
66527
66528  return rc;
66529}
66530#endif /* SQLITE_OMIT_QUICKBALANCE */
66531
66532#if 0
66533/*
66534** This function does not contribute anything to the operation of SQLite.
66535** it is sometimes activated temporarily while debugging code responsible
66536** for setting pointer-map entries.
66537*/
66538static int ptrmapCheckPages(MemPage **apPage, int nPage){
66539  int i, j;
66540  for(i=0; i<nPage; i++){
66541    Pgno n;
66542    u8 e;
66543    MemPage *pPage = apPage[i];
66544    BtShared *pBt = pPage->pBt;
66545    assert( pPage->isInit );
66546
66547    for(j=0; j<pPage->nCell; j++){
66548      CellInfo info;
66549      u8 *z;
66550
66551      z = findCell(pPage, j);
66552      pPage->xParseCell(pPage, z, &info);
66553      if( info.nLocal<info.nPayload ){
66554        Pgno ovfl = get4byte(&z[info.nSize-4]);
66555        ptrmapGet(pBt, ovfl, &e, &n);
66556        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
66557      }
66558      if( !pPage->leaf ){
66559        Pgno child = get4byte(z);
66560        ptrmapGet(pBt, child, &e, &n);
66561        assert( n==pPage->pgno && e==PTRMAP_BTREE );
66562      }
66563    }
66564    if( !pPage->leaf ){
66565      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
66566      ptrmapGet(pBt, child, &e, &n);
66567      assert( n==pPage->pgno && e==PTRMAP_BTREE );
66568    }
66569  }
66570  return 1;
66571}
66572#endif
66573
66574/*
66575** This function is used to copy the contents of the b-tree node stored
66576** on page pFrom to page pTo. If page pFrom was not a leaf page, then
66577** the pointer-map entries for each child page are updated so that the
66578** parent page stored in the pointer map is page pTo. If pFrom contained
66579** any cells with overflow page pointers, then the corresponding pointer
66580** map entries are also updated so that the parent page is page pTo.
66581**
66582** If pFrom is currently carrying any overflow cells (entries in the
66583** MemPage.apOvfl[] array), they are not copied to pTo.
66584**
66585** Before returning, page pTo is reinitialized using btreeInitPage().
66586**
66587** The performance of this function is not critical. It is only used by
66588** the balance_shallower() and balance_deeper() procedures, neither of
66589** which are called often under normal circumstances.
66590*/
66591static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
66592  if( (*pRC)==SQLITE_OK ){
66593    BtShared * const pBt = pFrom->pBt;
66594    u8 * const aFrom = pFrom->aData;
66595    u8 * const aTo = pTo->aData;
66596    int const iFromHdr = pFrom->hdrOffset;
66597    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
66598    int rc;
66599    int iData;
66600
66601
66602    assert( pFrom->isInit );
66603    assert( pFrom->nFree>=iToHdr );
66604    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
66605
66606    /* Copy the b-tree node content from page pFrom to page pTo. */
66607    iData = get2byte(&aFrom[iFromHdr+5]);
66608    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
66609    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
66610
66611    /* Reinitialize page pTo so that the contents of the MemPage structure
66612    ** match the new data. The initialization of pTo can actually fail under
66613    ** fairly obscure circumstances, even though it is a copy of initialized
66614    ** page pFrom.
66615    */
66616    pTo->isInit = 0;
66617    rc = btreeInitPage(pTo);
66618    if( rc!=SQLITE_OK ){
66619      *pRC = rc;
66620      return;
66621    }
66622
66623    /* If this is an auto-vacuum database, update the pointer-map entries
66624    ** for any b-tree or overflow pages that pTo now contains the pointers to.
66625    */
66626    if( ISAUTOVACUUM ){
66627      *pRC = setChildPtrmaps(pTo);
66628    }
66629  }
66630}
66631
66632/*
66633** This routine redistributes cells on the iParentIdx'th child of pParent
66634** (hereafter "the page") and up to 2 siblings so that all pages have about the
66635** same amount of free space. Usually a single sibling on either side of the
66636** page are used in the balancing, though both siblings might come from one
66637** side if the page is the first or last child of its parent. If the page
66638** has fewer than 2 siblings (something which can only happen if the page
66639** is a root page or a child of a root page) then all available siblings
66640** participate in the balancing.
66641**
66642** The number of siblings of the page might be increased or decreased by
66643** one or two in an effort to keep pages nearly full but not over full.
66644**
66645** Note that when this routine is called, some of the cells on the page
66646** might not actually be stored in MemPage.aData[]. This can happen
66647** if the page is overfull. This routine ensures that all cells allocated
66648** to the page and its siblings fit into MemPage.aData[] before returning.
66649**
66650** In the course of balancing the page and its siblings, cells may be
66651** inserted into or removed from the parent page (pParent). Doing so
66652** may cause the parent page to become overfull or underfull. If this
66653** happens, it is the responsibility of the caller to invoke the correct
66654** balancing routine to fix this problem (see the balance() routine).
66655**
66656** If this routine fails for any reason, it might leave the database
66657** in a corrupted state. So if this routine fails, the database should
66658** be rolled back.
66659**
66660** The third argument to this function, aOvflSpace, is a pointer to a
66661** buffer big enough to hold one page. If while inserting cells into the parent
66662** page (pParent) the parent page becomes overfull, this buffer is
66663** used to store the parent's overflow cells. Because this function inserts
66664** a maximum of four divider cells into the parent page, and the maximum
66665** size of a cell stored within an internal node is always less than 1/4
66666** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
66667** enough for all overflow cells.
66668**
66669** If aOvflSpace is set to a null pointer, this function returns
66670** SQLITE_NOMEM.
66671*/
66672static int balance_nonroot(
66673  MemPage *pParent,               /* Parent page of siblings being balanced */
66674  int iParentIdx,                 /* Index of "the page" in pParent */
66675  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
66676  int isRoot,                     /* True if pParent is a root-page */
66677  int bBulk                       /* True if this call is part of a bulk load */
66678){
66679  BtShared *pBt;               /* The whole database */
66680  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
66681  int nNew = 0;                /* Number of pages in apNew[] */
66682  int nOld;                    /* Number of pages in apOld[] */
66683  int i, j, k;                 /* Loop counters */
66684  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
66685  int rc = SQLITE_OK;          /* The return code */
66686  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
66687  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
66688  int usableSpace;             /* Bytes in pPage beyond the header */
66689  int pageFlags;               /* Value of pPage->aData[0] */
66690  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
66691  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
66692  int szScratch;               /* Size of scratch memory requested */
66693  MemPage *apOld[NB];          /* pPage and up to two siblings */
66694  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
66695  u8 *pRight;                  /* Location in parent of right-sibling pointer */
66696  u8 *apDiv[NB-1];             /* Divider cells in pParent */
66697  int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
66698  int cntOld[NB+2];            /* Old index in b.apCell[] */
66699  int szNew[NB+2];             /* Combined size of cells placed on i-th page */
66700  u8 *aSpace1;                 /* Space for copies of dividers cells */
66701  Pgno pgno;                   /* Temp var to store a page number in */
66702  u8 abDone[NB+2];             /* True after i'th new page is populated */
66703  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
66704  Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
66705  u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
66706  CellArray b;                  /* Parsed information on cells being balanced */
66707
66708  memset(abDone, 0, sizeof(abDone));
66709  b.nCell = 0;
66710  b.apCell = 0;
66711  pBt = pParent->pBt;
66712  assert( sqlite3_mutex_held(pBt->mutex) );
66713  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
66714
66715#if 0
66716  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
66717#endif
66718
66719  /* At this point pParent may have at most one overflow cell. And if
66720  ** this overflow cell is present, it must be the cell with
66721  ** index iParentIdx. This scenario comes about when this function
66722  ** is called (indirectly) from sqlite3BtreeDelete().
66723  */
66724  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
66725  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
66726
66727  if( !aOvflSpace ){
66728    return SQLITE_NOMEM_BKPT;
66729  }
66730
66731  /* Find the sibling pages to balance. Also locate the cells in pParent
66732  ** that divide the siblings. An attempt is made to find NN siblings on
66733  ** either side of pPage. More siblings are taken from one side, however,
66734  ** if there are fewer than NN siblings on the other side. If pParent
66735  ** has NB or fewer children then all children of pParent are taken.
66736  **
66737  ** This loop also drops the divider cells from the parent page. This
66738  ** way, the remainder of the function does not have to deal with any
66739  ** overflow cells in the parent page, since if any existed they will
66740  ** have already been removed.
66741  */
66742  i = pParent->nOverflow + pParent->nCell;
66743  if( i<2 ){
66744    nxDiv = 0;
66745  }else{
66746    assert( bBulk==0 || bBulk==1 );
66747    if( iParentIdx==0 ){
66748      nxDiv = 0;
66749    }else if( iParentIdx==i ){
66750      nxDiv = i-2+bBulk;
66751    }else{
66752      nxDiv = iParentIdx-1;
66753    }
66754    i = 2-bBulk;
66755  }
66756  nOld = i+1;
66757  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
66758    pRight = &pParent->aData[pParent->hdrOffset+8];
66759  }else{
66760    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
66761  }
66762  pgno = get4byte(pRight);
66763  while( 1 ){
66764    rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
66765    if( rc ){
66766      memset(apOld, 0, (i+1)*sizeof(MemPage*));
66767      goto balance_cleanup;
66768    }
66769    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
66770    if( (i--)==0 ) break;
66771
66772    if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
66773      apDiv[i] = pParent->apOvfl[0];
66774      pgno = get4byte(apDiv[i]);
66775      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
66776      pParent->nOverflow = 0;
66777    }else{
66778      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
66779      pgno = get4byte(apDiv[i]);
66780      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
66781
66782      /* Drop the cell from the parent page. apDiv[i] still points to
66783      ** the cell within the parent, even though it has been dropped.
66784      ** This is safe because dropping a cell only overwrites the first
66785      ** four bytes of it, and this function does not need the first
66786      ** four bytes of the divider cell. So the pointer is safe to use
66787      ** later on.
66788      **
66789      ** But not if we are in secure-delete mode. In secure-delete mode,
66790      ** the dropCell() routine will overwrite the entire cell with zeroes.
66791      ** In this case, temporarily copy the cell into the aOvflSpace[]
66792      ** buffer. It will be copied out again as soon as the aSpace[] buffer
66793      ** is allocated.  */
66794      if( pBt->btsFlags & BTS_FAST_SECURE ){
66795        int iOff;
66796
66797        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
66798        if( (iOff+szNew[i])>(int)pBt->usableSize ){
66799          rc = SQLITE_CORRUPT_BKPT;
66800          memset(apOld, 0, (i+1)*sizeof(MemPage*));
66801          goto balance_cleanup;
66802        }else{
66803          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
66804          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
66805        }
66806      }
66807      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
66808    }
66809  }
66810
66811  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
66812  ** alignment */
66813  nMaxCells = (nMaxCells + 3)&~3;
66814
66815  /*
66816  ** Allocate space for memory structures
66817  */
66818  szScratch =
66819       nMaxCells*sizeof(u8*)                       /* b.apCell */
66820     + nMaxCells*sizeof(u16)                       /* b.szCell */
66821     + pBt->pageSize;                              /* aSpace1 */
66822
66823  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
66824  ** that is more than 6 times the database page size. */
66825  assert( szScratch<=6*(int)pBt->pageSize );
66826  b.apCell = sqlite3ScratchMalloc( szScratch );
66827  if( b.apCell==0 ){
66828    rc = SQLITE_NOMEM_BKPT;
66829    goto balance_cleanup;
66830  }
66831  b.szCell = (u16*)&b.apCell[nMaxCells];
66832  aSpace1 = (u8*)&b.szCell[nMaxCells];
66833  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
66834
66835  /*
66836  ** Load pointers to all cells on sibling pages and the divider cells
66837  ** into the local b.apCell[] array.  Make copies of the divider cells
66838  ** into space obtained from aSpace1[]. The divider cells have already
66839  ** been removed from pParent.
66840  **
66841  ** If the siblings are on leaf pages, then the child pointers of the
66842  ** divider cells are stripped from the cells before they are copied
66843  ** into aSpace1[].  In this way, all cells in b.apCell[] are without
66844  ** child pointers.  If siblings are not leaves, then all cell in
66845  ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
66846  ** are alike.
66847  **
66848  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
66849  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
66850  */
66851  b.pRef = apOld[0];
66852  leafCorrection = b.pRef->leaf*4;
66853  leafData = b.pRef->intKeyLeaf;
66854  for(i=0; i<nOld; i++){
66855    MemPage *pOld = apOld[i];
66856    int limit = pOld->nCell;
66857    u8 *aData = pOld->aData;
66858    u16 maskPage = pOld->maskPage;
66859    u8 *piCell = aData + pOld->cellOffset;
66860    u8 *piEnd;
66861
66862    /* Verify that all sibling pages are of the same "type" (table-leaf,
66863    ** table-interior, index-leaf, or index-interior).
66864    */
66865    if( pOld->aData[0]!=apOld[0]->aData[0] ){
66866      rc = SQLITE_CORRUPT_BKPT;
66867      goto balance_cleanup;
66868    }
66869
66870    /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
66871    ** constains overflow cells, include them in the b.apCell[] array
66872    ** in the correct spot.
66873    **
66874    ** Note that when there are multiple overflow cells, it is always the
66875    ** case that they are sequential and adjacent.  This invariant arises
66876    ** because multiple overflows can only occurs when inserting divider
66877    ** cells into a parent on a prior balance, and divider cells are always
66878    ** adjacent and are inserted in order.  There is an assert() tagged
66879    ** with "NOTE 1" in the overflow cell insertion loop to prove this
66880    ** invariant.
66881    **
66882    ** This must be done in advance.  Once the balance starts, the cell
66883    ** offset section of the btree page will be overwritten and we will no
66884    ** long be able to find the cells if a pointer to each cell is not saved
66885    ** first.
66886    */
66887    memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
66888    if( pOld->nOverflow>0 ){
66889      limit = pOld->aiOvfl[0];
66890      for(j=0; j<limit; j++){
66891        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
66892        piCell += 2;
66893        b.nCell++;
66894      }
66895      for(k=0; k<pOld->nOverflow; k++){
66896        assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
66897        b.apCell[b.nCell] = pOld->apOvfl[k];
66898        b.nCell++;
66899      }
66900    }
66901    piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
66902    while( piCell<piEnd ){
66903      assert( b.nCell<nMaxCells );
66904      b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
66905      piCell += 2;
66906      b.nCell++;
66907    }
66908
66909    cntOld[i] = b.nCell;
66910    if( i<nOld-1 && !leafData){
66911      u16 sz = (u16)szNew[i];
66912      u8 *pTemp;
66913      assert( b.nCell<nMaxCells );
66914      b.szCell[b.nCell] = sz;
66915      pTemp = &aSpace1[iSpace1];
66916      iSpace1 += sz;
66917      assert( sz<=pBt->maxLocal+23 );
66918      assert( iSpace1 <= (int)pBt->pageSize );
66919      memcpy(pTemp, apDiv[i], sz);
66920      b.apCell[b.nCell] = pTemp+leafCorrection;
66921      assert( leafCorrection==0 || leafCorrection==4 );
66922      b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
66923      if( !pOld->leaf ){
66924        assert( leafCorrection==0 );
66925        assert( pOld->hdrOffset==0 );
66926        /* The right pointer of the child page pOld becomes the left
66927        ** pointer of the divider cell */
66928        memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
66929      }else{
66930        assert( leafCorrection==4 );
66931        while( b.szCell[b.nCell]<4 ){
66932          /* Do not allow any cells smaller than 4 bytes. If a smaller cell
66933          ** does exist, pad it with 0x00 bytes. */
66934          assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
66935          assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
66936          aSpace1[iSpace1++] = 0x00;
66937          b.szCell[b.nCell]++;
66938        }
66939      }
66940      b.nCell++;
66941    }
66942  }
66943
66944  /*
66945  ** Figure out the number of pages needed to hold all b.nCell cells.
66946  ** Store this number in "k".  Also compute szNew[] which is the total
66947  ** size of all cells on the i-th page and cntNew[] which is the index
66948  ** in b.apCell[] of the cell that divides page i from page i+1.
66949  ** cntNew[k] should equal b.nCell.
66950  **
66951  ** Values computed by this block:
66952  **
66953  **           k: The total number of sibling pages
66954  **    szNew[i]: Spaced used on the i-th sibling page.
66955  **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
66956  **              the right of the i-th sibling page.
66957  ** usableSpace: Number of bytes of space available on each sibling.
66958  **
66959  */
66960  usableSpace = pBt->usableSize - 12 + leafCorrection;
66961  for(i=0; i<nOld; i++){
66962    MemPage *p = apOld[i];
66963    szNew[i] = usableSpace - p->nFree;
66964    for(j=0; j<p->nOverflow; j++){
66965      szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
66966    }
66967    cntNew[i] = cntOld[i];
66968  }
66969  k = nOld;
66970  for(i=0; i<k; i++){
66971    int sz;
66972    while( szNew[i]>usableSpace ){
66973      if( i+1>=k ){
66974        k = i+2;
66975        if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
66976        szNew[k-1] = 0;
66977        cntNew[k-1] = b.nCell;
66978      }
66979      sz = 2 + cachedCellSize(&b, cntNew[i]-1);
66980      szNew[i] -= sz;
66981      if( !leafData ){
66982        if( cntNew[i]<b.nCell ){
66983          sz = 2 + cachedCellSize(&b, cntNew[i]);
66984        }else{
66985          sz = 0;
66986        }
66987      }
66988      szNew[i+1] += sz;
66989      cntNew[i]--;
66990    }
66991    while( cntNew[i]<b.nCell ){
66992      sz = 2 + cachedCellSize(&b, cntNew[i]);
66993      if( szNew[i]+sz>usableSpace ) break;
66994      szNew[i] += sz;
66995      cntNew[i]++;
66996      if( !leafData ){
66997        if( cntNew[i]<b.nCell ){
66998          sz = 2 + cachedCellSize(&b, cntNew[i]);
66999        }else{
67000          sz = 0;
67001        }
67002      }
67003      szNew[i+1] -= sz;
67004    }
67005    if( cntNew[i]>=b.nCell ){
67006      k = i+1;
67007    }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
67008      rc = SQLITE_CORRUPT_BKPT;
67009      goto balance_cleanup;
67010    }
67011  }
67012
67013  /*
67014  ** The packing computed by the previous block is biased toward the siblings
67015  ** on the left side (siblings with smaller keys). The left siblings are
67016  ** always nearly full, while the right-most sibling might be nearly empty.
67017  ** The next block of code attempts to adjust the packing of siblings to
67018  ** get a better balance.
67019  **
67020  ** This adjustment is more than an optimization.  The packing above might
67021  ** be so out of balance as to be illegal.  For example, the right-most
67022  ** sibling might be completely empty.  This adjustment is not optional.
67023  */
67024  for(i=k-1; i>0; i--){
67025    int szRight = szNew[i];  /* Size of sibling on the right */
67026    int szLeft = szNew[i-1]; /* Size of sibling on the left */
67027    int r;              /* Index of right-most cell in left sibling */
67028    int d;              /* Index of first cell to the left of right sibling */
67029
67030    r = cntNew[i-1] - 1;
67031    d = r + 1 - leafData;
67032    (void)cachedCellSize(&b, d);
67033    do{
67034      assert( d<nMaxCells );
67035      assert( r<nMaxCells );
67036      (void)cachedCellSize(&b, r);
67037      if( szRight!=0
67038       && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
67039        break;
67040      }
67041      szRight += b.szCell[d] + 2;
67042      szLeft -= b.szCell[r] + 2;
67043      cntNew[i-1] = r;
67044      r--;
67045      d--;
67046    }while( r>=0 );
67047    szNew[i] = szRight;
67048    szNew[i-1] = szLeft;
67049    if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
67050      rc = SQLITE_CORRUPT_BKPT;
67051      goto balance_cleanup;
67052    }
67053  }
67054
67055  /* Sanity check:  For a non-corrupt database file one of the follwing
67056  ** must be true:
67057  **    (1) We found one or more cells (cntNew[0])>0), or
67058  **    (2) pPage is a virtual root page.  A virtual root page is when
67059  **        the real root page is page 1 and we are the only child of
67060  **        that page.
67061  */
67062  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
67063  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
67064    apOld[0]->pgno, apOld[0]->nCell,
67065    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
67066    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
67067  ));
67068
67069  /*
67070  ** Allocate k new pages.  Reuse old pages where possible.
67071  */
67072  pageFlags = apOld[0]->aData[0];
67073  for(i=0; i<k; i++){
67074    MemPage *pNew;
67075    if( i<nOld ){
67076      pNew = apNew[i] = apOld[i];
67077      apOld[i] = 0;
67078      rc = sqlite3PagerWrite(pNew->pDbPage);
67079      nNew++;
67080      if( rc ) goto balance_cleanup;
67081    }else{
67082      assert( i>0 );
67083      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
67084      if( rc ) goto balance_cleanup;
67085      zeroPage(pNew, pageFlags);
67086      apNew[i] = pNew;
67087      nNew++;
67088      cntOld[i] = b.nCell;
67089
67090      /* Set the pointer-map entry for the new sibling page. */
67091      if( ISAUTOVACUUM ){
67092        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
67093        if( rc!=SQLITE_OK ){
67094          goto balance_cleanup;
67095        }
67096      }
67097    }
67098  }
67099
67100  /*
67101  ** Reassign page numbers so that the new pages are in ascending order.
67102  ** This helps to keep entries in the disk file in order so that a scan
67103  ** of the table is closer to a linear scan through the file. That in turn
67104  ** helps the operating system to deliver pages from the disk more rapidly.
67105  **
67106  ** An O(n^2) insertion sort algorithm is used, but since n is never more
67107  ** than (NB+2) (a small constant), that should not be a problem.
67108  **
67109  ** When NB==3, this one optimization makes the database about 25% faster
67110  ** for large insertions and deletions.
67111  */
67112  for(i=0; i<nNew; i++){
67113    aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
67114    aPgFlags[i] = apNew[i]->pDbPage->flags;
67115    for(j=0; j<i; j++){
67116      if( aPgno[j]==aPgno[i] ){
67117        /* This branch is taken if the set of sibling pages somehow contains
67118        ** duplicate entries. This can happen if the database is corrupt.
67119        ** It would be simpler to detect this as part of the loop below, but
67120        ** we do the detection here in order to avoid populating the pager
67121        ** cache with two separate objects associated with the same
67122        ** page number.  */
67123        assert( CORRUPT_DB );
67124        rc = SQLITE_CORRUPT_BKPT;
67125        goto balance_cleanup;
67126      }
67127    }
67128  }
67129  for(i=0; i<nNew; i++){
67130    int iBest = 0;                /* aPgno[] index of page number to use */
67131    for(j=1; j<nNew; j++){
67132      if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
67133    }
67134    pgno = aPgOrder[iBest];
67135    aPgOrder[iBest] = 0xffffffff;
67136    if( iBest!=i ){
67137      if( iBest>i ){
67138        sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
67139      }
67140      sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
67141      apNew[i]->pgno = pgno;
67142    }
67143  }
67144
67145  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
67146         "%d(%d nc=%d) %d(%d nc=%d)\n",
67147    apNew[0]->pgno, szNew[0], cntNew[0],
67148    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
67149    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
67150    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
67151    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
67152    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
67153    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
67154    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
67155    nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
67156  ));
67157
67158  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
67159  put4byte(pRight, apNew[nNew-1]->pgno);
67160
67161  /* If the sibling pages are not leaves, ensure that the right-child pointer
67162  ** of the right-most new sibling page is set to the value that was
67163  ** originally in the same field of the right-most old sibling page. */
67164  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
67165    MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
67166    memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
67167  }
67168
67169  /* Make any required updates to pointer map entries associated with
67170  ** cells stored on sibling pages following the balance operation. Pointer
67171  ** map entries associated with divider cells are set by the insertCell()
67172  ** routine. The associated pointer map entries are:
67173  **
67174  **   a) if the cell contains a reference to an overflow chain, the
67175  **      entry associated with the first page in the overflow chain, and
67176  **
67177  **   b) if the sibling pages are not leaves, the child page associated
67178  **      with the cell.
67179  **
67180  ** If the sibling pages are not leaves, then the pointer map entry
67181  ** associated with the right-child of each sibling may also need to be
67182  ** updated. This happens below, after the sibling pages have been
67183  ** populated, not here.
67184  */
67185  if( ISAUTOVACUUM ){
67186    MemPage *pNew = apNew[0];
67187    u8 *aOld = pNew->aData;
67188    int cntOldNext = pNew->nCell + pNew->nOverflow;
67189    int usableSize = pBt->usableSize;
67190    int iNew = 0;
67191    int iOld = 0;
67192
67193    for(i=0; i<b.nCell; i++){
67194      u8 *pCell = b.apCell[i];
67195      if( i==cntOldNext ){
67196        MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
67197        cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
67198        aOld = pOld->aData;
67199      }
67200      if( i==cntNew[iNew] ){
67201        pNew = apNew[++iNew];
67202        if( !leafData ) continue;
67203      }
67204
67205      /* Cell pCell is destined for new sibling page pNew. Originally, it
67206      ** was either part of sibling page iOld (possibly an overflow cell),
67207      ** or else the divider cell to the left of sibling page iOld. So,
67208      ** if sibling page iOld had the same page number as pNew, and if
67209      ** pCell really was a part of sibling page iOld (not a divider or
67210      ** overflow cell), we can skip updating the pointer map entries.  */
67211      if( iOld>=nNew
67212       || pNew->pgno!=aPgno[iOld]
67213       || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
67214      ){
67215        if( !leafCorrection ){
67216          ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
67217        }
67218        if( cachedCellSize(&b,i)>pNew->minLocal ){
67219          ptrmapPutOvflPtr(pNew, pCell, &rc);
67220        }
67221        if( rc ) goto balance_cleanup;
67222      }
67223    }
67224  }
67225
67226  /* Insert new divider cells into pParent. */
67227  for(i=0; i<nNew-1; i++){
67228    u8 *pCell;
67229    u8 *pTemp;
67230    int sz;
67231    MemPage *pNew = apNew[i];
67232    j = cntNew[i];
67233
67234    assert( j<nMaxCells );
67235    assert( b.apCell[j]!=0 );
67236    pCell = b.apCell[j];
67237    sz = b.szCell[j] + leafCorrection;
67238    pTemp = &aOvflSpace[iOvflSpace];
67239    if( !pNew->leaf ){
67240      memcpy(&pNew->aData[8], pCell, 4);
67241    }else if( leafData ){
67242      /* If the tree is a leaf-data tree, and the siblings are leaves,
67243      ** then there is no divider cell in b.apCell[]. Instead, the divider
67244      ** cell consists of the integer key for the right-most cell of
67245      ** the sibling-page assembled above only.
67246      */
67247      CellInfo info;
67248      j--;
67249      pNew->xParseCell(pNew, b.apCell[j], &info);
67250      pCell = pTemp;
67251      sz = 4 + putVarint(&pCell[4], info.nKey);
67252      pTemp = 0;
67253    }else{
67254      pCell -= 4;
67255      /* Obscure case for non-leaf-data trees: If the cell at pCell was
67256      ** previously stored on a leaf node, and its reported size was 4
67257      ** bytes, then it may actually be smaller than this
67258      ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
67259      ** any cell). But it is important to pass the correct size to
67260      ** insertCell(), so reparse the cell now.
67261      **
67262      ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
67263      ** and WITHOUT ROWID tables with exactly one column which is the
67264      ** primary key.
67265      */
67266      if( b.szCell[j]==4 ){
67267        assert(leafCorrection==4);
67268        sz = pParent->xCellSize(pParent, pCell);
67269      }
67270    }
67271    iOvflSpace += sz;
67272    assert( sz<=pBt->maxLocal+23 );
67273    assert( iOvflSpace <= (int)pBt->pageSize );
67274    insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
67275    if( rc!=SQLITE_OK ) goto balance_cleanup;
67276    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
67277  }
67278
67279  /* Now update the actual sibling pages. The order in which they are updated
67280  ** is important, as this code needs to avoid disrupting any page from which
67281  ** cells may still to be read. In practice, this means:
67282  **
67283  **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
67284  **      then it is not safe to update page apNew[iPg] until after
67285  **      the left-hand sibling apNew[iPg-1] has been updated.
67286  **
67287  **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
67288  **      then it is not safe to update page apNew[iPg] until after
67289  **      the right-hand sibling apNew[iPg+1] has been updated.
67290  **
67291  ** If neither of the above apply, the page is safe to update.
67292  **
67293  ** The iPg value in the following loop starts at nNew-1 goes down
67294  ** to 0, then back up to nNew-1 again, thus making two passes over
67295  ** the pages.  On the initial downward pass, only condition (1) above
67296  ** needs to be tested because (2) will always be true from the previous
67297  ** step.  On the upward pass, both conditions are always true, so the
67298  ** upwards pass simply processes pages that were missed on the downward
67299  ** pass.
67300  */
67301  for(i=1-nNew; i<nNew; i++){
67302    int iPg = i<0 ? -i : i;
67303    assert( iPg>=0 && iPg<nNew );
67304    if( abDone[iPg] ) continue;         /* Skip pages already processed */
67305    if( i>=0                            /* On the upwards pass, or... */
67306     || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
67307    ){
67308      int iNew;
67309      int iOld;
67310      int nNewCell;
67311
67312      /* Verify condition (1):  If cells are moving left, update iPg
67313      ** only after iPg-1 has already been updated. */
67314      assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
67315
67316      /* Verify condition (2):  If cells are moving right, update iPg
67317      ** only after iPg+1 has already been updated. */
67318      assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
67319
67320      if( iPg==0 ){
67321        iNew = iOld = 0;
67322        nNewCell = cntNew[0];
67323      }else{
67324        iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
67325        iNew = cntNew[iPg-1] + !leafData;
67326        nNewCell = cntNew[iPg] - iNew;
67327      }
67328
67329      rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
67330      if( rc ) goto balance_cleanup;
67331      abDone[iPg]++;
67332      apNew[iPg]->nFree = usableSpace-szNew[iPg];
67333      assert( apNew[iPg]->nOverflow==0 );
67334      assert( apNew[iPg]->nCell==nNewCell );
67335    }
67336  }
67337
67338  /* All pages have been processed exactly once */
67339  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
67340
67341  assert( nOld>0 );
67342  assert( nNew>0 );
67343
67344  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
67345    /* The root page of the b-tree now contains no cells. The only sibling
67346    ** page is the right-child of the parent. Copy the contents of the
67347    ** child page into the parent, decreasing the overall height of the
67348    ** b-tree structure by one. This is described as the "balance-shallower"
67349    ** sub-algorithm in some documentation.
67350    **
67351    ** If this is an auto-vacuum database, the call to copyNodeContent()
67352    ** sets all pointer-map entries corresponding to database image pages
67353    ** for which the pointer is stored within the content being copied.
67354    **
67355    ** It is critical that the child page be defragmented before being
67356    ** copied into the parent, because if the parent is page 1 then it will
67357    ** by smaller than the child due to the database header, and so all the
67358    ** free space needs to be up front.
67359    */
67360    assert( nNew==1 || CORRUPT_DB );
67361    rc = defragmentPage(apNew[0], -1);
67362    testcase( rc!=SQLITE_OK );
67363    assert( apNew[0]->nFree ==
67364        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
67365      || rc!=SQLITE_OK
67366    );
67367    copyNodeContent(apNew[0], pParent, &rc);
67368    freePage(apNew[0], &rc);
67369  }else if( ISAUTOVACUUM && !leafCorrection ){
67370    /* Fix the pointer map entries associated with the right-child of each
67371    ** sibling page. All other pointer map entries have already been taken
67372    ** care of.  */
67373    for(i=0; i<nNew; i++){
67374      u32 key = get4byte(&apNew[i]->aData[8]);
67375      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
67376    }
67377  }
67378
67379  assert( pParent->isInit );
67380  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
67381          nOld, nNew, b.nCell));
67382
67383  /* Free any old pages that were not reused as new pages.
67384  */
67385  for(i=nNew; i<nOld; i++){
67386    freePage(apOld[i], &rc);
67387  }
67388
67389#if 0
67390  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
67391    /* The ptrmapCheckPages() contains assert() statements that verify that
67392    ** all pointer map pages are set correctly. This is helpful while
67393    ** debugging. This is usually disabled because a corrupt database may
67394    ** cause an assert() statement to fail.  */
67395    ptrmapCheckPages(apNew, nNew);
67396    ptrmapCheckPages(&pParent, 1);
67397  }
67398#endif
67399
67400  /*
67401  ** Cleanup before returning.
67402  */
67403balance_cleanup:
67404  sqlite3ScratchFree(b.apCell);
67405  for(i=0; i<nOld; i++){
67406    releasePage(apOld[i]);
67407  }
67408  for(i=0; i<nNew; i++){
67409    releasePage(apNew[i]);
67410  }
67411
67412  return rc;
67413}
67414
67415
67416/*
67417** This function is called when the root page of a b-tree structure is
67418** overfull (has one or more overflow pages).
67419**
67420** A new child page is allocated and the contents of the current root
67421** page, including overflow cells, are copied into the child. The root
67422** page is then overwritten to make it an empty page with the right-child
67423** pointer pointing to the new page.
67424**
67425** Before returning, all pointer-map entries corresponding to pages
67426** that the new child-page now contains pointers to are updated. The
67427** entry corresponding to the new right-child pointer of the root
67428** page is also updated.
67429**
67430** If successful, *ppChild is set to contain a reference to the child
67431** page and SQLITE_OK is returned. In this case the caller is required
67432** to call releasePage() on *ppChild exactly once. If an error occurs,
67433** an error code is returned and *ppChild is set to 0.
67434*/
67435static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
67436  int rc;                        /* Return value from subprocedures */
67437  MemPage *pChild = 0;           /* Pointer to a new child page */
67438  Pgno pgnoChild = 0;            /* Page number of the new child page */
67439  BtShared *pBt = pRoot->pBt;    /* The BTree */
67440
67441  assert( pRoot->nOverflow>0 );
67442  assert( sqlite3_mutex_held(pBt->mutex) );
67443
67444  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
67445  ** page that will become the new right-child of pPage. Copy the contents
67446  ** of the node stored on pRoot into the new child page.
67447  */
67448  rc = sqlite3PagerWrite(pRoot->pDbPage);
67449  if( rc==SQLITE_OK ){
67450    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
67451    copyNodeContent(pRoot, pChild, &rc);
67452    if( ISAUTOVACUUM ){
67453      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
67454    }
67455  }
67456  if( rc ){
67457    *ppChild = 0;
67458    releasePage(pChild);
67459    return rc;
67460  }
67461  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
67462  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
67463  assert( pChild->nCell==pRoot->nCell );
67464
67465  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
67466
67467  /* Copy the overflow cells from pRoot to pChild */
67468  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
67469         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
67470  memcpy(pChild->apOvfl, pRoot->apOvfl,
67471         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
67472  pChild->nOverflow = pRoot->nOverflow;
67473
67474  /* Zero the contents of pRoot. Then install pChild as the right-child. */
67475  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
67476  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
67477
67478  *ppChild = pChild;
67479  return SQLITE_OK;
67480}
67481
67482/*
67483** The page that pCur currently points to has just been modified in
67484** some way. This function figures out if this modification means the
67485** tree needs to be balanced, and if so calls the appropriate balancing
67486** routine. Balancing routines are:
67487**
67488**   balance_quick()
67489**   balance_deeper()
67490**   balance_nonroot()
67491*/
67492static int balance(BtCursor *pCur){
67493  int rc = SQLITE_OK;
67494  const int nMin = pCur->pBt->usableSize * 2 / 3;
67495  u8 aBalanceQuickSpace[13];
67496  u8 *pFree = 0;
67497
67498  VVA_ONLY( int balance_quick_called = 0 );
67499  VVA_ONLY( int balance_deeper_called = 0 );
67500
67501  do {
67502    int iPage = pCur->iPage;
67503    MemPage *pPage = pCur->apPage[iPage];
67504
67505    if( iPage==0 ){
67506      if( pPage->nOverflow ){
67507        /* The root page of the b-tree is overfull. In this case call the
67508        ** balance_deeper() function to create a new child for the root-page
67509        ** and copy the current contents of the root-page to it. The
67510        ** next iteration of the do-loop will balance the child page.
67511        */
67512        assert( balance_deeper_called==0 );
67513        VVA_ONLY( balance_deeper_called++ );
67514        rc = balance_deeper(pPage, &pCur->apPage[1]);
67515        if( rc==SQLITE_OK ){
67516          pCur->iPage = 1;
67517          pCur->ix = 0;
67518          pCur->aiIdx[0] = 0;
67519          assert( pCur->apPage[1]->nOverflow );
67520        }
67521      }else{
67522        break;
67523      }
67524    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
67525      break;
67526    }else{
67527      MemPage * const pParent = pCur->apPage[iPage-1];
67528      int const iIdx = pCur->aiIdx[iPage-1];
67529
67530      rc = sqlite3PagerWrite(pParent->pDbPage);
67531      if( rc==SQLITE_OK ){
67532#ifndef SQLITE_OMIT_QUICKBALANCE
67533        if( pPage->intKeyLeaf
67534         && pPage->nOverflow==1
67535         && pPage->aiOvfl[0]==pPage->nCell
67536         && pParent->pgno!=1
67537         && pParent->nCell==iIdx
67538        ){
67539          /* Call balance_quick() to create a new sibling of pPage on which
67540          ** to store the overflow cell. balance_quick() inserts a new cell
67541          ** into pParent, which may cause pParent overflow. If this
67542          ** happens, the next iteration of the do-loop will balance pParent
67543          ** use either balance_nonroot() or balance_deeper(). Until this
67544          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
67545          ** buffer.
67546          **
67547          ** The purpose of the following assert() is to check that only a
67548          ** single call to balance_quick() is made for each call to this
67549          ** function. If this were not verified, a subtle bug involving reuse
67550          ** of the aBalanceQuickSpace[] might sneak in.
67551          */
67552          assert( balance_quick_called==0 );
67553          VVA_ONLY( balance_quick_called++ );
67554          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
67555        }else
67556#endif
67557        {
67558          /* In this case, call balance_nonroot() to redistribute cells
67559          ** between pPage and up to 2 of its sibling pages. This involves
67560          ** modifying the contents of pParent, which may cause pParent to
67561          ** become overfull or underfull. The next iteration of the do-loop
67562          ** will balance the parent page to correct this.
67563          **
67564          ** If the parent page becomes overfull, the overflow cell or cells
67565          ** are stored in the pSpace buffer allocated immediately below.
67566          ** A subsequent iteration of the do-loop will deal with this by
67567          ** calling balance_nonroot() (balance_deeper() may be called first,
67568          ** but it doesn't deal with overflow cells - just moves them to a
67569          ** different page). Once this subsequent call to balance_nonroot()
67570          ** has completed, it is safe to release the pSpace buffer used by
67571          ** the previous call, as the overflow cell data will have been
67572          ** copied either into the body of a database page or into the new
67573          ** pSpace buffer passed to the latter call to balance_nonroot().
67574          */
67575          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
67576          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
67577                               pCur->hints&BTREE_BULKLOAD);
67578          if( pFree ){
67579            /* If pFree is not NULL, it points to the pSpace buffer used
67580            ** by a previous call to balance_nonroot(). Its contents are
67581            ** now stored either on real database pages or within the
67582            ** new pSpace buffer, so it may be safely freed here. */
67583            sqlite3PageFree(pFree);
67584          }
67585
67586          /* The pSpace buffer will be freed after the next call to
67587          ** balance_nonroot(), or just before this function returns, whichever
67588          ** comes first. */
67589          pFree = pSpace;
67590        }
67591      }
67592
67593      pPage->nOverflow = 0;
67594
67595      /* The next iteration of the do-loop balances the parent page. */
67596      releasePage(pPage);
67597      pCur->iPage--;
67598      assert( pCur->iPage>=0 );
67599    }
67600  }while( rc==SQLITE_OK );
67601
67602  if( pFree ){
67603    sqlite3PageFree(pFree);
67604  }
67605  return rc;
67606}
67607
67608
67609/*
67610** Insert a new record into the BTree.  The content of the new record
67611** is described by the pX object.  The pCur cursor is used only to
67612** define what table the record should be inserted into, and is left
67613** pointing at a random location.
67614**
67615** For a table btree (used for rowid tables), only the pX.nKey value of
67616** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
67617** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
67618** hold the content of the row.
67619**
67620** For an index btree (used for indexes and WITHOUT ROWID tables), the
67621** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
67622** pX.pData,nData,nZero fields must be zero.
67623**
67624** If the seekResult parameter is non-zero, then a successful call to
67625** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
67626** been performed.  In other words, if seekResult!=0 then the cursor
67627** is currently pointing to a cell that will be adjacent to the cell
67628** to be inserted.  If seekResult<0 then pCur points to a cell that is
67629** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
67630** that is larger than (pKey,nKey).
67631**
67632** If seekResult==0, that means pCur is pointing at some unknown location.
67633** In that case, this routine must seek the cursor to the correct insertion
67634** point for (pKey,nKey) before doing the insertion.  For index btrees,
67635** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
67636** key values and pX->aMem can be used instead of pX->pKey to avoid having
67637** to decode the key.
67638*/
67639SQLITE_PRIVATE int sqlite3BtreeInsert(
67640  BtCursor *pCur,                /* Insert data into the table of this cursor */
67641  const BtreePayload *pX,        /* Content of the row to be inserted */
67642  int flags,                     /* True if this is likely an append */
67643  int seekResult                 /* Result of prior MovetoUnpacked() call */
67644){
67645  int rc;
67646  int loc = seekResult;          /* -1: before desired location  +1: after */
67647  int szNew = 0;
67648  int idx;
67649  MemPage *pPage;
67650  Btree *p = pCur->pBtree;
67651  BtShared *pBt = p->pBt;
67652  unsigned char *oldCell;
67653  unsigned char *newCell = 0;
67654
67655  assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
67656
67657  if( pCur->eState==CURSOR_FAULT ){
67658    assert( pCur->skipNext!=SQLITE_OK );
67659    return pCur->skipNext;
67660  }
67661
67662  assert( cursorOwnsBtShared(pCur) );
67663  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
67664              && pBt->inTransaction==TRANS_WRITE
67665              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
67666  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
67667
67668  /* Assert that the caller has been consistent. If this cursor was opened
67669  ** expecting an index b-tree, then the caller should be inserting blob
67670  ** keys with no associated data. If the cursor was opened expecting an
67671  ** intkey table, the caller should be inserting integer keys with a
67672  ** blob of associated data.  */
67673  assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
67674
67675  /* Save the positions of any other cursors open on this table.
67676  **
67677  ** In some cases, the call to btreeMoveto() below is a no-op. For
67678  ** example, when inserting data into a table with auto-generated integer
67679  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
67680  ** integer key to use. It then calls this function to actually insert the
67681  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
67682  ** that the cursor is already where it needs to be and returns without
67683  ** doing any work. To avoid thwarting these optimizations, it is important
67684  ** not to clear the cursor here.
67685  */
67686  if( pCur->curFlags & BTCF_Multiple ){
67687    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
67688    if( rc ) return rc;
67689  }
67690
67691  if( pCur->pKeyInfo==0 ){
67692    assert( pX->pKey==0 );
67693    /* If this is an insert into a table b-tree, invalidate any incrblob
67694    ** cursors open on the row being replaced */
67695    invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
67696
67697    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
67698    ** to a row with the same key as the new entry being inserted.  */
67699    assert( (flags & BTREE_SAVEPOSITION)==0 ||
67700            ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
67701
67702    /* If the cursor is currently on the last row and we are appending a
67703    ** new row onto the end, set the "loc" to avoid an unnecessary
67704    ** btreeMoveto() call */
67705    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
67706      loc = 0;
67707    }else if( loc==0 ){
67708      rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
67709      if( rc ) return rc;
67710    }
67711  }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
67712    if( pX->nMem ){
67713      UnpackedRecord r;
67714      r.pKeyInfo = pCur->pKeyInfo;
67715      r.aMem = pX->aMem;
67716      r.nField = pX->nMem;
67717      r.default_rc = 0;
67718      r.errCode = 0;
67719      r.r1 = 0;
67720      r.r2 = 0;
67721      r.eqSeen = 0;
67722      rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
67723    }else{
67724      rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
67725    }
67726    if( rc ) return rc;
67727  }
67728  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
67729
67730  pPage = pCur->apPage[pCur->iPage];
67731  assert( pPage->intKey || pX->nKey>=0 );
67732  assert( pPage->leaf || !pPage->intKey );
67733
67734  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
67735          pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
67736          loc==0 ? "overwrite" : "new entry"));
67737  assert( pPage->isInit );
67738  newCell = pBt->pTmpSpace;
67739  assert( newCell!=0 );
67740  rc = fillInCell(pPage, newCell, pX, &szNew);
67741  if( rc ) goto end_insert;
67742  assert( szNew==pPage->xCellSize(pPage, newCell) );
67743  assert( szNew <= MX_CELL_SIZE(pBt) );
67744  idx = pCur->ix;
67745  if( loc==0 ){
67746    CellInfo info;
67747    assert( idx<pPage->nCell );
67748    rc = sqlite3PagerWrite(pPage->pDbPage);
67749    if( rc ){
67750      goto end_insert;
67751    }
67752    oldCell = findCell(pPage, idx);
67753    if( !pPage->leaf ){
67754      memcpy(newCell, oldCell, 4);
67755    }
67756    rc = clearCell(pPage, oldCell, &info);
67757    if( info.nSize==szNew && info.nLocal==info.nPayload
67758     && (!ISAUTOVACUUM || szNew<pPage->minLocal)
67759    ){
67760      /* Overwrite the old cell with the new if they are the same size.
67761      ** We could also try to do this if the old cell is smaller, then add
67762      ** the leftover space to the free list.  But experiments show that
67763      ** doing that is no faster then skipping this optimization and just
67764      ** calling dropCell() and insertCell().
67765      **
67766      ** This optimization cannot be used on an autovacuum database if the
67767      ** new entry uses overflow pages, as the insertCell() call below is
67768      ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
67769      assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
67770      if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
67771      memcpy(oldCell, newCell, szNew);
67772      return SQLITE_OK;
67773    }
67774    dropCell(pPage, idx, info.nSize, &rc);
67775    if( rc ) goto end_insert;
67776  }else if( loc<0 && pPage->nCell>0 ){
67777    assert( pPage->leaf );
67778    idx = ++pCur->ix;
67779    pCur->curFlags &= ~BTCF_ValidNKey;
67780  }else{
67781    assert( pPage->leaf );
67782  }
67783  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
67784  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
67785  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
67786
67787  /* If no error has occurred and pPage has an overflow cell, call balance()
67788  ** to redistribute the cells within the tree. Since balance() may move
67789  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
67790  ** variables.
67791  **
67792  ** Previous versions of SQLite called moveToRoot() to move the cursor
67793  ** back to the root page as balance() used to invalidate the contents
67794  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
67795  ** set the cursor state to "invalid". This makes common insert operations
67796  ** slightly faster.
67797  **
67798  ** There is a subtle but important optimization here too. When inserting
67799  ** multiple records into an intkey b-tree using a single cursor (as can
67800  ** happen while processing an "INSERT INTO ... SELECT" statement), it
67801  ** is advantageous to leave the cursor pointing to the last entry in
67802  ** the b-tree if possible. If the cursor is left pointing to the last
67803  ** entry in the table, and the next row inserted has an integer key
67804  ** larger than the largest existing key, it is possible to insert the
67805  ** row without seeking the cursor. This can be a big performance boost.
67806  */
67807  pCur->info.nSize = 0;
67808  if( pPage->nOverflow ){
67809    assert( rc==SQLITE_OK );
67810    pCur->curFlags &= ~(BTCF_ValidNKey);
67811    rc = balance(pCur);
67812
67813    /* Must make sure nOverflow is reset to zero even if the balance()
67814    ** fails. Internal data structure corruption will result otherwise.
67815    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
67816    ** from trying to save the current position of the cursor.  */
67817    pCur->apPage[pCur->iPage]->nOverflow = 0;
67818    pCur->eState = CURSOR_INVALID;
67819    if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
67820      rc = moveToRoot(pCur);
67821      if( pCur->pKeyInfo ){
67822        assert( pCur->pKey==0 );
67823        pCur->pKey = sqlite3Malloc( pX->nKey );
67824        if( pCur->pKey==0 ){
67825          rc = SQLITE_NOMEM;
67826        }else{
67827          memcpy(pCur->pKey, pX->pKey, pX->nKey);
67828        }
67829      }
67830      pCur->eState = CURSOR_REQUIRESEEK;
67831      pCur->nKey = pX->nKey;
67832    }
67833  }
67834  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
67835
67836end_insert:
67837  return rc;
67838}
67839
67840/*
67841** Delete the entry that the cursor is pointing to.
67842**
67843** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
67844** the cursor is left pointing at an arbitrary location after the delete.
67845** But if that bit is set, then the cursor is left in a state such that
67846** the next call to BtreeNext() or BtreePrev() moves it to the same row
67847** as it would have been on if the call to BtreeDelete() had been omitted.
67848**
67849** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
67850** associated with a single table entry and its indexes.  Only one of those
67851** deletes is considered the "primary" delete.  The primary delete occurs
67852** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
67853** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
67854** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
67855** but which might be used by alternative storage engines.
67856*/
67857SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
67858  Btree *p = pCur->pBtree;
67859  BtShared *pBt = p->pBt;
67860  int rc;                              /* Return code */
67861  MemPage *pPage;                      /* Page to delete cell from */
67862  unsigned char *pCell;                /* Pointer to cell to delete */
67863  int iCellIdx;                        /* Index of cell to delete */
67864  int iCellDepth;                      /* Depth of node containing pCell */
67865  CellInfo info;                       /* Size of the cell being deleted */
67866  int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
67867  u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
67868
67869  assert( cursorOwnsBtShared(pCur) );
67870  assert( pBt->inTransaction==TRANS_WRITE );
67871  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
67872  assert( pCur->curFlags & BTCF_WriteFlag );
67873  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
67874  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
67875  assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
67876  assert( pCur->eState==CURSOR_VALID );
67877  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
67878
67879  iCellDepth = pCur->iPage;
67880  iCellIdx = pCur->ix;
67881  pPage = pCur->apPage[iCellDepth];
67882  pCell = findCell(pPage, iCellIdx);
67883
67884  /* If the bPreserve flag is set to true, then the cursor position must
67885  ** be preserved following this delete operation. If the current delete
67886  ** will cause a b-tree rebalance, then this is done by saving the cursor
67887  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
67888  ** returning.
67889  **
67890  ** Or, if the current delete will not cause a rebalance, then the cursor
67891  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
67892  ** before or after the deleted entry. In this case set bSkipnext to true.  */
67893  if( bPreserve ){
67894    if( !pPage->leaf
67895     || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
67896    ){
67897      /* A b-tree rebalance will be required after deleting this entry.
67898      ** Save the cursor key.  */
67899      rc = saveCursorKey(pCur);
67900      if( rc ) return rc;
67901    }else{
67902      bSkipnext = 1;
67903    }
67904  }
67905
67906  /* If the page containing the entry to delete is not a leaf page, move
67907  ** the cursor to the largest entry in the tree that is smaller than
67908  ** the entry being deleted. This cell will replace the cell being deleted
67909  ** from the internal node. The 'previous' entry is used for this instead
67910  ** of the 'next' entry, as the previous entry is always a part of the
67911  ** sub-tree headed by the child page of the cell being deleted. This makes
67912  ** balancing the tree following the delete operation easier.  */
67913  if( !pPage->leaf ){
67914    rc = sqlite3BtreePrevious(pCur, 0);
67915    assert( rc!=SQLITE_DONE );
67916    if( rc ) return rc;
67917  }
67918
67919  /* Save the positions of any other cursors open on this table before
67920  ** making any modifications.  */
67921  if( pCur->curFlags & BTCF_Multiple ){
67922    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
67923    if( rc ) return rc;
67924  }
67925
67926  /* If this is a delete operation to remove a row from a table b-tree,
67927  ** invalidate any incrblob cursors open on the row being deleted.  */
67928  if( pCur->pKeyInfo==0 ){
67929    invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
67930  }
67931
67932  /* Make the page containing the entry to be deleted writable. Then free any
67933  ** overflow pages associated with the entry and finally remove the cell
67934  ** itself from within the page.  */
67935  rc = sqlite3PagerWrite(pPage->pDbPage);
67936  if( rc ) return rc;
67937  rc = clearCell(pPage, pCell, &info);
67938  dropCell(pPage, iCellIdx, info.nSize, &rc);
67939  if( rc ) return rc;
67940
67941  /* If the cell deleted was not located on a leaf page, then the cursor
67942  ** is currently pointing to the largest entry in the sub-tree headed
67943  ** by the child-page of the cell that was just deleted from an internal
67944  ** node. The cell from the leaf node needs to be moved to the internal
67945  ** node to replace the deleted cell.  */
67946  if( !pPage->leaf ){
67947    MemPage *pLeaf = pCur->apPage[pCur->iPage];
67948    int nCell;
67949    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
67950    unsigned char *pTmp;
67951
67952    pCell = findCell(pLeaf, pLeaf->nCell-1);
67953    if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
67954    nCell = pLeaf->xCellSize(pLeaf, pCell);
67955    assert( MX_CELL_SIZE(pBt) >= nCell );
67956    pTmp = pBt->pTmpSpace;
67957    assert( pTmp!=0 );
67958    rc = sqlite3PagerWrite(pLeaf->pDbPage);
67959    if( rc==SQLITE_OK ){
67960      insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
67961    }
67962    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
67963    if( rc ) return rc;
67964  }
67965
67966  /* Balance the tree. If the entry deleted was located on a leaf page,
67967  ** then the cursor still points to that page. In this case the first
67968  ** call to balance() repairs the tree, and the if(...) condition is
67969  ** never true.
67970  **
67971  ** Otherwise, if the entry deleted was on an internal node page, then
67972  ** pCur is pointing to the leaf page from which a cell was removed to
67973  ** replace the cell deleted from the internal node. This is slightly
67974  ** tricky as the leaf node may be underfull, and the internal node may
67975  ** be either under or overfull. In this case run the balancing algorithm
67976  ** on the leaf node first. If the balance proceeds far enough up the
67977  ** tree that we can be sure that any problem in the internal node has
67978  ** been corrected, so be it. Otherwise, after balancing the leaf node,
67979  ** walk the cursor up the tree to the internal node and balance it as
67980  ** well.  */
67981  rc = balance(pCur);
67982  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
67983    while( pCur->iPage>iCellDepth ){
67984      releasePage(pCur->apPage[pCur->iPage--]);
67985    }
67986    rc = balance(pCur);
67987  }
67988
67989  if( rc==SQLITE_OK ){
67990    if( bSkipnext ){
67991      assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
67992      assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
67993      assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
67994      pCur->eState = CURSOR_SKIPNEXT;
67995      if( iCellIdx>=pPage->nCell ){
67996        pCur->skipNext = -1;
67997        pCur->ix = pPage->nCell-1;
67998      }else{
67999        pCur->skipNext = 1;
68000      }
68001    }else{
68002      rc = moveToRoot(pCur);
68003      if( bPreserve ){
68004        pCur->eState = CURSOR_REQUIRESEEK;
68005      }
68006    }
68007  }
68008  return rc;
68009}
68010
68011/*
68012** Create a new BTree table.  Write into *piTable the page
68013** number for the root page of the new table.
68014**
68015** The type of type is determined by the flags parameter.  Only the
68016** following values of flags are currently in use.  Other values for
68017** flags might not work:
68018**
68019**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
68020**     BTREE_ZERODATA                  Used for SQL indices
68021*/
68022static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
68023  BtShared *pBt = p->pBt;
68024  MemPage *pRoot;
68025  Pgno pgnoRoot;
68026  int rc;
68027  int ptfFlags;          /* Page-type flage for the root page of new table */
68028
68029  assert( sqlite3BtreeHoldsMutex(p) );
68030  assert( pBt->inTransaction==TRANS_WRITE );
68031  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
68032
68033#ifdef SQLITE_OMIT_AUTOVACUUM
68034  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
68035  if( rc ){
68036    return rc;
68037  }
68038#else
68039  if( pBt->autoVacuum ){
68040    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
68041    MemPage *pPageMove; /* The page to move to. */
68042
68043    /* Creating a new table may probably require moving an existing database
68044    ** to make room for the new tables root page. In case this page turns
68045    ** out to be an overflow page, delete all overflow page-map caches
68046    ** held by open cursors.
68047    */
68048    invalidateAllOverflowCache(pBt);
68049
68050    /* Read the value of meta[3] from the database to determine where the
68051    ** root page of the new table should go. meta[3] is the largest root-page
68052    ** created so far, so the new root-page is (meta[3]+1).
68053    */
68054    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
68055    pgnoRoot++;
68056
68057    /* The new root-page may not be allocated on a pointer-map page, or the
68058    ** PENDING_BYTE page.
68059    */
68060    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
68061        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
68062      pgnoRoot++;
68063    }
68064    assert( pgnoRoot>=3 || CORRUPT_DB );
68065    testcase( pgnoRoot<3 );
68066
68067    /* Allocate a page. The page that currently resides at pgnoRoot will
68068    ** be moved to the allocated page (unless the allocated page happens
68069    ** to reside at pgnoRoot).
68070    */
68071    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
68072    if( rc!=SQLITE_OK ){
68073      return rc;
68074    }
68075
68076    if( pgnoMove!=pgnoRoot ){
68077      /* pgnoRoot is the page that will be used for the root-page of
68078      ** the new table (assuming an error did not occur). But we were
68079      ** allocated pgnoMove. If required (i.e. if it was not allocated
68080      ** by extending the file), the current page at position pgnoMove
68081      ** is already journaled.
68082      */
68083      u8 eType = 0;
68084      Pgno iPtrPage = 0;
68085
68086      /* Save the positions of any open cursors. This is required in
68087      ** case they are holding a reference to an xFetch reference
68088      ** corresponding to page pgnoRoot.  */
68089      rc = saveAllCursors(pBt, 0, 0);
68090      releasePage(pPageMove);
68091      if( rc!=SQLITE_OK ){
68092        return rc;
68093      }
68094
68095      /* Move the page currently at pgnoRoot to pgnoMove. */
68096      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
68097      if( rc!=SQLITE_OK ){
68098        return rc;
68099      }
68100      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
68101      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
68102        rc = SQLITE_CORRUPT_BKPT;
68103      }
68104      if( rc!=SQLITE_OK ){
68105        releasePage(pRoot);
68106        return rc;
68107      }
68108      assert( eType!=PTRMAP_ROOTPAGE );
68109      assert( eType!=PTRMAP_FREEPAGE );
68110      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
68111      releasePage(pRoot);
68112
68113      /* Obtain the page at pgnoRoot */
68114      if( rc!=SQLITE_OK ){
68115        return rc;
68116      }
68117      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
68118      if( rc!=SQLITE_OK ){
68119        return rc;
68120      }
68121      rc = sqlite3PagerWrite(pRoot->pDbPage);
68122      if( rc!=SQLITE_OK ){
68123        releasePage(pRoot);
68124        return rc;
68125      }
68126    }else{
68127      pRoot = pPageMove;
68128    }
68129
68130    /* Update the pointer-map and meta-data with the new root-page number. */
68131    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
68132    if( rc ){
68133      releasePage(pRoot);
68134      return rc;
68135    }
68136
68137    /* When the new root page was allocated, page 1 was made writable in
68138    ** order either to increase the database filesize, or to decrement the
68139    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
68140    */
68141    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
68142    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
68143    if( NEVER(rc) ){
68144      releasePage(pRoot);
68145      return rc;
68146    }
68147
68148  }else{
68149    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
68150    if( rc ) return rc;
68151  }
68152#endif
68153  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
68154  if( createTabFlags & BTREE_INTKEY ){
68155    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
68156  }else{
68157    ptfFlags = PTF_ZERODATA | PTF_LEAF;
68158  }
68159  zeroPage(pRoot, ptfFlags);
68160  sqlite3PagerUnref(pRoot->pDbPage);
68161  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
68162  *piTable = (int)pgnoRoot;
68163  return SQLITE_OK;
68164}
68165SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
68166  int rc;
68167  sqlite3BtreeEnter(p);
68168  rc = btreeCreateTable(p, piTable, flags);
68169  sqlite3BtreeLeave(p);
68170  return rc;
68171}
68172
68173/*
68174** Erase the given database page and all its children.  Return
68175** the page to the freelist.
68176*/
68177static int clearDatabasePage(
68178  BtShared *pBt,           /* The BTree that contains the table */
68179  Pgno pgno,               /* Page number to clear */
68180  int freePageFlag,        /* Deallocate page if true */
68181  int *pnChange            /* Add number of Cells freed to this counter */
68182){
68183  MemPage *pPage;
68184  int rc;
68185  unsigned char *pCell;
68186  int i;
68187  int hdr;
68188  CellInfo info;
68189
68190  assert( sqlite3_mutex_held(pBt->mutex) );
68191  if( pgno>btreePagecount(pBt) ){
68192    return SQLITE_CORRUPT_BKPT;
68193  }
68194  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
68195  if( rc ) return rc;
68196  if( pPage->bBusy ){
68197    rc = SQLITE_CORRUPT_BKPT;
68198    goto cleardatabasepage_out;
68199  }
68200  pPage->bBusy = 1;
68201  hdr = pPage->hdrOffset;
68202  for(i=0; i<pPage->nCell; i++){
68203    pCell = findCell(pPage, i);
68204    if( !pPage->leaf ){
68205      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
68206      if( rc ) goto cleardatabasepage_out;
68207    }
68208    rc = clearCell(pPage, pCell, &info);
68209    if( rc ) goto cleardatabasepage_out;
68210  }
68211  if( !pPage->leaf ){
68212    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
68213    if( rc ) goto cleardatabasepage_out;
68214  }else if( pnChange ){
68215    assert( pPage->intKey || CORRUPT_DB );
68216    testcase( !pPage->intKey );
68217    *pnChange += pPage->nCell;
68218  }
68219  if( freePageFlag ){
68220    freePage(pPage, &rc);
68221  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
68222    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
68223  }
68224
68225cleardatabasepage_out:
68226  pPage->bBusy = 0;
68227  releasePage(pPage);
68228  return rc;
68229}
68230
68231/*
68232** Delete all information from a single table in the database.  iTable is
68233** the page number of the root of the table.  After this routine returns,
68234** the root page is empty, but still exists.
68235**
68236** This routine will fail with SQLITE_LOCKED if there are any open
68237** read cursors on the table.  Open write cursors are moved to the
68238** root of the table.
68239**
68240** If pnChange is not NULL, then table iTable must be an intkey table. The
68241** integer value pointed to by pnChange is incremented by the number of
68242** entries in the table.
68243*/
68244SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
68245  int rc;
68246  BtShared *pBt = p->pBt;
68247  sqlite3BtreeEnter(p);
68248  assert( p->inTrans==TRANS_WRITE );
68249
68250  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
68251
68252  if( SQLITE_OK==rc ){
68253    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
68254    ** is the root of a table b-tree - if it is not, the following call is
68255    ** a no-op).  */
68256    invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
68257    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
68258  }
68259  sqlite3BtreeLeave(p);
68260  return rc;
68261}
68262
68263/*
68264** Delete all information from the single table that pCur is open on.
68265**
68266** This routine only work for pCur on an ephemeral table.
68267*/
68268SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
68269  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
68270}
68271
68272/*
68273** Erase all information in a table and add the root of the table to
68274** the freelist.  Except, the root of the principle table (the one on
68275** page 1) is never added to the freelist.
68276**
68277** This routine will fail with SQLITE_LOCKED if there are any open
68278** cursors on the table.
68279**
68280** If AUTOVACUUM is enabled and the page at iTable is not the last
68281** root page in the database file, then the last root page
68282** in the database file is moved into the slot formerly occupied by
68283** iTable and that last slot formerly occupied by the last root page
68284** is added to the freelist instead of iTable.  In this say, all
68285** root pages are kept at the beginning of the database file, which
68286** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
68287** page number that used to be the last root page in the file before
68288** the move.  If no page gets moved, *piMoved is set to 0.
68289** The last root page is recorded in meta[3] and the value of
68290** meta[3] is updated by this procedure.
68291*/
68292static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
68293  int rc;
68294  MemPage *pPage = 0;
68295  BtShared *pBt = p->pBt;
68296
68297  assert( sqlite3BtreeHoldsMutex(p) );
68298  assert( p->inTrans==TRANS_WRITE );
68299  assert( iTable>=2 );
68300
68301  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
68302  if( rc ) return rc;
68303  rc = sqlite3BtreeClearTable(p, iTable, 0);
68304  if( rc ){
68305    releasePage(pPage);
68306    return rc;
68307  }
68308
68309  *piMoved = 0;
68310
68311#ifdef SQLITE_OMIT_AUTOVACUUM
68312  freePage(pPage, &rc);
68313  releasePage(pPage);
68314#else
68315  if( pBt->autoVacuum ){
68316    Pgno maxRootPgno;
68317    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
68318
68319    if( iTable==maxRootPgno ){
68320      /* If the table being dropped is the table with the largest root-page
68321      ** number in the database, put the root page on the free list.
68322      */
68323      freePage(pPage, &rc);
68324      releasePage(pPage);
68325      if( rc!=SQLITE_OK ){
68326        return rc;
68327      }
68328    }else{
68329      /* The table being dropped does not have the largest root-page
68330      ** number in the database. So move the page that does into the
68331      ** gap left by the deleted root-page.
68332      */
68333      MemPage *pMove;
68334      releasePage(pPage);
68335      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
68336      if( rc!=SQLITE_OK ){
68337        return rc;
68338      }
68339      rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
68340      releasePage(pMove);
68341      if( rc!=SQLITE_OK ){
68342        return rc;
68343      }
68344      pMove = 0;
68345      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
68346      freePage(pMove, &rc);
68347      releasePage(pMove);
68348      if( rc!=SQLITE_OK ){
68349        return rc;
68350      }
68351      *piMoved = maxRootPgno;
68352    }
68353
68354    /* Set the new 'max-root-page' value in the database header. This
68355    ** is the old value less one, less one more if that happens to
68356    ** be a root-page number, less one again if that is the
68357    ** PENDING_BYTE_PAGE.
68358    */
68359    maxRootPgno--;
68360    while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
68361           || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
68362      maxRootPgno--;
68363    }
68364    assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
68365
68366    rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
68367  }else{
68368    freePage(pPage, &rc);
68369    releasePage(pPage);
68370  }
68371#endif
68372  return rc;
68373}
68374SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
68375  int rc;
68376  sqlite3BtreeEnter(p);
68377  rc = btreeDropTable(p, iTable, piMoved);
68378  sqlite3BtreeLeave(p);
68379  return rc;
68380}
68381
68382
68383/*
68384** This function may only be called if the b-tree connection already
68385** has a read or write transaction open on the database.
68386**
68387** Read the meta-information out of a database file.  Meta[0]
68388** is the number of free pages currently in the database.  Meta[1]
68389** through meta[15] are available for use by higher layers.  Meta[0]
68390** is read-only, the others are read/write.
68391**
68392** The schema layer numbers meta values differently.  At the schema
68393** layer (and the SetCookie and ReadCookie opcodes) the number of
68394** free pages is not visible.  So Cookie[0] is the same as Meta[1].
68395**
68396** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
68397** of reading the value out of the header, it instead loads the "DataVersion"
68398** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
68399** database file.  It is a number computed by the pager.  But its access
68400** pattern is the same as header meta values, and so it is convenient to
68401** read it from this routine.
68402*/
68403SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
68404  BtShared *pBt = p->pBt;
68405
68406  sqlite3BtreeEnter(p);
68407  assert( p->inTrans>TRANS_NONE );
68408  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
68409  assert( pBt->pPage1 );
68410  assert( idx>=0 && idx<=15 );
68411
68412  if( idx==BTREE_DATA_VERSION ){
68413    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
68414  }else{
68415    *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
68416  }
68417
68418  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
68419  ** database, mark the database as read-only.  */
68420#ifdef SQLITE_OMIT_AUTOVACUUM
68421  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
68422    pBt->btsFlags |= BTS_READ_ONLY;
68423  }
68424#endif
68425
68426  sqlite3BtreeLeave(p);
68427}
68428
68429/*
68430** Write meta-information back into the database.  Meta[0] is
68431** read-only and may not be written.
68432*/
68433SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
68434  BtShared *pBt = p->pBt;
68435  unsigned char *pP1;
68436  int rc;
68437  assert( idx>=1 && idx<=15 );
68438  sqlite3BtreeEnter(p);
68439  assert( p->inTrans==TRANS_WRITE );
68440  assert( pBt->pPage1!=0 );
68441  pP1 = pBt->pPage1->aData;
68442  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
68443  if( rc==SQLITE_OK ){
68444    put4byte(&pP1[36 + idx*4], iMeta);
68445#ifndef SQLITE_OMIT_AUTOVACUUM
68446    if( idx==BTREE_INCR_VACUUM ){
68447      assert( pBt->autoVacuum || iMeta==0 );
68448      assert( iMeta==0 || iMeta==1 );
68449      pBt->incrVacuum = (u8)iMeta;
68450    }
68451#endif
68452  }
68453  sqlite3BtreeLeave(p);
68454  return rc;
68455}
68456
68457#ifndef SQLITE_OMIT_BTREECOUNT
68458/*
68459** The first argument, pCur, is a cursor opened on some b-tree. Count the
68460** number of entries in the b-tree and write the result to *pnEntry.
68461**
68462** SQLITE_OK is returned if the operation is successfully executed.
68463** Otherwise, if an error is encountered (i.e. an IO error or database
68464** corruption) an SQLite error code is returned.
68465*/
68466SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
68467  i64 nEntry = 0;                      /* Value to return in *pnEntry */
68468  int rc;                              /* Return code */
68469
68470  if( pCur->pgnoRoot==0 ){
68471    *pnEntry = 0;
68472    return SQLITE_OK;
68473  }
68474  rc = moveToRoot(pCur);
68475
68476  /* Unless an error occurs, the following loop runs one iteration for each
68477  ** page in the B-Tree structure (not including overflow pages).
68478  */
68479  while( rc==SQLITE_OK ){
68480    int iIdx;                          /* Index of child node in parent */
68481    MemPage *pPage;                    /* Current page of the b-tree */
68482
68483    /* If this is a leaf page or the tree is not an int-key tree, then
68484    ** this page contains countable entries. Increment the entry counter
68485    ** accordingly.
68486    */
68487    pPage = pCur->apPage[pCur->iPage];
68488    if( pPage->leaf || !pPage->intKey ){
68489      nEntry += pPage->nCell;
68490    }
68491
68492    /* pPage is a leaf node. This loop navigates the cursor so that it
68493    ** points to the first interior cell that it points to the parent of
68494    ** the next page in the tree that has not yet been visited. The
68495    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
68496    ** of the page, or to the number of cells in the page if the next page
68497    ** to visit is the right-child of its parent.
68498    **
68499    ** If all pages in the tree have been visited, return SQLITE_OK to the
68500    ** caller.
68501    */
68502    if( pPage->leaf ){
68503      do {
68504        if( pCur->iPage==0 ){
68505          /* All pages of the b-tree have been visited. Return successfully. */
68506          *pnEntry = nEntry;
68507          return moveToRoot(pCur);
68508        }
68509        moveToParent(pCur);
68510      }while ( pCur->ix>=pCur->apPage[pCur->iPage]->nCell );
68511
68512      pCur->ix++;
68513      pPage = pCur->apPage[pCur->iPage];
68514    }
68515
68516    /* Descend to the child node of the cell that the cursor currently
68517    ** points at. This is the right-child if (iIdx==pPage->nCell).
68518    */
68519    iIdx = pCur->ix;
68520    if( iIdx==pPage->nCell ){
68521      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
68522    }else{
68523      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
68524    }
68525  }
68526
68527  /* An error has occurred. Return an error code. */
68528  return rc;
68529}
68530#endif
68531
68532/*
68533** Return the pager associated with a BTree.  This routine is used for
68534** testing and debugging only.
68535*/
68536SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
68537  return p->pBt->pPager;
68538}
68539
68540#ifndef SQLITE_OMIT_INTEGRITY_CHECK
68541/*
68542** Append a message to the error message string.
68543*/
68544static void checkAppendMsg(
68545  IntegrityCk *pCheck,
68546  const char *zFormat,
68547  ...
68548){
68549  va_list ap;
68550  if( !pCheck->mxErr ) return;
68551  pCheck->mxErr--;
68552  pCheck->nErr++;
68553  va_start(ap, zFormat);
68554  if( pCheck->errMsg.nChar ){
68555    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
68556  }
68557  if( pCheck->zPfx ){
68558    sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
68559  }
68560  sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
68561  va_end(ap);
68562  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
68563    pCheck->mallocFailed = 1;
68564  }
68565}
68566#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68567
68568#ifndef SQLITE_OMIT_INTEGRITY_CHECK
68569
68570/*
68571** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
68572** corresponds to page iPg is already set.
68573*/
68574static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
68575  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
68576  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
68577}
68578
68579/*
68580** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
68581*/
68582static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
68583  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
68584  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
68585}
68586
68587
68588/*
68589** Add 1 to the reference count for page iPage.  If this is the second
68590** reference to the page, add an error message to pCheck->zErrMsg.
68591** Return 1 if there are 2 or more references to the page and 0 if
68592** if this is the first reference to the page.
68593**
68594** Also check that the page number is in bounds.
68595*/
68596static int checkRef(IntegrityCk *pCheck, Pgno iPage){
68597  if( iPage==0 ) return 1;
68598  if( iPage>pCheck->nPage ){
68599    checkAppendMsg(pCheck, "invalid page number %d", iPage);
68600    return 1;
68601  }
68602  if( getPageReferenced(pCheck, iPage) ){
68603    checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
68604    return 1;
68605  }
68606  setPageReferenced(pCheck, iPage);
68607  return 0;
68608}
68609
68610#ifndef SQLITE_OMIT_AUTOVACUUM
68611/*
68612** Check that the entry in the pointer-map for page iChild maps to
68613** page iParent, pointer type ptrType. If not, append an error message
68614** to pCheck.
68615*/
68616static void checkPtrmap(
68617  IntegrityCk *pCheck,   /* Integrity check context */
68618  Pgno iChild,           /* Child page number */
68619  u8 eType,              /* Expected pointer map type */
68620  Pgno iParent           /* Expected pointer map parent page number */
68621){
68622  int rc;
68623  u8 ePtrmapType;
68624  Pgno iPtrmapParent;
68625
68626  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
68627  if( rc!=SQLITE_OK ){
68628    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
68629    checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
68630    return;
68631  }
68632
68633  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
68634    checkAppendMsg(pCheck,
68635      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
68636      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
68637  }
68638}
68639#endif
68640
68641/*
68642** Check the integrity of the freelist or of an overflow page list.
68643** Verify that the number of pages on the list is N.
68644*/
68645static void checkList(
68646  IntegrityCk *pCheck,  /* Integrity checking context */
68647  int isFreeList,       /* True for a freelist.  False for overflow page list */
68648  int iPage,            /* Page number for first page in the list */
68649  int N                 /* Expected number of pages in the list */
68650){
68651  int i;
68652  int expected = N;
68653  int iFirst = iPage;
68654  while( N-- > 0 && pCheck->mxErr ){
68655    DbPage *pOvflPage;
68656    unsigned char *pOvflData;
68657    if( iPage<1 ){
68658      checkAppendMsg(pCheck,
68659         "%d of %d pages missing from overflow list starting at %d",
68660          N+1, expected, iFirst);
68661      break;
68662    }
68663    if( checkRef(pCheck, iPage) ) break;
68664    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
68665      checkAppendMsg(pCheck, "failed to get page %d", iPage);
68666      break;
68667    }
68668    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
68669    if( isFreeList ){
68670      int n = get4byte(&pOvflData[4]);
68671#ifndef SQLITE_OMIT_AUTOVACUUM
68672      if( pCheck->pBt->autoVacuum ){
68673        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
68674      }
68675#endif
68676      if( n>(int)pCheck->pBt->usableSize/4-2 ){
68677        checkAppendMsg(pCheck,
68678           "freelist leaf count too big on page %d", iPage);
68679        N--;
68680      }else{
68681        for(i=0; i<n; i++){
68682          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
68683#ifndef SQLITE_OMIT_AUTOVACUUM
68684          if( pCheck->pBt->autoVacuum ){
68685            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
68686          }
68687#endif
68688          checkRef(pCheck, iFreePage);
68689        }
68690        N -= n;
68691      }
68692    }
68693#ifndef SQLITE_OMIT_AUTOVACUUM
68694    else{
68695      /* If this database supports auto-vacuum and iPage is not the last
68696      ** page in this overflow list, check that the pointer-map entry for
68697      ** the following page matches iPage.
68698      */
68699      if( pCheck->pBt->autoVacuum && N>0 ){
68700        i = get4byte(pOvflData);
68701        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
68702      }
68703    }
68704#endif
68705    iPage = get4byte(pOvflData);
68706    sqlite3PagerUnref(pOvflPage);
68707
68708    if( isFreeList && N<(iPage!=0) ){
68709      checkAppendMsg(pCheck, "free-page count in header is too small");
68710    }
68711  }
68712}
68713#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68714
68715/*
68716** An implementation of a min-heap.
68717**
68718** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
68719** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
68720** and aHeap[N*2+1].
68721**
68722** The heap property is this:  Every node is less than or equal to both
68723** of its daughter nodes.  A consequence of the heap property is that the
68724** root node aHeap[1] is always the minimum value currently in the heap.
68725**
68726** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
68727** the heap, preserving the heap property.  The btreeHeapPull() routine
68728** removes the root element from the heap (the minimum value in the heap)
68729** and then moves other nodes around as necessary to preserve the heap
68730** property.
68731**
68732** This heap is used for cell overlap and coverage testing.  Each u32
68733** entry represents the span of a cell or freeblock on a btree page.
68734** The upper 16 bits are the index of the first byte of a range and the
68735** lower 16 bits are the index of the last byte of that range.
68736*/
68737static void btreeHeapInsert(u32 *aHeap, u32 x){
68738  u32 j, i = ++aHeap[0];
68739  aHeap[i] = x;
68740  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
68741    x = aHeap[j];
68742    aHeap[j] = aHeap[i];
68743    aHeap[i] = x;
68744    i = j;
68745  }
68746}
68747static int btreeHeapPull(u32 *aHeap, u32 *pOut){
68748  u32 j, i, x;
68749  if( (x = aHeap[0])==0 ) return 0;
68750  *pOut = aHeap[1];
68751  aHeap[1] = aHeap[x];
68752  aHeap[x] = 0xffffffff;
68753  aHeap[0]--;
68754  i = 1;
68755  while( (j = i*2)<=aHeap[0] ){
68756    if( aHeap[j]>aHeap[j+1] ) j++;
68757    if( aHeap[i]<aHeap[j] ) break;
68758    x = aHeap[i];
68759    aHeap[i] = aHeap[j];
68760    aHeap[j] = x;
68761    i = j;
68762  }
68763  return 1;
68764}
68765
68766#ifndef SQLITE_OMIT_INTEGRITY_CHECK
68767/*
68768** Do various sanity checks on a single page of a tree.  Return
68769** the tree depth.  Root pages return 0.  Parents of root pages
68770** return 1, and so forth.
68771**
68772** These checks are done:
68773**
68774**      1.  Make sure that cells and freeblocks do not overlap
68775**          but combine to completely cover the page.
68776**      2.  Make sure integer cell keys are in order.
68777**      3.  Check the integrity of overflow pages.
68778**      4.  Recursively call checkTreePage on all children.
68779**      5.  Verify that the depth of all children is the same.
68780*/
68781static int checkTreePage(
68782  IntegrityCk *pCheck,  /* Context for the sanity check */
68783  int iPage,            /* Page number of the page to check */
68784  i64 *piMinKey,        /* Write minimum integer primary key here */
68785  i64 maxKey            /* Error if integer primary key greater than this */
68786){
68787  MemPage *pPage = 0;      /* The page being analyzed */
68788  int i;                   /* Loop counter */
68789  int rc;                  /* Result code from subroutine call */
68790  int depth = -1, d2;      /* Depth of a subtree */
68791  int pgno;                /* Page number */
68792  int nFrag;               /* Number of fragmented bytes on the page */
68793  int hdr;                 /* Offset to the page header */
68794  int cellStart;           /* Offset to the start of the cell pointer array */
68795  int nCell;               /* Number of cells */
68796  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
68797  int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
68798                           ** False if IPK must be strictly less than maxKey */
68799  u8 *data;                /* Page content */
68800  u8 *pCell;               /* Cell content */
68801  u8 *pCellIdx;            /* Next element of the cell pointer array */
68802  BtShared *pBt;           /* The BtShared object that owns pPage */
68803  u32 pc;                  /* Address of a cell */
68804  u32 usableSize;          /* Usable size of the page */
68805  u32 contentOffset;       /* Offset to the start of the cell content area */
68806  u32 *heap = 0;           /* Min-heap used for checking cell coverage */
68807  u32 x, prev = 0;         /* Next and previous entry on the min-heap */
68808  const char *saved_zPfx = pCheck->zPfx;
68809  int saved_v1 = pCheck->v1;
68810  int saved_v2 = pCheck->v2;
68811  u8 savedIsInit = 0;
68812
68813  /* Check that the page exists
68814  */
68815  pBt = pCheck->pBt;
68816  usableSize = pBt->usableSize;
68817  if( iPage==0 ) return 0;
68818  if( checkRef(pCheck, iPage) ) return 0;
68819  pCheck->zPfx = "Page %d: ";
68820  pCheck->v1 = iPage;
68821  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
68822    checkAppendMsg(pCheck,
68823       "unable to get the page. error code=%d", rc);
68824    goto end_of_check;
68825  }
68826
68827  /* Clear MemPage.isInit to make sure the corruption detection code in
68828  ** btreeInitPage() is executed.  */
68829  savedIsInit = pPage->isInit;
68830  pPage->isInit = 0;
68831  if( (rc = btreeInitPage(pPage))!=0 ){
68832    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
68833    checkAppendMsg(pCheck,
68834                   "btreeInitPage() returns error code %d", rc);
68835    goto end_of_check;
68836  }
68837  data = pPage->aData;
68838  hdr = pPage->hdrOffset;
68839
68840  /* Set up for cell analysis */
68841  pCheck->zPfx = "On tree page %d cell %d: ";
68842  contentOffset = get2byteNotZero(&data[hdr+5]);
68843  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
68844
68845  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
68846  ** number of cells on the page. */
68847  nCell = get2byte(&data[hdr+3]);
68848  assert( pPage->nCell==nCell );
68849
68850  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
68851  ** immediately follows the b-tree page header. */
68852  cellStart = hdr + 12 - 4*pPage->leaf;
68853  assert( pPage->aCellIdx==&data[cellStart] );
68854  pCellIdx = &data[cellStart + 2*(nCell-1)];
68855
68856  if( !pPage->leaf ){
68857    /* Analyze the right-child page of internal pages */
68858    pgno = get4byte(&data[hdr+8]);
68859#ifndef SQLITE_OMIT_AUTOVACUUM
68860    if( pBt->autoVacuum ){
68861      pCheck->zPfx = "On page %d at right child: ";
68862      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
68863    }
68864#endif
68865    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
68866    keyCanBeEqual = 0;
68867  }else{
68868    /* For leaf pages, the coverage check will occur in the same loop
68869    ** as the other cell checks, so initialize the heap.  */
68870    heap = pCheck->heap;
68871    heap[0] = 0;
68872  }
68873
68874  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
68875  ** integer offsets to the cell contents. */
68876  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
68877    CellInfo info;
68878
68879    /* Check cell size */
68880    pCheck->v2 = i;
68881    assert( pCellIdx==&data[cellStart + i*2] );
68882    pc = get2byteAligned(pCellIdx);
68883    pCellIdx -= 2;
68884    if( pc<contentOffset || pc>usableSize-4 ){
68885      checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
68886                             pc, contentOffset, usableSize-4);
68887      doCoverageCheck = 0;
68888      continue;
68889    }
68890    pCell = &data[pc];
68891    pPage->xParseCell(pPage, pCell, &info);
68892    if( pc+info.nSize>usableSize ){
68893      checkAppendMsg(pCheck, "Extends off end of page");
68894      doCoverageCheck = 0;
68895      continue;
68896    }
68897
68898    /* Check for integer primary key out of range */
68899    if( pPage->intKey ){
68900      if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
68901        checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
68902      }
68903      maxKey = info.nKey;
68904      keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
68905    }
68906
68907    /* Check the content overflow list */
68908    if( info.nPayload>info.nLocal ){
68909      int nPage;       /* Number of pages on the overflow chain */
68910      Pgno pgnoOvfl;   /* First page of the overflow chain */
68911      assert( pc + info.nSize - 4 <= usableSize );
68912      nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
68913      pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
68914#ifndef SQLITE_OMIT_AUTOVACUUM
68915      if( pBt->autoVacuum ){
68916        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
68917      }
68918#endif
68919      checkList(pCheck, 0, pgnoOvfl, nPage);
68920    }
68921
68922    if( !pPage->leaf ){
68923      /* Check sanity of left child page for internal pages */
68924      pgno = get4byte(pCell);
68925#ifndef SQLITE_OMIT_AUTOVACUUM
68926      if( pBt->autoVacuum ){
68927        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
68928      }
68929#endif
68930      d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
68931      keyCanBeEqual = 0;
68932      if( d2!=depth ){
68933        checkAppendMsg(pCheck, "Child page depth differs");
68934        depth = d2;
68935      }
68936    }else{
68937      /* Populate the coverage-checking heap for leaf pages */
68938      btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
68939    }
68940  }
68941  *piMinKey = maxKey;
68942
68943  /* Check for complete coverage of the page
68944  */
68945  pCheck->zPfx = 0;
68946  if( doCoverageCheck && pCheck->mxErr>0 ){
68947    /* For leaf pages, the min-heap has already been initialized and the
68948    ** cells have already been inserted.  But for internal pages, that has
68949    ** not yet been done, so do it now */
68950    if( !pPage->leaf ){
68951      heap = pCheck->heap;
68952      heap[0] = 0;
68953      for(i=nCell-1; i>=0; i--){
68954        u32 size;
68955        pc = get2byteAligned(&data[cellStart+i*2]);
68956        size = pPage->xCellSize(pPage, &data[pc]);
68957        btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
68958      }
68959    }
68960    /* Add the freeblocks to the min-heap
68961    **
68962    ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
68963    ** is the offset of the first freeblock, or zero if there are no
68964    ** freeblocks on the page.
68965    */
68966    i = get2byte(&data[hdr+1]);
68967    while( i>0 ){
68968      int size, j;
68969      assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
68970      size = get2byte(&data[i+2]);
68971      assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
68972      btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
68973      /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
68974      ** big-endian integer which is the offset in the b-tree page of the next
68975      ** freeblock in the chain, or zero if the freeblock is the last on the
68976      ** chain. */
68977      j = get2byte(&data[i]);
68978      /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
68979      ** increasing offset. */
68980      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
68981      assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
68982      i = j;
68983    }
68984    /* Analyze the min-heap looking for overlap between cells and/or
68985    ** freeblocks, and counting the number of untracked bytes in nFrag.
68986    **
68987    ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
68988    ** There is an implied first entry the covers the page header, the cell
68989    ** pointer index, and the gap between the cell pointer index and the start
68990    ** of cell content.
68991    **
68992    ** The loop below pulls entries from the min-heap in order and compares
68993    ** the start_address against the previous end_address.  If there is an
68994    ** overlap, that means bytes are used multiple times.  If there is a gap,
68995    ** that gap is added to the fragmentation count.
68996    */
68997    nFrag = 0;
68998    prev = contentOffset - 1;   /* Implied first min-heap entry */
68999    while( btreeHeapPull(heap,&x) ){
69000      if( (prev&0xffff)>=(x>>16) ){
69001        checkAppendMsg(pCheck,
69002          "Multiple uses for byte %u of page %d", x>>16, iPage);
69003        break;
69004      }else{
69005        nFrag += (x>>16) - (prev&0xffff) - 1;
69006        prev = x;
69007      }
69008    }
69009    nFrag += usableSize - (prev&0xffff) - 1;
69010    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
69011    ** is stored in the fifth field of the b-tree page header.
69012    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
69013    ** number of fragmented free bytes within the cell content area.
69014    */
69015    if( heap[0]==0 && nFrag!=data[hdr+7] ){
69016      checkAppendMsg(pCheck,
69017          "Fragmentation of %d bytes reported as %d on page %d",
69018          nFrag, data[hdr+7], iPage);
69019    }
69020  }
69021
69022end_of_check:
69023  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
69024  releasePage(pPage);
69025  pCheck->zPfx = saved_zPfx;
69026  pCheck->v1 = saved_v1;
69027  pCheck->v2 = saved_v2;
69028  return depth+1;
69029}
69030#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69031
69032#ifndef SQLITE_OMIT_INTEGRITY_CHECK
69033/*
69034** This routine does a complete check of the given BTree file.  aRoot[] is
69035** an array of pages numbers were each page number is the root page of
69036** a table.  nRoot is the number of entries in aRoot.
69037**
69038** A read-only or read-write transaction must be opened before calling
69039** this function.
69040**
69041** Write the number of error seen in *pnErr.  Except for some memory
69042** allocation errors,  an error message held in memory obtained from
69043** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
69044** returned.  If a memory allocation error occurs, NULL is returned.
69045*/
69046SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
69047  Btree *p,     /* The btree to be checked */
69048  int *aRoot,   /* An array of root pages numbers for individual trees */
69049  int nRoot,    /* Number of entries in aRoot[] */
69050  int mxErr,    /* Stop reporting errors after this many */
69051  int *pnErr    /* Write number of errors seen to this variable */
69052){
69053  Pgno i;
69054  IntegrityCk sCheck;
69055  BtShared *pBt = p->pBt;
69056  int savedDbFlags = pBt->db->flags;
69057  char zErr[100];
69058  VVA_ONLY( int nRef );
69059
69060  sqlite3BtreeEnter(p);
69061  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
69062  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
69063  assert( nRef>=0 );
69064  sCheck.pBt = pBt;
69065  sCheck.pPager = pBt->pPager;
69066  sCheck.nPage = btreePagecount(sCheck.pBt);
69067  sCheck.mxErr = mxErr;
69068  sCheck.nErr = 0;
69069  sCheck.mallocFailed = 0;
69070  sCheck.zPfx = 0;
69071  sCheck.v1 = 0;
69072  sCheck.v2 = 0;
69073  sCheck.aPgRef = 0;
69074  sCheck.heap = 0;
69075  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
69076  sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
69077  if( sCheck.nPage==0 ){
69078    goto integrity_ck_cleanup;
69079  }
69080
69081  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
69082  if( !sCheck.aPgRef ){
69083    sCheck.mallocFailed = 1;
69084    goto integrity_ck_cleanup;
69085  }
69086  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
69087  if( sCheck.heap==0 ){
69088    sCheck.mallocFailed = 1;
69089    goto integrity_ck_cleanup;
69090  }
69091
69092  i = PENDING_BYTE_PAGE(pBt);
69093  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
69094
69095  /* Check the integrity of the freelist
69096  */
69097  sCheck.zPfx = "Main freelist: ";
69098  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
69099            get4byte(&pBt->pPage1->aData[36]));
69100  sCheck.zPfx = 0;
69101
69102  /* Check all the tables.
69103  */
69104  testcase( pBt->db->flags & SQLITE_CellSizeCk );
69105  pBt->db->flags &= ~SQLITE_CellSizeCk;
69106  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
69107    i64 notUsed;
69108    if( aRoot[i]==0 ) continue;
69109#ifndef SQLITE_OMIT_AUTOVACUUM
69110    if( pBt->autoVacuum && aRoot[i]>1 ){
69111      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
69112    }
69113#endif
69114    checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
69115  }
69116  pBt->db->flags = savedDbFlags;
69117
69118  /* Make sure every page in the file is referenced
69119  */
69120  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
69121#ifdef SQLITE_OMIT_AUTOVACUUM
69122    if( getPageReferenced(&sCheck, i)==0 ){
69123      checkAppendMsg(&sCheck, "Page %d is never used", i);
69124    }
69125#else
69126    /* If the database supports auto-vacuum, make sure no tables contain
69127    ** references to pointer-map pages.
69128    */
69129    if( getPageReferenced(&sCheck, i)==0 &&
69130       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
69131      checkAppendMsg(&sCheck, "Page %d is never used", i);
69132    }
69133    if( getPageReferenced(&sCheck, i)!=0 &&
69134       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
69135      checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
69136    }
69137#endif
69138  }
69139
69140  /* Clean  up and report errors.
69141  */
69142integrity_ck_cleanup:
69143  sqlite3PageFree(sCheck.heap);
69144  sqlite3_free(sCheck.aPgRef);
69145  if( sCheck.mallocFailed ){
69146    sqlite3StrAccumReset(&sCheck.errMsg);
69147    sCheck.nErr++;
69148  }
69149  *pnErr = sCheck.nErr;
69150  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
69151  /* Make sure this analysis did not leave any unref() pages. */
69152  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
69153  sqlite3BtreeLeave(p);
69154  return sqlite3StrAccumFinish(&sCheck.errMsg);
69155}
69156#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69157
69158/*
69159** Return the full pathname of the underlying database file.  Return
69160** an empty string if the database is in-memory or a TEMP database.
69161**
69162** The pager filename is invariant as long as the pager is
69163** open so it is safe to access without the BtShared mutex.
69164*/
69165SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
69166  assert( p->pBt->pPager!=0 );
69167  return sqlite3PagerFilename(p->pBt->pPager, 1);
69168}
69169
69170/*
69171** Return the pathname of the journal file for this database. The return
69172** value of this routine is the same regardless of whether the journal file
69173** has been created or not.
69174**
69175** The pager journal filename is invariant as long as the pager is
69176** open so it is safe to access without the BtShared mutex.
69177*/
69178SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
69179  assert( p->pBt->pPager!=0 );
69180  return sqlite3PagerJournalname(p->pBt->pPager);
69181}
69182
69183/*
69184** Return non-zero if a transaction is active.
69185*/
69186SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
69187  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
69188  return (p && (p->inTrans==TRANS_WRITE));
69189}
69190
69191#ifndef SQLITE_OMIT_WAL
69192/*
69193** Run a checkpoint on the Btree passed as the first argument.
69194**
69195** Return SQLITE_LOCKED if this or any other connection has an open
69196** transaction on the shared-cache the argument Btree is connected to.
69197**
69198** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
69199*/
69200SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
69201  int rc = SQLITE_OK;
69202  if( p ){
69203    BtShared *pBt = p->pBt;
69204    sqlite3BtreeEnter(p);
69205    if( pBt->inTransaction!=TRANS_NONE ){
69206      rc = SQLITE_LOCKED;
69207    }else{
69208      rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
69209    }
69210    sqlite3BtreeLeave(p);
69211  }
69212  return rc;
69213}
69214#endif
69215
69216/*
69217** Return non-zero if a read (or write) transaction is active.
69218*/
69219SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
69220  assert( p );
69221  assert( sqlite3_mutex_held(p->db->mutex) );
69222  return p->inTrans!=TRANS_NONE;
69223}
69224
69225SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
69226  assert( p );
69227  assert( sqlite3_mutex_held(p->db->mutex) );
69228  return p->nBackup!=0;
69229}
69230
69231/*
69232** This function returns a pointer to a blob of memory associated with
69233** a single shared-btree. The memory is used by client code for its own
69234** purposes (for example, to store a high-level schema associated with
69235** the shared-btree). The btree layer manages reference counting issues.
69236**
69237** The first time this is called on a shared-btree, nBytes bytes of memory
69238** are allocated, zeroed, and returned to the caller. For each subsequent
69239** call the nBytes parameter is ignored and a pointer to the same blob
69240** of memory returned.
69241**
69242** If the nBytes parameter is 0 and the blob of memory has not yet been
69243** allocated, a null pointer is returned. If the blob has already been
69244** allocated, it is returned as normal.
69245**
69246** Just before the shared-btree is closed, the function passed as the
69247** xFree argument when the memory allocation was made is invoked on the
69248** blob of allocated memory. The xFree function should not call sqlite3_free()
69249** on the memory, the btree layer does that.
69250*/
69251SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
69252  BtShared *pBt = p->pBt;
69253  sqlite3BtreeEnter(p);
69254  if( !pBt->pSchema && nBytes ){
69255    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
69256    pBt->xFreeSchema = xFree;
69257  }
69258  sqlite3BtreeLeave(p);
69259  return pBt->pSchema;
69260}
69261
69262/*
69263** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
69264** btree as the argument handle holds an exclusive lock on the
69265** sqlite_master table. Otherwise SQLITE_OK.
69266*/
69267SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
69268  int rc;
69269  assert( sqlite3_mutex_held(p->db->mutex) );
69270  sqlite3BtreeEnter(p);
69271  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
69272  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
69273  sqlite3BtreeLeave(p);
69274  return rc;
69275}
69276
69277
69278#ifndef SQLITE_OMIT_SHARED_CACHE
69279/*
69280** Obtain a lock on the table whose root page is iTab.  The
69281** lock is a write lock if isWritelock is true or a read lock
69282** if it is false.
69283*/
69284SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
69285  int rc = SQLITE_OK;
69286  assert( p->inTrans!=TRANS_NONE );
69287  if( p->sharable ){
69288    u8 lockType = READ_LOCK + isWriteLock;
69289    assert( READ_LOCK+1==WRITE_LOCK );
69290    assert( isWriteLock==0 || isWriteLock==1 );
69291
69292    sqlite3BtreeEnter(p);
69293    rc = querySharedCacheTableLock(p, iTab, lockType);
69294    if( rc==SQLITE_OK ){
69295      rc = setSharedCacheTableLock(p, iTab, lockType);
69296    }
69297    sqlite3BtreeLeave(p);
69298  }
69299  return rc;
69300}
69301#endif
69302
69303#ifndef SQLITE_OMIT_INCRBLOB
69304/*
69305** Argument pCsr must be a cursor opened for writing on an
69306** INTKEY table currently pointing at a valid table entry.
69307** This function modifies the data stored as part of that entry.
69308**
69309** Only the data content may only be modified, it is not possible to
69310** change the length of the data stored. If this function is called with
69311** parameters that attempt to write past the end of the existing data,
69312** no modifications are made and SQLITE_CORRUPT is returned.
69313*/
69314SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
69315  int rc;
69316  assert( cursorOwnsBtShared(pCsr) );
69317  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
69318  assert( pCsr->curFlags & BTCF_Incrblob );
69319
69320  rc = restoreCursorPosition(pCsr);
69321  if( rc!=SQLITE_OK ){
69322    return rc;
69323  }
69324  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
69325  if( pCsr->eState!=CURSOR_VALID ){
69326    return SQLITE_ABORT;
69327  }
69328
69329  /* Save the positions of all other cursors open on this table. This is
69330  ** required in case any of them are holding references to an xFetch
69331  ** version of the b-tree page modified by the accessPayload call below.
69332  **
69333  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
69334  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
69335  ** saveAllCursors can only return SQLITE_OK.
69336  */
69337  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
69338  assert( rc==SQLITE_OK );
69339
69340  /* Check some assumptions:
69341  **   (a) the cursor is open for writing,
69342  **   (b) there is a read/write transaction open,
69343  **   (c) the connection holds a write-lock on the table (if required),
69344  **   (d) there are no conflicting read-locks, and
69345  **   (e) the cursor points at a valid row of an intKey table.
69346  */
69347  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
69348    return SQLITE_READONLY;
69349  }
69350  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
69351              && pCsr->pBt->inTransaction==TRANS_WRITE );
69352  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
69353  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
69354  assert( pCsr->apPage[pCsr->iPage]->intKey );
69355
69356  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
69357}
69358
69359/*
69360** Mark this cursor as an incremental blob cursor.
69361*/
69362SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
69363  pCur->curFlags |= BTCF_Incrblob;
69364  pCur->pBtree->hasIncrblobCur = 1;
69365}
69366#endif
69367
69368/*
69369** Set both the "read version" (single byte at byte offset 18) and
69370** "write version" (single byte at byte offset 19) fields in the database
69371** header to iVersion.
69372*/
69373SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
69374  BtShared *pBt = pBtree->pBt;
69375  int rc;                         /* Return code */
69376
69377  assert( iVersion==1 || iVersion==2 );
69378
69379  /* If setting the version fields to 1, do not automatically open the
69380  ** WAL connection, even if the version fields are currently set to 2.
69381  */
69382  pBt->btsFlags &= ~BTS_NO_WAL;
69383  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
69384
69385  rc = sqlite3BtreeBeginTrans(pBtree, 0);
69386  if( rc==SQLITE_OK ){
69387    u8 *aData = pBt->pPage1->aData;
69388    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
69389      rc = sqlite3BtreeBeginTrans(pBtree, 2);
69390      if( rc==SQLITE_OK ){
69391        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
69392        if( rc==SQLITE_OK ){
69393          aData[18] = (u8)iVersion;
69394          aData[19] = (u8)iVersion;
69395        }
69396      }
69397    }
69398  }
69399
69400  pBt->btsFlags &= ~BTS_NO_WAL;
69401  return rc;
69402}
69403
69404/*
69405** Return true if the cursor has a hint specified.  This routine is
69406** only used from within assert() statements
69407*/
69408SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
69409  return (pCsr->hints & mask)!=0;
69410}
69411
69412/*
69413** Return true if the given Btree is read-only.
69414*/
69415SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
69416  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
69417}
69418
69419/*
69420** Return the size of the header added to each page by this module.
69421*/
69422SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
69423
69424#if !defined(SQLITE_OMIT_SHARED_CACHE)
69425/*
69426** Return true if the Btree passed as the only argument is sharable.
69427*/
69428SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
69429  return p->sharable;
69430}
69431
69432/*
69433** Return the number of connections to the BtShared object accessed by
69434** the Btree handle passed as the only argument. For private caches
69435** this is always 1. For shared caches it may be 1 or greater.
69436*/
69437SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
69438  testcase( p->sharable );
69439  return p->pBt->nRef;
69440}
69441#endif
69442
69443/************** End of btree.c ***********************************************/
69444/************** Begin file backup.c ******************************************/
69445/*
69446** 2009 January 28
69447**
69448** The author disclaims copyright to this source code.  In place of
69449** a legal notice, here is a blessing:
69450**
69451**    May you do good and not evil.
69452**    May you find forgiveness for yourself and forgive others.
69453**    May you share freely, never taking more than you give.
69454**
69455*************************************************************************
69456** This file contains the implementation of the sqlite3_backup_XXX()
69457** API functions and the related features.
69458*/
69459/* #include "sqliteInt.h" */
69460/* #include "btreeInt.h" */
69461
69462/*
69463** Structure allocated for each backup operation.
69464*/
69465struct sqlite3_backup {
69466  sqlite3* pDestDb;        /* Destination database handle */
69467  Btree *pDest;            /* Destination b-tree file */
69468  u32 iDestSchema;         /* Original schema cookie in destination */
69469  int bDestLocked;         /* True once a write-transaction is open on pDest */
69470
69471  Pgno iNext;              /* Page number of the next source page to copy */
69472  sqlite3* pSrcDb;         /* Source database handle */
69473  Btree *pSrc;             /* Source b-tree file */
69474
69475  int rc;                  /* Backup process error code */
69476
69477  /* These two variables are set by every call to backup_step(). They are
69478  ** read by calls to backup_remaining() and backup_pagecount().
69479  */
69480  Pgno nRemaining;         /* Number of pages left to copy */
69481  Pgno nPagecount;         /* Total number of pages to copy */
69482
69483  int isAttached;          /* True once backup has been registered with pager */
69484  sqlite3_backup *pNext;   /* Next backup associated with source pager */
69485};
69486
69487/*
69488** THREAD SAFETY NOTES:
69489**
69490**   Once it has been created using backup_init(), a single sqlite3_backup
69491**   structure may be accessed via two groups of thread-safe entry points:
69492**
69493**     * Via the sqlite3_backup_XXX() API function backup_step() and
69494**       backup_finish(). Both these functions obtain the source database
69495**       handle mutex and the mutex associated with the source BtShared
69496**       structure, in that order.
69497**
69498**     * Via the BackupUpdate() and BackupRestart() functions, which are
69499**       invoked by the pager layer to report various state changes in
69500**       the page cache associated with the source database. The mutex
69501**       associated with the source database BtShared structure will always
69502**       be held when either of these functions are invoked.
69503**
69504**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
69505**   backup_pagecount() are not thread-safe functions. If they are called
69506**   while some other thread is calling backup_step() or backup_finish(),
69507**   the values returned may be invalid. There is no way for a call to
69508**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
69509**   or backup_pagecount().
69510**
69511**   Depending on the SQLite configuration, the database handles and/or
69512**   the Btree objects may have their own mutexes that require locking.
69513**   Non-sharable Btrees (in-memory databases for example), do not have
69514**   associated mutexes.
69515*/
69516
69517/*
69518** Return a pointer corresponding to database zDb (i.e. "main", "temp")
69519** in connection handle pDb. If such a database cannot be found, return
69520** a NULL pointer and write an error message to pErrorDb.
69521**
69522** If the "temp" database is requested, it may need to be opened by this
69523** function. If an error occurs while doing so, return 0 and write an
69524** error message to pErrorDb.
69525*/
69526static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
69527  int i = sqlite3FindDbName(pDb, zDb);
69528
69529  if( i==1 ){
69530    Parse sParse;
69531    int rc = 0;
69532    memset(&sParse, 0, sizeof(sParse));
69533    sParse.db = pDb;
69534    if( sqlite3OpenTempDatabase(&sParse) ){
69535      sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
69536      rc = SQLITE_ERROR;
69537    }
69538    sqlite3DbFree(pErrorDb, sParse.zErrMsg);
69539    sqlite3ParserReset(&sParse);
69540    if( rc ){
69541      return 0;
69542    }
69543  }
69544
69545  if( i<0 ){
69546    sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
69547    return 0;
69548  }
69549
69550  return pDb->aDb[i].pBt;
69551}
69552
69553/*
69554** Attempt to set the page size of the destination to match the page size
69555** of the source.
69556*/
69557static int setDestPgsz(sqlite3_backup *p){
69558  int rc;
69559  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
69560  return rc;
69561}
69562
69563/*
69564** Check that there is no open read-transaction on the b-tree passed as the
69565** second argument. If there is not, return SQLITE_OK. Otherwise, if there
69566** is an open read-transaction, return SQLITE_ERROR and leave an error
69567** message in database handle db.
69568*/
69569static int checkReadTransaction(sqlite3 *db, Btree *p){
69570  if( sqlite3BtreeIsInReadTrans(p) ){
69571    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
69572    return SQLITE_ERROR;
69573  }
69574  return SQLITE_OK;
69575}
69576
69577/*
69578** Create an sqlite3_backup process to copy the contents of zSrcDb from
69579** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
69580** a pointer to the new sqlite3_backup object.
69581**
69582** If an error occurs, NULL is returned and an error code and error message
69583** stored in database handle pDestDb.
69584*/
69585SQLITE_API sqlite3_backup *sqlite3_backup_init(
69586  sqlite3* pDestDb,                     /* Database to write to */
69587  const char *zDestDb,                  /* Name of database within pDestDb */
69588  sqlite3* pSrcDb,                      /* Database connection to read from */
69589  const char *zSrcDb                    /* Name of database within pSrcDb */
69590){
69591  sqlite3_backup *p;                    /* Value to return */
69592
69593#ifdef SQLITE_ENABLE_API_ARMOR
69594  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
69595    (void)SQLITE_MISUSE_BKPT;
69596    return 0;
69597  }
69598#endif
69599
69600  /* Lock the source database handle. The destination database
69601  ** handle is not locked in this routine, but it is locked in
69602  ** sqlite3_backup_step(). The user is required to ensure that no
69603  ** other thread accesses the destination handle for the duration
69604  ** of the backup operation.  Any attempt to use the destination
69605  ** database connection while a backup is in progress may cause
69606  ** a malfunction or a deadlock.
69607  */
69608  sqlite3_mutex_enter(pSrcDb->mutex);
69609  sqlite3_mutex_enter(pDestDb->mutex);
69610
69611  if( pSrcDb==pDestDb ){
69612    sqlite3ErrorWithMsg(
69613        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
69614    );
69615    p = 0;
69616  }else {
69617    /* Allocate space for a new sqlite3_backup object...
69618    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
69619    ** call to sqlite3_backup_init() and is destroyed by a call to
69620    ** sqlite3_backup_finish(). */
69621    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
69622    if( !p ){
69623      sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
69624    }
69625  }
69626
69627  /* If the allocation succeeded, populate the new object. */
69628  if( p ){
69629    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
69630    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
69631    p->pDestDb = pDestDb;
69632    p->pSrcDb = pSrcDb;
69633    p->iNext = 1;
69634    p->isAttached = 0;
69635
69636    if( 0==p->pSrc || 0==p->pDest
69637     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
69638     ){
69639      /* One (or both) of the named databases did not exist or an OOM
69640      ** error was hit. Or there is a transaction open on the destination
69641      ** database. The error has already been written into the pDestDb
69642      ** handle. All that is left to do here is free the sqlite3_backup
69643      ** structure.  */
69644      sqlite3_free(p);
69645      p = 0;
69646    }
69647  }
69648  if( p ){
69649    p->pSrc->nBackup++;
69650  }
69651
69652  sqlite3_mutex_leave(pDestDb->mutex);
69653  sqlite3_mutex_leave(pSrcDb->mutex);
69654  return p;
69655}
69656
69657/*
69658** Argument rc is an SQLite error code. Return true if this error is
69659** considered fatal if encountered during a backup operation. All errors
69660** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
69661*/
69662static int isFatalError(int rc){
69663  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
69664}
69665
69666/*
69667** Parameter zSrcData points to a buffer containing the data for
69668** page iSrcPg from the source database. Copy this data into the
69669** destination database.
69670*/
69671static int backupOnePage(
69672  sqlite3_backup *p,              /* Backup handle */
69673  Pgno iSrcPg,                    /* Source database page to backup */
69674  const u8 *zSrcData,             /* Source database page data */
69675  int bUpdate                     /* True for an update, false otherwise */
69676){
69677  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
69678  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
69679  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
69680  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
69681  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
69682#ifdef SQLITE_HAS_CODEC
69683  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
69684  ** guaranteed that the shared-mutex is held by this thread, handle
69685  ** p->pSrc may not actually be the owner.  */
69686  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
69687  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
69688#endif
69689  int rc = SQLITE_OK;
69690  i64 iOff;
69691
69692  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
69693  assert( p->bDestLocked );
69694  assert( !isFatalError(p->rc) );
69695  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
69696  assert( zSrcData );
69697
69698  /* Catch the case where the destination is an in-memory database and the
69699  ** page sizes of the source and destination differ.
69700  */
69701  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
69702    rc = SQLITE_READONLY;
69703  }
69704
69705#ifdef SQLITE_HAS_CODEC
69706  /* Backup is not possible if the page size of the destination is changing
69707  ** and a codec is in use.
69708  */
69709  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
69710    rc = SQLITE_READONLY;
69711  }
69712
69713  /* Backup is not possible if the number of bytes of reserve space differ
69714  ** between source and destination.  If there is a difference, try to
69715  ** fix the destination to agree with the source.  If that is not possible,
69716  ** then the backup cannot proceed.
69717  */
69718  if( nSrcReserve!=nDestReserve ){
69719    u32 newPgsz = nSrcPgsz;
69720    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
69721    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
69722  }
69723#endif
69724
69725  /* This loop runs once for each destination page spanned by the source
69726  ** page. For each iteration, variable iOff is set to the byte offset
69727  ** of the destination page.
69728  */
69729  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
69730    DbPage *pDestPg = 0;
69731    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
69732    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
69733    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
69734     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
69735    ){
69736      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
69737      u8 *zDestData = sqlite3PagerGetData(pDestPg);
69738      u8 *zOut = &zDestData[iOff%nDestPgsz];
69739
69740      /* Copy the data from the source page into the destination page.
69741      ** Then clear the Btree layer MemPage.isInit flag. Both this module
69742      ** and the pager code use this trick (clearing the first byte
69743      ** of the page 'extra' space to invalidate the Btree layers
69744      ** cached parse of the page). MemPage.isInit is marked
69745      ** "MUST BE FIRST" for this purpose.
69746      */
69747      memcpy(zOut, zIn, nCopy);
69748      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
69749      if( iOff==0 && bUpdate==0 ){
69750        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
69751      }
69752    }
69753    sqlite3PagerUnref(pDestPg);
69754  }
69755
69756  return rc;
69757}
69758
69759/*
69760** If pFile is currently larger than iSize bytes, then truncate it to
69761** exactly iSize bytes. If pFile is not larger than iSize bytes, then
69762** this function is a no-op.
69763**
69764** Return SQLITE_OK if everything is successful, or an SQLite error
69765** code if an error occurs.
69766*/
69767static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
69768  i64 iCurrent;
69769  int rc = sqlite3OsFileSize(pFile, &iCurrent);
69770  if( rc==SQLITE_OK && iCurrent>iSize ){
69771    rc = sqlite3OsTruncate(pFile, iSize);
69772  }
69773  return rc;
69774}
69775
69776/*
69777** Register this backup object with the associated source pager for
69778** callbacks when pages are changed or the cache invalidated.
69779*/
69780static void attachBackupObject(sqlite3_backup *p){
69781  sqlite3_backup **pp;
69782  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
69783  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
69784  p->pNext = *pp;
69785  *pp = p;
69786  p->isAttached = 1;
69787}
69788
69789/*
69790** Copy nPage pages from the source b-tree to the destination.
69791*/
69792SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
69793  int rc;
69794  int destMode;       /* Destination journal mode */
69795  int pgszSrc = 0;    /* Source page size */
69796  int pgszDest = 0;   /* Destination page size */
69797
69798#ifdef SQLITE_ENABLE_API_ARMOR
69799  if( p==0 ) return SQLITE_MISUSE_BKPT;
69800#endif
69801  sqlite3_mutex_enter(p->pSrcDb->mutex);
69802  sqlite3BtreeEnter(p->pSrc);
69803  if( p->pDestDb ){
69804    sqlite3_mutex_enter(p->pDestDb->mutex);
69805  }
69806
69807  rc = p->rc;
69808  if( !isFatalError(rc) ){
69809    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
69810    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
69811    int ii;                            /* Iterator variable */
69812    int nSrcPage = -1;                 /* Size of source db in pages */
69813    int bCloseTrans = 0;               /* True if src db requires unlocking */
69814
69815    /* If the source pager is currently in a write-transaction, return
69816    ** SQLITE_BUSY immediately.
69817    */
69818    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
69819      rc = SQLITE_BUSY;
69820    }else{
69821      rc = SQLITE_OK;
69822    }
69823
69824    /* If there is no open read-transaction on the source database, open
69825    ** one now. If a transaction is opened here, then it will be closed
69826    ** before this function exits.
69827    */
69828    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
69829      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
69830      bCloseTrans = 1;
69831    }
69832
69833    /* If the destination database has not yet been locked (i.e. if this
69834    ** is the first call to backup_step() for the current backup operation),
69835    ** try to set its page size to the same as the source database. This
69836    ** is especially important on ZipVFS systems, as in that case it is
69837    ** not possible to create a database file that uses one page size by
69838    ** writing to it with another.  */
69839    if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
69840      rc = SQLITE_NOMEM;
69841    }
69842
69843    /* Lock the destination database, if it is not locked already. */
69844    if( SQLITE_OK==rc && p->bDestLocked==0
69845     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
69846    ){
69847      p->bDestLocked = 1;
69848      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
69849    }
69850
69851    /* Do not allow backup if the destination database is in WAL mode
69852    ** and the page sizes are different between source and destination */
69853    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
69854    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
69855    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
69856    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
69857      rc = SQLITE_READONLY;
69858    }
69859
69860    /* Now that there is a read-lock on the source database, query the
69861    ** source pager for the number of pages in the database.
69862    */
69863    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
69864    assert( nSrcPage>=0 );
69865    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
69866      const Pgno iSrcPg = p->iNext;                 /* Source page number */
69867      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
69868        DbPage *pSrcPg;                             /* Source page object */
69869        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
69870        if( rc==SQLITE_OK ){
69871          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
69872          sqlite3PagerUnref(pSrcPg);
69873        }
69874      }
69875      p->iNext++;
69876    }
69877    if( rc==SQLITE_OK ){
69878      p->nPagecount = nSrcPage;
69879      p->nRemaining = nSrcPage+1-p->iNext;
69880      if( p->iNext>(Pgno)nSrcPage ){
69881        rc = SQLITE_DONE;
69882      }else if( !p->isAttached ){
69883        attachBackupObject(p);
69884      }
69885    }
69886
69887    /* Update the schema version field in the destination database. This
69888    ** is to make sure that the schema-version really does change in
69889    ** the case where the source and destination databases have the
69890    ** same schema version.
69891    */
69892    if( rc==SQLITE_DONE ){
69893      if( nSrcPage==0 ){
69894        rc = sqlite3BtreeNewDb(p->pDest);
69895        nSrcPage = 1;
69896      }
69897      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
69898        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
69899      }
69900      if( rc==SQLITE_OK ){
69901        if( p->pDestDb ){
69902          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
69903        }
69904        if( destMode==PAGER_JOURNALMODE_WAL ){
69905          rc = sqlite3BtreeSetVersion(p->pDest, 2);
69906        }
69907      }
69908      if( rc==SQLITE_OK ){
69909        int nDestTruncate;
69910        /* Set nDestTruncate to the final number of pages in the destination
69911        ** database. The complication here is that the destination page
69912        ** size may be different to the source page size.
69913        **
69914        ** If the source page size is smaller than the destination page size,
69915        ** round up. In this case the call to sqlite3OsTruncate() below will
69916        ** fix the size of the file. However it is important to call
69917        ** sqlite3PagerTruncateImage() here so that any pages in the
69918        ** destination file that lie beyond the nDestTruncate page mark are
69919        ** journalled by PagerCommitPhaseOne() before they are destroyed
69920        ** by the file truncation.
69921        */
69922        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
69923        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
69924        if( pgszSrc<pgszDest ){
69925          int ratio = pgszDest/pgszSrc;
69926          nDestTruncate = (nSrcPage+ratio-1)/ratio;
69927          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
69928            nDestTruncate--;
69929          }
69930        }else{
69931          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
69932        }
69933        assert( nDestTruncate>0 );
69934
69935        if( pgszSrc<pgszDest ){
69936          /* If the source page-size is smaller than the destination page-size,
69937          ** two extra things may need to happen:
69938          **
69939          **   * The destination may need to be truncated, and
69940          **
69941          **   * Data stored on the pages immediately following the
69942          **     pending-byte page in the source database may need to be
69943          **     copied into the destination database.
69944          */
69945          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
69946          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
69947          Pgno iPg;
69948          int nDstPage;
69949          i64 iOff;
69950          i64 iEnd;
69951
69952          assert( pFile );
69953          assert( nDestTruncate==0
69954              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
69955                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
69956             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
69957          ));
69958
69959          /* This block ensures that all data required to recreate the original
69960          ** database has been stored in the journal for pDestPager and the
69961          ** journal synced to disk. So at this point we may safely modify
69962          ** the database file in any way, knowing that if a power failure
69963          ** occurs, the original database will be reconstructed from the
69964          ** journal file.  */
69965          sqlite3PagerPagecount(pDestPager, &nDstPage);
69966          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
69967            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
69968              DbPage *pPg;
69969              rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
69970              if( rc==SQLITE_OK ){
69971                rc = sqlite3PagerWrite(pPg);
69972                sqlite3PagerUnref(pPg);
69973              }
69974            }
69975          }
69976          if( rc==SQLITE_OK ){
69977            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
69978          }
69979
69980          /* Write the extra pages and truncate the database file as required */
69981          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
69982          for(
69983            iOff=PENDING_BYTE+pgszSrc;
69984            rc==SQLITE_OK && iOff<iEnd;
69985            iOff+=pgszSrc
69986          ){
69987            PgHdr *pSrcPg = 0;
69988            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
69989            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
69990            if( rc==SQLITE_OK ){
69991              u8 *zData = sqlite3PagerGetData(pSrcPg);
69992              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
69993            }
69994            sqlite3PagerUnref(pSrcPg);
69995          }
69996          if( rc==SQLITE_OK ){
69997            rc = backupTruncateFile(pFile, iSize);
69998          }
69999
70000          /* Sync the database file to disk. */
70001          if( rc==SQLITE_OK ){
70002            rc = sqlite3PagerSync(pDestPager, 0);
70003          }
70004        }else{
70005          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
70006          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
70007        }
70008
70009        /* Finish committing the transaction to the destination database. */
70010        if( SQLITE_OK==rc
70011         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
70012        ){
70013          rc = SQLITE_DONE;
70014        }
70015      }
70016    }
70017
70018    /* If bCloseTrans is true, then this function opened a read transaction
70019    ** on the source database. Close the read transaction here. There is
70020    ** no need to check the return values of the btree methods here, as
70021    ** "committing" a read-only transaction cannot fail.
70022    */
70023    if( bCloseTrans ){
70024      TESTONLY( int rc2 );
70025      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
70026      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
70027      assert( rc2==SQLITE_OK );
70028    }
70029
70030    if( rc==SQLITE_IOERR_NOMEM ){
70031      rc = SQLITE_NOMEM_BKPT;
70032    }
70033    p->rc = rc;
70034  }
70035  if( p->pDestDb ){
70036    sqlite3_mutex_leave(p->pDestDb->mutex);
70037  }
70038  sqlite3BtreeLeave(p->pSrc);
70039  sqlite3_mutex_leave(p->pSrcDb->mutex);
70040  return rc;
70041}
70042
70043/*
70044** Release all resources associated with an sqlite3_backup* handle.
70045*/
70046SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
70047  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
70048  sqlite3 *pSrcDb;                     /* Source database connection */
70049  int rc;                              /* Value to return */
70050
70051  /* Enter the mutexes */
70052  if( p==0 ) return SQLITE_OK;
70053  pSrcDb = p->pSrcDb;
70054  sqlite3_mutex_enter(pSrcDb->mutex);
70055  sqlite3BtreeEnter(p->pSrc);
70056  if( p->pDestDb ){
70057    sqlite3_mutex_enter(p->pDestDb->mutex);
70058  }
70059
70060  /* Detach this backup from the source pager. */
70061  if( p->pDestDb ){
70062    p->pSrc->nBackup--;
70063  }
70064  if( p->isAttached ){
70065    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
70066    while( *pp!=p ){
70067      pp = &(*pp)->pNext;
70068    }
70069    *pp = p->pNext;
70070  }
70071
70072  /* If a transaction is still open on the Btree, roll it back. */
70073  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
70074
70075  /* Set the error code of the destination database handle. */
70076  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
70077  if( p->pDestDb ){
70078    sqlite3Error(p->pDestDb, rc);
70079
70080    /* Exit the mutexes and free the backup context structure. */
70081    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
70082  }
70083  sqlite3BtreeLeave(p->pSrc);
70084  if( p->pDestDb ){
70085    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
70086    ** call to sqlite3_backup_init() and is destroyed by a call to
70087    ** sqlite3_backup_finish(). */
70088    sqlite3_free(p);
70089  }
70090  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
70091  return rc;
70092}
70093
70094/*
70095** Return the number of pages still to be backed up as of the most recent
70096** call to sqlite3_backup_step().
70097*/
70098SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
70099#ifdef SQLITE_ENABLE_API_ARMOR
70100  if( p==0 ){
70101    (void)SQLITE_MISUSE_BKPT;
70102    return 0;
70103  }
70104#endif
70105  return p->nRemaining;
70106}
70107
70108/*
70109** Return the total number of pages in the source database as of the most
70110** recent call to sqlite3_backup_step().
70111*/
70112SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
70113#ifdef SQLITE_ENABLE_API_ARMOR
70114  if( p==0 ){
70115    (void)SQLITE_MISUSE_BKPT;
70116    return 0;
70117  }
70118#endif
70119  return p->nPagecount;
70120}
70121
70122/*
70123** This function is called after the contents of page iPage of the
70124** source database have been modified. If page iPage has already been
70125** copied into the destination database, then the data written to the
70126** destination is now invalidated. The destination copy of iPage needs
70127** to be updated with the new data before the backup operation is
70128** complete.
70129**
70130** It is assumed that the mutex associated with the BtShared object
70131** corresponding to the source database is held when this function is
70132** called.
70133*/
70134static SQLITE_NOINLINE void backupUpdate(
70135  sqlite3_backup *p,
70136  Pgno iPage,
70137  const u8 *aData
70138){
70139  assert( p!=0 );
70140  do{
70141    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
70142    if( !isFatalError(p->rc) && iPage<p->iNext ){
70143      /* The backup process p has already copied page iPage. But now it
70144      ** has been modified by a transaction on the source pager. Copy
70145      ** the new data into the backup.
70146      */
70147      int rc;
70148      assert( p->pDestDb );
70149      sqlite3_mutex_enter(p->pDestDb->mutex);
70150      rc = backupOnePage(p, iPage, aData, 1);
70151      sqlite3_mutex_leave(p->pDestDb->mutex);
70152      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
70153      if( rc!=SQLITE_OK ){
70154        p->rc = rc;
70155      }
70156    }
70157  }while( (p = p->pNext)!=0 );
70158}
70159SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
70160  if( pBackup ) backupUpdate(pBackup, iPage, aData);
70161}
70162
70163/*
70164** Restart the backup process. This is called when the pager layer
70165** detects that the database has been modified by an external database
70166** connection. In this case there is no way of knowing which of the
70167** pages that have been copied into the destination database are still
70168** valid and which are not, so the entire process needs to be restarted.
70169**
70170** It is assumed that the mutex associated with the BtShared object
70171** corresponding to the source database is held when this function is
70172** called.
70173*/
70174SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
70175  sqlite3_backup *p;                   /* Iterator variable */
70176  for(p=pBackup; p; p=p->pNext){
70177    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
70178    p->iNext = 1;
70179  }
70180}
70181
70182#ifndef SQLITE_OMIT_VACUUM
70183/*
70184** Copy the complete content of pBtFrom into pBtTo.  A transaction
70185** must be active for both files.
70186**
70187** The size of file pTo may be reduced by this operation. If anything
70188** goes wrong, the transaction on pTo is rolled back. If successful, the
70189** transaction is committed before returning.
70190*/
70191SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
70192  int rc;
70193  sqlite3_file *pFd;              /* File descriptor for database pTo */
70194  sqlite3_backup b;
70195  sqlite3BtreeEnter(pTo);
70196  sqlite3BtreeEnter(pFrom);
70197
70198  assert( sqlite3BtreeIsInTrans(pTo) );
70199  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
70200  if( pFd->pMethods ){
70201    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
70202    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
70203    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
70204    if( rc ) goto copy_finished;
70205  }
70206
70207  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
70208  ** to 0. This is used by the implementations of sqlite3_backup_step()
70209  ** and sqlite3_backup_finish() to detect that they are being called
70210  ** from this function, not directly by the user.
70211  */
70212  memset(&b, 0, sizeof(b));
70213  b.pSrcDb = pFrom->db;
70214  b.pSrc = pFrom;
70215  b.pDest = pTo;
70216  b.iNext = 1;
70217
70218#ifdef SQLITE_HAS_CODEC
70219  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
70220#endif
70221
70222  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
70223  ** file. By passing this as the number of pages to copy to
70224  ** sqlite3_backup_step(), we can guarantee that the copy finishes
70225  ** within a single call (unless an error occurs). The assert() statement
70226  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
70227  ** or an error code.  */
70228  sqlite3_backup_step(&b, 0x7FFFFFFF);
70229  assert( b.rc!=SQLITE_OK );
70230
70231  rc = sqlite3_backup_finish(&b);
70232  if( rc==SQLITE_OK ){
70233    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
70234  }else{
70235    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
70236  }
70237
70238  assert( sqlite3BtreeIsInTrans(pTo)==0 );
70239copy_finished:
70240  sqlite3BtreeLeave(pFrom);
70241  sqlite3BtreeLeave(pTo);
70242  return rc;
70243}
70244#endif /* SQLITE_OMIT_VACUUM */
70245
70246/************** End of backup.c **********************************************/
70247/************** Begin file vdbemem.c *****************************************/
70248/*
70249** 2004 May 26
70250**
70251** The author disclaims copyright to this source code.  In place of
70252** a legal notice, here is a blessing:
70253**
70254**    May you do good and not evil.
70255**    May you find forgiveness for yourself and forgive others.
70256**    May you share freely, never taking more than you give.
70257**
70258*************************************************************************
70259**
70260** This file contains code use to manipulate "Mem" structure.  A "Mem"
70261** stores a single value in the VDBE.  Mem is an opaque structure visible
70262** only within the VDBE.  Interface routines refer to a Mem using the
70263** name sqlite_value
70264*/
70265/* #include "sqliteInt.h" */
70266/* #include "vdbeInt.h" */
70267
70268#ifdef SQLITE_DEBUG
70269/*
70270** Check invariants on a Mem object.
70271**
70272** This routine is intended for use inside of assert() statements, like
70273** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
70274*/
70275SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
70276  /* If MEM_Dyn is set then Mem.xDel!=0.
70277  ** Mem.xDel might not be initialized if MEM_Dyn is clear.
70278  */
70279  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
70280
70281  /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
70282  ** ensure that if Mem.szMalloc>0 then it is safe to do
70283  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
70284  ** That saves a few cycles in inner loops. */
70285  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
70286
70287  /* Cannot be both MEM_Int and MEM_Real at the same time */
70288  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
70289
70290  if( p->flags & MEM_Null ){
70291    /* Cannot be both MEM_Null and some other type */
70292    assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob
70293                         |MEM_RowSet|MEM_Frame|MEM_Agg|MEM_Zero))==0 );
70294
70295    /* If MEM_Null is set, then either the value is a pure NULL (the usual
70296    ** case) or it is a pointer set using sqlite3_bind_pointer() or
70297    ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be
70298    ** set.
70299    */
70300    if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
70301      /* This is a pointer type.  There may be a flag to indicate what to
70302      ** do with the pointer. */
70303      assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
70304              ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
70305              ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
70306
70307      /* No other bits set */
70308      assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
70309                           |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
70310    }else{
70311      /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
70312      ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
70313    }
70314  }else{
70315    /* The MEM_Cleared bit is only allowed on NULLs */
70316    assert( (p->flags & MEM_Cleared)==0 );
70317  }
70318
70319  /* The szMalloc field holds the correct memory allocation size */
70320  assert( p->szMalloc==0
70321       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
70322
70323  /* If p holds a string or blob, the Mem.z must point to exactly
70324  ** one of the following:
70325  **
70326  **   (1) Memory in Mem.zMalloc and managed by the Mem object
70327  **   (2) Memory to be freed using Mem.xDel
70328  **   (3) An ephemeral string or blob
70329  **   (4) A static string or blob
70330  */
70331  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
70332    assert(
70333      ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
70334      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
70335      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
70336      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
70337    );
70338  }
70339  return 1;
70340}
70341#endif
70342
70343
70344/*
70345** If pMem is an object with a valid string representation, this routine
70346** ensures the internal encoding for the string representation is
70347** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
70348**
70349** If pMem is not a string object, or the encoding of the string
70350** representation is already stored using the requested encoding, then this
70351** routine is a no-op.
70352**
70353** SQLITE_OK is returned if the conversion is successful (or not required).
70354** SQLITE_NOMEM may be returned if a malloc() fails during conversion
70355** between formats.
70356*/
70357SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
70358#ifndef SQLITE_OMIT_UTF16
70359  int rc;
70360#endif
70361  assert( (pMem->flags&MEM_RowSet)==0 );
70362  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
70363           || desiredEnc==SQLITE_UTF16BE );
70364  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
70365    return SQLITE_OK;
70366  }
70367  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70368#ifdef SQLITE_OMIT_UTF16
70369  return SQLITE_ERROR;
70370#else
70371
70372  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
70373  ** then the encoding of the value may not have changed.
70374  */
70375  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
70376  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
70377  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
70378  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
70379  return rc;
70380#endif
70381}
70382
70383/*
70384** Make sure pMem->z points to a writable allocation of at least
70385** min(n,32) bytes.
70386**
70387** If the bPreserve argument is true, then copy of the content of
70388** pMem->z into the new allocation.  pMem must be either a string or
70389** blob if bPreserve is true.  If bPreserve is false, any prior content
70390** in pMem->z is discarded.
70391*/
70392SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
70393  assert( sqlite3VdbeCheckMemInvariants(pMem) );
70394  assert( (pMem->flags&MEM_RowSet)==0 );
70395  testcase( pMem->db==0 );
70396
70397  /* If the bPreserve flag is set to true, then the memory cell must already
70398  ** contain a valid string or blob value.  */
70399  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
70400  testcase( bPreserve && pMem->z==0 );
70401
70402  assert( pMem->szMalloc==0
70403       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
70404  if( n<32 ) n = 32;
70405  if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
70406    pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
70407    bPreserve = 0;
70408  }else{
70409    if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
70410    pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
70411  }
70412  if( pMem->zMalloc==0 ){
70413    sqlite3VdbeMemSetNull(pMem);
70414    pMem->z = 0;
70415    pMem->szMalloc = 0;
70416    return SQLITE_NOMEM_BKPT;
70417  }else{
70418    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
70419  }
70420
70421  if( bPreserve && pMem->z && ALWAYS(pMem->z!=pMem->zMalloc) ){
70422    memcpy(pMem->zMalloc, pMem->z, pMem->n);
70423  }
70424  if( (pMem->flags&MEM_Dyn)!=0 ){
70425    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
70426    pMem->xDel((void *)(pMem->z));
70427  }
70428
70429  pMem->z = pMem->zMalloc;
70430  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
70431  return SQLITE_OK;
70432}
70433
70434/*
70435** Change the pMem->zMalloc allocation to be at least szNew bytes.
70436** If pMem->zMalloc already meets or exceeds the requested size, this
70437** routine is a no-op.
70438**
70439** Any prior string or blob content in the pMem object may be discarded.
70440** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
70441** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
70442** values are preserved.
70443**
70444** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
70445** if unable to complete the resizing.
70446*/
70447SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
70448  assert( szNew>0 );
70449  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
70450  if( pMem->szMalloc<szNew ){
70451    return sqlite3VdbeMemGrow(pMem, szNew, 0);
70452  }
70453  assert( (pMem->flags & MEM_Dyn)==0 );
70454  pMem->z = pMem->zMalloc;
70455  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
70456  return SQLITE_OK;
70457}
70458
70459/*
70460** Change pMem so that its MEM_Str or MEM_Blob value is stored in
70461** MEM.zMalloc, where it can be safely written.
70462**
70463** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
70464*/
70465SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
70466  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70467  assert( (pMem->flags&MEM_RowSet)==0 );
70468  if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
70469    if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
70470    if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
70471      if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
70472        return SQLITE_NOMEM_BKPT;
70473      }
70474      pMem->z[pMem->n] = 0;
70475      pMem->z[pMem->n+1] = 0;
70476      pMem->flags |= MEM_Term;
70477    }
70478  }
70479  pMem->flags &= ~MEM_Ephem;
70480#ifdef SQLITE_DEBUG
70481  pMem->pScopyFrom = 0;
70482#endif
70483
70484  return SQLITE_OK;
70485}
70486
70487/*
70488** If the given Mem* has a zero-filled tail, turn it into an ordinary
70489** blob stored in dynamically allocated space.
70490*/
70491#ifndef SQLITE_OMIT_INCRBLOB
70492SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
70493  int nByte;
70494  assert( pMem->flags & MEM_Zero );
70495  assert( pMem->flags&MEM_Blob );
70496  assert( (pMem->flags&MEM_RowSet)==0 );
70497  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70498
70499  /* Set nByte to the number of bytes required to store the expanded blob. */
70500  nByte = pMem->n + pMem->u.nZero;
70501  if( nByte<=0 ){
70502    nByte = 1;
70503  }
70504  if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
70505    return SQLITE_NOMEM_BKPT;
70506  }
70507
70508  memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
70509  pMem->n += pMem->u.nZero;
70510  pMem->flags &= ~(MEM_Zero|MEM_Term);
70511  return SQLITE_OK;
70512}
70513#endif
70514
70515/*
70516** It is already known that pMem contains an unterminated string.
70517** Add the zero terminator.
70518*/
70519static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
70520  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
70521    return SQLITE_NOMEM_BKPT;
70522  }
70523  pMem->z[pMem->n] = 0;
70524  pMem->z[pMem->n+1] = 0;
70525  pMem->flags |= MEM_Term;
70526  return SQLITE_OK;
70527}
70528
70529/*
70530** Make sure the given Mem is \u0000 terminated.
70531*/
70532SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
70533  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70534  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
70535  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
70536  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
70537    return SQLITE_OK;   /* Nothing to do */
70538  }else{
70539    return vdbeMemAddTerminator(pMem);
70540  }
70541}
70542
70543/*
70544** Add MEM_Str to the set of representations for the given Mem.  Numbers
70545** are converted using sqlite3_snprintf().  Converting a BLOB to a string
70546** is a no-op.
70547**
70548** Existing representations MEM_Int and MEM_Real are invalidated if
70549** bForce is true but are retained if bForce is false.
70550**
70551** A MEM_Null value will never be passed to this function. This function is
70552** used for converting values to text for returning to the user (i.e. via
70553** sqlite3_value_text()), or for ensuring that values to be used as btree
70554** keys are strings. In the former case a NULL pointer is returned the
70555** user and the latter is an internal programming error.
70556*/
70557SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
70558  int fg = pMem->flags;
70559  const int nByte = 32;
70560
70561  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70562  assert( !(fg&MEM_Zero) );
70563  assert( !(fg&(MEM_Str|MEM_Blob)) );
70564  assert( fg&(MEM_Int|MEM_Real) );
70565  assert( (pMem->flags&MEM_RowSet)==0 );
70566  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70567
70568
70569  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
70570    pMem->enc = 0;
70571    return SQLITE_NOMEM_BKPT;
70572  }
70573
70574  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
70575  ** string representation of the value. Then, if the required encoding
70576  ** is UTF-16le or UTF-16be do a translation.
70577  **
70578  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
70579  */
70580  if( fg & MEM_Int ){
70581    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
70582  }else{
70583    assert( fg & MEM_Real );
70584    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
70585  }
70586  pMem->n = sqlite3Strlen30(pMem->z);
70587  pMem->enc = SQLITE_UTF8;
70588  pMem->flags |= MEM_Str|MEM_Term;
70589  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
70590  sqlite3VdbeChangeEncoding(pMem, enc);
70591  return SQLITE_OK;
70592}
70593
70594/*
70595** Memory cell pMem contains the context of an aggregate function.
70596** This routine calls the finalize method for that function.  The
70597** result of the aggregate is stored back into pMem.
70598**
70599** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
70600** otherwise.
70601*/
70602SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
70603  int rc = SQLITE_OK;
70604  if( ALWAYS(pFunc && pFunc->xFinalize) ){
70605    sqlite3_context ctx;
70606    Mem t;
70607    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
70608    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70609    memset(&ctx, 0, sizeof(ctx));
70610    memset(&t, 0, sizeof(t));
70611    t.flags = MEM_Null;
70612    t.db = pMem->db;
70613    ctx.pOut = &t;
70614    ctx.pMem = pMem;
70615    ctx.pFunc = pFunc;
70616    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
70617    assert( (pMem->flags & MEM_Dyn)==0 );
70618    if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
70619    memcpy(pMem, &t, sizeof(t));
70620    rc = ctx.isError;
70621  }
70622  return rc;
70623}
70624
70625/*
70626** If the memory cell contains a value that must be freed by
70627** invoking the external callback in Mem.xDel, then this routine
70628** will free that value.  It also sets Mem.flags to MEM_Null.
70629**
70630** This is a helper routine for sqlite3VdbeMemSetNull() and
70631** for sqlite3VdbeMemRelease().  Use those other routines as the
70632** entry point for releasing Mem resources.
70633*/
70634static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
70635  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
70636  assert( VdbeMemDynamic(p) );
70637  if( p->flags&MEM_Agg ){
70638    sqlite3VdbeMemFinalize(p, p->u.pDef);
70639    assert( (p->flags & MEM_Agg)==0 );
70640    testcase( p->flags & MEM_Dyn );
70641  }
70642  if( p->flags&MEM_Dyn ){
70643    assert( (p->flags&MEM_RowSet)==0 );
70644    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
70645    p->xDel((void *)p->z);
70646  }else if( p->flags&MEM_RowSet ){
70647    sqlite3RowSetClear(p->u.pRowSet);
70648  }else if( p->flags&MEM_Frame ){
70649    VdbeFrame *pFrame = p->u.pFrame;
70650    pFrame->pParent = pFrame->v->pDelFrame;
70651    pFrame->v->pDelFrame = pFrame;
70652  }
70653  p->flags = MEM_Null;
70654}
70655
70656/*
70657** Release memory held by the Mem p, both external memory cleared
70658** by p->xDel and memory in p->zMalloc.
70659**
70660** This is a helper routine invoked by sqlite3VdbeMemRelease() in
70661** the unusual case where there really is memory in p that needs
70662** to be freed.
70663*/
70664static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
70665  if( VdbeMemDynamic(p) ){
70666    vdbeMemClearExternAndSetNull(p);
70667  }
70668  if( p->szMalloc ){
70669    sqlite3DbFreeNN(p->db, p->zMalloc);
70670    p->szMalloc = 0;
70671  }
70672  p->z = 0;
70673}
70674
70675/*
70676** Release any memory resources held by the Mem.  Both the memory that is
70677** free by Mem.xDel and the Mem.zMalloc allocation are freed.
70678**
70679** Use this routine prior to clean up prior to abandoning a Mem, or to
70680** reset a Mem back to its minimum memory utilization.
70681**
70682** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
70683** prior to inserting new content into the Mem.
70684*/
70685SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
70686  assert( sqlite3VdbeCheckMemInvariants(p) );
70687  if( VdbeMemDynamic(p) || p->szMalloc ){
70688    vdbeMemClear(p);
70689  }
70690}
70691
70692/*
70693** Convert a 64-bit IEEE double into a 64-bit signed integer.
70694** If the double is out of range of a 64-bit signed integer then
70695** return the closest available 64-bit signed integer.
70696*/
70697static SQLITE_NOINLINE i64 doubleToInt64(double r){
70698#ifdef SQLITE_OMIT_FLOATING_POINT
70699  /* When floating-point is omitted, double and int64 are the same thing */
70700  return r;
70701#else
70702  /*
70703  ** Many compilers we encounter do not define constants for the
70704  ** minimum and maximum 64-bit integers, or they define them
70705  ** inconsistently.  And many do not understand the "LL" notation.
70706  ** So we define our own static constants here using nothing
70707  ** larger than a 32-bit integer constant.
70708  */
70709  static const i64 maxInt = LARGEST_INT64;
70710  static const i64 minInt = SMALLEST_INT64;
70711
70712  if( r<=(double)minInt ){
70713    return minInt;
70714  }else if( r>=(double)maxInt ){
70715    return maxInt;
70716  }else{
70717    return (i64)r;
70718  }
70719#endif
70720}
70721
70722/*
70723** Return some kind of integer value which is the best we can do
70724** at representing the value that *pMem describes as an integer.
70725** If pMem is an integer, then the value is exact.  If pMem is
70726** a floating-point then the value returned is the integer part.
70727** If pMem is a string or blob, then we make an attempt to convert
70728** it into an integer and return that.  If pMem represents an
70729** an SQL-NULL value, return 0.
70730**
70731** If pMem represents a string value, its encoding might be changed.
70732*/
70733static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
70734  i64 value = 0;
70735  sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
70736  return value;
70737}
70738SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
70739  int flags;
70740  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70741  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70742  flags = pMem->flags;
70743  if( flags & MEM_Int ){
70744    return pMem->u.i;
70745  }else if( flags & MEM_Real ){
70746    return doubleToInt64(pMem->u.r);
70747  }else if( flags & (MEM_Str|MEM_Blob) ){
70748    assert( pMem->z || pMem->n==0 );
70749    return memIntValue(pMem);
70750  }else{
70751    return 0;
70752  }
70753}
70754
70755/*
70756** Return the best representation of pMem that we can get into a
70757** double.  If pMem is already a double or an integer, return its
70758** value.  If it is a string or blob, try to convert it to a double.
70759** If it is a NULL, return 0.0.
70760*/
70761static SQLITE_NOINLINE double memRealValue(Mem *pMem){
70762  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70763  double val = (double)0;
70764  sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
70765  return val;
70766}
70767SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
70768  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70769  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70770  if( pMem->flags & MEM_Real ){
70771    return pMem->u.r;
70772  }else if( pMem->flags & MEM_Int ){
70773    return (double)pMem->u.i;
70774  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
70775    return memRealValue(pMem);
70776  }else{
70777    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
70778    return (double)0;
70779  }
70780}
70781
70782/*
70783** The MEM structure is already a MEM_Real.  Try to also make it a
70784** MEM_Int if we can.
70785*/
70786SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
70787  i64 ix;
70788  assert( pMem->flags & MEM_Real );
70789  assert( (pMem->flags & MEM_RowSet)==0 );
70790  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70791  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70792
70793  ix = doubleToInt64(pMem->u.r);
70794
70795  /* Only mark the value as an integer if
70796  **
70797  **    (1) the round-trip conversion real->int->real is a no-op, and
70798  **    (2) The integer is neither the largest nor the smallest
70799  **        possible integer (ticket #3922)
70800  **
70801  ** The second and third terms in the following conditional enforces
70802  ** the second condition under the assumption that addition overflow causes
70803  ** values to wrap around.
70804  */
70805  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
70806    pMem->u.i = ix;
70807    MemSetTypeFlag(pMem, MEM_Int);
70808  }
70809}
70810
70811/*
70812** Convert pMem to type integer.  Invalidate any prior representations.
70813*/
70814SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
70815  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70816  assert( (pMem->flags & MEM_RowSet)==0 );
70817  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70818
70819  pMem->u.i = sqlite3VdbeIntValue(pMem);
70820  MemSetTypeFlag(pMem, MEM_Int);
70821  return SQLITE_OK;
70822}
70823
70824/*
70825** Convert pMem so that it is of type MEM_Real.
70826** Invalidate any prior representations.
70827*/
70828SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
70829  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70830  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
70831
70832  pMem->u.r = sqlite3VdbeRealValue(pMem);
70833  MemSetTypeFlag(pMem, MEM_Real);
70834  return SQLITE_OK;
70835}
70836
70837/*
70838** Convert pMem so that it has types MEM_Real or MEM_Int or both.
70839** Invalidate any prior representations.
70840**
70841** Every effort is made to force the conversion, even if the input
70842** is a string that does not look completely like a number.  Convert
70843** as much of the string as we can and ignore the rest.
70844*/
70845SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
70846  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
70847    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
70848    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
70849    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
70850      MemSetTypeFlag(pMem, MEM_Int);
70851    }else{
70852      pMem->u.r = sqlite3VdbeRealValue(pMem);
70853      MemSetTypeFlag(pMem, MEM_Real);
70854      sqlite3VdbeIntegerAffinity(pMem);
70855    }
70856  }
70857  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
70858  pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
70859  return SQLITE_OK;
70860}
70861
70862/*
70863** Cast the datatype of the value in pMem according to the affinity
70864** "aff".  Casting is different from applying affinity in that a cast
70865** is forced.  In other words, the value is converted into the desired
70866** affinity even if that results in loss of data.  This routine is
70867** used (for example) to implement the SQL "cast()" operator.
70868*/
70869SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
70870  if( pMem->flags & MEM_Null ) return;
70871  switch( aff ){
70872    case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
70873      if( (pMem->flags & MEM_Blob)==0 ){
70874        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
70875        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
70876        if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
70877      }else{
70878        pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
70879      }
70880      break;
70881    }
70882    case SQLITE_AFF_NUMERIC: {
70883      sqlite3VdbeMemNumerify(pMem);
70884      break;
70885    }
70886    case SQLITE_AFF_INTEGER: {
70887      sqlite3VdbeMemIntegerify(pMem);
70888      break;
70889    }
70890    case SQLITE_AFF_REAL: {
70891      sqlite3VdbeMemRealify(pMem);
70892      break;
70893    }
70894    default: {
70895      assert( aff==SQLITE_AFF_TEXT );
70896      assert( MEM_Str==(MEM_Blob>>3) );
70897      pMem->flags |= (pMem->flags&MEM_Blob)>>3;
70898      sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
70899      assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
70900      pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
70901      break;
70902    }
70903  }
70904}
70905
70906/*
70907** Initialize bulk memory to be a consistent Mem object.
70908**
70909** The minimum amount of initialization feasible is performed.
70910*/
70911SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
70912  assert( (flags & ~MEM_TypeMask)==0 );
70913  pMem->flags = flags;
70914  pMem->db = db;
70915  pMem->szMalloc = 0;
70916}
70917
70918
70919/*
70920** Delete any previous value and set the value stored in *pMem to NULL.
70921**
70922** This routine calls the Mem.xDel destructor to dispose of values that
70923** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
70924** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
70925** routine to invoke the destructor and deallocates Mem.zMalloc.
70926**
70927** Use this routine to reset the Mem prior to insert a new value.
70928**
70929** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
70930*/
70931SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
70932  if( VdbeMemDynamic(pMem) ){
70933    vdbeMemClearExternAndSetNull(pMem);
70934  }else{
70935    pMem->flags = MEM_Null;
70936  }
70937}
70938SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
70939  sqlite3VdbeMemSetNull((Mem*)p);
70940}
70941
70942/*
70943** Delete any previous value and set the value to be a BLOB of length
70944** n containing all zeros.
70945*/
70946SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
70947  sqlite3VdbeMemRelease(pMem);
70948  pMem->flags = MEM_Blob|MEM_Zero;
70949  pMem->n = 0;
70950  if( n<0 ) n = 0;
70951  pMem->u.nZero = n;
70952  pMem->enc = SQLITE_UTF8;
70953  pMem->z = 0;
70954}
70955
70956/*
70957** The pMem is known to contain content that needs to be destroyed prior
70958** to a value change.  So invoke the destructor, then set the value to
70959** a 64-bit integer.
70960*/
70961static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
70962  sqlite3VdbeMemSetNull(pMem);
70963  pMem->u.i = val;
70964  pMem->flags = MEM_Int;
70965}
70966
70967/*
70968** Delete any previous value and set the value stored in *pMem to val,
70969** manifest type INTEGER.
70970*/
70971SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
70972  if( VdbeMemDynamic(pMem) ){
70973    vdbeReleaseAndSetInt64(pMem, val);
70974  }else{
70975    pMem->u.i = val;
70976    pMem->flags = MEM_Int;
70977  }
70978}
70979
70980/* A no-op destructor */
70981static void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
70982
70983/*
70984** Set the value stored in *pMem should already be a NULL.
70985** Also store a pointer to go with it.
70986*/
70987SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
70988  Mem *pMem,
70989  void *pPtr,
70990  const char *zPType,
70991  void (*xDestructor)(void*)
70992){
70993  assert( pMem->flags==MEM_Null );
70994  pMem->u.zPType = zPType ? zPType : "";
70995  pMem->z = pPtr;
70996  pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
70997  pMem->eSubtype = 'p';
70998  pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
70999}
71000
71001#ifndef SQLITE_OMIT_FLOATING_POINT
71002/*
71003** Delete any previous value and set the value stored in *pMem to val,
71004** manifest type REAL.
71005*/
71006SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
71007  sqlite3VdbeMemSetNull(pMem);
71008  if( !sqlite3IsNaN(val) ){
71009    pMem->u.r = val;
71010    pMem->flags = MEM_Real;
71011  }
71012}
71013#endif
71014
71015/*
71016** Delete any previous value and set the value of pMem to be an
71017** empty boolean index.
71018*/
71019SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
71020  sqlite3 *db = pMem->db;
71021  assert( db!=0 );
71022  assert( (pMem->flags & MEM_RowSet)==0 );
71023  sqlite3VdbeMemRelease(pMem);
71024  pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
71025  if( db->mallocFailed ){
71026    pMem->flags = MEM_Null;
71027    pMem->szMalloc = 0;
71028  }else{
71029    assert( pMem->zMalloc );
71030    pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
71031    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
71032    assert( pMem->u.pRowSet!=0 );
71033    pMem->flags = MEM_RowSet;
71034  }
71035}
71036
71037/*
71038** Return true if the Mem object contains a TEXT or BLOB that is
71039** too large - whose size exceeds SQLITE_MAX_LENGTH.
71040*/
71041SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
71042  assert( p->db!=0 );
71043  if( p->flags & (MEM_Str|MEM_Blob) ){
71044    int n = p->n;
71045    if( p->flags & MEM_Zero ){
71046      n += p->u.nZero;
71047    }
71048    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
71049  }
71050  return 0;
71051}
71052
71053#ifdef SQLITE_DEBUG
71054/*
71055** This routine prepares a memory cell for modification by breaking
71056** its link to a shallow copy and by marking any current shallow
71057** copies of this cell as invalid.
71058**
71059** This is used for testing and debugging only - to make sure shallow
71060** copies are not misused.
71061*/
71062SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
71063  int i;
71064  Mem *pX;
71065  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
71066    if( pX->pScopyFrom==pMem ){
71067      pX->flags |= MEM_Undefined;
71068      pX->pScopyFrom = 0;
71069    }
71070  }
71071  pMem->pScopyFrom = 0;
71072}
71073#endif /* SQLITE_DEBUG */
71074
71075
71076/*
71077** Make an shallow copy of pFrom into pTo.  Prior contents of
71078** pTo are freed.  The pFrom->z field is not duplicated.  If
71079** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
71080** and flags gets srcType (either MEM_Ephem or MEM_Static).
71081*/
71082static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
71083  vdbeMemClearExternAndSetNull(pTo);
71084  assert( !VdbeMemDynamic(pTo) );
71085  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
71086}
71087SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
71088  assert( (pFrom->flags & MEM_RowSet)==0 );
71089  assert( pTo->db==pFrom->db );
71090  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
71091  memcpy(pTo, pFrom, MEMCELLSIZE);
71092  if( (pFrom->flags&MEM_Static)==0 ){
71093    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
71094    assert( srcType==MEM_Ephem || srcType==MEM_Static );
71095    pTo->flags |= srcType;
71096  }
71097}
71098
71099/*
71100** Make a full copy of pFrom into pTo.  Prior contents of pTo are
71101** freed before the copy is made.
71102*/
71103SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
71104  int rc = SQLITE_OK;
71105
71106  assert( (pFrom->flags & MEM_RowSet)==0 );
71107  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
71108  memcpy(pTo, pFrom, MEMCELLSIZE);
71109  pTo->flags &= ~MEM_Dyn;
71110  if( pTo->flags&(MEM_Str|MEM_Blob) ){
71111    if( 0==(pFrom->flags&MEM_Static) ){
71112      pTo->flags |= MEM_Ephem;
71113      rc = sqlite3VdbeMemMakeWriteable(pTo);
71114    }
71115  }
71116
71117  return rc;
71118}
71119
71120/*
71121** Transfer the contents of pFrom to pTo. Any existing value in pTo is
71122** freed. If pFrom contains ephemeral data, a copy is made.
71123**
71124** pFrom contains an SQL NULL when this routine returns.
71125*/
71126SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
71127  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
71128  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
71129  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
71130
71131  sqlite3VdbeMemRelease(pTo);
71132  memcpy(pTo, pFrom, sizeof(Mem));
71133  pFrom->flags = MEM_Null;
71134  pFrom->szMalloc = 0;
71135}
71136
71137/*
71138** Change the value of a Mem to be a string or a BLOB.
71139**
71140** The memory management strategy depends on the value of the xDel
71141** parameter. If the value passed is SQLITE_TRANSIENT, then the
71142** string is copied into a (possibly existing) buffer managed by the
71143** Mem structure. Otherwise, any existing buffer is freed and the
71144** pointer copied.
71145**
71146** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
71147** size limit) then no memory allocation occurs.  If the string can be
71148** stored without allocating memory, then it is.  If a memory allocation
71149** is required to store the string, then value of pMem is unchanged.  In
71150** either case, SQLITE_TOOBIG is returned.
71151*/
71152SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
71153  Mem *pMem,          /* Memory cell to set to string value */
71154  const char *z,      /* String pointer */
71155  int n,              /* Bytes in string, or negative */
71156  u8 enc,             /* Encoding of z.  0 for BLOBs */
71157  void (*xDel)(void*) /* Destructor function */
71158){
71159  int nByte = n;      /* New value for pMem->n */
71160  int iLimit;         /* Maximum allowed string or blob size */
71161  u16 flags = 0;      /* New value for pMem->flags */
71162
71163  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
71164  assert( (pMem->flags & MEM_RowSet)==0 );
71165
71166  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
71167  if( !z ){
71168    sqlite3VdbeMemSetNull(pMem);
71169    return SQLITE_OK;
71170  }
71171
71172  if( pMem->db ){
71173    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
71174  }else{
71175    iLimit = SQLITE_MAX_LENGTH;
71176  }
71177  flags = (enc==0?MEM_Blob:MEM_Str);
71178  if( nByte<0 ){
71179    assert( enc!=0 );
71180    if( enc==SQLITE_UTF8 ){
71181      nByte = sqlite3Strlen30(z);
71182      if( nByte>iLimit ) nByte = iLimit+1;
71183    }else{
71184      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
71185    }
71186    flags |= MEM_Term;
71187  }
71188
71189  /* The following block sets the new values of Mem.z and Mem.xDel. It
71190  ** also sets a flag in local variable "flags" to indicate the memory
71191  ** management (one of MEM_Dyn or MEM_Static).
71192  */
71193  if( xDel==SQLITE_TRANSIENT ){
71194    int nAlloc = nByte;
71195    if( flags&MEM_Term ){
71196      nAlloc += (enc==SQLITE_UTF8?1:2);
71197    }
71198    if( nByte>iLimit ){
71199      return SQLITE_TOOBIG;
71200    }
71201    testcase( nAlloc==0 );
71202    testcase( nAlloc==31 );
71203    testcase( nAlloc==32 );
71204    if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
71205      return SQLITE_NOMEM_BKPT;
71206    }
71207    memcpy(pMem->z, z, nAlloc);
71208  }else if( xDel==SQLITE_DYNAMIC ){
71209    sqlite3VdbeMemRelease(pMem);
71210    pMem->zMalloc = pMem->z = (char *)z;
71211    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
71212  }else{
71213    sqlite3VdbeMemRelease(pMem);
71214    pMem->z = (char *)z;
71215    pMem->xDel = xDel;
71216    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
71217  }
71218
71219  pMem->n = nByte;
71220  pMem->flags = flags;
71221  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
71222
71223#ifndef SQLITE_OMIT_UTF16
71224  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
71225    return SQLITE_NOMEM_BKPT;
71226  }
71227#endif
71228
71229  if( nByte>iLimit ){
71230    return SQLITE_TOOBIG;
71231  }
71232
71233  return SQLITE_OK;
71234}
71235
71236/*
71237** Move data out of a btree key or data field and into a Mem structure.
71238** The data is payload from the entry that pCur is currently pointing
71239** to.  offset and amt determine what portion of the data or key to retrieve.
71240** The result is written into the pMem element.
71241**
71242** The pMem object must have been initialized.  This routine will use
71243** pMem->zMalloc to hold the content from the btree, if possible.  New
71244** pMem->zMalloc space will be allocated if necessary.  The calling routine
71245** is responsible for making sure that the pMem object is eventually
71246** destroyed.
71247**
71248** If this routine fails for any reason (malloc returns NULL or unable
71249** to read from the disk) then the pMem is left in an inconsistent state.
71250*/
71251static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
71252  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
71253  u32 offset,       /* Offset from the start of data to return bytes from. */
71254  u32 amt,          /* Number of bytes to return. */
71255  Mem *pMem         /* OUT: Return data in this Mem structure. */
71256){
71257  int rc;
71258  pMem->flags = MEM_Null;
71259  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
71260    rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
71261    if( rc==SQLITE_OK ){
71262      pMem->z[amt] = 0;
71263      pMem->z[amt+1] = 0;
71264      pMem->flags = MEM_Blob|MEM_Term;
71265      pMem->n = (int)amt;
71266    }else{
71267      sqlite3VdbeMemRelease(pMem);
71268    }
71269  }
71270  return rc;
71271}
71272SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
71273  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
71274  u32 offset,       /* Offset from the start of data to return bytes from. */
71275  u32 amt,          /* Number of bytes to return. */
71276  Mem *pMem         /* OUT: Return data in this Mem structure. */
71277){
71278  char *zData;        /* Data from the btree layer */
71279  u32 available = 0;  /* Number of bytes available on the local btree page */
71280  int rc = SQLITE_OK; /* Return code */
71281
71282  assert( sqlite3BtreeCursorIsValid(pCur) );
71283  assert( !VdbeMemDynamic(pMem) );
71284
71285  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
71286  ** that both the BtShared and database handle mutexes are held. */
71287  assert( (pMem->flags & MEM_RowSet)==0 );
71288  zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
71289  assert( zData!=0 );
71290
71291  if( offset+amt<=available ){
71292    pMem->z = &zData[offset];
71293    pMem->flags = MEM_Blob|MEM_Ephem;
71294    pMem->n = (int)amt;
71295  }else{
71296    rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
71297  }
71298
71299  return rc;
71300}
71301
71302/*
71303** The pVal argument is known to be a value other than NULL.
71304** Convert it into a string with encoding enc and return a pointer
71305** to a zero-terminated version of that string.
71306*/
71307static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
71308  assert( pVal!=0 );
71309  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
71310  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
71311  assert( (pVal->flags & MEM_RowSet)==0 );
71312  assert( (pVal->flags & (MEM_Null))==0 );
71313  if( pVal->flags & (MEM_Blob|MEM_Str) ){
71314    if( ExpandBlob(pVal) ) return 0;
71315    pVal->flags |= MEM_Str;
71316    if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
71317      sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
71318    }
71319    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
71320      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
71321      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
71322        return 0;
71323      }
71324    }
71325    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
71326  }else{
71327    sqlite3VdbeMemStringify(pVal, enc, 0);
71328    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
71329  }
71330  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
71331              || pVal->db->mallocFailed );
71332  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
71333    return pVal->z;
71334  }else{
71335    return 0;
71336  }
71337}
71338
71339/* This function is only available internally, it is not part of the
71340** external API. It works in a similar way to sqlite3_value_text(),
71341** except the data returned is in the encoding specified by the second
71342** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
71343** SQLITE_UTF8.
71344**
71345** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
71346** If that is the case, then the result must be aligned on an even byte
71347** boundary.
71348*/
71349SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
71350  if( !pVal ) return 0;
71351  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
71352  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
71353  assert( (pVal->flags & MEM_RowSet)==0 );
71354  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
71355    return pVal->z;
71356  }
71357  if( pVal->flags&MEM_Null ){
71358    return 0;
71359  }
71360  return valueToText(pVal, enc);
71361}
71362
71363/*
71364** Create a new sqlite3_value object.
71365*/
71366SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
71367  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
71368  if( p ){
71369    p->flags = MEM_Null;
71370    p->db = db;
71371  }
71372  return p;
71373}
71374
71375/*
71376** Context object passed by sqlite3Stat4ProbeSetValue() through to
71377** valueNew(). See comments above valueNew() for details.
71378*/
71379struct ValueNewStat4Ctx {
71380  Parse *pParse;
71381  Index *pIdx;
71382  UnpackedRecord **ppRec;
71383  int iVal;
71384};
71385
71386/*
71387** Allocate and return a pointer to a new sqlite3_value object. If
71388** the second argument to this function is NULL, the object is allocated
71389** by calling sqlite3ValueNew().
71390**
71391** Otherwise, if the second argument is non-zero, then this function is
71392** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
71393** already been allocated, allocate the UnpackedRecord structure that
71394** that function will return to its caller here. Then return a pointer to
71395** an sqlite3_value within the UnpackedRecord.a[] array.
71396*/
71397static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
71398#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71399  if( p ){
71400    UnpackedRecord *pRec = p->ppRec[0];
71401
71402    if( pRec==0 ){
71403      Index *pIdx = p->pIdx;      /* Index being probed */
71404      int nByte;                  /* Bytes of space to allocate */
71405      int i;                      /* Counter variable */
71406      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
71407
71408      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
71409      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
71410      if( pRec ){
71411        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
71412        if( pRec->pKeyInfo ){
71413          assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
71414          assert( pRec->pKeyInfo->enc==ENC(db) );
71415          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
71416          for(i=0; i<nCol; i++){
71417            pRec->aMem[i].flags = MEM_Null;
71418            pRec->aMem[i].db = db;
71419          }
71420        }else{
71421          sqlite3DbFreeNN(db, pRec);
71422          pRec = 0;
71423        }
71424      }
71425      if( pRec==0 ) return 0;
71426      p->ppRec[0] = pRec;
71427    }
71428
71429    pRec->nField = p->iVal+1;
71430    return &pRec->aMem[p->iVal];
71431  }
71432#else
71433  UNUSED_PARAMETER(p);
71434#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
71435  return sqlite3ValueNew(db);
71436}
71437
71438/*
71439** The expression object indicated by the second argument is guaranteed
71440** to be a scalar SQL function. If
71441**
71442**   * all function arguments are SQL literals,
71443**   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
71444**   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
71445**
71446** then this routine attempts to invoke the SQL function. Assuming no
71447** error occurs, output parameter (*ppVal) is set to point to a value
71448** object containing the result before returning SQLITE_OK.
71449**
71450** Affinity aff is applied to the result of the function before returning.
71451** If the result is a text value, the sqlite3_value object uses encoding
71452** enc.
71453**
71454** If the conditions above are not met, this function returns SQLITE_OK
71455** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
71456** NULL and an SQLite error code returned.
71457*/
71458#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71459static int valueFromFunction(
71460  sqlite3 *db,                    /* The database connection */
71461  Expr *p,                        /* The expression to evaluate */
71462  u8 enc,                         /* Encoding to use */
71463  u8 aff,                         /* Affinity to use */
71464  sqlite3_value **ppVal,          /* Write the new value here */
71465  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
71466){
71467  sqlite3_context ctx;            /* Context object for function invocation */
71468  sqlite3_value **apVal = 0;      /* Function arguments */
71469  int nVal = 0;                   /* Size of apVal[] array */
71470  FuncDef *pFunc = 0;             /* Function definition */
71471  sqlite3_value *pVal = 0;        /* New value */
71472  int rc = SQLITE_OK;             /* Return code */
71473  ExprList *pList = 0;            /* Function arguments */
71474  int i;                          /* Iterator variable */
71475
71476  assert( pCtx!=0 );
71477  assert( (p->flags & EP_TokenOnly)==0 );
71478  pList = p->x.pList;
71479  if( pList ) nVal = pList->nExpr;
71480  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
71481  assert( pFunc );
71482  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
71483   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
71484  ){
71485    return SQLITE_OK;
71486  }
71487
71488  if( pList ){
71489    apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
71490    if( apVal==0 ){
71491      rc = SQLITE_NOMEM_BKPT;
71492      goto value_from_function_out;
71493    }
71494    for(i=0; i<nVal; i++){
71495      rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
71496      if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
71497    }
71498  }
71499
71500  pVal = valueNew(db, pCtx);
71501  if( pVal==0 ){
71502    rc = SQLITE_NOMEM_BKPT;
71503    goto value_from_function_out;
71504  }
71505
71506  assert( pCtx->pParse->rc==SQLITE_OK );
71507  memset(&ctx, 0, sizeof(ctx));
71508  ctx.pOut = pVal;
71509  ctx.pFunc = pFunc;
71510  pFunc->xSFunc(&ctx, nVal, apVal);
71511  if( ctx.isError ){
71512    rc = ctx.isError;
71513    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
71514  }else{
71515    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
71516    assert( rc==SQLITE_OK );
71517    rc = sqlite3VdbeChangeEncoding(pVal, enc);
71518    if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
71519      rc = SQLITE_TOOBIG;
71520      pCtx->pParse->nErr++;
71521    }
71522  }
71523  pCtx->pParse->rc = rc;
71524
71525 value_from_function_out:
71526  if( rc!=SQLITE_OK ){
71527    pVal = 0;
71528  }
71529  if( apVal ){
71530    for(i=0; i<nVal; i++){
71531      sqlite3ValueFree(apVal[i]);
71532    }
71533    sqlite3DbFreeNN(db, apVal);
71534  }
71535
71536  *ppVal = pVal;
71537  return rc;
71538}
71539#else
71540# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
71541#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
71542
71543/*
71544** Extract a value from the supplied expression in the manner described
71545** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
71546** using valueNew().
71547**
71548** If pCtx is NULL and an error occurs after the sqlite3_value object
71549** has been allocated, it is freed before returning. Or, if pCtx is not
71550** NULL, it is assumed that the caller will free any allocated object
71551** in all cases.
71552*/
71553static int valueFromExpr(
71554  sqlite3 *db,                    /* The database connection */
71555  Expr *pExpr,                    /* The expression to evaluate */
71556  u8 enc,                         /* Encoding to use */
71557  u8 affinity,                    /* Affinity to use */
71558  sqlite3_value **ppVal,          /* Write the new value here */
71559  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
71560){
71561  int op;
71562  char *zVal = 0;
71563  sqlite3_value *pVal = 0;
71564  int negInt = 1;
71565  const char *zNeg = "";
71566  int rc = SQLITE_OK;
71567
71568  assert( pExpr!=0 );
71569  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
71570  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
71571
71572  /* Compressed expressions only appear when parsing the DEFAULT clause
71573  ** on a table column definition, and hence only when pCtx==0.  This
71574  ** check ensures that an EP_TokenOnly expression is never passed down
71575  ** into valueFromFunction(). */
71576  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
71577
71578  if( op==TK_CAST ){
71579    u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
71580    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
71581    testcase( rc!=SQLITE_OK );
71582    if( *ppVal ){
71583      sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
71584      sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
71585    }
71586    return rc;
71587  }
71588
71589  /* Handle negative integers in a single step.  This is needed in the
71590  ** case when the value is -9223372036854775808.
71591  */
71592  if( op==TK_UMINUS
71593   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
71594    pExpr = pExpr->pLeft;
71595    op = pExpr->op;
71596    negInt = -1;
71597    zNeg = "-";
71598  }
71599
71600  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
71601    pVal = valueNew(db, pCtx);
71602    if( pVal==0 ) goto no_mem;
71603    if( ExprHasProperty(pExpr, EP_IntValue) ){
71604      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
71605    }else{
71606      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
71607      if( zVal==0 ) goto no_mem;
71608      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
71609    }
71610    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
71611      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
71612    }else{
71613      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
71614    }
71615    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
71616    if( enc!=SQLITE_UTF8 ){
71617      rc = sqlite3VdbeChangeEncoding(pVal, enc);
71618    }
71619  }else if( op==TK_UMINUS ) {
71620    /* This branch happens for multiple negative signs.  Ex: -(-5) */
71621    if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
71622     && pVal!=0
71623    ){
71624      sqlite3VdbeMemNumerify(pVal);
71625      if( pVal->flags & MEM_Real ){
71626        pVal->u.r = -pVal->u.r;
71627      }else if( pVal->u.i==SMALLEST_INT64 ){
71628        pVal->u.r = -(double)SMALLEST_INT64;
71629        MemSetTypeFlag(pVal, MEM_Real);
71630      }else{
71631        pVal->u.i = -pVal->u.i;
71632      }
71633      sqlite3ValueApplyAffinity(pVal, affinity, enc);
71634    }
71635  }else if( op==TK_NULL ){
71636    pVal = valueNew(db, pCtx);
71637    if( pVal==0 ) goto no_mem;
71638    sqlite3VdbeMemNumerify(pVal);
71639  }
71640#ifndef SQLITE_OMIT_BLOB_LITERAL
71641  else if( op==TK_BLOB ){
71642    int nVal;
71643    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
71644    assert( pExpr->u.zToken[1]=='\'' );
71645    pVal = valueNew(db, pCtx);
71646    if( !pVal ) goto no_mem;
71647    zVal = &pExpr->u.zToken[2];
71648    nVal = sqlite3Strlen30(zVal)-1;
71649    assert( zVal[nVal]=='\'' );
71650    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
71651                         0, SQLITE_DYNAMIC);
71652  }
71653#endif
71654
71655#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71656  else if( op==TK_FUNCTION && pCtx!=0 ){
71657    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
71658  }
71659#endif
71660
71661  *ppVal = pVal;
71662  return rc;
71663
71664no_mem:
71665  sqlite3OomFault(db);
71666  sqlite3DbFree(db, zVal);
71667  assert( *ppVal==0 );
71668#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71669  if( pCtx==0 ) sqlite3ValueFree(pVal);
71670#else
71671  assert( pCtx==0 ); sqlite3ValueFree(pVal);
71672#endif
71673  return SQLITE_NOMEM_BKPT;
71674}
71675
71676/*
71677** Create a new sqlite3_value object, containing the value of pExpr.
71678**
71679** This only works for very simple expressions that consist of one constant
71680** token (i.e. "5", "5.1", "'a string'"). If the expression can
71681** be converted directly into a value, then the value is allocated and
71682** a pointer written to *ppVal. The caller is responsible for deallocating
71683** the value by passing it to sqlite3ValueFree() later on. If the expression
71684** cannot be converted to a value, then *ppVal is set to NULL.
71685*/
71686SQLITE_PRIVATE int sqlite3ValueFromExpr(
71687  sqlite3 *db,              /* The database connection */
71688  Expr *pExpr,              /* The expression to evaluate */
71689  u8 enc,                   /* Encoding to use */
71690  u8 affinity,              /* Affinity to use */
71691  sqlite3_value **ppVal     /* Write the new value here */
71692){
71693  return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
71694}
71695
71696#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
71697/*
71698** The implementation of the sqlite_record() function. This function accepts
71699** a single argument of any type. The return value is a formatted database
71700** record (a blob) containing the argument value.
71701**
71702** This is used to convert the value stored in the 'sample' column of the
71703** sqlite_stat3 table to the record format SQLite uses internally.
71704*/
71705static void recordFunc(
71706  sqlite3_context *context,
71707  int argc,
71708  sqlite3_value **argv
71709){
71710  const int file_format = 1;
71711  u32 iSerial;                    /* Serial type */
71712  int nSerial;                    /* Bytes of space for iSerial as varint */
71713  u32 nVal;                       /* Bytes of space required for argv[0] */
71714  int nRet;
71715  sqlite3 *db;
71716  u8 *aRet;
71717
71718  UNUSED_PARAMETER( argc );
71719  iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
71720  nSerial = sqlite3VarintLen(iSerial);
71721  db = sqlite3_context_db_handle(context);
71722
71723  nRet = 1 + nSerial + nVal;
71724  aRet = sqlite3DbMallocRawNN(db, nRet);
71725  if( aRet==0 ){
71726    sqlite3_result_error_nomem(context);
71727  }else{
71728    aRet[0] = nSerial+1;
71729    putVarint32(&aRet[1], iSerial);
71730    sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
71731    sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
71732    sqlite3DbFreeNN(db, aRet);
71733  }
71734}
71735
71736/*
71737** Register built-in functions used to help read ANALYZE data.
71738*/
71739SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
71740  static FuncDef aAnalyzeTableFuncs[] = {
71741    FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
71742  };
71743  sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
71744}
71745
71746/*
71747** Attempt to extract a value from pExpr and use it to construct *ppVal.
71748**
71749** If pAlloc is not NULL, then an UnpackedRecord object is created for
71750** pAlloc if one does not exist and the new value is added to the
71751** UnpackedRecord object.
71752**
71753** A value is extracted in the following cases:
71754**
71755**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
71756**
71757**  * The expression is a bound variable, and this is a reprepare, or
71758**
71759**  * The expression is a literal value.
71760**
71761** On success, *ppVal is made to point to the extracted value.  The caller
71762** is responsible for ensuring that the value is eventually freed.
71763*/
71764static int stat4ValueFromExpr(
71765  Parse *pParse,                  /* Parse context */
71766  Expr *pExpr,                    /* The expression to extract a value from */
71767  u8 affinity,                    /* Affinity to use */
71768  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
71769  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
71770){
71771  int rc = SQLITE_OK;
71772  sqlite3_value *pVal = 0;
71773  sqlite3 *db = pParse->db;
71774
71775  /* Skip over any TK_COLLATE nodes */
71776  pExpr = sqlite3ExprSkipCollate(pExpr);
71777
71778  assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
71779  if( !pExpr ){
71780    pVal = valueNew(db, pAlloc);
71781    if( pVal ){
71782      sqlite3VdbeMemSetNull((Mem*)pVal);
71783    }
71784  }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
71785    Vdbe *v;
71786    int iBindVar = pExpr->iColumn;
71787    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
71788    if( (v = pParse->pReprepare)!=0 ){
71789      pVal = valueNew(db, pAlloc);
71790      if( pVal ){
71791        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
71792        sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
71793        pVal->db = pParse->db;
71794      }
71795    }
71796  }else{
71797    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
71798  }
71799
71800  assert( pVal==0 || pVal->db==db );
71801  *ppVal = pVal;
71802  return rc;
71803}
71804
71805/*
71806** This function is used to allocate and populate UnpackedRecord
71807** structures intended to be compared against sample index keys stored
71808** in the sqlite_stat4 table.
71809**
71810** A single call to this function populates zero or more fields of the
71811** record starting with field iVal (fields are numbered from left to
71812** right starting with 0). A single field is populated if:
71813**
71814**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
71815**
71816**  * The expression is a bound variable, and this is a reprepare, or
71817**
71818**  * The sqlite3ValueFromExpr() function is able to extract a value
71819**    from the expression (i.e. the expression is a literal value).
71820**
71821** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
71822** vector components that match either of the two latter criteria listed
71823** above.
71824**
71825** Before any value is appended to the record, the affinity of the
71826** corresponding column within index pIdx is applied to it. Before
71827** this function returns, output parameter *pnExtract is set to the
71828** number of values appended to the record.
71829**
71830** When this function is called, *ppRec must either point to an object
71831** allocated by an earlier call to this function, or must be NULL. If it
71832** is NULL and a value can be successfully extracted, a new UnpackedRecord
71833** is allocated (and *ppRec set to point to it) before returning.
71834**
71835** Unless an error is encountered, SQLITE_OK is returned. It is not an
71836** error if a value cannot be extracted from pExpr. If an error does
71837** occur, an SQLite error code is returned.
71838*/
71839SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
71840  Parse *pParse,                  /* Parse context */
71841  Index *pIdx,                    /* Index being probed */
71842  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
71843  Expr *pExpr,                    /* The expression to extract a value from */
71844  int nElem,                      /* Maximum number of values to append */
71845  int iVal,                       /* Array element to populate */
71846  int *pnExtract                  /* OUT: Values appended to the record */
71847){
71848  int rc = SQLITE_OK;
71849  int nExtract = 0;
71850
71851  if( pExpr==0 || pExpr->op!=TK_SELECT ){
71852    int i;
71853    struct ValueNewStat4Ctx alloc;
71854
71855    alloc.pParse = pParse;
71856    alloc.pIdx = pIdx;
71857    alloc.ppRec = ppRec;
71858
71859    for(i=0; i<nElem; i++){
71860      sqlite3_value *pVal = 0;
71861      Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
71862      u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
71863      alloc.iVal = iVal+i;
71864      rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
71865      if( !pVal ) break;
71866      nExtract++;
71867    }
71868  }
71869
71870  *pnExtract = nExtract;
71871  return rc;
71872}
71873
71874/*
71875** Attempt to extract a value from expression pExpr using the methods
71876** as described for sqlite3Stat4ProbeSetValue() above.
71877**
71878** If successful, set *ppVal to point to a new value object and return
71879** SQLITE_OK. If no value can be extracted, but no other error occurs
71880** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
71881** does occur, return an SQLite error code. The final value of *ppVal
71882** is undefined in this case.
71883*/
71884SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
71885  Parse *pParse,                  /* Parse context */
71886  Expr *pExpr,                    /* The expression to extract a value from */
71887  u8 affinity,                    /* Affinity to use */
71888  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
71889){
71890  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
71891}
71892
71893/*
71894** Extract the iCol-th column from the nRec-byte record in pRec.  Write
71895** the column value into *ppVal.  If *ppVal is initially NULL then a new
71896** sqlite3_value object is allocated.
71897**
71898** If *ppVal is initially NULL then the caller is responsible for
71899** ensuring that the value written into *ppVal is eventually freed.
71900*/
71901SQLITE_PRIVATE int sqlite3Stat4Column(
71902  sqlite3 *db,                    /* Database handle */
71903  const void *pRec,               /* Pointer to buffer containing record */
71904  int nRec,                       /* Size of buffer pRec in bytes */
71905  int iCol,                       /* Column to extract */
71906  sqlite3_value **ppVal           /* OUT: Extracted value */
71907){
71908  u32 t;                          /* a column type code */
71909  int nHdr;                       /* Size of the header in the record */
71910  int iHdr;                       /* Next unread header byte */
71911  int iField;                     /* Next unread data byte */
71912  int szField;                    /* Size of the current data field */
71913  int i;                          /* Column index */
71914  u8 *a = (u8*)pRec;              /* Typecast byte array */
71915  Mem *pMem = *ppVal;             /* Write result into this Mem object */
71916
71917  assert( iCol>0 );
71918  iHdr = getVarint32(a, nHdr);
71919  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
71920  iField = nHdr;
71921  for(i=0; i<=iCol; i++){
71922    iHdr += getVarint32(&a[iHdr], t);
71923    testcase( iHdr==nHdr );
71924    testcase( iHdr==nHdr+1 );
71925    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
71926    szField = sqlite3VdbeSerialTypeLen(t);
71927    iField += szField;
71928  }
71929  testcase( iField==nRec );
71930  testcase( iField==nRec+1 );
71931  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
71932  if( pMem==0 ){
71933    pMem = *ppVal = sqlite3ValueNew(db);
71934    if( pMem==0 ) return SQLITE_NOMEM_BKPT;
71935  }
71936  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
71937  pMem->enc = ENC(db);
71938  return SQLITE_OK;
71939}
71940
71941/*
71942** Unless it is NULL, the argument must be an UnpackedRecord object returned
71943** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
71944** the object.
71945*/
71946SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
71947  if( pRec ){
71948    int i;
71949    int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
71950    Mem *aMem = pRec->aMem;
71951    sqlite3 *db = aMem[0].db;
71952    for(i=0; i<nCol; i++){
71953      sqlite3VdbeMemRelease(&aMem[i]);
71954    }
71955    sqlite3KeyInfoUnref(pRec->pKeyInfo);
71956    sqlite3DbFreeNN(db, pRec);
71957  }
71958}
71959#endif /* ifdef SQLITE_ENABLE_STAT4 */
71960
71961/*
71962** Change the string value of an sqlite3_value object
71963*/
71964SQLITE_PRIVATE void sqlite3ValueSetStr(
71965  sqlite3_value *v,     /* Value to be set */
71966  int n,                /* Length of string z */
71967  const void *z,        /* Text of the new string */
71968  u8 enc,               /* Encoding to use */
71969  void (*xDel)(void*)   /* Destructor for the string */
71970){
71971  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
71972}
71973
71974/*
71975** Free an sqlite3_value object
71976*/
71977SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
71978  if( !v ) return;
71979  sqlite3VdbeMemRelease((Mem *)v);
71980  sqlite3DbFreeNN(((Mem*)v)->db, v);
71981}
71982
71983/*
71984** The sqlite3ValueBytes() routine returns the number of bytes in the
71985** sqlite3_value object assuming that it uses the encoding "enc".
71986** The valueBytes() routine is a helper function.
71987*/
71988static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
71989  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
71990}
71991SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
71992  Mem *p = (Mem*)pVal;
71993  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
71994  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
71995    return p->n;
71996  }
71997  if( (p->flags & MEM_Blob)!=0 ){
71998    if( p->flags & MEM_Zero ){
71999      return p->n + p->u.nZero;
72000    }else{
72001      return p->n;
72002    }
72003  }
72004  if( p->flags & MEM_Null ) return 0;
72005  return valueBytes(pVal, enc);
72006}
72007
72008/************** End of vdbemem.c *********************************************/
72009/************** Begin file vdbeaux.c *****************************************/
72010/*
72011** 2003 September 6
72012**
72013** The author disclaims copyright to this source code.  In place of
72014** a legal notice, here is a blessing:
72015**
72016**    May you do good and not evil.
72017**    May you find forgiveness for yourself and forgive others.
72018**    May you share freely, never taking more than you give.
72019**
72020*************************************************************************
72021** This file contains code used for creating, destroying, and populating
72022** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
72023*/
72024/* #include "sqliteInt.h" */
72025/* #include "vdbeInt.h" */
72026
72027/*
72028** Create a new virtual database engine.
72029*/
72030SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
72031  sqlite3 *db = pParse->db;
72032  Vdbe *p;
72033  p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
72034  if( p==0 ) return 0;
72035  memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
72036  p->db = db;
72037  if( db->pVdbe ){
72038    db->pVdbe->pPrev = p;
72039  }
72040  p->pNext = db->pVdbe;
72041  p->pPrev = 0;
72042  db->pVdbe = p;
72043  p->magic = VDBE_MAGIC_INIT;
72044  p->pParse = pParse;
72045  assert( pParse->aLabel==0 );
72046  assert( pParse->nLabel==0 );
72047  assert( pParse->nOpAlloc==0 );
72048  assert( pParse->szOpAlloc==0 );
72049  return p;
72050}
72051
72052/*
72053** Change the error string stored in Vdbe.zErrMsg
72054*/
72055SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
72056  va_list ap;
72057  sqlite3DbFree(p->db, p->zErrMsg);
72058  va_start(ap, zFormat);
72059  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
72060  va_end(ap);
72061}
72062
72063/*
72064** Remember the SQL string for a prepared statement.
72065*/
72066SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
72067  if( p==0 ) return;
72068  p->prepFlags = prepFlags;
72069  if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
72070    p->expmask = 0;
72071  }
72072  assert( p->zSql==0 );
72073  p->zSql = sqlite3DbStrNDup(p->db, z, n);
72074}
72075
72076/*
72077** Swap all content between two VDBE structures.
72078*/
72079SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
72080  Vdbe tmp, *pTmp;
72081  char *zTmp;
72082  assert( pA->db==pB->db );
72083  tmp = *pA;
72084  *pA = *pB;
72085  *pB = tmp;
72086  pTmp = pA->pNext;
72087  pA->pNext = pB->pNext;
72088  pB->pNext = pTmp;
72089  pTmp = pA->pPrev;
72090  pA->pPrev = pB->pPrev;
72091  pB->pPrev = pTmp;
72092  zTmp = pA->zSql;
72093  pA->zSql = pB->zSql;
72094  pB->zSql = zTmp;
72095  pB->expmask = pA->expmask;
72096  pB->prepFlags = pA->prepFlags;
72097  memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
72098  pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
72099}
72100
72101/*
72102** Resize the Vdbe.aOp array so that it is at least nOp elements larger
72103** than its current size. nOp is guaranteed to be less than or equal
72104** to 1024/sizeof(Op).
72105**
72106** If an out-of-memory error occurs while resizing the array, return
72107** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
72108** unchanged (this is so that any opcodes already allocated can be
72109** correctly deallocated along with the rest of the Vdbe).
72110*/
72111static int growOpArray(Vdbe *v, int nOp){
72112  VdbeOp *pNew;
72113  Parse *p = v->pParse;
72114
72115  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
72116  ** more frequent reallocs and hence provide more opportunities for
72117  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
72118  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
72119  ** by the minimum* amount required until the size reaches 512.  Normal
72120  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
72121  ** size of the op array or add 1KB of space, whichever is smaller. */
72122#ifdef SQLITE_TEST_REALLOC_STRESS
72123  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
72124#else
72125  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
72126  UNUSED_PARAMETER(nOp);
72127#endif
72128
72129  /* Ensure that the size of a VDBE does not grow too large */
72130  if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
72131    sqlite3OomFault(p->db);
72132    return SQLITE_NOMEM;
72133  }
72134
72135  assert( nOp<=(1024/sizeof(Op)) );
72136  assert( nNew>=(p->nOpAlloc+nOp) );
72137  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
72138  if( pNew ){
72139    p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
72140    p->nOpAlloc = p->szOpAlloc/sizeof(Op);
72141    v->aOp = pNew;
72142  }
72143  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
72144}
72145
72146#ifdef SQLITE_DEBUG
72147/* This routine is just a convenient place to set a breakpoint that will
72148** fire after each opcode is inserted and displayed using
72149** "PRAGMA vdbe_addoptrace=on".
72150*/
72151static void test_addop_breakpoint(void){
72152  static int n = 0;
72153  n++;
72154}
72155#endif
72156
72157/*
72158** Add a new instruction to the list of instructions current in the
72159** VDBE.  Return the address of the new instruction.
72160**
72161** Parameters:
72162**
72163**    p               Pointer to the VDBE
72164**
72165**    op              The opcode for this instruction
72166**
72167**    p1, p2, p3      Operands
72168**
72169** Use the sqlite3VdbeResolveLabel() function to fix an address and
72170** the sqlite3VdbeChangeP4() function to change the value of the P4
72171** operand.
72172*/
72173static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
72174  assert( p->pParse->nOpAlloc<=p->nOp );
72175  if( growOpArray(p, 1) ) return 1;
72176  assert( p->pParse->nOpAlloc>p->nOp );
72177  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
72178}
72179SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
72180  int i;
72181  VdbeOp *pOp;
72182
72183  i = p->nOp;
72184  assert( p->magic==VDBE_MAGIC_INIT );
72185  assert( op>=0 && op<0xff );
72186  if( p->pParse->nOpAlloc<=i ){
72187    return growOp3(p, op, p1, p2, p3);
72188  }
72189  p->nOp++;
72190  pOp = &p->aOp[i];
72191  pOp->opcode = (u8)op;
72192  pOp->p5 = 0;
72193  pOp->p1 = p1;
72194  pOp->p2 = p2;
72195  pOp->p3 = p3;
72196  pOp->p4.p = 0;
72197  pOp->p4type = P4_NOTUSED;
72198#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72199  pOp->zComment = 0;
72200#endif
72201#ifdef SQLITE_DEBUG
72202  if( p->db->flags & SQLITE_VdbeAddopTrace ){
72203    int jj, kk;
72204    Parse *pParse = p->pParse;
72205    for(jj=kk=0; jj<pParse->nColCache; jj++){
72206      struct yColCache *x = pParse->aColCache + jj;
72207      printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
72208      kk++;
72209    }
72210    if( kk ) printf("\n");
72211    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
72212    test_addop_breakpoint();
72213  }
72214#endif
72215#ifdef VDBE_PROFILE
72216  pOp->cycles = 0;
72217  pOp->cnt = 0;
72218#endif
72219#ifdef SQLITE_VDBE_COVERAGE
72220  pOp->iSrcLine = 0;
72221#endif
72222  return i;
72223}
72224SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
72225  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
72226}
72227SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
72228  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
72229}
72230SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
72231  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
72232}
72233
72234/* Generate code for an unconditional jump to instruction iDest
72235*/
72236SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
72237  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
72238}
72239
72240/* Generate code to cause the string zStr to be loaded into
72241** register iDest
72242*/
72243SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
72244  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
72245}
72246
72247/*
72248** Generate code that initializes multiple registers to string or integer
72249** constants.  The registers begin with iDest and increase consecutively.
72250** One register is initialized for each characgter in zTypes[].  For each
72251** "s" character in zTypes[], the register is a string if the argument is
72252** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
72253** in zTypes[], the register is initialized to an integer.
72254**
72255** If the input string does not end with "X" then an OP_ResultRow instruction
72256** is generated for the values inserted.
72257*/
72258SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
72259  va_list ap;
72260  int i;
72261  char c;
72262  va_start(ap, zTypes);
72263  for(i=0; (c = zTypes[i])!=0; i++){
72264    if( c=='s' ){
72265      const char *z = va_arg(ap, const char*);
72266      sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
72267    }else if( c=='i' ){
72268      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
72269    }else{
72270      goto skip_op_resultrow;
72271    }
72272  }
72273  sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
72274skip_op_resultrow:
72275  va_end(ap);
72276}
72277
72278/*
72279** Add an opcode that includes the p4 value as a pointer.
72280*/
72281SQLITE_PRIVATE int sqlite3VdbeAddOp4(
72282  Vdbe *p,            /* Add the opcode to this VM */
72283  int op,             /* The new opcode */
72284  int p1,             /* The P1 operand */
72285  int p2,             /* The P2 operand */
72286  int p3,             /* The P3 operand */
72287  const char *zP4,    /* The P4 operand */
72288  int p4type          /* P4 operand type */
72289){
72290  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
72291  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
72292  return addr;
72293}
72294
72295/*
72296** Add an opcode that includes the p4 value with a P4_INT64 or
72297** P4_REAL type.
72298*/
72299SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
72300  Vdbe *p,            /* Add the opcode to this VM */
72301  int op,             /* The new opcode */
72302  int p1,             /* The P1 operand */
72303  int p2,             /* The P2 operand */
72304  int p3,             /* The P3 operand */
72305  const u8 *zP4,      /* The P4 operand */
72306  int p4type          /* P4 operand type */
72307){
72308  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
72309  if( p4copy ) memcpy(p4copy, zP4, 8);
72310  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
72311}
72312
72313/*
72314** Add an OP_ParseSchema opcode.  This routine is broken out from
72315** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
72316** as having been used.
72317**
72318** The zWhere string must have been obtained from sqlite3_malloc().
72319** This routine will take ownership of the allocated memory.
72320*/
72321SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
72322  int j;
72323  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
72324  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
72325}
72326
72327/*
72328** Add an opcode that includes the p4 value as an integer.
72329*/
72330SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
72331  Vdbe *p,            /* Add the opcode to this VM */
72332  int op,             /* The new opcode */
72333  int p1,             /* The P1 operand */
72334  int p2,             /* The P2 operand */
72335  int p3,             /* The P3 operand */
72336  int p4              /* The P4 operand as an integer */
72337){
72338  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
72339  if( p->db->mallocFailed==0 ){
72340    VdbeOp *pOp = &p->aOp[addr];
72341    pOp->p4type = P4_INT32;
72342    pOp->p4.i = p4;
72343  }
72344  return addr;
72345}
72346
72347/* Insert the end of a co-routine
72348*/
72349SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
72350  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
72351
72352  /* Clear the temporary register cache, thereby ensuring that each
72353  ** co-routine has its own independent set of registers, because co-routines
72354  ** might expect their registers to be preserved across an OP_Yield, and
72355  ** that could cause problems if two or more co-routines are using the same
72356  ** temporary register.
72357  */
72358  v->pParse->nTempReg = 0;
72359  v->pParse->nRangeReg = 0;
72360}
72361
72362/*
72363** Create a new symbolic label for an instruction that has yet to be
72364** coded.  The symbolic label is really just a negative number.  The
72365** label can be used as the P2 value of an operation.  Later, when
72366** the label is resolved to a specific address, the VDBE will scan
72367** through its operation list and change all values of P2 which match
72368** the label into the resolved address.
72369**
72370** The VDBE knows that a P2 value is a label because labels are
72371** always negative and P2 values are suppose to be non-negative.
72372** Hence, a negative P2 value is a label that has yet to be resolved.
72373**
72374** Zero is returned if a malloc() fails.
72375*/
72376SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
72377  Parse *p = v->pParse;
72378  int i = p->nLabel++;
72379  assert( v->magic==VDBE_MAGIC_INIT );
72380  if( (i & (i-1))==0 ){
72381    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
72382                                       (i*2+1)*sizeof(p->aLabel[0]));
72383  }
72384  if( p->aLabel ){
72385    p->aLabel[i] = -1;
72386  }
72387  return ADDR(i);
72388}
72389
72390/*
72391** Resolve label "x" to be the address of the next instruction to
72392** be inserted.  The parameter "x" must have been obtained from
72393** a prior call to sqlite3VdbeMakeLabel().
72394*/
72395SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
72396  Parse *p = v->pParse;
72397  int j = ADDR(x);
72398  assert( v->magic==VDBE_MAGIC_INIT );
72399  assert( j<p->nLabel );
72400  assert( j>=0 );
72401  if( p->aLabel ){
72402    p->aLabel[j] = v->nOp;
72403  }
72404}
72405
72406/*
72407** Mark the VDBE as one that can only be run one time.
72408*/
72409SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
72410  p->runOnlyOnce = 1;
72411}
72412
72413/*
72414** Mark the VDBE as one that can only be run multiple times.
72415*/
72416SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
72417  p->runOnlyOnce = 0;
72418}
72419
72420#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
72421
72422/*
72423** The following type and function are used to iterate through all opcodes
72424** in a Vdbe main program and each of the sub-programs (triggers) it may
72425** invoke directly or indirectly. It should be used as follows:
72426**
72427**   Op *pOp;
72428**   VdbeOpIter sIter;
72429**
72430**   memset(&sIter, 0, sizeof(sIter));
72431**   sIter.v = v;                            // v is of type Vdbe*
72432**   while( (pOp = opIterNext(&sIter)) ){
72433**     // Do something with pOp
72434**   }
72435**   sqlite3DbFree(v->db, sIter.apSub);
72436**
72437*/
72438typedef struct VdbeOpIter VdbeOpIter;
72439struct VdbeOpIter {
72440  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
72441  SubProgram **apSub;        /* Array of subprograms */
72442  int nSub;                  /* Number of entries in apSub */
72443  int iAddr;                 /* Address of next instruction to return */
72444  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
72445};
72446static Op *opIterNext(VdbeOpIter *p){
72447  Vdbe *v = p->v;
72448  Op *pRet = 0;
72449  Op *aOp;
72450  int nOp;
72451
72452  if( p->iSub<=p->nSub ){
72453
72454    if( p->iSub==0 ){
72455      aOp = v->aOp;
72456      nOp = v->nOp;
72457    }else{
72458      aOp = p->apSub[p->iSub-1]->aOp;
72459      nOp = p->apSub[p->iSub-1]->nOp;
72460    }
72461    assert( p->iAddr<nOp );
72462
72463    pRet = &aOp[p->iAddr];
72464    p->iAddr++;
72465    if( p->iAddr==nOp ){
72466      p->iSub++;
72467      p->iAddr = 0;
72468    }
72469
72470    if( pRet->p4type==P4_SUBPROGRAM ){
72471      int nByte = (p->nSub+1)*sizeof(SubProgram*);
72472      int j;
72473      for(j=0; j<p->nSub; j++){
72474        if( p->apSub[j]==pRet->p4.pProgram ) break;
72475      }
72476      if( j==p->nSub ){
72477        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
72478        if( !p->apSub ){
72479          pRet = 0;
72480        }else{
72481          p->apSub[p->nSub++] = pRet->p4.pProgram;
72482        }
72483      }
72484    }
72485  }
72486
72487  return pRet;
72488}
72489
72490/*
72491** Check if the program stored in the VM associated with pParse may
72492** throw an ABORT exception (causing the statement, but not entire transaction
72493** to be rolled back). This condition is true if the main program or any
72494** sub-programs contains any of the following:
72495**
72496**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
72497**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
72498**   *  OP_Destroy
72499**   *  OP_VUpdate
72500**   *  OP_VRename
72501**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
72502**   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
72503**
72504** Then check that the value of Parse.mayAbort is true if an
72505** ABORT may be thrown, or false otherwise. Return true if it does
72506** match, or false otherwise. This function is intended to be used as
72507** part of an assert statement in the compiler. Similar to:
72508**
72509**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
72510*/
72511SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
72512  int hasAbort = 0;
72513  int hasFkCounter = 0;
72514  int hasCreateTable = 0;
72515  int hasInitCoroutine = 0;
72516  Op *pOp;
72517  VdbeOpIter sIter;
72518  memset(&sIter, 0, sizeof(sIter));
72519  sIter.v = v;
72520
72521  while( (pOp = opIterNext(&sIter))!=0 ){
72522    int opcode = pOp->opcode;
72523    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
72524     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
72525      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
72526    ){
72527      hasAbort = 1;
72528      break;
72529    }
72530    if( opcode==OP_CreateTable ) hasCreateTable = 1;
72531    if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
72532#ifndef SQLITE_OMIT_FOREIGN_KEY
72533    if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
72534      hasFkCounter = 1;
72535    }
72536#endif
72537  }
72538  sqlite3DbFree(v->db, sIter.apSub);
72539
72540  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
72541  ** If malloc failed, then the while() loop above may not have iterated
72542  ** through all opcodes and hasAbort may be set incorrectly. Return
72543  ** true for this case to prevent the assert() in the callers frame
72544  ** from failing.  */
72545  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
72546              || (hasCreateTable && hasInitCoroutine) );
72547}
72548#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
72549
72550/*
72551** This routine is called after all opcodes have been inserted.  It loops
72552** through all the opcodes and fixes up some details.
72553**
72554** (1) For each jump instruction with a negative P2 value (a label)
72555**     resolve the P2 value to an actual address.
72556**
72557** (2) Compute the maximum number of arguments used by any SQL function
72558**     and store that value in *pMaxFuncArgs.
72559**
72560** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
72561**     indicate what the prepared statement actually does.
72562**
72563** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
72564**
72565** (5) Reclaim the memory allocated for storing labels.
72566**
72567** This routine will only function correctly if the mkopcodeh.tcl generator
72568** script numbers the opcodes correctly.  Changes to this routine must be
72569** coordinated with changes to mkopcodeh.tcl.
72570*/
72571static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
72572  int nMaxArgs = *pMaxFuncArgs;
72573  Op *pOp;
72574  Parse *pParse = p->pParse;
72575  int *aLabel = pParse->aLabel;
72576  p->readOnly = 1;
72577  p->bIsReader = 0;
72578  pOp = &p->aOp[p->nOp-1];
72579  while(1){
72580
72581    /* Only JUMP opcodes and the short list of special opcodes in the switch
72582    ** below need to be considered.  The mkopcodeh.tcl generator script groups
72583    ** all these opcodes together near the front of the opcode list.  Skip
72584    ** any opcode that does not need processing by virtual of the fact that
72585    ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
72586    */
72587    if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
72588      /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
72589      ** cases from this switch! */
72590      switch( pOp->opcode ){
72591        case OP_Transaction: {
72592          if( pOp->p2!=0 ) p->readOnly = 0;
72593          /* fall thru */
72594        }
72595        case OP_AutoCommit:
72596        case OP_Savepoint: {
72597          p->bIsReader = 1;
72598          break;
72599        }
72600#ifndef SQLITE_OMIT_WAL
72601        case OP_Checkpoint:
72602#endif
72603        case OP_Vacuum:
72604        case OP_JournalMode: {
72605          p->readOnly = 0;
72606          p->bIsReader = 1;
72607          break;
72608        }
72609#ifndef SQLITE_OMIT_VIRTUALTABLE
72610        case OP_VUpdate: {
72611          if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
72612          break;
72613        }
72614        case OP_VFilter: {
72615          int n;
72616          assert( (pOp - p->aOp) >= 3 );
72617          assert( pOp[-1].opcode==OP_Integer );
72618          n = pOp[-1].p1;
72619          if( n>nMaxArgs ) nMaxArgs = n;
72620          break;
72621        }
72622#endif
72623        case OP_Next:
72624        case OP_NextIfOpen:
72625        case OP_SorterNext: {
72626          pOp->p4.xAdvance = sqlite3BtreeNext;
72627          pOp->p4type = P4_ADVANCE;
72628          break;
72629        }
72630        case OP_Prev:
72631        case OP_PrevIfOpen: {
72632          pOp->p4.xAdvance = sqlite3BtreePrevious;
72633          pOp->p4type = P4_ADVANCE;
72634          break;
72635        }
72636      }
72637      if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
72638        assert( ADDR(pOp->p2)<pParse->nLabel );
72639        pOp->p2 = aLabel[ADDR(pOp->p2)];
72640      }
72641    }
72642    if( pOp==p->aOp ) break;
72643    pOp--;
72644  }
72645  sqlite3DbFree(p->db, pParse->aLabel);
72646  pParse->aLabel = 0;
72647  pParse->nLabel = 0;
72648  *pMaxFuncArgs = nMaxArgs;
72649  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
72650}
72651
72652/*
72653** Return the address of the next instruction to be inserted.
72654*/
72655SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
72656  assert( p->magic==VDBE_MAGIC_INIT );
72657  return p->nOp;
72658}
72659
72660/*
72661** Verify that at least N opcode slots are available in p without
72662** having to malloc for more space (except when compiled using
72663** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
72664** to verify that certain calls to sqlite3VdbeAddOpList() can never
72665** fail due to a OOM fault and hence that the return value from
72666** sqlite3VdbeAddOpList() will always be non-NULL.
72667*/
72668#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
72669SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
72670  assert( p->nOp + N <= p->pParse->nOpAlloc );
72671}
72672#endif
72673
72674/*
72675** Verify that the VM passed as the only argument does not contain
72676** an OP_ResultRow opcode. Fail an assert() if it does. This is used
72677** by code in pragma.c to ensure that the implementation of certain
72678** pragmas comports with the flags specified in the mkpragmatab.tcl
72679** script.
72680*/
72681#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
72682SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
72683  int i;
72684  for(i=0; i<p->nOp; i++){
72685    assert( p->aOp[i].opcode!=OP_ResultRow );
72686  }
72687}
72688#endif
72689
72690/*
72691** This function returns a pointer to the array of opcodes associated with
72692** the Vdbe passed as the first argument. It is the callers responsibility
72693** to arrange for the returned array to be eventually freed using the
72694** vdbeFreeOpArray() function.
72695**
72696** Before returning, *pnOp is set to the number of entries in the returned
72697** array. Also, *pnMaxArg is set to the larger of its current value and
72698** the number of entries in the Vdbe.apArg[] array required to execute the
72699** returned program.
72700*/
72701SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
72702  VdbeOp *aOp = p->aOp;
72703  assert( aOp && !p->db->mallocFailed );
72704
72705  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
72706  assert( DbMaskAllZero(p->btreeMask) );
72707
72708  resolveP2Values(p, pnMaxArg);
72709  *pnOp = p->nOp;
72710  p->aOp = 0;
72711  return aOp;
72712}
72713
72714/*
72715** Add a whole list of operations to the operation stack.  Return a
72716** pointer to the first operation inserted.
72717**
72718** Non-zero P2 arguments to jump instructions are automatically adjusted
72719** so that the jump target is relative to the first operation inserted.
72720*/
72721SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
72722  Vdbe *p,                     /* Add opcodes to the prepared statement */
72723  int nOp,                     /* Number of opcodes to add */
72724  VdbeOpList const *aOp,       /* The opcodes to be added */
72725  int iLineno                  /* Source-file line number of first opcode */
72726){
72727  int i;
72728  VdbeOp *pOut, *pFirst;
72729  assert( nOp>0 );
72730  assert( p->magic==VDBE_MAGIC_INIT );
72731  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
72732    return 0;
72733  }
72734  pFirst = pOut = &p->aOp[p->nOp];
72735  for(i=0; i<nOp; i++, aOp++, pOut++){
72736    pOut->opcode = aOp->opcode;
72737    pOut->p1 = aOp->p1;
72738    pOut->p2 = aOp->p2;
72739    assert( aOp->p2>=0 );
72740    if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
72741      pOut->p2 += p->nOp;
72742    }
72743    pOut->p3 = aOp->p3;
72744    pOut->p4type = P4_NOTUSED;
72745    pOut->p4.p = 0;
72746    pOut->p5 = 0;
72747#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72748    pOut->zComment = 0;
72749#endif
72750#ifdef SQLITE_VDBE_COVERAGE
72751    pOut->iSrcLine = iLineno+i;
72752#else
72753    (void)iLineno;
72754#endif
72755#ifdef SQLITE_DEBUG
72756    if( p->db->flags & SQLITE_VdbeAddopTrace ){
72757      sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
72758    }
72759#endif
72760  }
72761  p->nOp += nOp;
72762  return pFirst;
72763}
72764
72765#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
72766/*
72767** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
72768*/
72769SQLITE_PRIVATE void sqlite3VdbeScanStatus(
72770  Vdbe *p,                        /* VM to add scanstatus() to */
72771  int addrExplain,                /* Address of OP_Explain (or 0) */
72772  int addrLoop,                   /* Address of loop counter */
72773  int addrVisit,                  /* Address of rows visited counter */
72774  LogEst nEst,                    /* Estimated number of output rows */
72775  const char *zName               /* Name of table or index being scanned */
72776){
72777  int nByte = (p->nScan+1) * sizeof(ScanStatus);
72778  ScanStatus *aNew;
72779  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
72780  if( aNew ){
72781    ScanStatus *pNew = &aNew[p->nScan++];
72782    pNew->addrExplain = addrExplain;
72783    pNew->addrLoop = addrLoop;
72784    pNew->addrVisit = addrVisit;
72785    pNew->nEst = nEst;
72786    pNew->zName = sqlite3DbStrDup(p->db, zName);
72787    p->aScan = aNew;
72788  }
72789}
72790#endif
72791
72792
72793/*
72794** Change the value of the opcode, or P1, P2, P3, or P5 operands
72795** for a specific instruction.
72796*/
72797SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
72798  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
72799}
72800SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
72801  sqlite3VdbeGetOp(p,addr)->p1 = val;
72802}
72803SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
72804  sqlite3VdbeGetOp(p,addr)->p2 = val;
72805}
72806SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
72807  sqlite3VdbeGetOp(p,addr)->p3 = val;
72808}
72809SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
72810  assert( p->nOp>0 || p->db->mallocFailed );
72811  if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
72812}
72813
72814/*
72815** Change the P2 operand of instruction addr so that it points to
72816** the address of the next instruction to be coded.
72817*/
72818SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
72819  sqlite3VdbeChangeP2(p, addr, p->nOp);
72820}
72821
72822
72823/*
72824** If the input FuncDef structure is ephemeral, then free it.  If
72825** the FuncDef is not ephermal, then do nothing.
72826*/
72827static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
72828  if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
72829    sqlite3DbFreeNN(db, pDef);
72830  }
72831}
72832
72833static void vdbeFreeOpArray(sqlite3 *, Op *, int);
72834
72835/*
72836** Delete a P4 value if necessary.
72837*/
72838static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
72839  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
72840  sqlite3DbFreeNN(db, p);
72841}
72842static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
72843  freeEphemeralFunction(db, p->pFunc);
72844 sqlite3DbFreeNN(db, p);
72845}
72846static void freeP4(sqlite3 *db, int p4type, void *p4){
72847  assert( db );
72848  switch( p4type ){
72849    case P4_FUNCCTX: {
72850      freeP4FuncCtx(db, (sqlite3_context*)p4);
72851      break;
72852    }
72853    case P4_REAL:
72854    case P4_INT64:
72855    case P4_DYNAMIC:
72856    case P4_INTARRAY: {
72857      sqlite3DbFree(db, p4);
72858      break;
72859    }
72860    case P4_KEYINFO: {
72861      if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
72862      break;
72863    }
72864#ifdef SQLITE_ENABLE_CURSOR_HINTS
72865    case P4_EXPR: {
72866      sqlite3ExprDelete(db, (Expr*)p4);
72867      break;
72868    }
72869#endif
72870    case P4_FUNCDEF: {
72871      freeEphemeralFunction(db, (FuncDef*)p4);
72872      break;
72873    }
72874    case P4_MEM: {
72875      if( db->pnBytesFreed==0 ){
72876        sqlite3ValueFree((sqlite3_value*)p4);
72877      }else{
72878        freeP4Mem(db, (Mem*)p4);
72879      }
72880      break;
72881    }
72882    case P4_VTAB : {
72883      if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
72884      break;
72885    }
72886  }
72887}
72888
72889/*
72890** Free the space allocated for aOp and any p4 values allocated for the
72891** opcodes contained within. If aOp is not NULL it is assumed to contain
72892** nOp entries.
72893*/
72894static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
72895  if( aOp ){
72896    Op *pOp;
72897    for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
72898      if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
72899#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72900      sqlite3DbFree(db, pOp->zComment);
72901#endif
72902    }
72903    sqlite3DbFreeNN(db, aOp);
72904  }
72905}
72906
72907/*
72908** Link the SubProgram object passed as the second argument into the linked
72909** list at Vdbe.pSubProgram. This list is used to delete all sub-program
72910** objects when the VM is no longer required.
72911*/
72912SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
72913  p->pNext = pVdbe->pProgram;
72914  pVdbe->pProgram = p;
72915}
72916
72917/*
72918** Change the opcode at addr into OP_Noop
72919*/
72920SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
72921  VdbeOp *pOp;
72922  if( p->db->mallocFailed ) return 0;
72923  assert( addr>=0 && addr<p->nOp );
72924  pOp = &p->aOp[addr];
72925  freeP4(p->db, pOp->p4type, pOp->p4.p);
72926  pOp->p4type = P4_NOTUSED;
72927  pOp->p4.z = 0;
72928  pOp->opcode = OP_Noop;
72929  return 1;
72930}
72931
72932/*
72933** If the last opcode is "op" and it is not a jump destination,
72934** then remove it.  Return true if and only if an opcode was removed.
72935*/
72936SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
72937  if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
72938    return sqlite3VdbeChangeToNoop(p, p->nOp-1);
72939  }else{
72940    return 0;
72941  }
72942}
72943
72944/*
72945** Change the value of the P4 operand for a specific instruction.
72946** This routine is useful when a large program is loaded from a
72947** static array using sqlite3VdbeAddOpList but we want to make a
72948** few minor changes to the program.
72949**
72950** If n>=0 then the P4 operand is dynamic, meaning that a copy of
72951** the string is made into memory obtained from sqlite3_malloc().
72952** A value of n==0 means copy bytes of zP4 up to and including the
72953** first null byte.  If n>0 then copy n+1 bytes of zP4.
72954**
72955** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
72956** to a string or structure that is guaranteed to exist for the lifetime of
72957** the Vdbe. In these cases we can just copy the pointer.
72958**
72959** If addr<0 then change P4 on the most recently inserted instruction.
72960*/
72961static void SQLITE_NOINLINE vdbeChangeP4Full(
72962  Vdbe *p,
72963  Op *pOp,
72964  const char *zP4,
72965  int n
72966){
72967  if( pOp->p4type ){
72968    freeP4(p->db, pOp->p4type, pOp->p4.p);
72969    pOp->p4type = 0;
72970    pOp->p4.p = 0;
72971  }
72972  if( n<0 ){
72973    sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
72974  }else{
72975    if( n==0 ) n = sqlite3Strlen30(zP4);
72976    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
72977    pOp->p4type = P4_DYNAMIC;
72978  }
72979}
72980SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
72981  Op *pOp;
72982  sqlite3 *db;
72983  assert( p!=0 );
72984  db = p->db;
72985  assert( p->magic==VDBE_MAGIC_INIT );
72986  assert( p->aOp!=0 || db->mallocFailed );
72987  if( db->mallocFailed ){
72988    if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
72989    return;
72990  }
72991  assert( p->nOp>0 );
72992  assert( addr<p->nOp );
72993  if( addr<0 ){
72994    addr = p->nOp - 1;
72995  }
72996  pOp = &p->aOp[addr];
72997  if( n>=0 || pOp->p4type ){
72998    vdbeChangeP4Full(p, pOp, zP4, n);
72999    return;
73000  }
73001  if( n==P4_INT32 ){
73002    /* Note: this cast is safe, because the origin data point was an int
73003    ** that was cast to a (const char *). */
73004    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
73005    pOp->p4type = P4_INT32;
73006  }else if( zP4!=0 ){
73007    assert( n<0 );
73008    pOp->p4.p = (void*)zP4;
73009    pOp->p4type = (signed char)n;
73010    if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
73011  }
73012}
73013
73014/*
73015** Change the P4 operand of the most recently coded instruction
73016** to the value defined by the arguments.  This is a high-speed
73017** version of sqlite3VdbeChangeP4().
73018**
73019** The P4 operand must not have been previously defined.  And the new
73020** P4 must not be P4_INT32.  Use sqlite3VdbeChangeP4() in either of
73021** those cases.
73022*/
73023SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
73024  VdbeOp *pOp;
73025  assert( n!=P4_INT32 && n!=P4_VTAB );
73026  assert( n<=0 );
73027  if( p->db->mallocFailed ){
73028    freeP4(p->db, n, pP4);
73029  }else{
73030    assert( pP4!=0 );
73031    assert( p->nOp>0 );
73032    pOp = &p->aOp[p->nOp-1];
73033    assert( pOp->p4type==P4_NOTUSED );
73034    pOp->p4type = n;
73035    pOp->p4.p = pP4;
73036  }
73037}
73038
73039/*
73040** Set the P4 on the most recently added opcode to the KeyInfo for the
73041** index given.
73042*/
73043SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
73044  Vdbe *v = pParse->pVdbe;
73045  KeyInfo *pKeyInfo;
73046  assert( v!=0 );
73047  assert( pIdx!=0 );
73048  pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
73049  if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
73050}
73051
73052#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
73053/*
73054** Change the comment on the most recently coded instruction.  Or
73055** insert a No-op and add the comment to that new instruction.  This
73056** makes the code easier to read during debugging.  None of this happens
73057** in a production build.
73058*/
73059static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
73060  assert( p->nOp>0 || p->aOp==0 );
73061  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
73062  if( p->nOp ){
73063    assert( p->aOp );
73064    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
73065    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
73066  }
73067}
73068SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
73069  va_list ap;
73070  if( p ){
73071    va_start(ap, zFormat);
73072    vdbeVComment(p, zFormat, ap);
73073    va_end(ap);
73074  }
73075}
73076SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
73077  va_list ap;
73078  if( p ){
73079    sqlite3VdbeAddOp0(p, OP_Noop);
73080    va_start(ap, zFormat);
73081    vdbeVComment(p, zFormat, ap);
73082    va_end(ap);
73083  }
73084}
73085#endif  /* NDEBUG */
73086
73087#ifdef SQLITE_VDBE_COVERAGE
73088/*
73089** Set the value if the iSrcLine field for the previously coded instruction.
73090*/
73091SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
73092  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
73093}
73094#endif /* SQLITE_VDBE_COVERAGE */
73095
73096/*
73097** Return the opcode for a given address.  If the address is -1, then
73098** return the most recently inserted opcode.
73099**
73100** If a memory allocation error has occurred prior to the calling of this
73101** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
73102** is readable but not writable, though it is cast to a writable value.
73103** The return of a dummy opcode allows the call to continue functioning
73104** after an OOM fault without having to check to see if the return from
73105** this routine is a valid pointer.  But because the dummy.opcode is 0,
73106** dummy will never be written to.  This is verified by code inspection and
73107** by running with Valgrind.
73108*/
73109SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
73110  /* C89 specifies that the constant "dummy" will be initialized to all
73111  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
73112  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
73113  assert( p->magic==VDBE_MAGIC_INIT );
73114  if( addr<0 ){
73115    addr = p->nOp - 1;
73116  }
73117  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
73118  if( p->db->mallocFailed ){
73119    return (VdbeOp*)&dummy;
73120  }else{
73121    return &p->aOp[addr];
73122  }
73123}
73124
73125#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
73126/*
73127** Return an integer value for one of the parameters to the opcode pOp
73128** determined by character c.
73129*/
73130static int translateP(char c, const Op *pOp){
73131  if( c=='1' ) return pOp->p1;
73132  if( c=='2' ) return pOp->p2;
73133  if( c=='3' ) return pOp->p3;
73134  if( c=='4' ) return pOp->p4.i;
73135  return pOp->p5;
73136}
73137
73138/*
73139** Compute a string for the "comment" field of a VDBE opcode listing.
73140**
73141** The Synopsis: field in comments in the vdbe.c source file gets converted
73142** to an extra string that is appended to the sqlite3OpcodeName().  In the
73143** absence of other comments, this synopsis becomes the comment on the opcode.
73144** Some translation occurs:
73145**
73146**       "PX"      ->  "r[X]"
73147**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
73148**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
73149**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
73150*/
73151static int displayComment(
73152  const Op *pOp,     /* The opcode to be commented */
73153  const char *zP4,   /* Previously obtained value for P4 */
73154  char *zTemp,       /* Write result here */
73155  int nTemp          /* Space available in zTemp[] */
73156){
73157  const char *zOpName;
73158  const char *zSynopsis;
73159  int nOpName;
73160  int ii, jj;
73161  char zAlt[50];
73162  zOpName = sqlite3OpcodeName(pOp->opcode);
73163  nOpName = sqlite3Strlen30(zOpName);
73164  if( zOpName[nOpName+1] ){
73165    int seenCom = 0;
73166    char c;
73167    zSynopsis = zOpName += nOpName + 1;
73168    if( strncmp(zSynopsis,"IF ",3)==0 ){
73169      if( pOp->p5 & SQLITE_STOREP2 ){
73170        sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
73171      }else{
73172        sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
73173      }
73174      zSynopsis = zAlt;
73175    }
73176    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
73177      if( c=='P' ){
73178        c = zSynopsis[++ii];
73179        if( c=='4' ){
73180          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
73181        }else if( c=='X' ){
73182          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
73183          seenCom = 1;
73184        }else{
73185          int v1 = translateP(c, pOp);
73186          int v2;
73187          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
73188          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
73189            ii += 3;
73190            jj += sqlite3Strlen30(zTemp+jj);
73191            v2 = translateP(zSynopsis[ii], pOp);
73192            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
73193              ii += 2;
73194              v2++;
73195            }
73196            if( v2>1 ){
73197              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
73198            }
73199          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
73200            ii += 4;
73201          }
73202        }
73203        jj += sqlite3Strlen30(zTemp+jj);
73204      }else{
73205        zTemp[jj++] = c;
73206      }
73207    }
73208    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
73209      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
73210      jj += sqlite3Strlen30(zTemp+jj);
73211    }
73212    if( jj<nTemp ) zTemp[jj] = 0;
73213  }else if( pOp->zComment ){
73214    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
73215    jj = sqlite3Strlen30(zTemp);
73216  }else{
73217    zTemp[0] = 0;
73218    jj = 0;
73219  }
73220  return jj;
73221}
73222#endif /* SQLITE_DEBUG */
73223
73224#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
73225/*
73226** Translate the P4.pExpr value for an OP_CursorHint opcode into text
73227** that can be displayed in the P4 column of EXPLAIN output.
73228*/
73229static void displayP4Expr(StrAccum *p, Expr *pExpr){
73230  const char *zOp = 0;
73231  switch( pExpr->op ){
73232    case TK_STRING:
73233      sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
73234      break;
73235    case TK_INTEGER:
73236      sqlite3XPrintf(p, "%d", pExpr->u.iValue);
73237      break;
73238    case TK_NULL:
73239      sqlite3XPrintf(p, "NULL");
73240      break;
73241    case TK_REGISTER: {
73242      sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
73243      break;
73244    }
73245    case TK_COLUMN: {
73246      if( pExpr->iColumn<0 ){
73247        sqlite3XPrintf(p, "rowid");
73248      }else{
73249        sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
73250      }
73251      break;
73252    }
73253    case TK_LT:      zOp = "LT";      break;
73254    case TK_LE:      zOp = "LE";      break;
73255    case TK_GT:      zOp = "GT";      break;
73256    case TK_GE:      zOp = "GE";      break;
73257    case TK_NE:      zOp = "NE";      break;
73258    case TK_EQ:      zOp = "EQ";      break;
73259    case TK_IS:      zOp = "IS";      break;
73260    case TK_ISNOT:   zOp = "ISNOT";   break;
73261    case TK_AND:     zOp = "AND";     break;
73262    case TK_OR:      zOp = "OR";      break;
73263    case TK_PLUS:    zOp = "ADD";     break;
73264    case TK_STAR:    zOp = "MUL";     break;
73265    case TK_MINUS:   zOp = "SUB";     break;
73266    case TK_REM:     zOp = "REM";     break;
73267    case TK_BITAND:  zOp = "BITAND";  break;
73268    case TK_BITOR:   zOp = "BITOR";   break;
73269    case TK_SLASH:   zOp = "DIV";     break;
73270    case TK_LSHIFT:  zOp = "LSHIFT";  break;
73271    case TK_RSHIFT:  zOp = "RSHIFT";  break;
73272    case TK_CONCAT:  zOp = "CONCAT";  break;
73273    case TK_UMINUS:  zOp = "MINUS";   break;
73274    case TK_UPLUS:   zOp = "PLUS";    break;
73275    case TK_BITNOT:  zOp = "BITNOT";  break;
73276    case TK_NOT:     zOp = "NOT";     break;
73277    case TK_ISNULL:  zOp = "ISNULL";  break;
73278    case TK_NOTNULL: zOp = "NOTNULL"; break;
73279
73280    default:
73281      sqlite3XPrintf(p, "%s", "expr");
73282      break;
73283  }
73284
73285  if( zOp ){
73286    sqlite3XPrintf(p, "%s(", zOp);
73287    displayP4Expr(p, pExpr->pLeft);
73288    if( pExpr->pRight ){
73289      sqlite3StrAccumAppend(p, ",", 1);
73290      displayP4Expr(p, pExpr->pRight);
73291    }
73292    sqlite3StrAccumAppend(p, ")", 1);
73293  }
73294}
73295#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
73296
73297
73298#if VDBE_DISPLAY_P4
73299/*
73300** Compute a string that describes the P4 parameter for an opcode.
73301** Use zTemp for any required temporary buffer space.
73302*/
73303static char *displayP4(Op *pOp, char *zTemp, int nTemp){
73304  char *zP4 = zTemp;
73305  StrAccum x;
73306  assert( nTemp>=20 );
73307  sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
73308  switch( pOp->p4type ){
73309    case P4_KEYINFO: {
73310      int j;
73311      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
73312      assert( pKeyInfo->aSortOrder!=0 );
73313      sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
73314      for(j=0; j<pKeyInfo->nField; j++){
73315        CollSeq *pColl = pKeyInfo->aColl[j];
73316        const char *zColl = pColl ? pColl->zName : "";
73317        if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
73318        sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
73319      }
73320      sqlite3StrAccumAppend(&x, ")", 1);
73321      break;
73322    }
73323#ifdef SQLITE_ENABLE_CURSOR_HINTS
73324    case P4_EXPR: {
73325      displayP4Expr(&x, pOp->p4.pExpr);
73326      break;
73327    }
73328#endif
73329    case P4_COLLSEQ: {
73330      CollSeq *pColl = pOp->p4.pColl;
73331      sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
73332      break;
73333    }
73334    case P4_FUNCDEF: {
73335      FuncDef *pDef = pOp->p4.pFunc;
73336      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
73337      break;
73338    }
73339#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
73340    case P4_FUNCCTX: {
73341      FuncDef *pDef = pOp->p4.pCtx->pFunc;
73342      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
73343      break;
73344    }
73345#endif
73346    case P4_INT64: {
73347      sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
73348      break;
73349    }
73350    case P4_INT32: {
73351      sqlite3XPrintf(&x, "%d", pOp->p4.i);
73352      break;
73353    }
73354    case P4_REAL: {
73355      sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
73356      break;
73357    }
73358    case P4_MEM: {
73359      Mem *pMem = pOp->p4.pMem;
73360      if( pMem->flags & MEM_Str ){
73361        zP4 = pMem->z;
73362      }else if( pMem->flags & MEM_Int ){
73363        sqlite3XPrintf(&x, "%lld", pMem->u.i);
73364      }else if( pMem->flags & MEM_Real ){
73365        sqlite3XPrintf(&x, "%.16g", pMem->u.r);
73366      }else if( pMem->flags & MEM_Null ){
73367        zP4 = "NULL";
73368      }else{
73369        assert( pMem->flags & MEM_Blob );
73370        zP4 = "(blob)";
73371      }
73372      break;
73373    }
73374#ifndef SQLITE_OMIT_VIRTUALTABLE
73375    case P4_VTAB: {
73376      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
73377      sqlite3XPrintf(&x, "vtab:%p", pVtab);
73378      break;
73379    }
73380#endif
73381    case P4_INTARRAY: {
73382      int i;
73383      int *ai = pOp->p4.ai;
73384      int n = ai[0];   /* The first element of an INTARRAY is always the
73385                       ** count of the number of elements to follow */
73386      for(i=1; i<n; i++){
73387        sqlite3XPrintf(&x, ",%d", ai[i]);
73388      }
73389      zTemp[0] = '[';
73390      sqlite3StrAccumAppend(&x, "]", 1);
73391      break;
73392    }
73393    case P4_SUBPROGRAM: {
73394      sqlite3XPrintf(&x, "program");
73395      break;
73396    }
73397    case P4_ADVANCE: {
73398      zTemp[0] = 0;
73399      break;
73400    }
73401    case P4_TABLE: {
73402      sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
73403      break;
73404    }
73405    default: {
73406      zP4 = pOp->p4.z;
73407      if( zP4==0 ){
73408        zP4 = zTemp;
73409        zTemp[0] = 0;
73410      }
73411    }
73412  }
73413  sqlite3StrAccumFinish(&x);
73414  assert( zP4!=0 );
73415  return zP4;
73416}
73417#endif /* VDBE_DISPLAY_P4 */
73418
73419/*
73420** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
73421**
73422** The prepared statements need to know in advance the complete set of
73423** attached databases that will be use.  A mask of these databases
73424** is maintained in p->btreeMask.  The p->lockMask value is the subset of
73425** p->btreeMask of databases that will require a lock.
73426*/
73427SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
73428  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
73429  assert( i<(int)sizeof(p->btreeMask)*8 );
73430  DbMaskSet(p->btreeMask, i);
73431  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
73432    DbMaskSet(p->lockMask, i);
73433  }
73434}
73435
73436#if !defined(SQLITE_OMIT_SHARED_CACHE)
73437/*
73438** If SQLite is compiled to support shared-cache mode and to be threadsafe,
73439** this routine obtains the mutex associated with each BtShared structure
73440** that may be accessed by the VM passed as an argument. In doing so it also
73441** sets the BtShared.db member of each of the BtShared structures, ensuring
73442** that the correct busy-handler callback is invoked if required.
73443**
73444** If SQLite is not threadsafe but does support shared-cache mode, then
73445** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
73446** of all of BtShared structures accessible via the database handle
73447** associated with the VM.
73448**
73449** If SQLite is not threadsafe and does not support shared-cache mode, this
73450** function is a no-op.
73451**
73452** The p->btreeMask field is a bitmask of all btrees that the prepared
73453** statement p will ever use.  Let N be the number of bits in p->btreeMask
73454** corresponding to btrees that use shared cache.  Then the runtime of
73455** this routine is N*N.  But as N is rarely more than 1, this should not
73456** be a problem.
73457*/
73458SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
73459  int i;
73460  sqlite3 *db;
73461  Db *aDb;
73462  int nDb;
73463  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
73464  db = p->db;
73465  aDb = db->aDb;
73466  nDb = db->nDb;
73467  for(i=0; i<nDb; i++){
73468    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
73469      sqlite3BtreeEnter(aDb[i].pBt);
73470    }
73471  }
73472}
73473#endif
73474
73475#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
73476/*
73477** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
73478*/
73479static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
73480  int i;
73481  sqlite3 *db;
73482  Db *aDb;
73483  int nDb;
73484  db = p->db;
73485  aDb = db->aDb;
73486  nDb = db->nDb;
73487  for(i=0; i<nDb; i++){
73488    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
73489      sqlite3BtreeLeave(aDb[i].pBt);
73490    }
73491  }
73492}
73493SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
73494  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
73495  vdbeLeave(p);
73496}
73497#endif
73498
73499#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
73500/*
73501** Print a single opcode.  This routine is used for debugging only.
73502*/
73503SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
73504  char *zP4;
73505  char zPtr[50];
73506  char zCom[100];
73507  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
73508  if( pOut==0 ) pOut = stdout;
73509  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
73510#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
73511  displayComment(pOp, zP4, zCom, sizeof(zCom));
73512#else
73513  zCom[0] = 0;
73514#endif
73515  /* NB:  The sqlite3OpcodeName() function is implemented by code created
73516  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
73517  ** information from the vdbe.c source text */
73518  fprintf(pOut, zFormat1, pc,
73519      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
73520      zCom
73521  );
73522  fflush(pOut);
73523}
73524#endif
73525
73526/*
73527** Initialize an array of N Mem element.
73528*/
73529static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
73530  while( (N--)>0 ){
73531    p->db = db;
73532    p->flags = flags;
73533    p->szMalloc = 0;
73534#ifdef SQLITE_DEBUG
73535    p->pScopyFrom = 0;
73536#endif
73537    p++;
73538  }
73539}
73540
73541/*
73542** Release an array of N Mem elements
73543*/
73544static void releaseMemArray(Mem *p, int N){
73545  if( p && N ){
73546    Mem *pEnd = &p[N];
73547    sqlite3 *db = p->db;
73548    if( db->pnBytesFreed ){
73549      do{
73550        if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
73551      }while( (++p)<pEnd );
73552      return;
73553    }
73554    do{
73555      assert( (&p[1])==pEnd || p[0].db==p[1].db );
73556      assert( sqlite3VdbeCheckMemInvariants(p) );
73557
73558      /* This block is really an inlined version of sqlite3VdbeMemRelease()
73559      ** that takes advantage of the fact that the memory cell value is
73560      ** being set to NULL after releasing any dynamic resources.
73561      **
73562      ** The justification for duplicating code is that according to
73563      ** callgrind, this causes a certain test case to hit the CPU 4.7
73564      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
73565      ** sqlite3MemRelease() were called from here. With -O2, this jumps
73566      ** to 6.6 percent. The test case is inserting 1000 rows into a table
73567      ** with no indexes using a single prepared INSERT statement, bind()
73568      ** and reset(). Inserts are grouped into a transaction.
73569      */
73570      testcase( p->flags & MEM_Agg );
73571      testcase( p->flags & MEM_Dyn );
73572      testcase( p->flags & MEM_Frame );
73573      testcase( p->flags & MEM_RowSet );
73574      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
73575        sqlite3VdbeMemRelease(p);
73576      }else if( p->szMalloc ){
73577        sqlite3DbFreeNN(db, p->zMalloc);
73578        p->szMalloc = 0;
73579      }
73580
73581      p->flags = MEM_Undefined;
73582    }while( (++p)<pEnd );
73583  }
73584}
73585
73586/*
73587** Delete a VdbeFrame object and its contents. VdbeFrame objects are
73588** allocated by the OP_Program opcode in sqlite3VdbeExec().
73589*/
73590SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
73591  int i;
73592  Mem *aMem = VdbeFrameMem(p);
73593  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
73594  for(i=0; i<p->nChildCsr; i++){
73595    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
73596  }
73597  releaseMemArray(aMem, p->nChildMem);
73598  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
73599  sqlite3DbFree(p->v->db, p);
73600}
73601
73602#ifndef SQLITE_OMIT_EXPLAIN
73603/*
73604** Give a listing of the program in the virtual machine.
73605**
73606** The interface is the same as sqlite3VdbeExec().  But instead of
73607** running the code, it invokes the callback once for each instruction.
73608** This feature is used to implement "EXPLAIN".
73609**
73610** When p->explain==1, each instruction is listed.  When
73611** p->explain==2, only OP_Explain instructions are listed and these
73612** are shown in a different format.  p->explain==2 is used to implement
73613** EXPLAIN QUERY PLAN.
73614**
73615** When p->explain==1, first the main program is listed, then each of
73616** the trigger subprograms are listed one by one.
73617*/
73618SQLITE_PRIVATE int sqlite3VdbeList(
73619  Vdbe *p                   /* The VDBE */
73620){
73621  int nRow;                            /* Stop when row count reaches this */
73622  int nSub = 0;                        /* Number of sub-vdbes seen so far */
73623  SubProgram **apSub = 0;              /* Array of sub-vdbes */
73624  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
73625  sqlite3 *db = p->db;                 /* The database connection */
73626  int i;                               /* Loop counter */
73627  int rc = SQLITE_OK;                  /* Return code */
73628  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
73629
73630  assert( p->explain );
73631  assert( p->magic==VDBE_MAGIC_RUN );
73632  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
73633
73634  /* Even though this opcode does not use dynamic strings for
73635  ** the result, result columns may become dynamic if the user calls
73636  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
73637  */
73638  releaseMemArray(pMem, 8);
73639  p->pResultSet = 0;
73640
73641  if( p->rc==SQLITE_NOMEM_BKPT ){
73642    /* This happens if a malloc() inside a call to sqlite3_column_text() or
73643    ** sqlite3_column_text16() failed.  */
73644    sqlite3OomFault(db);
73645    return SQLITE_ERROR;
73646  }
73647
73648  /* When the number of output rows reaches nRow, that means the
73649  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
73650  ** nRow is the sum of the number of rows in the main program, plus
73651  ** the sum of the number of rows in all trigger subprograms encountered
73652  ** so far.  The nRow value will increase as new trigger subprograms are
73653  ** encountered, but p->pc will eventually catch up to nRow.
73654  */
73655  nRow = p->nOp;
73656  if( p->explain==1 ){
73657    /* The first 8 memory cells are used for the result set.  So we will
73658    ** commandeer the 9th cell to use as storage for an array of pointers
73659    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
73660    ** cells.  */
73661    assert( p->nMem>9 );
73662    pSub = &p->aMem[9];
73663    if( pSub->flags&MEM_Blob ){
73664      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
73665      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
73666      nSub = pSub->n/sizeof(Vdbe*);
73667      apSub = (SubProgram **)pSub->z;
73668    }
73669    for(i=0; i<nSub; i++){
73670      nRow += apSub[i]->nOp;
73671    }
73672  }
73673
73674  do{
73675    i = p->pc++;
73676  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
73677  if( i>=nRow ){
73678    p->rc = SQLITE_OK;
73679    rc = SQLITE_DONE;
73680  }else if( db->u1.isInterrupted ){
73681    p->rc = SQLITE_INTERRUPT;
73682    rc = SQLITE_ERROR;
73683    sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
73684  }else{
73685    char *zP4;
73686    Op *pOp;
73687    if( i<p->nOp ){
73688      /* The output line number is small enough that we are still in the
73689      ** main program. */
73690      pOp = &p->aOp[i];
73691    }else{
73692      /* We are currently listing subprograms.  Figure out which one and
73693      ** pick up the appropriate opcode. */
73694      int j;
73695      i -= p->nOp;
73696      for(j=0; i>=apSub[j]->nOp; j++){
73697        i -= apSub[j]->nOp;
73698      }
73699      pOp = &apSub[j]->aOp[i];
73700    }
73701    if( p->explain==1 ){
73702      pMem->flags = MEM_Int;
73703      pMem->u.i = i;                                /* Program counter */
73704      pMem++;
73705
73706      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
73707      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
73708      assert( pMem->z!=0 );
73709      pMem->n = sqlite3Strlen30(pMem->z);
73710      pMem->enc = SQLITE_UTF8;
73711      pMem++;
73712
73713      /* When an OP_Program opcode is encounter (the only opcode that has
73714      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
73715      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
73716      ** has not already been seen.
73717      */
73718      if( pOp->p4type==P4_SUBPROGRAM ){
73719        int nByte = (nSub+1)*sizeof(SubProgram*);
73720        int j;
73721        for(j=0; j<nSub; j++){
73722          if( apSub[j]==pOp->p4.pProgram ) break;
73723        }
73724        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
73725          apSub = (SubProgram **)pSub->z;
73726          apSub[nSub++] = pOp->p4.pProgram;
73727          pSub->flags |= MEM_Blob;
73728          pSub->n = nSub*sizeof(SubProgram*);
73729        }
73730      }
73731    }
73732
73733    pMem->flags = MEM_Int;
73734    pMem->u.i = pOp->p1;                          /* P1 */
73735    pMem++;
73736
73737    pMem->flags = MEM_Int;
73738    pMem->u.i = pOp->p2;                          /* P2 */
73739    pMem++;
73740
73741    pMem->flags = MEM_Int;
73742    pMem->u.i = pOp->p3;                          /* P3 */
73743    pMem++;
73744
73745    if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
73746      assert( p->db->mallocFailed );
73747      return SQLITE_ERROR;
73748    }
73749    pMem->flags = MEM_Str|MEM_Term;
73750    zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
73751    if( zP4!=pMem->z ){
73752      pMem->n = 0;
73753      sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
73754    }else{
73755      assert( pMem->z!=0 );
73756      pMem->n = sqlite3Strlen30(pMem->z);
73757      pMem->enc = SQLITE_UTF8;
73758    }
73759    pMem++;
73760
73761    if( p->explain==1 ){
73762      if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
73763        assert( p->db->mallocFailed );
73764        return SQLITE_ERROR;
73765      }
73766      pMem->flags = MEM_Str|MEM_Term;
73767      pMem->n = 2;
73768      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
73769      pMem->enc = SQLITE_UTF8;
73770      pMem++;
73771
73772#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
73773      if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
73774        assert( p->db->mallocFailed );
73775        return SQLITE_ERROR;
73776      }
73777      pMem->flags = MEM_Str|MEM_Term;
73778      pMem->n = displayComment(pOp, zP4, pMem->z, 500);
73779      pMem->enc = SQLITE_UTF8;
73780#else
73781      pMem->flags = MEM_Null;                       /* Comment */
73782#endif
73783    }
73784
73785    p->nResColumn = 8 - 4*(p->explain-1);
73786    p->pResultSet = &p->aMem[1];
73787    p->rc = SQLITE_OK;
73788    rc = SQLITE_ROW;
73789  }
73790  return rc;
73791}
73792#endif /* SQLITE_OMIT_EXPLAIN */
73793
73794#ifdef SQLITE_DEBUG
73795/*
73796** Print the SQL that was used to generate a VDBE program.
73797*/
73798SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
73799  const char *z = 0;
73800  if( p->zSql ){
73801    z = p->zSql;
73802  }else if( p->nOp>=1 ){
73803    const VdbeOp *pOp = &p->aOp[0];
73804    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
73805      z = pOp->p4.z;
73806      while( sqlite3Isspace(*z) ) z++;
73807    }
73808  }
73809  if( z ) printf("SQL: [%s]\n", z);
73810}
73811#endif
73812
73813#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
73814/*
73815** Print an IOTRACE message showing SQL content.
73816*/
73817SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
73818  int nOp = p->nOp;
73819  VdbeOp *pOp;
73820  if( sqlite3IoTrace==0 ) return;
73821  if( nOp<1 ) return;
73822  pOp = &p->aOp[0];
73823  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
73824    int i, j;
73825    char z[1000];
73826    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
73827    for(i=0; sqlite3Isspace(z[i]); i++){}
73828    for(j=0; z[i]; i++){
73829      if( sqlite3Isspace(z[i]) ){
73830        if( z[i-1]!=' ' ){
73831          z[j++] = ' ';
73832        }
73833      }else{
73834        z[j++] = z[i];
73835      }
73836    }
73837    z[j] = 0;
73838    sqlite3IoTrace("SQL %s\n", z);
73839  }
73840}
73841#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
73842
73843/* An instance of this object describes bulk memory available for use
73844** by subcomponents of a prepared statement.  Space is allocated out
73845** of a ReusableSpace object by the allocSpace() routine below.
73846*/
73847struct ReusableSpace {
73848  u8 *pSpace;          /* Available memory */
73849  int nFree;           /* Bytes of available memory */
73850  int nNeeded;         /* Total bytes that could not be allocated */
73851};
73852
73853/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
73854** from the ReusableSpace object.  Return a pointer to the allocated
73855** memory on success.  If insufficient memory is available in the
73856** ReusableSpace object, increase the ReusableSpace.nNeeded
73857** value by the amount needed and return NULL.
73858**
73859** If pBuf is not initially NULL, that means that the memory has already
73860** been allocated by a prior call to this routine, so just return a copy
73861** of pBuf and leave ReusableSpace unchanged.
73862**
73863** This allocator is employed to repurpose unused slots at the end of the
73864** opcode array of prepared state for other memory needs of the prepared
73865** statement.
73866*/
73867static void *allocSpace(
73868  struct ReusableSpace *p,  /* Bulk memory available for allocation */
73869  void *pBuf,               /* Pointer to a prior allocation */
73870  int nByte                 /* Bytes of memory needed */
73871){
73872  assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
73873  if( pBuf==0 ){
73874    nByte = ROUND8(nByte);
73875    if( nByte <= p->nFree ){
73876      p->nFree -= nByte;
73877      pBuf = &p->pSpace[p->nFree];
73878    }else{
73879      p->nNeeded += nByte;
73880    }
73881  }
73882  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
73883  return pBuf;
73884}
73885
73886/*
73887** Rewind the VDBE back to the beginning in preparation for
73888** running it.
73889*/
73890SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
73891#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
73892  int i;
73893#endif
73894  assert( p!=0 );
73895  assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
73896
73897  /* There should be at least one opcode.
73898  */
73899  assert( p->nOp>0 );
73900
73901  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
73902  p->magic = VDBE_MAGIC_RUN;
73903
73904#ifdef SQLITE_DEBUG
73905  for(i=0; i<p->nMem; i++){
73906    assert( p->aMem[i].db==p->db );
73907  }
73908#endif
73909  p->pc = -1;
73910  p->rc = SQLITE_OK;
73911  p->errorAction = OE_Abort;
73912  p->nChange = 0;
73913  p->cacheCtr = 1;
73914  p->minWriteFileFormat = 255;
73915  p->iStatement = 0;
73916  p->nFkConstraint = 0;
73917#ifdef VDBE_PROFILE
73918  for(i=0; i<p->nOp; i++){
73919    p->aOp[i].cnt = 0;
73920    p->aOp[i].cycles = 0;
73921  }
73922#endif
73923}
73924
73925/*
73926** Prepare a virtual machine for execution for the first time after
73927** creating the virtual machine.  This involves things such
73928** as allocating registers and initializing the program counter.
73929** After the VDBE has be prepped, it can be executed by one or more
73930** calls to sqlite3VdbeExec().
73931**
73932** This function may be called exactly once on each virtual machine.
73933** After this routine is called the VM has been "packaged" and is ready
73934** to run.  After this routine is called, further calls to
73935** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
73936** the Vdbe from the Parse object that helped generate it so that the
73937** the Vdbe becomes an independent entity and the Parse object can be
73938** destroyed.
73939**
73940** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
73941** to its initial state after it has been run.
73942*/
73943SQLITE_PRIVATE void sqlite3VdbeMakeReady(
73944  Vdbe *p,                       /* The VDBE */
73945  Parse *pParse                  /* Parsing context */
73946){
73947  sqlite3 *db;                   /* The database connection */
73948  int nVar;                      /* Number of parameters */
73949  int nMem;                      /* Number of VM memory registers */
73950  int nCursor;                   /* Number of cursors required */
73951  int nArg;                      /* Number of arguments in subprograms */
73952  int n;                         /* Loop counter */
73953  struct ReusableSpace x;        /* Reusable bulk memory */
73954
73955  assert( p!=0 );
73956  assert( p->nOp>0 );
73957  assert( pParse!=0 );
73958  assert( p->magic==VDBE_MAGIC_INIT );
73959  assert( pParse==p->pParse );
73960  db = p->db;
73961  assert( db->mallocFailed==0 );
73962  nVar = pParse->nVar;
73963  nMem = pParse->nMem;
73964  nCursor = pParse->nTab;
73965  nArg = pParse->nMaxArg;
73966
73967  /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
73968  ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
73969  ** space at the end of aMem[] for cursors 1 and greater.
73970  ** See also: allocateCursor().
73971  */
73972  nMem += nCursor;
73973  if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
73974
73975  /* Figure out how much reusable memory is available at the end of the
73976  ** opcode array.  This extra memory will be reallocated for other elements
73977  ** of the prepared statement.
73978  */
73979  n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
73980  x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
73981  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
73982  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
73983  assert( x.nFree>=0 );
73984  assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
73985
73986  resolveP2Values(p, &nArg);
73987  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
73988  if( pParse->explain && nMem<10 ){
73989    nMem = 10;
73990  }
73991  p->expired = 0;
73992
73993  /* Memory for registers, parameters, cursor, etc, is allocated in one or two
73994  ** passes.  On the first pass, we try to reuse unused memory at the
73995  ** end of the opcode array.  If we are unable to satisfy all memory
73996  ** requirements by reusing the opcode array tail, then the second
73997  ** pass will fill in the remainder using a fresh memory allocation.
73998  **
73999  ** This two-pass approach that reuses as much memory as possible from
74000  ** the leftover memory at the end of the opcode array.  This can significantly
74001  ** reduce the amount of memory held by a prepared statement.
74002  */
74003  do {
74004    x.nNeeded = 0;
74005    p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
74006    p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
74007    p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
74008    p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
74009#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
74010    p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
74011#endif
74012    if( x.nNeeded==0 ) break;
74013    x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
74014    x.nFree = x.nNeeded;
74015  }while( !db->mallocFailed );
74016
74017  p->pVList = pParse->pVList;
74018  pParse->pVList =  0;
74019  p->explain = pParse->explain;
74020  if( db->mallocFailed ){
74021    p->nVar = 0;
74022    p->nCursor = 0;
74023    p->nMem = 0;
74024  }else{
74025    p->nCursor = nCursor;
74026    p->nVar = (ynVar)nVar;
74027    initMemArray(p->aVar, nVar, db, MEM_Null);
74028    p->nMem = nMem;
74029    initMemArray(p->aMem, nMem, db, MEM_Undefined);
74030    memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
74031#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
74032    memset(p->anExec, 0, p->nOp*sizeof(i64));
74033#endif
74034  }
74035  sqlite3VdbeRewind(p);
74036}
74037
74038/*
74039** Close a VDBE cursor and release all the resources that cursor
74040** happens to hold.
74041*/
74042SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
74043  if( pCx==0 ){
74044    return;
74045  }
74046  assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
74047  switch( pCx->eCurType ){
74048    case CURTYPE_SORTER: {
74049      sqlite3VdbeSorterClose(p->db, pCx);
74050      break;
74051    }
74052    case CURTYPE_BTREE: {
74053      if( pCx->isEphemeral ){
74054        if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
74055        /* The pCx->pCursor will be close automatically, if it exists, by
74056        ** the call above. */
74057      }else{
74058        assert( pCx->uc.pCursor!=0 );
74059        sqlite3BtreeCloseCursor(pCx->uc.pCursor);
74060      }
74061      break;
74062    }
74063#ifndef SQLITE_OMIT_VIRTUALTABLE
74064    case CURTYPE_VTAB: {
74065      sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
74066      const sqlite3_module *pModule = pVCur->pVtab->pModule;
74067      assert( pVCur->pVtab->nRef>0 );
74068      pVCur->pVtab->nRef--;
74069      pModule->xClose(pVCur);
74070      break;
74071    }
74072#endif
74073  }
74074}
74075
74076/*
74077** Close all cursors in the current frame.
74078*/
74079static void closeCursorsInFrame(Vdbe *p){
74080  if( p->apCsr ){
74081    int i;
74082    for(i=0; i<p->nCursor; i++){
74083      VdbeCursor *pC = p->apCsr[i];
74084      if( pC ){
74085        sqlite3VdbeFreeCursor(p, pC);
74086        p->apCsr[i] = 0;
74087      }
74088    }
74089  }
74090}
74091
74092/*
74093** Copy the values stored in the VdbeFrame structure to its Vdbe. This
74094** is used, for example, when a trigger sub-program is halted to restore
74095** control to the main program.
74096*/
74097SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
74098  Vdbe *v = pFrame->v;
74099  closeCursorsInFrame(v);
74100#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
74101  v->anExec = pFrame->anExec;
74102#endif
74103  v->aOp = pFrame->aOp;
74104  v->nOp = pFrame->nOp;
74105  v->aMem = pFrame->aMem;
74106  v->nMem = pFrame->nMem;
74107  v->apCsr = pFrame->apCsr;
74108  v->nCursor = pFrame->nCursor;
74109  v->db->lastRowid = pFrame->lastRowid;
74110  v->nChange = pFrame->nChange;
74111  v->db->nChange = pFrame->nDbChange;
74112  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
74113  v->pAuxData = pFrame->pAuxData;
74114  pFrame->pAuxData = 0;
74115  return pFrame->pc;
74116}
74117
74118/*
74119** Close all cursors.
74120**
74121** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
74122** cell array. This is necessary as the memory cell array may contain
74123** pointers to VdbeFrame objects, which may in turn contain pointers to
74124** open cursors.
74125*/
74126static void closeAllCursors(Vdbe *p){
74127  if( p->pFrame ){
74128    VdbeFrame *pFrame;
74129    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
74130    sqlite3VdbeFrameRestore(pFrame);
74131    p->pFrame = 0;
74132    p->nFrame = 0;
74133  }
74134  assert( p->nFrame==0 );
74135  closeCursorsInFrame(p);
74136  if( p->aMem ){
74137    releaseMemArray(p->aMem, p->nMem);
74138  }
74139  while( p->pDelFrame ){
74140    VdbeFrame *pDel = p->pDelFrame;
74141    p->pDelFrame = pDel->pParent;
74142    sqlite3VdbeFrameDelete(pDel);
74143  }
74144
74145  /* Delete any auxdata allocations made by the VM */
74146  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
74147  assert( p->pAuxData==0 );
74148}
74149
74150/*
74151** Clean up the VM after a single run.
74152*/
74153static void Cleanup(Vdbe *p){
74154  sqlite3 *db = p->db;
74155
74156#ifdef SQLITE_DEBUG
74157  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
74158  ** Vdbe.aMem[] arrays have already been cleaned up.  */
74159  int i;
74160  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
74161  if( p->aMem ){
74162    for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
74163  }
74164#endif
74165
74166  sqlite3DbFree(db, p->zErrMsg);
74167  p->zErrMsg = 0;
74168  p->pResultSet = 0;
74169}
74170
74171/*
74172** Set the number of result columns that will be returned by this SQL
74173** statement. This is now set at compile time, rather than during
74174** execution of the vdbe program so that sqlite3_column_count() can
74175** be called on an SQL statement before sqlite3_step().
74176*/
74177SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
74178  int n;
74179  sqlite3 *db = p->db;
74180
74181  if( p->nResColumn ){
74182    releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
74183    sqlite3DbFree(db, p->aColName);
74184  }
74185  n = nResColumn*COLNAME_N;
74186  p->nResColumn = (u16)nResColumn;
74187  p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
74188  if( p->aColName==0 ) return;
74189  initMemArray(p->aColName, n, db, MEM_Null);
74190}
74191
74192/*
74193** Set the name of the idx'th column to be returned by the SQL statement.
74194** zName must be a pointer to a nul terminated string.
74195**
74196** This call must be made after a call to sqlite3VdbeSetNumCols().
74197**
74198** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
74199** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
74200** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
74201*/
74202SQLITE_PRIVATE int sqlite3VdbeSetColName(
74203  Vdbe *p,                         /* Vdbe being configured */
74204  int idx,                         /* Index of column zName applies to */
74205  int var,                         /* One of the COLNAME_* constants */
74206  const char *zName,               /* Pointer to buffer containing name */
74207  void (*xDel)(void*)              /* Memory management strategy for zName */
74208){
74209  int rc;
74210  Mem *pColName;
74211  assert( idx<p->nResColumn );
74212  assert( var<COLNAME_N );
74213  if( p->db->mallocFailed ){
74214    assert( !zName || xDel!=SQLITE_DYNAMIC );
74215    return SQLITE_NOMEM_BKPT;
74216  }
74217  assert( p->aColName!=0 );
74218  pColName = &(p->aColName[idx+var*p->nResColumn]);
74219  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
74220  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
74221  return rc;
74222}
74223
74224/*
74225** A read or write transaction may or may not be active on database handle
74226** db. If a transaction is active, commit it. If there is a
74227** write-transaction spanning more than one database file, this routine
74228** takes care of the master journal trickery.
74229*/
74230static int vdbeCommit(sqlite3 *db, Vdbe *p){
74231  int i;
74232  int nTrans = 0;  /* Number of databases with an active write-transaction
74233                   ** that are candidates for a two-phase commit using a
74234                   ** master-journal */
74235  int rc = SQLITE_OK;
74236  int needXcommit = 0;
74237
74238#ifdef SQLITE_OMIT_VIRTUALTABLE
74239  /* With this option, sqlite3VtabSync() is defined to be simply
74240  ** SQLITE_OK so p is not used.
74241  */
74242  UNUSED_PARAMETER(p);
74243#endif
74244
74245  /* Before doing anything else, call the xSync() callback for any
74246  ** virtual module tables written in this transaction. This has to
74247  ** be done before determining whether a master journal file is
74248  ** required, as an xSync() callback may add an attached database
74249  ** to the transaction.
74250  */
74251  rc = sqlite3VtabSync(db, p);
74252
74253  /* This loop determines (a) if the commit hook should be invoked and
74254  ** (b) how many database files have open write transactions, not
74255  ** including the temp database. (b) is important because if more than
74256  ** one database file has an open write transaction, a master journal
74257  ** file is required for an atomic commit.
74258  */
74259  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
74260    Btree *pBt = db->aDb[i].pBt;
74261    if( sqlite3BtreeIsInTrans(pBt) ){
74262      /* Whether or not a database might need a master journal depends upon
74263      ** its journal mode (among other things).  This matrix determines which
74264      ** journal modes use a master journal and which do not */
74265      static const u8 aMJNeeded[] = {
74266        /* DELETE   */  1,
74267        /* PERSIST   */ 1,
74268        /* OFF       */ 0,
74269        /* TRUNCATE  */ 1,
74270        /* MEMORY    */ 0,
74271        /* WAL       */ 0
74272      };
74273      Pager *pPager;   /* Pager associated with pBt */
74274      needXcommit = 1;
74275      sqlite3BtreeEnter(pBt);
74276      pPager = sqlite3BtreePager(pBt);
74277      if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
74278       && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
74279      ){
74280        assert( i!=1 );
74281        nTrans++;
74282      }
74283      rc = sqlite3PagerExclusiveLock(pPager);
74284      sqlite3BtreeLeave(pBt);
74285    }
74286  }
74287  if( rc!=SQLITE_OK ){
74288    return rc;
74289  }
74290
74291  /* If there are any write-transactions at all, invoke the commit hook */
74292  if( needXcommit && db->xCommitCallback ){
74293    rc = db->xCommitCallback(db->pCommitArg);
74294    if( rc ){
74295      return SQLITE_CONSTRAINT_COMMITHOOK;
74296    }
74297  }
74298
74299  /* The simple case - no more than one database file (not counting the
74300  ** TEMP database) has a transaction active.   There is no need for the
74301  ** master-journal.
74302  **
74303  ** If the return value of sqlite3BtreeGetFilename() is a zero length
74304  ** string, it means the main database is :memory: or a temp file.  In
74305  ** that case we do not support atomic multi-file commits, so use the
74306  ** simple case then too.
74307  */
74308  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
74309   || nTrans<=1
74310  ){
74311    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
74312      Btree *pBt = db->aDb[i].pBt;
74313      if( pBt ){
74314        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
74315      }
74316    }
74317
74318    /* Do the commit only if all databases successfully complete phase 1.
74319    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
74320    ** IO error while deleting or truncating a journal file. It is unlikely,
74321    ** but could happen. In this case abandon processing and return the error.
74322    */
74323    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
74324      Btree *pBt = db->aDb[i].pBt;
74325      if( pBt ){
74326        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
74327      }
74328    }
74329    if( rc==SQLITE_OK ){
74330      sqlite3VtabCommit(db);
74331    }
74332  }
74333
74334  /* The complex case - There is a multi-file write-transaction active.
74335  ** This requires a master journal file to ensure the transaction is
74336  ** committed atomically.
74337  */
74338#ifndef SQLITE_OMIT_DISKIO
74339  else{
74340    sqlite3_vfs *pVfs = db->pVfs;
74341    char *zMaster = 0;   /* File-name for the master journal */
74342    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
74343    sqlite3_file *pMaster = 0;
74344    i64 offset = 0;
74345    int res;
74346    int retryCount = 0;
74347    int nMainFile;
74348
74349    /* Select a master journal file name */
74350    nMainFile = sqlite3Strlen30(zMainFile);
74351    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
74352    if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
74353    do {
74354      u32 iRandom;
74355      if( retryCount ){
74356        if( retryCount>100 ){
74357          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
74358          sqlite3OsDelete(pVfs, zMaster, 0);
74359          break;
74360        }else if( retryCount==1 ){
74361          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
74362        }
74363      }
74364      retryCount++;
74365      sqlite3_randomness(sizeof(iRandom), &iRandom);
74366      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
74367                               (iRandom>>8)&0xffffff, iRandom&0xff);
74368      /* The antipenultimate character of the master journal name must
74369      ** be "9" to avoid name collisions when using 8+3 filenames. */
74370      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
74371      sqlite3FileSuffix3(zMainFile, zMaster);
74372      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
74373    }while( rc==SQLITE_OK && res );
74374    if( rc==SQLITE_OK ){
74375      /* Open the master journal. */
74376      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
74377          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
74378          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
74379      );
74380    }
74381    if( rc!=SQLITE_OK ){
74382      sqlite3DbFree(db, zMaster);
74383      return rc;
74384    }
74385
74386    /* Write the name of each database file in the transaction into the new
74387    ** master journal file. If an error occurs at this point close
74388    ** and delete the master journal file. All the individual journal files
74389    ** still have 'null' as the master journal pointer, so they will roll
74390    ** back independently if a failure occurs.
74391    */
74392    for(i=0; i<db->nDb; i++){
74393      Btree *pBt = db->aDb[i].pBt;
74394      if( sqlite3BtreeIsInTrans(pBt) ){
74395        char const *zFile = sqlite3BtreeGetJournalname(pBt);
74396        if( zFile==0 ){
74397          continue;  /* Ignore TEMP and :memory: databases */
74398        }
74399        assert( zFile[0]!=0 );
74400        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
74401        offset += sqlite3Strlen30(zFile)+1;
74402        if( rc!=SQLITE_OK ){
74403          sqlite3OsCloseFree(pMaster);
74404          sqlite3OsDelete(pVfs, zMaster, 0);
74405          sqlite3DbFree(db, zMaster);
74406          return rc;
74407        }
74408      }
74409    }
74410
74411    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
74412    ** flag is set this is not required.
74413    */
74414    if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
74415     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
74416    ){
74417      sqlite3OsCloseFree(pMaster);
74418      sqlite3OsDelete(pVfs, zMaster, 0);
74419      sqlite3DbFree(db, zMaster);
74420      return rc;
74421    }
74422
74423    /* Sync all the db files involved in the transaction. The same call
74424    ** sets the master journal pointer in each individual journal. If
74425    ** an error occurs here, do not delete the master journal file.
74426    **
74427    ** If the error occurs during the first call to
74428    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
74429    ** master journal file will be orphaned. But we cannot delete it,
74430    ** in case the master journal file name was written into the journal
74431    ** file before the failure occurred.
74432    */
74433    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
74434      Btree *pBt = db->aDb[i].pBt;
74435      if( pBt ){
74436        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
74437      }
74438    }
74439    sqlite3OsCloseFree(pMaster);
74440    assert( rc!=SQLITE_BUSY );
74441    if( rc!=SQLITE_OK ){
74442      sqlite3DbFree(db, zMaster);
74443      return rc;
74444    }
74445
74446    /* Delete the master journal file. This commits the transaction. After
74447    ** doing this the directory is synced again before any individual
74448    ** transaction files are deleted.
74449    */
74450    rc = sqlite3OsDelete(pVfs, zMaster, 1);
74451    sqlite3DbFree(db, zMaster);
74452    zMaster = 0;
74453    if( rc ){
74454      return rc;
74455    }
74456
74457    /* All files and directories have already been synced, so the following
74458    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
74459    ** deleting or truncating journals. If something goes wrong while
74460    ** this is happening we don't really care. The integrity of the
74461    ** transaction is already guaranteed, but some stray 'cold' journals
74462    ** may be lying around. Returning an error code won't help matters.
74463    */
74464    disable_simulated_io_errors();
74465    sqlite3BeginBenignMalloc();
74466    for(i=0; i<db->nDb; i++){
74467      Btree *pBt = db->aDb[i].pBt;
74468      if( pBt ){
74469        sqlite3BtreeCommitPhaseTwo(pBt, 1);
74470      }
74471    }
74472    sqlite3EndBenignMalloc();
74473    enable_simulated_io_errors();
74474
74475    sqlite3VtabCommit(db);
74476  }
74477#endif
74478
74479  return rc;
74480}
74481
74482/*
74483** This routine checks that the sqlite3.nVdbeActive count variable
74484** matches the number of vdbe's in the list sqlite3.pVdbe that are
74485** currently active. An assertion fails if the two counts do not match.
74486** This is an internal self-check only - it is not an essential processing
74487** step.
74488**
74489** This is a no-op if NDEBUG is defined.
74490*/
74491#ifndef NDEBUG
74492static void checkActiveVdbeCnt(sqlite3 *db){
74493  Vdbe *p;
74494  int cnt = 0;
74495  int nWrite = 0;
74496  int nRead = 0;
74497  p = db->pVdbe;
74498  while( p ){
74499    if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
74500      cnt++;
74501      if( p->readOnly==0 ) nWrite++;
74502      if( p->bIsReader ) nRead++;
74503    }
74504    p = p->pNext;
74505  }
74506  assert( cnt==db->nVdbeActive );
74507  assert( nWrite==db->nVdbeWrite );
74508  assert( nRead==db->nVdbeRead );
74509}
74510#else
74511#define checkActiveVdbeCnt(x)
74512#endif
74513
74514/*
74515** If the Vdbe passed as the first argument opened a statement-transaction,
74516** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
74517** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
74518** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
74519** statement transaction is committed.
74520**
74521** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
74522** Otherwise SQLITE_OK.
74523*/
74524static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
74525  sqlite3 *const db = p->db;
74526  int rc = SQLITE_OK;
74527  int i;
74528  const int iSavepoint = p->iStatement-1;
74529
74530  assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
74531  assert( db->nStatement>0 );
74532  assert( p->iStatement==(db->nStatement+db->nSavepoint) );
74533
74534  for(i=0; i<db->nDb; i++){
74535    int rc2 = SQLITE_OK;
74536    Btree *pBt = db->aDb[i].pBt;
74537    if( pBt ){
74538      if( eOp==SAVEPOINT_ROLLBACK ){
74539        rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
74540      }
74541      if( rc2==SQLITE_OK ){
74542        rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
74543      }
74544      if( rc==SQLITE_OK ){
74545        rc = rc2;
74546      }
74547    }
74548  }
74549  db->nStatement--;
74550  p->iStatement = 0;
74551
74552  if( rc==SQLITE_OK ){
74553    if( eOp==SAVEPOINT_ROLLBACK ){
74554      rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
74555    }
74556    if( rc==SQLITE_OK ){
74557      rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
74558    }
74559  }
74560
74561  /* If the statement transaction is being rolled back, also restore the
74562  ** database handles deferred constraint counter to the value it had when
74563  ** the statement transaction was opened.  */
74564  if( eOp==SAVEPOINT_ROLLBACK ){
74565    db->nDeferredCons = p->nStmtDefCons;
74566    db->nDeferredImmCons = p->nStmtDefImmCons;
74567  }
74568  return rc;
74569}
74570SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
74571  if( p->db->nStatement && p->iStatement ){
74572    return vdbeCloseStatement(p, eOp);
74573  }
74574  return SQLITE_OK;
74575}
74576
74577
74578/*
74579** This function is called when a transaction opened by the database
74580** handle associated with the VM passed as an argument is about to be
74581** committed. If there are outstanding deferred foreign key constraint
74582** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
74583**
74584** If there are outstanding FK violations and this function returns
74585** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
74586** and write an error message to it. Then return SQLITE_ERROR.
74587*/
74588#ifndef SQLITE_OMIT_FOREIGN_KEY
74589SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
74590  sqlite3 *db = p->db;
74591  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
74592   || (!deferred && p->nFkConstraint>0)
74593  ){
74594    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
74595    p->errorAction = OE_Abort;
74596    sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
74597    return SQLITE_ERROR;
74598  }
74599  return SQLITE_OK;
74600}
74601#endif
74602
74603/*
74604** This routine is called the when a VDBE tries to halt.  If the VDBE
74605** has made changes and is in autocommit mode, then commit those
74606** changes.  If a rollback is needed, then do the rollback.
74607**
74608** This routine is the only way to move the state of a VM from
74609** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
74610** call this on a VM that is in the SQLITE_MAGIC_HALT state.
74611**
74612** Return an error code.  If the commit could not complete because of
74613** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
74614** means the close did not happen and needs to be repeated.
74615*/
74616SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
74617  int rc;                         /* Used to store transient return codes */
74618  sqlite3 *db = p->db;
74619
74620  /* This function contains the logic that determines if a statement or
74621  ** transaction will be committed or rolled back as a result of the
74622  ** execution of this virtual machine.
74623  **
74624  ** If any of the following errors occur:
74625  **
74626  **     SQLITE_NOMEM
74627  **     SQLITE_IOERR
74628  **     SQLITE_FULL
74629  **     SQLITE_INTERRUPT
74630  **
74631  ** Then the internal cache might have been left in an inconsistent
74632  ** state.  We need to rollback the statement transaction, if there is
74633  ** one, or the complete transaction if there is no statement transaction.
74634  */
74635
74636  if( p->magic!=VDBE_MAGIC_RUN ){
74637    return SQLITE_OK;
74638  }
74639  if( db->mallocFailed ){
74640    p->rc = SQLITE_NOMEM_BKPT;
74641  }
74642  closeAllCursors(p);
74643  checkActiveVdbeCnt(db);
74644
74645  /* No commit or rollback needed if the program never started or if the
74646  ** SQL statement does not read or write a database file.  */
74647  if( p->pc>=0 && p->bIsReader ){
74648    int mrc;   /* Primary error code from p->rc */
74649    int eStatementOp = 0;
74650    int isSpecialError;            /* Set to true if a 'special' error */
74651
74652    /* Lock all btrees used by the statement */
74653    sqlite3VdbeEnter(p);
74654
74655    /* Check for one of the special errors */
74656    mrc = p->rc & 0xff;
74657    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
74658                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
74659    if( isSpecialError ){
74660      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
74661      ** no rollback is necessary. Otherwise, at least a savepoint
74662      ** transaction must be rolled back to restore the database to a
74663      ** consistent state.
74664      **
74665      ** Even if the statement is read-only, it is important to perform
74666      ** a statement or transaction rollback operation. If the error
74667      ** occurred while writing to the journal, sub-journal or database
74668      ** file as part of an effort to free up cache space (see function
74669      ** pagerStress() in pager.c), the rollback is required to restore
74670      ** the pager to a consistent state.
74671      */
74672      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
74673        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
74674          eStatementOp = SAVEPOINT_ROLLBACK;
74675        }else{
74676          /* We are forced to roll back the active transaction. Before doing
74677          ** so, abort any other statements this handle currently has active.
74678          */
74679          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
74680          sqlite3CloseSavepoints(db);
74681          db->autoCommit = 1;
74682          p->nChange = 0;
74683        }
74684      }
74685    }
74686
74687    /* Check for immediate foreign key violations. */
74688    if( p->rc==SQLITE_OK ){
74689      sqlite3VdbeCheckFk(p, 0);
74690    }
74691
74692    /* If the auto-commit flag is set and this is the only active writer
74693    ** VM, then we do either a commit or rollback of the current transaction.
74694    **
74695    ** Note: This block also runs if one of the special errors handled
74696    ** above has occurred.
74697    */
74698    if( !sqlite3VtabInSync(db)
74699     && db->autoCommit
74700     && db->nVdbeWrite==(p->readOnly==0)
74701    ){
74702      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
74703        rc = sqlite3VdbeCheckFk(p, 1);
74704        if( rc!=SQLITE_OK ){
74705          if( NEVER(p->readOnly) ){
74706            sqlite3VdbeLeave(p);
74707            return SQLITE_ERROR;
74708          }
74709          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
74710        }else{
74711          /* The auto-commit flag is true, the vdbe program was successful
74712          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
74713          ** key constraints to hold up the transaction. This means a commit
74714          ** is required. */
74715          rc = vdbeCommit(db, p);
74716        }
74717        if( rc==SQLITE_BUSY && p->readOnly ){
74718          sqlite3VdbeLeave(p);
74719          return SQLITE_BUSY;
74720        }else if( rc!=SQLITE_OK ){
74721          p->rc = rc;
74722          sqlite3RollbackAll(db, SQLITE_OK);
74723          p->nChange = 0;
74724        }else{
74725          db->nDeferredCons = 0;
74726          db->nDeferredImmCons = 0;
74727          db->flags &= ~SQLITE_DeferFKs;
74728          sqlite3CommitInternalChanges(db);
74729        }
74730      }else{
74731        sqlite3RollbackAll(db, SQLITE_OK);
74732        p->nChange = 0;
74733      }
74734      db->nStatement = 0;
74735    }else if( eStatementOp==0 ){
74736      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
74737        eStatementOp = SAVEPOINT_RELEASE;
74738      }else if( p->errorAction==OE_Abort ){
74739        eStatementOp = SAVEPOINT_ROLLBACK;
74740      }else{
74741        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
74742        sqlite3CloseSavepoints(db);
74743        db->autoCommit = 1;
74744        p->nChange = 0;
74745      }
74746    }
74747
74748    /* If eStatementOp is non-zero, then a statement transaction needs to
74749    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
74750    ** do so. If this operation returns an error, and the current statement
74751    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
74752    ** current statement error code.
74753    */
74754    if( eStatementOp ){
74755      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
74756      if( rc ){
74757        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
74758          p->rc = rc;
74759          sqlite3DbFree(db, p->zErrMsg);
74760          p->zErrMsg = 0;
74761        }
74762        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
74763        sqlite3CloseSavepoints(db);
74764        db->autoCommit = 1;
74765        p->nChange = 0;
74766      }
74767    }
74768
74769    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
74770    ** has been rolled back, update the database connection change-counter.
74771    */
74772    if( p->changeCntOn ){
74773      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
74774        sqlite3VdbeSetChanges(db, p->nChange);
74775      }else{
74776        sqlite3VdbeSetChanges(db, 0);
74777      }
74778      p->nChange = 0;
74779    }
74780
74781    /* Release the locks */
74782    sqlite3VdbeLeave(p);
74783  }
74784
74785  /* We have successfully halted and closed the VM.  Record this fact. */
74786  if( p->pc>=0 ){
74787    db->nVdbeActive--;
74788    if( !p->readOnly ) db->nVdbeWrite--;
74789    if( p->bIsReader ) db->nVdbeRead--;
74790    assert( db->nVdbeActive>=db->nVdbeRead );
74791    assert( db->nVdbeRead>=db->nVdbeWrite );
74792    assert( db->nVdbeWrite>=0 );
74793  }
74794  p->magic = VDBE_MAGIC_HALT;
74795  checkActiveVdbeCnt(db);
74796  if( db->mallocFailed ){
74797    p->rc = SQLITE_NOMEM_BKPT;
74798  }
74799
74800  /* If the auto-commit flag is set to true, then any locks that were held
74801  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
74802  ** to invoke any required unlock-notify callbacks.
74803  */
74804  if( db->autoCommit ){
74805    sqlite3ConnectionUnlocked(db);
74806  }
74807
74808  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
74809  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
74810}
74811
74812
74813/*
74814** Each VDBE holds the result of the most recent sqlite3_step() call
74815** in p->rc.  This routine sets that result back to SQLITE_OK.
74816*/
74817SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
74818  p->rc = SQLITE_OK;
74819}
74820
74821/*
74822** Copy the error code and error message belonging to the VDBE passed
74823** as the first argument to its database handle (so that they will be
74824** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
74825**
74826** This function does not clear the VDBE error code or message, just
74827** copies them to the database handle.
74828*/
74829SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
74830  sqlite3 *db = p->db;
74831  int rc = p->rc;
74832  if( p->zErrMsg ){
74833    db->bBenignMalloc++;
74834    sqlite3BeginBenignMalloc();
74835    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
74836    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
74837    sqlite3EndBenignMalloc();
74838    db->bBenignMalloc--;
74839  }else if( db->pErr ){
74840    sqlite3ValueSetNull(db->pErr);
74841  }
74842  db->errCode = rc;
74843  return rc;
74844}
74845
74846#ifdef SQLITE_ENABLE_SQLLOG
74847/*
74848** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
74849** invoke it.
74850*/
74851static void vdbeInvokeSqllog(Vdbe *v){
74852  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
74853    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
74854    assert( v->db->init.busy==0 );
74855    if( zExpanded ){
74856      sqlite3GlobalConfig.xSqllog(
74857          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
74858      );
74859      sqlite3DbFree(v->db, zExpanded);
74860    }
74861  }
74862}
74863#else
74864# define vdbeInvokeSqllog(x)
74865#endif
74866
74867/*
74868** Clean up a VDBE after execution but do not delete the VDBE just yet.
74869** Write any error messages into *pzErrMsg.  Return the result code.
74870**
74871** After this routine is run, the VDBE should be ready to be executed
74872** again.
74873**
74874** To look at it another way, this routine resets the state of the
74875** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
74876** VDBE_MAGIC_INIT.
74877*/
74878SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
74879  sqlite3 *db;
74880  db = p->db;
74881
74882  /* If the VM did not run to completion or if it encountered an
74883  ** error, then it might not have been halted properly.  So halt
74884  ** it now.
74885  */
74886  sqlite3VdbeHalt(p);
74887
74888  /* If the VDBE has be run even partially, then transfer the error code
74889  ** and error message from the VDBE into the main database structure.  But
74890  ** if the VDBE has just been set to run but has not actually executed any
74891  ** instructions yet, leave the main database error information unchanged.
74892  */
74893  if( p->pc>=0 ){
74894    vdbeInvokeSqllog(p);
74895    sqlite3VdbeTransferError(p);
74896    sqlite3DbFree(db, p->zErrMsg);
74897    p->zErrMsg = 0;
74898    if( p->runOnlyOnce ) p->expired = 1;
74899  }else if( p->rc && p->expired ){
74900    /* The expired flag was set on the VDBE before the first call
74901    ** to sqlite3_step(). For consistency (since sqlite3_step() was
74902    ** called), set the database error in this case as well.
74903    */
74904    sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
74905    sqlite3DbFree(db, p->zErrMsg);
74906    p->zErrMsg = 0;
74907  }
74908
74909  /* Reclaim all memory used by the VDBE
74910  */
74911  Cleanup(p);
74912
74913  /* Save profiling information from this VDBE run.
74914  */
74915#ifdef VDBE_PROFILE
74916  {
74917    FILE *out = fopen("vdbe_profile.out", "a");
74918    if( out ){
74919      int i;
74920      fprintf(out, "---- ");
74921      for(i=0; i<p->nOp; i++){
74922        fprintf(out, "%02x", p->aOp[i].opcode);
74923      }
74924      fprintf(out, "\n");
74925      if( p->zSql ){
74926        char c, pc = 0;
74927        fprintf(out, "-- ");
74928        for(i=0; (c = p->zSql[i])!=0; i++){
74929          if( pc=='\n' ) fprintf(out, "-- ");
74930          putc(c, out);
74931          pc = c;
74932        }
74933        if( pc!='\n' ) fprintf(out, "\n");
74934      }
74935      for(i=0; i<p->nOp; i++){
74936        char zHdr[100];
74937        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
74938           p->aOp[i].cnt,
74939           p->aOp[i].cycles,
74940           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
74941        );
74942        fprintf(out, "%s", zHdr);
74943        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
74944      }
74945      fclose(out);
74946    }
74947  }
74948#endif
74949  p->magic = VDBE_MAGIC_RESET;
74950  return p->rc & db->errMask;
74951}
74952
74953/*
74954** Clean up and delete a VDBE after execution.  Return an integer which is
74955** the result code.  Write any error message text into *pzErrMsg.
74956*/
74957SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
74958  int rc = SQLITE_OK;
74959  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
74960    rc = sqlite3VdbeReset(p);
74961    assert( (rc & p->db->errMask)==rc );
74962  }
74963  sqlite3VdbeDelete(p);
74964  return rc;
74965}
74966
74967/*
74968** If parameter iOp is less than zero, then invoke the destructor for
74969** all auxiliary data pointers currently cached by the VM passed as
74970** the first argument.
74971**
74972** Or, if iOp is greater than or equal to zero, then the destructor is
74973** only invoked for those auxiliary data pointers created by the user
74974** function invoked by the OP_Function opcode at instruction iOp of
74975** VM pVdbe, and only then if:
74976**
74977**    * the associated function parameter is the 32nd or later (counting
74978**      from left to right), or
74979**
74980**    * the corresponding bit in argument mask is clear (where the first
74981**      function parameter corresponds to bit 0 etc.).
74982*/
74983SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
74984  while( *pp ){
74985    AuxData *pAux = *pp;
74986    if( (iOp<0)
74987     || (pAux->iAuxOp==iOp
74988          && pAux->iAuxArg>=0
74989          && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
74990    ){
74991      testcase( pAux->iAuxArg==31 );
74992      if( pAux->xDeleteAux ){
74993        pAux->xDeleteAux(pAux->pAux);
74994      }
74995      *pp = pAux->pNextAux;
74996      sqlite3DbFree(db, pAux);
74997    }else{
74998      pp= &pAux->pNextAux;
74999    }
75000  }
75001}
75002
75003/*
75004** Free all memory associated with the Vdbe passed as the second argument,
75005** except for object itself, which is preserved.
75006**
75007** The difference between this function and sqlite3VdbeDelete() is that
75008** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
75009** the database connection and frees the object itself.
75010*/
75011SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
75012  SubProgram *pSub, *pNext;
75013  assert( p->db==0 || p->db==db );
75014  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
75015  for(pSub=p->pProgram; pSub; pSub=pNext){
75016    pNext = pSub->pNext;
75017    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
75018    sqlite3DbFree(db, pSub);
75019  }
75020  if( p->magic!=VDBE_MAGIC_INIT ){
75021    releaseMemArray(p->aVar, p->nVar);
75022    sqlite3DbFree(db, p->pVList);
75023    sqlite3DbFree(db, p->pFree);
75024  }
75025  vdbeFreeOpArray(db, p->aOp, p->nOp);
75026  sqlite3DbFree(db, p->aColName);
75027  sqlite3DbFree(db, p->zSql);
75028#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
75029  {
75030    int i;
75031    for(i=0; i<p->nScan; i++){
75032      sqlite3DbFree(db, p->aScan[i].zName);
75033    }
75034    sqlite3DbFree(db, p->aScan);
75035  }
75036#endif
75037}
75038
75039/*
75040** Delete an entire VDBE.
75041*/
75042SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
75043  sqlite3 *db;
75044
75045  if( NEVER(p==0) ) return;
75046  db = p->db;
75047  assert( sqlite3_mutex_held(db->mutex) );
75048  sqlite3VdbeClearObject(db, p);
75049  if( p->pPrev ){
75050    p->pPrev->pNext = p->pNext;
75051  }else{
75052    assert( db->pVdbe==p );
75053    db->pVdbe = p->pNext;
75054  }
75055  if( p->pNext ){
75056    p->pNext->pPrev = p->pPrev;
75057  }
75058  p->magic = VDBE_MAGIC_DEAD;
75059  p->db = 0;
75060  sqlite3DbFreeNN(db, p);
75061}
75062
75063/*
75064** The cursor "p" has a pending seek operation that has not yet been
75065** carried out.  Seek the cursor now.  If an error occurs, return
75066** the appropriate error code.
75067*/
75068static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
75069  int res, rc;
75070#ifdef SQLITE_TEST
75071  extern int sqlite3_search_count;
75072#endif
75073  assert( p->deferredMoveto );
75074  assert( p->isTable );
75075  assert( p->eCurType==CURTYPE_BTREE );
75076  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
75077  if( rc ) return rc;
75078  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
75079#ifdef SQLITE_TEST
75080  sqlite3_search_count++;
75081#endif
75082  p->deferredMoveto = 0;
75083  p->cacheStatus = CACHE_STALE;
75084  return SQLITE_OK;
75085}
75086
75087/*
75088** Something has moved cursor "p" out of place.  Maybe the row it was
75089** pointed to was deleted out from under it.  Or maybe the btree was
75090** rebalanced.  Whatever the cause, try to restore "p" to the place it
75091** is supposed to be pointing.  If the row was deleted out from under the
75092** cursor, set the cursor to point to a NULL row.
75093*/
75094static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
75095  int isDifferentRow, rc;
75096  assert( p->eCurType==CURTYPE_BTREE );
75097  assert( p->uc.pCursor!=0 );
75098  assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
75099  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
75100  p->cacheStatus = CACHE_STALE;
75101  if( isDifferentRow ) p->nullRow = 1;
75102  return rc;
75103}
75104
75105/*
75106** Check to ensure that the cursor is valid.  Restore the cursor
75107** if need be.  Return any I/O error from the restore operation.
75108*/
75109SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
75110  assert( p->eCurType==CURTYPE_BTREE );
75111  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
75112    return handleMovedCursor(p);
75113  }
75114  return SQLITE_OK;
75115}
75116
75117/*
75118** Make sure the cursor p is ready to read or write the row to which it
75119** was last positioned.  Return an error code if an OOM fault or I/O error
75120** prevents us from positioning the cursor to its correct position.
75121**
75122** If a MoveTo operation is pending on the given cursor, then do that
75123** MoveTo now.  If no move is pending, check to see if the row has been
75124** deleted out from under the cursor and if it has, mark the row as
75125** a NULL row.
75126**
75127** If the cursor is already pointing to the correct row and that row has
75128** not been deleted out from under the cursor, then this routine is a no-op.
75129*/
75130SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
75131  VdbeCursor *p = *pp;
75132  if( p->eCurType==CURTYPE_BTREE ){
75133    if( p->deferredMoveto ){
75134      int iMap;
75135      if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
75136        *pp = p->pAltCursor;
75137        *piCol = iMap - 1;
75138        return SQLITE_OK;
75139      }
75140      return handleDeferredMoveto(p);
75141    }
75142    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
75143      return handleMovedCursor(p);
75144    }
75145  }
75146  return SQLITE_OK;
75147}
75148
75149/*
75150** The following functions:
75151**
75152** sqlite3VdbeSerialType()
75153** sqlite3VdbeSerialTypeLen()
75154** sqlite3VdbeSerialLen()
75155** sqlite3VdbeSerialPut()
75156** sqlite3VdbeSerialGet()
75157**
75158** encapsulate the code that serializes values for storage in SQLite
75159** data and index records. Each serialized value consists of a
75160** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
75161** integer, stored as a varint.
75162**
75163** In an SQLite index record, the serial type is stored directly before
75164** the blob of data that it corresponds to. In a table record, all serial
75165** types are stored at the start of the record, and the blobs of data at
75166** the end. Hence these functions allow the caller to handle the
75167** serial-type and data blob separately.
75168**
75169** The following table describes the various storage classes for data:
75170**
75171**   serial type        bytes of data      type
75172**   --------------     ---------------    ---------------
75173**      0                     0            NULL
75174**      1                     1            signed integer
75175**      2                     2            signed integer
75176**      3                     3            signed integer
75177**      4                     4            signed integer
75178**      5                     6            signed integer
75179**      6                     8            signed integer
75180**      7                     8            IEEE float
75181**      8                     0            Integer constant 0
75182**      9                     0            Integer constant 1
75183**     10,11                               reserved for expansion
75184**    N>=12 and even       (N-12)/2        BLOB
75185**    N>=13 and odd        (N-13)/2        text
75186**
75187** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
75188** of SQLite will not understand those serial types.
75189*/
75190
75191/*
75192** Return the serial-type for the value stored in pMem.
75193*/
75194SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
75195  int flags = pMem->flags;
75196  u32 n;
75197
75198  assert( pLen!=0 );
75199  if( flags&MEM_Null ){
75200    *pLen = 0;
75201    return 0;
75202  }
75203  if( flags&MEM_Int ){
75204    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
75205#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
75206    i64 i = pMem->u.i;
75207    u64 u;
75208    if( i<0 ){
75209      u = ~i;
75210    }else{
75211      u = i;
75212    }
75213    if( u<=127 ){
75214      if( (i&1)==i && file_format>=4 ){
75215        *pLen = 0;
75216        return 8+(u32)u;
75217      }else{
75218        *pLen = 1;
75219        return 1;
75220      }
75221    }
75222    if( u<=32767 ){ *pLen = 2; return 2; }
75223    if( u<=8388607 ){ *pLen = 3; return 3; }
75224    if( u<=2147483647 ){ *pLen = 4; return 4; }
75225    if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
75226    *pLen = 8;
75227    return 6;
75228  }
75229  if( flags&MEM_Real ){
75230    *pLen = 8;
75231    return 7;
75232  }
75233  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
75234  assert( pMem->n>=0 );
75235  n = (u32)pMem->n;
75236  if( flags & MEM_Zero ){
75237    n += pMem->u.nZero;
75238  }
75239  *pLen = n;
75240  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
75241}
75242
75243/*
75244** The sizes for serial types less than 128
75245*/
75246static const u8 sqlite3SmallTypeSizes[] = {
75247        /*  0   1   2   3   4   5   6   7   8   9 */
75248/*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
75249/*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
75250/*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
75251/*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
75252/*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
75253/*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
75254/*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
75255/*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
75256/*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
75257/*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
75258/* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
75259/* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
75260/* 120 */  54, 54, 55, 55, 56, 56, 57, 57
75261};
75262
75263/*
75264** Return the length of the data corresponding to the supplied serial-type.
75265*/
75266SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
75267  if( serial_type>=128 ){
75268    return (serial_type-12)/2;
75269  }else{
75270    assert( serial_type<12
75271            || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
75272    return sqlite3SmallTypeSizes[serial_type];
75273  }
75274}
75275SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
75276  assert( serial_type<128 );
75277  return sqlite3SmallTypeSizes[serial_type];
75278}
75279
75280/*
75281** If we are on an architecture with mixed-endian floating
75282** points (ex: ARM7) then swap the lower 4 bytes with the
75283** upper 4 bytes.  Return the result.
75284**
75285** For most architectures, this is a no-op.
75286**
75287** (later):  It is reported to me that the mixed-endian problem
75288** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
75289** that early versions of GCC stored the two words of a 64-bit
75290** float in the wrong order.  And that error has been propagated
75291** ever since.  The blame is not necessarily with GCC, though.
75292** GCC might have just copying the problem from a prior compiler.
75293** I am also told that newer versions of GCC that follow a different
75294** ABI get the byte order right.
75295**
75296** Developers using SQLite on an ARM7 should compile and run their
75297** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
75298** enabled, some asserts below will ensure that the byte order of
75299** floating point values is correct.
75300**
75301** (2007-08-30)  Frank van Vugt has studied this problem closely
75302** and has send his findings to the SQLite developers.  Frank
75303** writes that some Linux kernels offer floating point hardware
75304** emulation that uses only 32-bit mantissas instead of a full
75305** 48-bits as required by the IEEE standard.  (This is the
75306** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
75307** byte swapping becomes very complicated.  To avoid problems,
75308** the necessary byte swapping is carried out using a 64-bit integer
75309** rather than a 64-bit float.  Frank assures us that the code here
75310** works for him.  We, the developers, have no way to independently
75311** verify this, but Frank seems to know what he is talking about
75312** so we trust him.
75313*/
75314#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
75315static u64 floatSwap(u64 in){
75316  union {
75317    u64 r;
75318    u32 i[2];
75319  } u;
75320  u32 t;
75321
75322  u.r = in;
75323  t = u.i[0];
75324  u.i[0] = u.i[1];
75325  u.i[1] = t;
75326  return u.r;
75327}
75328# define swapMixedEndianFloat(X)  X = floatSwap(X)
75329#else
75330# define swapMixedEndianFloat(X)
75331#endif
75332
75333/*
75334** Write the serialized data blob for the value stored in pMem into
75335** buf. It is assumed that the caller has allocated sufficient space.
75336** Return the number of bytes written.
75337**
75338** nBuf is the amount of space left in buf[].  The caller is responsible
75339** for allocating enough space to buf[] to hold the entire field, exclusive
75340** of the pMem->u.nZero bytes for a MEM_Zero value.
75341**
75342** Return the number of bytes actually written into buf[].  The number
75343** of bytes in the zero-filled tail is included in the return value only
75344** if those bytes were zeroed in buf[].
75345*/
75346SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
75347  u32 len;
75348
75349  /* Integer and Real */
75350  if( serial_type<=7 && serial_type>0 ){
75351    u64 v;
75352    u32 i;
75353    if( serial_type==7 ){
75354      assert( sizeof(v)==sizeof(pMem->u.r) );
75355      memcpy(&v, &pMem->u.r, sizeof(v));
75356      swapMixedEndianFloat(v);
75357    }else{
75358      v = pMem->u.i;
75359    }
75360    len = i = sqlite3SmallTypeSizes[serial_type];
75361    assert( i>0 );
75362    do{
75363      buf[--i] = (u8)(v&0xFF);
75364      v >>= 8;
75365    }while( i );
75366    return len;
75367  }
75368
75369  /* String or blob */
75370  if( serial_type>=12 ){
75371    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
75372             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
75373    len = pMem->n;
75374    if( len>0 ) memcpy(buf, pMem->z, len);
75375    return len;
75376  }
75377
75378  /* NULL or constants 0 or 1 */
75379  return 0;
75380}
75381
75382/* Input "x" is a sequence of unsigned characters that represent a
75383** big-endian integer.  Return the equivalent native integer
75384*/
75385#define ONE_BYTE_INT(x)    ((i8)(x)[0])
75386#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
75387#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
75388#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
75389#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
75390
75391/*
75392** Deserialize the data blob pointed to by buf as serial type serial_type
75393** and store the result in pMem.  Return the number of bytes read.
75394**
75395** This function is implemented as two separate routines for performance.
75396** The few cases that require local variables are broken out into a separate
75397** routine so that in most cases the overhead of moving the stack pointer
75398** is avoided.
75399*/
75400static u32 SQLITE_NOINLINE serialGet(
75401  const unsigned char *buf,     /* Buffer to deserialize from */
75402  u32 serial_type,              /* Serial type to deserialize */
75403  Mem *pMem                     /* Memory cell to write value into */
75404){
75405  u64 x = FOUR_BYTE_UINT(buf);
75406  u32 y = FOUR_BYTE_UINT(buf+4);
75407  x = (x<<32) + y;
75408  if( serial_type==6 ){
75409    /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
75410    ** twos-complement integer. */
75411    pMem->u.i = *(i64*)&x;
75412    pMem->flags = MEM_Int;
75413    testcase( pMem->u.i<0 );
75414  }else{
75415    /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
75416    ** floating point number. */
75417#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
75418    /* Verify that integers and floating point values use the same
75419    ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
75420    ** defined that 64-bit floating point values really are mixed
75421    ** endian.
75422    */
75423    static const u64 t1 = ((u64)0x3ff00000)<<32;
75424    static const double r1 = 1.0;
75425    u64 t2 = t1;
75426    swapMixedEndianFloat(t2);
75427    assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
75428#endif
75429    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
75430    swapMixedEndianFloat(x);
75431    memcpy(&pMem->u.r, &x, sizeof(x));
75432    pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
75433  }
75434  return 8;
75435}
75436SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
75437  const unsigned char *buf,     /* Buffer to deserialize from */
75438  u32 serial_type,              /* Serial type to deserialize */
75439  Mem *pMem                     /* Memory cell to write value into */
75440){
75441  switch( serial_type ){
75442    case 10:   /* Reserved for future use */
75443    case 11:   /* Reserved for future use */
75444    case 0: {  /* Null */
75445      /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
75446      pMem->flags = MEM_Null;
75447      break;
75448    }
75449    case 1: {
75450      /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
75451      ** integer. */
75452      pMem->u.i = ONE_BYTE_INT(buf);
75453      pMem->flags = MEM_Int;
75454      testcase( pMem->u.i<0 );
75455      return 1;
75456    }
75457    case 2: { /* 2-byte signed integer */
75458      /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
75459      ** twos-complement integer. */
75460      pMem->u.i = TWO_BYTE_INT(buf);
75461      pMem->flags = MEM_Int;
75462      testcase( pMem->u.i<0 );
75463      return 2;
75464    }
75465    case 3: { /* 3-byte signed integer */
75466      /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
75467      ** twos-complement integer. */
75468      pMem->u.i = THREE_BYTE_INT(buf);
75469      pMem->flags = MEM_Int;
75470      testcase( pMem->u.i<0 );
75471      return 3;
75472    }
75473    case 4: { /* 4-byte signed integer */
75474      /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
75475      ** twos-complement integer. */
75476      pMem->u.i = FOUR_BYTE_INT(buf);
75477#ifdef __HP_cc
75478      /* Work around a sign-extension bug in the HP compiler for HP/UX */
75479      if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
75480#endif
75481      pMem->flags = MEM_Int;
75482      testcase( pMem->u.i<0 );
75483      return 4;
75484    }
75485    case 5: { /* 6-byte signed integer */
75486      /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
75487      ** twos-complement integer. */
75488      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
75489      pMem->flags = MEM_Int;
75490      testcase( pMem->u.i<0 );
75491      return 6;
75492    }
75493    case 6:   /* 8-byte signed integer */
75494    case 7: { /* IEEE floating point */
75495      /* These use local variables, so do them in a separate routine
75496      ** to avoid having to move the frame pointer in the common case */
75497      return serialGet(buf,serial_type,pMem);
75498    }
75499    case 8:    /* Integer 0 */
75500    case 9: {  /* Integer 1 */
75501      /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
75502      /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
75503      pMem->u.i = serial_type-8;
75504      pMem->flags = MEM_Int;
75505      return 0;
75506    }
75507    default: {
75508      /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
75509      ** length.
75510      ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
75511      ** (N-13)/2 bytes in length. */
75512      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
75513      pMem->z = (char *)buf;
75514      pMem->n = (serial_type-12)/2;
75515      pMem->flags = aFlag[serial_type&1];
75516      return pMem->n;
75517    }
75518  }
75519  return 0;
75520}
75521/*
75522** This routine is used to allocate sufficient space for an UnpackedRecord
75523** structure large enough to be used with sqlite3VdbeRecordUnpack() if
75524** the first argument is a pointer to KeyInfo structure pKeyInfo.
75525**
75526** The space is either allocated using sqlite3DbMallocRaw() or from within
75527** the unaligned buffer passed via the second and third arguments (presumably
75528** stack space). If the former, then *ppFree is set to a pointer that should
75529** be eventually freed by the caller using sqlite3DbFree(). Or, if the
75530** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
75531** before returning.
75532**
75533** If an OOM error occurs, NULL is returned.
75534*/
75535SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
75536  KeyInfo *pKeyInfo               /* Description of the record */
75537){
75538  UnpackedRecord *p;              /* Unpacked record to return */
75539  int nByte;                      /* Number of bytes required for *p */
75540  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
75541  p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
75542  if( !p ) return 0;
75543  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
75544  assert( pKeyInfo->aSortOrder!=0 );
75545  p->pKeyInfo = pKeyInfo;
75546  p->nField = pKeyInfo->nField + 1;
75547  return p;
75548}
75549
75550/*
75551** Given the nKey-byte encoding of a record in pKey[], populate the
75552** UnpackedRecord structure indicated by the fourth argument with the
75553** contents of the decoded record.
75554*/
75555SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
75556  KeyInfo *pKeyInfo,     /* Information about the record format */
75557  int nKey,              /* Size of the binary record */
75558  const void *pKey,      /* The binary record */
75559  UnpackedRecord *p      /* Populate this structure before returning. */
75560){
75561  const unsigned char *aKey = (const unsigned char *)pKey;
75562  int d;
75563  u32 idx;                        /* Offset in aKey[] to read from */
75564  u16 u;                          /* Unsigned loop counter */
75565  u32 szHdr;
75566  Mem *pMem = p->aMem;
75567
75568  p->default_rc = 0;
75569  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
75570  idx = getVarint32(aKey, szHdr);
75571  d = szHdr;
75572  u = 0;
75573  while( idx<szHdr && d<=nKey ){
75574    u32 serial_type;
75575
75576    idx += getVarint32(&aKey[idx], serial_type);
75577    pMem->enc = pKeyInfo->enc;
75578    pMem->db = pKeyInfo->db;
75579    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
75580    pMem->szMalloc = 0;
75581    pMem->z = 0;
75582    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
75583    pMem++;
75584    if( (++u)>=p->nField ) break;
75585  }
75586  assert( u<=pKeyInfo->nField + 1 );
75587  p->nField = u;
75588}
75589
75590#ifdef SQLITE_DEBUG
75591/*
75592** This function compares two index or table record keys in the same way
75593** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
75594** this function deserializes and compares values using the
75595** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
75596** in assert() statements to ensure that the optimized code in
75597** sqlite3VdbeRecordCompare() returns results with these two primitives.
75598**
75599** Return true if the result of comparison is equivalent to desiredResult.
75600** Return false if there is a disagreement.
75601*/
75602static int vdbeRecordCompareDebug(
75603  int nKey1, const void *pKey1, /* Left key */
75604  const UnpackedRecord *pPKey2, /* Right key */
75605  int desiredResult             /* Correct answer */
75606){
75607  u32 d1;            /* Offset into aKey[] of next data element */
75608  u32 idx1;          /* Offset into aKey[] of next header element */
75609  u32 szHdr1;        /* Number of bytes in header */
75610  int i = 0;
75611  int rc = 0;
75612  const unsigned char *aKey1 = (const unsigned char *)pKey1;
75613  KeyInfo *pKeyInfo;
75614  Mem mem1;
75615
75616  pKeyInfo = pPKey2->pKeyInfo;
75617  if( pKeyInfo->db==0 ) return 1;
75618  mem1.enc = pKeyInfo->enc;
75619  mem1.db = pKeyInfo->db;
75620  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
75621  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
75622
75623  /* Compilers may complain that mem1.u.i is potentially uninitialized.
75624  ** We could initialize it, as shown here, to silence those complaints.
75625  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
75626  ** the unnecessary initialization has a measurable negative performance
75627  ** impact, since this routine is a very high runner.  And so, we choose
75628  ** to ignore the compiler warnings and leave this variable uninitialized.
75629  */
75630  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
75631
75632  idx1 = getVarint32(aKey1, szHdr1);
75633  if( szHdr1>98307 ) return SQLITE_CORRUPT;
75634  d1 = szHdr1;
75635  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
75636  assert( pKeyInfo->aSortOrder!=0 );
75637  assert( pKeyInfo->nField>0 );
75638  assert( idx1<=szHdr1 || CORRUPT_DB );
75639  do{
75640    u32 serial_type1;
75641
75642    /* Read the serial types for the next element in each key. */
75643    idx1 += getVarint32( aKey1+idx1, serial_type1 );
75644
75645    /* Verify that there is enough key space remaining to avoid
75646    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
75647    ** always be greater than or equal to the amount of required key space.
75648    ** Use that approximation to avoid the more expensive call to
75649    ** sqlite3VdbeSerialTypeLen() in the common case.
75650    */
75651    if( d1+serial_type1+2>(u32)nKey1
75652     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
75653    ){
75654      break;
75655    }
75656
75657    /* Extract the values to be compared.
75658    */
75659    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
75660
75661    /* Do the comparison
75662    */
75663    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
75664    if( rc!=0 ){
75665      assert( mem1.szMalloc==0 );  /* See comment below */
75666      if( pKeyInfo->aSortOrder[i] ){
75667        rc = -rc;  /* Invert the result for DESC sort order. */
75668      }
75669      goto debugCompareEnd;
75670    }
75671    i++;
75672  }while( idx1<szHdr1 && i<pPKey2->nField );
75673
75674  /* No memory allocation is ever used on mem1.  Prove this using
75675  ** the following assert().  If the assert() fails, it indicates a
75676  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
75677  */
75678  assert( mem1.szMalloc==0 );
75679
75680  /* rc==0 here means that one of the keys ran out of fields and
75681  ** all the fields up to that point were equal. Return the default_rc
75682  ** value.  */
75683  rc = pPKey2->default_rc;
75684
75685debugCompareEnd:
75686  if( desiredResult==0 && rc==0 ) return 1;
75687  if( desiredResult<0 && rc<0 ) return 1;
75688  if( desiredResult>0 && rc>0 ) return 1;
75689  if( CORRUPT_DB ) return 1;
75690  if( pKeyInfo->db->mallocFailed ) return 1;
75691  return 0;
75692}
75693#endif
75694
75695#ifdef SQLITE_DEBUG
75696/*
75697** Count the number of fields (a.k.a. columns) in the record given by
75698** pKey,nKey.  The verify that this count is less than or equal to the
75699** limit given by pKeyInfo->nField + pKeyInfo->nXField.
75700**
75701** If this constraint is not satisfied, it means that the high-speed
75702** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
75703** not work correctly.  If this assert() ever fires, it probably means
75704** that the KeyInfo.nField or KeyInfo.nXField values were computed
75705** incorrectly.
75706*/
75707static void vdbeAssertFieldCountWithinLimits(
75708  int nKey, const void *pKey,   /* The record to verify */
75709  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
75710){
75711  int nField = 0;
75712  u32 szHdr;
75713  u32 idx;
75714  u32 notUsed;
75715  const unsigned char *aKey = (const unsigned char*)pKey;
75716
75717  if( CORRUPT_DB ) return;
75718  idx = getVarint32(aKey, szHdr);
75719  assert( nKey>=0 );
75720  assert( szHdr<=(u32)nKey );
75721  while( idx<szHdr ){
75722    idx += getVarint32(aKey+idx, notUsed);
75723    nField++;
75724  }
75725  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
75726}
75727#else
75728# define vdbeAssertFieldCountWithinLimits(A,B,C)
75729#endif
75730
75731/*
75732** Both *pMem1 and *pMem2 contain string values. Compare the two values
75733** using the collation sequence pColl. As usual, return a negative , zero
75734** or positive value if *pMem1 is less than, equal to or greater than
75735** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
75736*/
75737static int vdbeCompareMemString(
75738  const Mem *pMem1,
75739  const Mem *pMem2,
75740  const CollSeq *pColl,
75741  u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
75742){
75743  if( pMem1->enc==pColl->enc ){
75744    /* The strings are already in the correct encoding.  Call the
75745     ** comparison function directly */
75746    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
75747  }else{
75748    int rc;
75749    const void *v1, *v2;
75750    Mem c1;
75751    Mem c2;
75752    sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
75753    sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
75754    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
75755    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
75756    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
75757    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
75758    if( (v1==0 || v2==0) ){
75759      if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
75760      rc = 0;
75761    }else{
75762      rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
75763    }
75764    sqlite3VdbeMemRelease(&c1);
75765    sqlite3VdbeMemRelease(&c2);
75766    return rc;
75767  }
75768}
75769
75770/*
75771** The input pBlob is guaranteed to be a Blob that is not marked
75772** with MEM_Zero.  Return true if it could be a zero-blob.
75773*/
75774static int isAllZero(const char *z, int n){
75775  int i;
75776  for(i=0; i<n; i++){
75777    if( z[i] ) return 0;
75778  }
75779  return 1;
75780}
75781
75782/*
75783** Compare two blobs.  Return negative, zero, or positive if the first
75784** is less than, equal to, or greater than the second, respectively.
75785** If one blob is a prefix of the other, then the shorter is the lessor.
75786*/
75787static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
75788  int c;
75789  int n1 = pB1->n;
75790  int n2 = pB2->n;
75791
75792  /* It is possible to have a Blob value that has some non-zero content
75793  ** followed by zero content.  But that only comes up for Blobs formed
75794  ** by the OP_MakeRecord opcode, and such Blobs never get passed into
75795  ** sqlite3MemCompare(). */
75796  assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
75797  assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
75798
75799  if( (pB1->flags|pB2->flags) & MEM_Zero ){
75800    if( pB1->flags & pB2->flags & MEM_Zero ){
75801      return pB1->u.nZero - pB2->u.nZero;
75802    }else if( pB1->flags & MEM_Zero ){
75803      if( !isAllZero(pB2->z, pB2->n) ) return -1;
75804      return pB1->u.nZero - n2;
75805    }else{
75806      if( !isAllZero(pB1->z, pB1->n) ) return +1;
75807      return n1 - pB2->u.nZero;
75808    }
75809  }
75810  c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
75811  if( c ) return c;
75812  return n1 - n2;
75813}
75814
75815/*
75816** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
75817** number.  Return negative, zero, or positive if the first (i64) is less than,
75818** equal to, or greater than the second (double).
75819*/
75820static int sqlite3IntFloatCompare(i64 i, double r){
75821  if( sizeof(LONGDOUBLE_TYPE)>8 ){
75822    LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
75823    if( x<r ) return -1;
75824    if( x>r ) return +1;
75825    return 0;
75826  }else{
75827    i64 y;
75828    double s;
75829    if( r<-9223372036854775808.0 ) return +1;
75830    if( r>9223372036854775807.0 ) return -1;
75831    y = (i64)r;
75832    if( i<y ) return -1;
75833    if( i>y ){
75834      if( y==SMALLEST_INT64 && r>0.0 ) return -1;
75835      return +1;
75836    }
75837    s = (double)i;
75838    if( s<r ) return -1;
75839    if( s>r ) return +1;
75840    return 0;
75841  }
75842}
75843
75844/*
75845** Compare the values contained by the two memory cells, returning
75846** negative, zero or positive if pMem1 is less than, equal to, or greater
75847** than pMem2. Sorting order is NULL's first, followed by numbers (integers
75848** and reals) sorted numerically, followed by text ordered by the collating
75849** sequence pColl and finally blob's ordered by memcmp().
75850**
75851** Two NULL values are considered equal by this function.
75852*/
75853SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
75854  int f1, f2;
75855  int combined_flags;
75856
75857  f1 = pMem1->flags;
75858  f2 = pMem2->flags;
75859  combined_flags = f1|f2;
75860  assert( (combined_flags & MEM_RowSet)==0 );
75861
75862  /* If one value is NULL, it is less than the other. If both values
75863  ** are NULL, return 0.
75864  */
75865  if( combined_flags&MEM_Null ){
75866    return (f2&MEM_Null) - (f1&MEM_Null);
75867  }
75868
75869  /* At least one of the two values is a number
75870  */
75871  if( combined_flags&(MEM_Int|MEM_Real) ){
75872    if( (f1 & f2 & MEM_Int)!=0 ){
75873      if( pMem1->u.i < pMem2->u.i ) return -1;
75874      if( pMem1->u.i > pMem2->u.i ) return +1;
75875      return 0;
75876    }
75877    if( (f1 & f2 & MEM_Real)!=0 ){
75878      if( pMem1->u.r < pMem2->u.r ) return -1;
75879      if( pMem1->u.r > pMem2->u.r ) return +1;
75880      return 0;
75881    }
75882    if( (f1&MEM_Int)!=0 ){
75883      if( (f2&MEM_Real)!=0 ){
75884        return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
75885      }else{
75886        return -1;
75887      }
75888    }
75889    if( (f1&MEM_Real)!=0 ){
75890      if( (f2&MEM_Int)!=0 ){
75891        return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
75892      }else{
75893        return -1;
75894      }
75895    }
75896    return +1;
75897  }
75898
75899  /* If one value is a string and the other is a blob, the string is less.
75900  ** If both are strings, compare using the collating functions.
75901  */
75902  if( combined_flags&MEM_Str ){
75903    if( (f1 & MEM_Str)==0 ){
75904      return 1;
75905    }
75906    if( (f2 & MEM_Str)==0 ){
75907      return -1;
75908    }
75909
75910    assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
75911    assert( pMem1->enc==SQLITE_UTF8 ||
75912            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
75913
75914    /* The collation sequence must be defined at this point, even if
75915    ** the user deletes the collation sequence after the vdbe program is
75916    ** compiled (this was not always the case).
75917    */
75918    assert( !pColl || pColl->xCmp );
75919
75920    if( pColl ){
75921      return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
75922    }
75923    /* If a NULL pointer was passed as the collate function, fall through
75924    ** to the blob case and use memcmp().  */
75925  }
75926
75927  /* Both values must be blobs.  Compare using memcmp().  */
75928  return sqlite3BlobCompare(pMem1, pMem2);
75929}
75930
75931
75932/*
75933** The first argument passed to this function is a serial-type that
75934** corresponds to an integer - all values between 1 and 9 inclusive
75935** except 7. The second points to a buffer containing an integer value
75936** serialized according to serial_type. This function deserializes
75937** and returns the value.
75938*/
75939static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
75940  u32 y;
75941  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
75942  switch( serial_type ){
75943    case 0:
75944    case 1:
75945      testcase( aKey[0]&0x80 );
75946      return ONE_BYTE_INT(aKey);
75947    case 2:
75948      testcase( aKey[0]&0x80 );
75949      return TWO_BYTE_INT(aKey);
75950    case 3:
75951      testcase( aKey[0]&0x80 );
75952      return THREE_BYTE_INT(aKey);
75953    case 4: {
75954      testcase( aKey[0]&0x80 );
75955      y = FOUR_BYTE_UINT(aKey);
75956      return (i64)*(int*)&y;
75957    }
75958    case 5: {
75959      testcase( aKey[0]&0x80 );
75960      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
75961    }
75962    case 6: {
75963      u64 x = FOUR_BYTE_UINT(aKey);
75964      testcase( aKey[0]&0x80 );
75965      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
75966      return (i64)*(i64*)&x;
75967    }
75968  }
75969
75970  return (serial_type - 8);
75971}
75972
75973/*
75974** This function compares the two table rows or index records
75975** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
75976** or positive integer if key1 is less than, equal to or
75977** greater than key2.  The {nKey1, pKey1} key must be a blob
75978** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
75979** key must be a parsed key such as obtained from
75980** sqlite3VdbeParseRecord.
75981**
75982** If argument bSkip is non-zero, it is assumed that the caller has already
75983** determined that the first fields of the keys are equal.
75984**
75985** Key1 and Key2 do not have to contain the same number of fields. If all
75986** fields that appear in both keys are equal, then pPKey2->default_rc is
75987** returned.
75988**
75989** If database corruption is discovered, set pPKey2->errCode to
75990** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
75991** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
75992** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
75993*/
75994SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
75995  int nKey1, const void *pKey1,   /* Left key */
75996  UnpackedRecord *pPKey2,         /* Right key */
75997  int bSkip                       /* If true, skip the first field */
75998){
75999  u32 d1;                         /* Offset into aKey[] of next data element */
76000  int i;                          /* Index of next field to compare */
76001  u32 szHdr1;                     /* Size of record header in bytes */
76002  u32 idx1;                       /* Offset of first type in header */
76003  int rc = 0;                     /* Return value */
76004  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
76005  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
76006  const unsigned char *aKey1 = (const unsigned char *)pKey1;
76007  Mem mem1;
76008
76009  /* If bSkip is true, then the caller has already determined that the first
76010  ** two elements in the keys are equal. Fix the various stack variables so
76011  ** that this routine begins comparing at the second field. */
76012  if( bSkip ){
76013    u32 s1;
76014    idx1 = 1 + getVarint32(&aKey1[1], s1);
76015    szHdr1 = aKey1[0];
76016    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
76017    i = 1;
76018    pRhs++;
76019  }else{
76020    idx1 = getVarint32(aKey1, szHdr1);
76021    d1 = szHdr1;
76022    if( d1>(unsigned)nKey1 ){
76023      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
76024      return 0;  /* Corruption */
76025    }
76026    i = 0;
76027  }
76028
76029  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
76030  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
76031       || CORRUPT_DB );
76032  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
76033  assert( pPKey2->pKeyInfo->nField>0 );
76034  assert( idx1<=szHdr1 || CORRUPT_DB );
76035  do{
76036    u32 serial_type;
76037
76038    /* RHS is an integer */
76039    if( pRhs->flags & MEM_Int ){
76040      serial_type = aKey1[idx1];
76041      testcase( serial_type==12 );
76042      if( serial_type>=10 ){
76043        rc = +1;
76044      }else if( serial_type==0 ){
76045        rc = -1;
76046      }else if( serial_type==7 ){
76047        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
76048        rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
76049      }else{
76050        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
76051        i64 rhs = pRhs->u.i;
76052        if( lhs<rhs ){
76053          rc = -1;
76054        }else if( lhs>rhs ){
76055          rc = +1;
76056        }
76057      }
76058    }
76059
76060    /* RHS is real */
76061    else if( pRhs->flags & MEM_Real ){
76062      serial_type = aKey1[idx1];
76063      if( serial_type>=10 ){
76064        /* Serial types 12 or greater are strings and blobs (greater than
76065        ** numbers). Types 10 and 11 are currently "reserved for future
76066        ** use", so it doesn't really matter what the results of comparing
76067        ** them to numberic values are.  */
76068        rc = +1;
76069      }else if( serial_type==0 ){
76070        rc = -1;
76071      }else{
76072        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
76073        if( serial_type==7 ){
76074          if( mem1.u.r<pRhs->u.r ){
76075            rc = -1;
76076          }else if( mem1.u.r>pRhs->u.r ){
76077            rc = +1;
76078          }
76079        }else{
76080          rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
76081        }
76082      }
76083    }
76084
76085    /* RHS is a string */
76086    else if( pRhs->flags & MEM_Str ){
76087      getVarint32(&aKey1[idx1], serial_type);
76088      testcase( serial_type==12 );
76089      if( serial_type<12 ){
76090        rc = -1;
76091      }else if( !(serial_type & 0x01) ){
76092        rc = +1;
76093      }else{
76094        mem1.n = (serial_type - 12) / 2;
76095        testcase( (d1+mem1.n)==(unsigned)nKey1 );
76096        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
76097        if( (d1+mem1.n) > (unsigned)nKey1 ){
76098          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
76099          return 0;                /* Corruption */
76100        }else if( pKeyInfo->aColl[i] ){
76101          mem1.enc = pKeyInfo->enc;
76102          mem1.db = pKeyInfo->db;
76103          mem1.flags = MEM_Str;
76104          mem1.z = (char*)&aKey1[d1];
76105          rc = vdbeCompareMemString(
76106              &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
76107          );
76108        }else{
76109          int nCmp = MIN(mem1.n, pRhs->n);
76110          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
76111          if( rc==0 ) rc = mem1.n - pRhs->n;
76112        }
76113      }
76114    }
76115
76116    /* RHS is a blob */
76117    else if( pRhs->flags & MEM_Blob ){
76118      assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
76119      getVarint32(&aKey1[idx1], serial_type);
76120      testcase( serial_type==12 );
76121      if( serial_type<12 || (serial_type & 0x01) ){
76122        rc = -1;
76123      }else{
76124        int nStr = (serial_type - 12) / 2;
76125        testcase( (d1+nStr)==(unsigned)nKey1 );
76126        testcase( (d1+nStr+1)==(unsigned)nKey1 );
76127        if( (d1+nStr) > (unsigned)nKey1 ){
76128          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
76129          return 0;                /* Corruption */
76130        }else if( pRhs->flags & MEM_Zero ){
76131          if( !isAllZero((const char*)&aKey1[d1],nStr) ){
76132            rc = 1;
76133          }else{
76134            rc = nStr - pRhs->u.nZero;
76135          }
76136        }else{
76137          int nCmp = MIN(nStr, pRhs->n);
76138          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
76139          if( rc==0 ) rc = nStr - pRhs->n;
76140        }
76141      }
76142    }
76143
76144    /* RHS is null */
76145    else{
76146      serial_type = aKey1[idx1];
76147      rc = (serial_type!=0);
76148    }
76149
76150    if( rc!=0 ){
76151      if( pKeyInfo->aSortOrder[i] ){
76152        rc = -rc;
76153      }
76154      assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
76155      assert( mem1.szMalloc==0 );  /* See comment below */
76156      return rc;
76157    }
76158
76159    i++;
76160    pRhs++;
76161    d1 += sqlite3VdbeSerialTypeLen(serial_type);
76162    idx1 += sqlite3VarintLen(serial_type);
76163  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
76164
76165  /* No memory allocation is ever used on mem1.  Prove this using
76166  ** the following assert().  If the assert() fails, it indicates a
76167  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
76168  assert( mem1.szMalloc==0 );
76169
76170  /* rc==0 here means that one or both of the keys ran out of fields and
76171  ** all the fields up to that point were equal. Return the default_rc
76172  ** value.  */
76173  assert( CORRUPT_DB
76174       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
76175       || pKeyInfo->db->mallocFailed
76176  );
76177  pPKey2->eqSeen = 1;
76178  return pPKey2->default_rc;
76179}
76180SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
76181  int nKey1, const void *pKey1,   /* Left key */
76182  UnpackedRecord *pPKey2          /* Right key */
76183){
76184  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
76185}
76186
76187
76188/*
76189** This function is an optimized version of sqlite3VdbeRecordCompare()
76190** that (a) the first field of pPKey2 is an integer, and (b) the
76191** size-of-header varint at the start of (pKey1/nKey1) fits in a single
76192** byte (i.e. is less than 128).
76193**
76194** To avoid concerns about buffer overreads, this routine is only used
76195** on schemas where the maximum valid header size is 63 bytes or less.
76196*/
76197static int vdbeRecordCompareInt(
76198  int nKey1, const void *pKey1, /* Left key */
76199  UnpackedRecord *pPKey2        /* Right key */
76200){
76201  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
76202  int serial_type = ((const u8*)pKey1)[1];
76203  int res;
76204  u32 y;
76205  u64 x;
76206  i64 v;
76207  i64 lhs;
76208
76209  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
76210  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
76211  switch( serial_type ){
76212    case 1: { /* 1-byte signed integer */
76213      lhs = ONE_BYTE_INT(aKey);
76214      testcase( lhs<0 );
76215      break;
76216    }
76217    case 2: { /* 2-byte signed integer */
76218      lhs = TWO_BYTE_INT(aKey);
76219      testcase( lhs<0 );
76220      break;
76221    }
76222    case 3: { /* 3-byte signed integer */
76223      lhs = THREE_BYTE_INT(aKey);
76224      testcase( lhs<0 );
76225      break;
76226    }
76227    case 4: { /* 4-byte signed integer */
76228      y = FOUR_BYTE_UINT(aKey);
76229      lhs = (i64)*(int*)&y;
76230      testcase( lhs<0 );
76231      break;
76232    }
76233    case 5: { /* 6-byte signed integer */
76234      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
76235      testcase( lhs<0 );
76236      break;
76237    }
76238    case 6: { /* 8-byte signed integer */
76239      x = FOUR_BYTE_UINT(aKey);
76240      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
76241      lhs = *(i64*)&x;
76242      testcase( lhs<0 );
76243      break;
76244    }
76245    case 8:
76246      lhs = 0;
76247      break;
76248    case 9:
76249      lhs = 1;
76250      break;
76251
76252    /* This case could be removed without changing the results of running
76253    ** this code. Including it causes gcc to generate a faster switch
76254    ** statement (since the range of switch targets now starts at zero and
76255    ** is contiguous) but does not cause any duplicate code to be generated
76256    ** (as gcc is clever enough to combine the two like cases). Other
76257    ** compilers might be similar.  */
76258    case 0: case 7:
76259      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
76260
76261    default:
76262      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
76263  }
76264
76265  v = pPKey2->aMem[0].u.i;
76266  if( v>lhs ){
76267    res = pPKey2->r1;
76268  }else if( v<lhs ){
76269    res = pPKey2->r2;
76270  }else if( pPKey2->nField>1 ){
76271    /* The first fields of the two keys are equal. Compare the trailing
76272    ** fields.  */
76273    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
76274  }else{
76275    /* The first fields of the two keys are equal and there are no trailing
76276    ** fields. Return pPKey2->default_rc in this case. */
76277    res = pPKey2->default_rc;
76278    pPKey2->eqSeen = 1;
76279  }
76280
76281  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
76282  return res;
76283}
76284
76285/*
76286** This function is an optimized version of sqlite3VdbeRecordCompare()
76287** that (a) the first field of pPKey2 is a string, that (b) the first field
76288** uses the collation sequence BINARY and (c) that the size-of-header varint
76289** at the start of (pKey1/nKey1) fits in a single byte.
76290*/
76291static int vdbeRecordCompareString(
76292  int nKey1, const void *pKey1, /* Left key */
76293  UnpackedRecord *pPKey2        /* Right key */
76294){
76295  const u8 *aKey1 = (const u8*)pKey1;
76296  int serial_type;
76297  int res;
76298
76299  assert( pPKey2->aMem[0].flags & MEM_Str );
76300  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
76301  getVarint32(&aKey1[1], serial_type);
76302  if( serial_type<12 ){
76303    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
76304  }else if( !(serial_type & 0x01) ){
76305    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
76306  }else{
76307    int nCmp;
76308    int nStr;
76309    int szHdr = aKey1[0];
76310
76311    nStr = (serial_type-12) / 2;
76312    if( (szHdr + nStr) > nKey1 ){
76313      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
76314      return 0;    /* Corruption */
76315    }
76316    nCmp = MIN( pPKey2->aMem[0].n, nStr );
76317    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
76318
76319    if( res==0 ){
76320      res = nStr - pPKey2->aMem[0].n;
76321      if( res==0 ){
76322        if( pPKey2->nField>1 ){
76323          res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
76324        }else{
76325          res = pPKey2->default_rc;
76326          pPKey2->eqSeen = 1;
76327        }
76328      }else if( res>0 ){
76329        res = pPKey2->r2;
76330      }else{
76331        res = pPKey2->r1;
76332      }
76333    }else if( res>0 ){
76334      res = pPKey2->r2;
76335    }else{
76336      res = pPKey2->r1;
76337    }
76338  }
76339
76340  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
76341       || CORRUPT_DB
76342       || pPKey2->pKeyInfo->db->mallocFailed
76343  );
76344  return res;
76345}
76346
76347/*
76348** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
76349** suitable for comparing serialized records to the unpacked record passed
76350** as the only argument.
76351*/
76352SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
76353  /* varintRecordCompareInt() and varintRecordCompareString() both assume
76354  ** that the size-of-header varint that occurs at the start of each record
76355  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
76356  ** also assumes that it is safe to overread a buffer by at least the
76357  ** maximum possible legal header size plus 8 bytes. Because there is
76358  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
76359  ** buffer passed to varintRecordCompareInt() this makes it convenient to
76360  ** limit the size of the header to 64 bytes in cases where the first field
76361  ** is an integer.
76362  **
76363  ** The easiest way to enforce this limit is to consider only records with
76364  ** 13 fields or less. If the first field is an integer, the maximum legal
76365  ** header size is (12*5 + 1 + 1) bytes.  */
76366  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
76367    int flags = p->aMem[0].flags;
76368    if( p->pKeyInfo->aSortOrder[0] ){
76369      p->r1 = 1;
76370      p->r2 = -1;
76371    }else{
76372      p->r1 = -1;
76373      p->r2 = 1;
76374    }
76375    if( (flags & MEM_Int) ){
76376      return vdbeRecordCompareInt;
76377    }
76378    testcase( flags & MEM_Real );
76379    testcase( flags & MEM_Null );
76380    testcase( flags & MEM_Blob );
76381    if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
76382      assert( flags & MEM_Str );
76383      return vdbeRecordCompareString;
76384    }
76385  }
76386
76387  return sqlite3VdbeRecordCompare;
76388}
76389
76390/*
76391** pCur points at an index entry created using the OP_MakeRecord opcode.
76392** Read the rowid (the last field in the record) and store it in *rowid.
76393** Return SQLITE_OK if everything works, or an error code otherwise.
76394**
76395** pCur might be pointing to text obtained from a corrupt database file.
76396** So the content cannot be trusted.  Do appropriate checks on the content.
76397*/
76398SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
76399  i64 nCellKey = 0;
76400  int rc;
76401  u32 szHdr;        /* Size of the header */
76402  u32 typeRowid;    /* Serial type of the rowid */
76403  u32 lenRowid;     /* Size of the rowid */
76404  Mem m, v;
76405
76406  /* Get the size of the index entry.  Only indices entries of less
76407  ** than 2GiB are support - anything large must be database corruption.
76408  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
76409  ** this code can safely assume that nCellKey is 32-bits
76410  */
76411  assert( sqlite3BtreeCursorIsValid(pCur) );
76412  nCellKey = sqlite3BtreePayloadSize(pCur);
76413  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
76414
76415  /* Read in the complete content of the index entry */
76416  sqlite3VdbeMemInit(&m, db, 0);
76417  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
76418  if( rc ){
76419    return rc;
76420  }
76421
76422  /* The index entry must begin with a header size */
76423  (void)getVarint32((u8*)m.z, szHdr);
76424  testcase( szHdr==3 );
76425  testcase( szHdr==m.n );
76426  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
76427    goto idx_rowid_corruption;
76428  }
76429
76430  /* The last field of the index should be an integer - the ROWID.
76431  ** Verify that the last entry really is an integer. */
76432  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
76433  testcase( typeRowid==1 );
76434  testcase( typeRowid==2 );
76435  testcase( typeRowid==3 );
76436  testcase( typeRowid==4 );
76437  testcase( typeRowid==5 );
76438  testcase( typeRowid==6 );
76439  testcase( typeRowid==8 );
76440  testcase( typeRowid==9 );
76441  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
76442    goto idx_rowid_corruption;
76443  }
76444  lenRowid = sqlite3SmallTypeSizes[typeRowid];
76445  testcase( (u32)m.n==szHdr+lenRowid );
76446  if( unlikely((u32)m.n<szHdr+lenRowid) ){
76447    goto idx_rowid_corruption;
76448  }
76449
76450  /* Fetch the integer off the end of the index record */
76451  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
76452  *rowid = v.u.i;
76453  sqlite3VdbeMemRelease(&m);
76454  return SQLITE_OK;
76455
76456  /* Jump here if database corruption is detected after m has been
76457  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
76458idx_rowid_corruption:
76459  testcase( m.szMalloc!=0 );
76460  sqlite3VdbeMemRelease(&m);
76461  return SQLITE_CORRUPT_BKPT;
76462}
76463
76464/*
76465** Compare the key of the index entry that cursor pC is pointing to against
76466** the key string in pUnpacked.  Write into *pRes a number
76467** that is negative, zero, or positive if pC is less than, equal to,
76468** or greater than pUnpacked.  Return SQLITE_OK on success.
76469**
76470** pUnpacked is either created without a rowid or is truncated so that it
76471** omits the rowid at the end.  The rowid at the end of the index entry
76472** is ignored as well.  Hence, this routine only compares the prefixes
76473** of the keys prior to the final rowid, not the entire key.
76474*/
76475SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
76476  sqlite3 *db,                     /* Database connection */
76477  VdbeCursor *pC,                  /* The cursor to compare against */
76478  UnpackedRecord *pUnpacked,       /* Unpacked version of key */
76479  int *res                         /* Write the comparison result here */
76480){
76481  i64 nCellKey = 0;
76482  int rc;
76483  BtCursor *pCur;
76484  Mem m;
76485
76486  assert( pC->eCurType==CURTYPE_BTREE );
76487  pCur = pC->uc.pCursor;
76488  assert( sqlite3BtreeCursorIsValid(pCur) );
76489  nCellKey = sqlite3BtreePayloadSize(pCur);
76490  /* nCellKey will always be between 0 and 0xffffffff because of the way
76491  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
76492  if( nCellKey<=0 || nCellKey>0x7fffffff ){
76493    *res = 0;
76494    return SQLITE_CORRUPT_BKPT;
76495  }
76496  sqlite3VdbeMemInit(&m, db, 0);
76497  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
76498  if( rc ){
76499    return rc;
76500  }
76501  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
76502  sqlite3VdbeMemRelease(&m);
76503  return SQLITE_OK;
76504}
76505
76506/*
76507** This routine sets the value to be returned by subsequent calls to
76508** sqlite3_changes() on the database handle 'db'.
76509*/
76510SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
76511  assert( sqlite3_mutex_held(db->mutex) );
76512  db->nChange = nChange;
76513  db->nTotalChange += nChange;
76514}
76515
76516/*
76517** Set a flag in the vdbe to update the change counter when it is finalised
76518** or reset.
76519*/
76520SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
76521  v->changeCntOn = 1;
76522}
76523
76524/*
76525** Mark every prepared statement associated with a database connection
76526** as expired.
76527**
76528** An expired statement means that recompilation of the statement is
76529** recommend.  Statements expire when things happen that make their
76530** programs obsolete.  Removing user-defined functions or collating
76531** sequences, or changing an authorization function are the types of
76532** things that make prepared statements obsolete.
76533*/
76534SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
76535  Vdbe *p;
76536  for(p = db->pVdbe; p; p=p->pNext){
76537    p->expired = 1;
76538  }
76539}
76540
76541/*
76542** Return the database associated with the Vdbe.
76543*/
76544SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
76545  return v->db;
76546}
76547
76548/*
76549** Return the SQLITE_PREPARE flags for a Vdbe.
76550*/
76551SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
76552  return v->prepFlags;
76553}
76554
76555/*
76556** Return a pointer to an sqlite3_value structure containing the value bound
76557** parameter iVar of VM v. Except, if the value is an SQL NULL, return
76558** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
76559** constants) to the value before returning it.
76560**
76561** The returned value must be freed by the caller using sqlite3ValueFree().
76562*/
76563SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
76564  assert( iVar>0 );
76565  if( v ){
76566    Mem *pMem = &v->aVar[iVar-1];
76567    assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
76568    if( 0==(pMem->flags & MEM_Null) ){
76569      sqlite3_value *pRet = sqlite3ValueNew(v->db);
76570      if( pRet ){
76571        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
76572        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
76573      }
76574      return pRet;
76575    }
76576  }
76577  return 0;
76578}
76579
76580/*
76581** Configure SQL variable iVar so that binding a new value to it signals
76582** to sqlite3_reoptimize() that re-preparing the statement may result
76583** in a better query plan.
76584*/
76585SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
76586  assert( iVar>0 );
76587  assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
76588  if( iVar>=32 ){
76589    v->expmask |= 0x80000000;
76590  }else{
76591    v->expmask |= ((u32)1 << (iVar-1));
76592  }
76593}
76594
76595/*
76596** Cause a function to throw an error if it was call from OP_PureFunc
76597** rather than OP_Function.
76598**
76599** OP_PureFunc means that the function must be deterministic, and should
76600** throw an error if it is given inputs that would make it non-deterministic.
76601** This routine is invoked by date/time functions that use non-deterministic
76602** features such as 'now'.
76603*/
76604SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
76605#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
76606  if( pCtx->pVdbe==0 ) return 1;
76607#endif
76608  if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
76609    sqlite3_result_error(pCtx,
76610       "non-deterministic function in index expression or CHECK constraint",
76611       -1);
76612    return 0;
76613  }
76614  return 1;
76615}
76616
76617#ifndef SQLITE_OMIT_VIRTUALTABLE
76618/*
76619** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
76620** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
76621** in memory obtained from sqlite3DbMalloc).
76622*/
76623SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
76624  if( pVtab->zErrMsg ){
76625    sqlite3 *db = p->db;
76626    sqlite3DbFree(db, p->zErrMsg);
76627    p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
76628    sqlite3_free(pVtab->zErrMsg);
76629    pVtab->zErrMsg = 0;
76630  }
76631}
76632#endif /* SQLITE_OMIT_VIRTUALTABLE */
76633
76634#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76635
76636/*
76637** If the second argument is not NULL, release any allocations associated
76638** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
76639** structure itself, using sqlite3DbFree().
76640**
76641** This function is used to free UnpackedRecord structures allocated by
76642** the vdbeUnpackRecord() function found in vdbeapi.c.
76643*/
76644static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
76645  if( p ){
76646    int i;
76647    for(i=0; i<nField; i++){
76648      Mem *pMem = &p->aMem[i];
76649      if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
76650    }
76651    sqlite3DbFreeNN(db, p);
76652  }
76653}
76654#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76655
76656#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76657/*
76658** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
76659** then cursor passed as the second argument should point to the row about
76660** to be update or deleted. If the application calls sqlite3_preupdate_old(),
76661** the required value will be read from the row the cursor points to.
76662*/
76663SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
76664  Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
76665  VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
76666  int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
76667  const char *zDb,                /* Database name */
76668  Table *pTab,                    /* Modified table */
76669  i64 iKey1,                      /* Initial key value */
76670  int iReg                        /* Register for new.* record */
76671){
76672  sqlite3 *db = v->db;
76673  i64 iKey2;
76674  PreUpdate preupdate;
76675  const char *zTbl = pTab->zName;
76676  static const u8 fakeSortOrder = 0;
76677
76678  assert( db->pPreUpdate==0 );
76679  memset(&preupdate, 0, sizeof(PreUpdate));
76680  if( HasRowid(pTab)==0 ){
76681    iKey1 = iKey2 = 0;
76682    preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
76683  }else{
76684    if( op==SQLITE_UPDATE ){
76685      iKey2 = v->aMem[iReg].u.i;
76686    }else{
76687      iKey2 = iKey1;
76688    }
76689  }
76690
76691  assert( pCsr->nField==pTab->nCol
76692       || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
76693  );
76694
76695  preupdate.v = v;
76696  preupdate.pCsr = pCsr;
76697  preupdate.op = op;
76698  preupdate.iNewReg = iReg;
76699  preupdate.keyinfo.db = db;
76700  preupdate.keyinfo.enc = ENC(db);
76701  preupdate.keyinfo.nField = pTab->nCol;
76702  preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
76703  preupdate.iKey1 = iKey1;
76704  preupdate.iKey2 = iKey2;
76705  preupdate.pTab = pTab;
76706
76707  db->pPreUpdate = &preupdate;
76708  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
76709  db->pPreUpdate = 0;
76710  sqlite3DbFree(db, preupdate.aRecord);
76711  vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pUnpacked);
76712  vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pNewUnpacked);
76713  if( preupdate.aNew ){
76714    int i;
76715    for(i=0; i<pCsr->nField; i++){
76716      sqlite3VdbeMemRelease(&preupdate.aNew[i]);
76717    }
76718    sqlite3DbFreeNN(db, preupdate.aNew);
76719  }
76720}
76721#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76722
76723/************** End of vdbeaux.c *********************************************/
76724/************** Begin file vdbeapi.c *****************************************/
76725/*
76726** 2004 May 26
76727**
76728** The author disclaims copyright to this source code.  In place of
76729** a legal notice, here is a blessing:
76730**
76731**    May you do good and not evil.
76732**    May you find forgiveness for yourself and forgive others.
76733**    May you share freely, never taking more than you give.
76734**
76735*************************************************************************
76736**
76737** This file contains code use to implement APIs that are part of the
76738** VDBE.
76739*/
76740/* #include "sqliteInt.h" */
76741/* #include "vdbeInt.h" */
76742
76743#ifndef SQLITE_OMIT_DEPRECATED
76744/*
76745** Return TRUE (non-zero) of the statement supplied as an argument needs
76746** to be recompiled.  A statement needs to be recompiled whenever the
76747** execution environment changes in a way that would alter the program
76748** that sqlite3_prepare() generates.  For example, if new functions or
76749** collating sequences are registered or if an authorizer function is
76750** added or changed.
76751*/
76752SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
76753  Vdbe *p = (Vdbe*)pStmt;
76754  return p==0 || p->expired;
76755}
76756#endif
76757
76758/*
76759** Check on a Vdbe to make sure it has not been finalized.  Log
76760** an error and return true if it has been finalized (or is otherwise
76761** invalid).  Return false if it is ok.
76762*/
76763static int vdbeSafety(Vdbe *p){
76764  if( p->db==0 ){
76765    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
76766    return 1;
76767  }else{
76768    return 0;
76769  }
76770}
76771static int vdbeSafetyNotNull(Vdbe *p){
76772  if( p==0 ){
76773    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
76774    return 1;
76775  }else{
76776    return vdbeSafety(p);
76777  }
76778}
76779
76780#ifndef SQLITE_OMIT_TRACE
76781/*
76782** Invoke the profile callback.  This routine is only called if we already
76783** know that the profile callback is defined and needs to be invoked.
76784*/
76785static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
76786  sqlite3_int64 iNow;
76787  sqlite3_int64 iElapse;
76788  assert( p->startTime>0 );
76789  assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
76790  assert( db->init.busy==0 );
76791  assert( p->zSql!=0 );
76792  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
76793  iElapse = (iNow - p->startTime)*1000000;
76794  if( db->xProfile ){
76795    db->xProfile(db->pProfileArg, p->zSql, iElapse);
76796  }
76797  if( db->mTrace & SQLITE_TRACE_PROFILE ){
76798    db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
76799  }
76800  p->startTime = 0;
76801}
76802/*
76803** The checkProfileCallback(DB,P) macro checks to see if a profile callback
76804** is needed, and it invokes the callback if it is needed.
76805*/
76806# define checkProfileCallback(DB,P) \
76807   if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
76808#else
76809# define checkProfileCallback(DB,P)  /*no-op*/
76810#endif
76811
76812/*
76813** The following routine destroys a virtual machine that is created by
76814** the sqlite3_compile() routine. The integer returned is an SQLITE_
76815** success/failure code that describes the result of executing the virtual
76816** machine.
76817**
76818** This routine sets the error code and string returned by
76819** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
76820*/
76821SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
76822  int rc;
76823  if( pStmt==0 ){
76824    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
76825    ** pointer is a harmless no-op. */
76826    rc = SQLITE_OK;
76827  }else{
76828    Vdbe *v = (Vdbe*)pStmt;
76829    sqlite3 *db = v->db;
76830    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
76831    sqlite3_mutex_enter(db->mutex);
76832    checkProfileCallback(db, v);
76833    rc = sqlite3VdbeFinalize(v);
76834    rc = sqlite3ApiExit(db, rc);
76835    sqlite3LeaveMutexAndCloseZombie(db);
76836  }
76837  return rc;
76838}
76839
76840/*
76841** Terminate the current execution of an SQL statement and reset it
76842** back to its starting state so that it can be reused. A success code from
76843** the prior execution is returned.
76844**
76845** This routine sets the error code and string returned by
76846** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
76847*/
76848SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
76849  int rc;
76850  if( pStmt==0 ){
76851    rc = SQLITE_OK;
76852  }else{
76853    Vdbe *v = (Vdbe*)pStmt;
76854    sqlite3 *db = v->db;
76855    sqlite3_mutex_enter(db->mutex);
76856    checkProfileCallback(db, v);
76857    rc = sqlite3VdbeReset(v);
76858    sqlite3VdbeRewind(v);
76859    assert( (rc & (db->errMask))==rc );
76860    rc = sqlite3ApiExit(db, rc);
76861    sqlite3_mutex_leave(db->mutex);
76862  }
76863  return rc;
76864}
76865
76866/*
76867** Set all the parameters in the compiled SQL statement to NULL.
76868*/
76869SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
76870  int i;
76871  int rc = SQLITE_OK;
76872  Vdbe *p = (Vdbe*)pStmt;
76873#if SQLITE_THREADSAFE
76874  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
76875#endif
76876  sqlite3_mutex_enter(mutex);
76877  for(i=0; i<p->nVar; i++){
76878    sqlite3VdbeMemRelease(&p->aVar[i]);
76879    p->aVar[i].flags = MEM_Null;
76880  }
76881  assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
76882  if( p->expmask ){
76883    p->expired = 1;
76884  }
76885  sqlite3_mutex_leave(mutex);
76886  return rc;
76887}
76888
76889
76890/**************************** sqlite3_value_  *******************************
76891** The following routines extract information from a Mem or sqlite3_value
76892** structure.
76893*/
76894SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
76895  Mem *p = (Mem*)pVal;
76896  if( p->flags & (MEM_Blob|MEM_Str) ){
76897    if( ExpandBlob(p)!=SQLITE_OK ){
76898      assert( p->flags==MEM_Null && p->z==0 );
76899      return 0;
76900    }
76901    p->flags |= MEM_Blob;
76902    return p->n ? p->z : 0;
76903  }else{
76904    return sqlite3_value_text(pVal);
76905  }
76906}
76907SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
76908  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
76909}
76910SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
76911  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
76912}
76913SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
76914  return sqlite3VdbeRealValue((Mem*)pVal);
76915}
76916SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
76917  return (int)sqlite3VdbeIntValue((Mem*)pVal);
76918}
76919SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
76920  return sqlite3VdbeIntValue((Mem*)pVal);
76921}
76922SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
76923  Mem *pMem = (Mem*)pVal;
76924  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
76925}
76926SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
76927  Mem *p = (Mem*)pVal;
76928  if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
76929                 (MEM_Null|MEM_Term|MEM_Subtype)
76930   && zPType!=0
76931   && p->eSubtype=='p'
76932   && strcmp(p->u.zPType, zPType)==0
76933  ){
76934    return (void*)p->z;
76935  }else{
76936    return 0;
76937  }
76938}
76939SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
76940  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
76941}
76942#ifndef SQLITE_OMIT_UTF16
76943SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
76944  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
76945}
76946SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
76947  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
76948}
76949SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
76950  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
76951}
76952#endif /* SQLITE_OMIT_UTF16 */
76953/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
76954** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
76955** point number string BLOB NULL
76956*/
76957SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
76958  static const u8 aType[] = {
76959     SQLITE_BLOB,     /* 0x00 */
76960     SQLITE_NULL,     /* 0x01 */
76961     SQLITE_TEXT,     /* 0x02 */
76962     SQLITE_NULL,     /* 0x03 */
76963     SQLITE_INTEGER,  /* 0x04 */
76964     SQLITE_NULL,     /* 0x05 */
76965     SQLITE_INTEGER,  /* 0x06 */
76966     SQLITE_NULL,     /* 0x07 */
76967     SQLITE_FLOAT,    /* 0x08 */
76968     SQLITE_NULL,     /* 0x09 */
76969     SQLITE_FLOAT,    /* 0x0a */
76970     SQLITE_NULL,     /* 0x0b */
76971     SQLITE_INTEGER,  /* 0x0c */
76972     SQLITE_NULL,     /* 0x0d */
76973     SQLITE_INTEGER,  /* 0x0e */
76974     SQLITE_NULL,     /* 0x0f */
76975     SQLITE_BLOB,     /* 0x10 */
76976     SQLITE_NULL,     /* 0x11 */
76977     SQLITE_TEXT,     /* 0x12 */
76978     SQLITE_NULL,     /* 0x13 */
76979     SQLITE_INTEGER,  /* 0x14 */
76980     SQLITE_NULL,     /* 0x15 */
76981     SQLITE_INTEGER,  /* 0x16 */
76982     SQLITE_NULL,     /* 0x17 */
76983     SQLITE_FLOAT,    /* 0x18 */
76984     SQLITE_NULL,     /* 0x19 */
76985     SQLITE_FLOAT,    /* 0x1a */
76986     SQLITE_NULL,     /* 0x1b */
76987     SQLITE_INTEGER,  /* 0x1c */
76988     SQLITE_NULL,     /* 0x1d */
76989     SQLITE_INTEGER,  /* 0x1e */
76990     SQLITE_NULL,     /* 0x1f */
76991  };
76992  return aType[pVal->flags&MEM_AffMask];
76993}
76994
76995/* Make a copy of an sqlite3_value object
76996*/
76997SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
76998  sqlite3_value *pNew;
76999  if( pOrig==0 ) return 0;
77000  pNew = sqlite3_malloc( sizeof(*pNew) );
77001  if( pNew==0 ) return 0;
77002  memset(pNew, 0, sizeof(*pNew));
77003  memcpy(pNew, pOrig, MEMCELLSIZE);
77004  pNew->flags &= ~MEM_Dyn;
77005  pNew->db = 0;
77006  if( pNew->flags&(MEM_Str|MEM_Blob) ){
77007    pNew->flags &= ~(MEM_Static|MEM_Dyn);
77008    pNew->flags |= MEM_Ephem;
77009    if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
77010      sqlite3ValueFree(pNew);
77011      pNew = 0;
77012    }
77013  }
77014  return pNew;
77015}
77016
77017/* Destroy an sqlite3_value object previously obtained from
77018** sqlite3_value_dup().
77019*/
77020SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
77021  sqlite3ValueFree(pOld);
77022}
77023
77024
77025/**************************** sqlite3_result_  *******************************
77026** The following routines are used by user-defined functions to specify
77027** the function result.
77028**
77029** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
77030** result as a string or blob but if the string or blob is too large, it
77031** then sets the error code to SQLITE_TOOBIG
77032**
77033** The invokeValueDestructor(P,X) routine invokes destructor function X()
77034** on value P is not going to be used and need to be destroyed.
77035*/
77036static void setResultStrOrError(
77037  sqlite3_context *pCtx,  /* Function context */
77038  const char *z,          /* String pointer */
77039  int n,                  /* Bytes in string, or negative */
77040  u8 enc,                 /* Encoding of z.  0 for BLOBs */
77041  void (*xDel)(void*)     /* Destructor function */
77042){
77043  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
77044    sqlite3_result_error_toobig(pCtx);
77045  }
77046}
77047static int invokeValueDestructor(
77048  const void *p,             /* Value to destroy */
77049  void (*xDel)(void*),       /* The destructor */
77050  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
77051){
77052  assert( xDel!=SQLITE_DYNAMIC );
77053  if( xDel==0 ){
77054    /* noop */
77055  }else if( xDel==SQLITE_TRANSIENT ){
77056    /* noop */
77057  }else{
77058    xDel((void*)p);
77059  }
77060  if( pCtx ) sqlite3_result_error_toobig(pCtx);
77061  return SQLITE_TOOBIG;
77062}
77063SQLITE_API void sqlite3_result_blob(
77064  sqlite3_context *pCtx,
77065  const void *z,
77066  int n,
77067  void (*xDel)(void *)
77068){
77069  assert( n>=0 );
77070  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77071  setResultStrOrError(pCtx, z, n, 0, xDel);
77072}
77073SQLITE_API void sqlite3_result_blob64(
77074  sqlite3_context *pCtx,
77075  const void *z,
77076  sqlite3_uint64 n,
77077  void (*xDel)(void *)
77078){
77079  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77080  assert( xDel!=SQLITE_DYNAMIC );
77081  if( n>0x7fffffff ){
77082    (void)invokeValueDestructor(z, xDel, pCtx);
77083  }else{
77084    setResultStrOrError(pCtx, z, (int)n, 0, xDel);
77085  }
77086}
77087SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
77088  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77089  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
77090}
77091SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
77092  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77093  pCtx->isError = SQLITE_ERROR;
77094  pCtx->fErrorOrAux = 1;
77095  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
77096}
77097#ifndef SQLITE_OMIT_UTF16
77098SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
77099  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77100  pCtx->isError = SQLITE_ERROR;
77101  pCtx->fErrorOrAux = 1;
77102  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
77103}
77104#endif
77105SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
77106  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77107  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
77108}
77109SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
77110  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77111  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
77112}
77113SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
77114  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77115  sqlite3VdbeMemSetNull(pCtx->pOut);
77116}
77117SQLITE_API void sqlite3_result_pointer(
77118  sqlite3_context *pCtx,
77119  void *pPtr,
77120  const char *zPType,
77121  void (*xDestructor)(void*)
77122){
77123  Mem *pOut = pCtx->pOut;
77124  assert( sqlite3_mutex_held(pOut->db->mutex) );
77125  sqlite3VdbeMemSetNull(pOut);
77126  sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
77127}
77128SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
77129  Mem *pOut = pCtx->pOut;
77130  assert( sqlite3_mutex_held(pOut->db->mutex) );
77131  pOut->eSubtype = eSubtype & 0xff;
77132  pOut->flags |= MEM_Subtype;
77133}
77134SQLITE_API void sqlite3_result_text(
77135  sqlite3_context *pCtx,
77136  const char *z,
77137  int n,
77138  void (*xDel)(void *)
77139){
77140  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77141  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
77142}
77143SQLITE_API void sqlite3_result_text64(
77144  sqlite3_context *pCtx,
77145  const char *z,
77146  sqlite3_uint64 n,
77147  void (*xDel)(void *),
77148  unsigned char enc
77149){
77150  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77151  assert( xDel!=SQLITE_DYNAMIC );
77152  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
77153  if( n>0x7fffffff ){
77154    (void)invokeValueDestructor(z, xDel, pCtx);
77155  }else{
77156    setResultStrOrError(pCtx, z, (int)n, enc, xDel);
77157  }
77158}
77159#ifndef SQLITE_OMIT_UTF16
77160SQLITE_API void sqlite3_result_text16(
77161  sqlite3_context *pCtx,
77162  const void *z,
77163  int n,
77164  void (*xDel)(void *)
77165){
77166  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77167  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
77168}
77169SQLITE_API void sqlite3_result_text16be(
77170  sqlite3_context *pCtx,
77171  const void *z,
77172  int n,
77173  void (*xDel)(void *)
77174){
77175  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77176  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
77177}
77178SQLITE_API void sqlite3_result_text16le(
77179  sqlite3_context *pCtx,
77180  const void *z,
77181  int n,
77182  void (*xDel)(void *)
77183){
77184  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77185  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
77186}
77187#endif /* SQLITE_OMIT_UTF16 */
77188SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
77189  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77190  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
77191}
77192SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
77193  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77194  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
77195}
77196SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
77197  Mem *pOut = pCtx->pOut;
77198  assert( sqlite3_mutex_held(pOut->db->mutex) );
77199  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
77200    return SQLITE_TOOBIG;
77201  }
77202  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
77203  return SQLITE_OK;
77204}
77205SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
77206  pCtx->isError = errCode;
77207  pCtx->fErrorOrAux = 1;
77208#ifdef SQLITE_DEBUG
77209  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
77210#endif
77211  if( pCtx->pOut->flags & MEM_Null ){
77212    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
77213                         SQLITE_UTF8, SQLITE_STATIC);
77214  }
77215}
77216
77217/* Force an SQLITE_TOOBIG error. */
77218SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
77219  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77220  pCtx->isError = SQLITE_TOOBIG;
77221  pCtx->fErrorOrAux = 1;
77222  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
77223                       SQLITE_UTF8, SQLITE_STATIC);
77224}
77225
77226/* An SQLITE_NOMEM error. */
77227SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
77228  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77229  sqlite3VdbeMemSetNull(pCtx->pOut);
77230  pCtx->isError = SQLITE_NOMEM_BKPT;
77231  pCtx->fErrorOrAux = 1;
77232  sqlite3OomFault(pCtx->pOut->db);
77233}
77234
77235/*
77236** This function is called after a transaction has been committed. It
77237** invokes callbacks registered with sqlite3_wal_hook() as required.
77238*/
77239static int doWalCallbacks(sqlite3 *db){
77240  int rc = SQLITE_OK;
77241#ifndef SQLITE_OMIT_WAL
77242  int i;
77243  for(i=0; i<db->nDb; i++){
77244    Btree *pBt = db->aDb[i].pBt;
77245    if( pBt ){
77246      int nEntry;
77247      sqlite3BtreeEnter(pBt);
77248      nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
77249      sqlite3BtreeLeave(pBt);
77250      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
77251        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
77252      }
77253    }
77254  }
77255#endif
77256  return rc;
77257}
77258
77259
77260/*
77261** Execute the statement pStmt, either until a row of data is ready, the
77262** statement is completely executed or an error occurs.
77263**
77264** This routine implements the bulk of the logic behind the sqlite_step()
77265** API.  The only thing omitted is the automatic recompile if a
77266** schema change has occurred.  That detail is handled by the
77267** outer sqlite3_step() wrapper procedure.
77268*/
77269static int sqlite3Step(Vdbe *p){
77270  sqlite3 *db;
77271  int rc;
77272
77273  assert(p);
77274  if( p->magic!=VDBE_MAGIC_RUN ){
77275    /* We used to require that sqlite3_reset() be called before retrying
77276    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
77277    ** with version 3.7.0, we changed this so that sqlite3_reset() would
77278    ** be called automatically instead of throwing the SQLITE_MISUSE error.
77279    ** This "automatic-reset" change is not technically an incompatibility,
77280    ** since any application that receives an SQLITE_MISUSE is broken by
77281    ** definition.
77282    **
77283    ** Nevertheless, some published applications that were originally written
77284    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
77285    ** returns, and those were broken by the automatic-reset change.  As a
77286    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
77287    ** legacy behavior of returning SQLITE_MISUSE for cases where the
77288    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
77289    ** or SQLITE_BUSY error.
77290    */
77291#ifdef SQLITE_OMIT_AUTORESET
77292    if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
77293      sqlite3_reset((sqlite3_stmt*)p);
77294    }else{
77295      return SQLITE_MISUSE_BKPT;
77296    }
77297#else
77298    sqlite3_reset((sqlite3_stmt*)p);
77299#endif
77300  }
77301
77302  /* Check that malloc() has not failed. If it has, return early. */
77303  db = p->db;
77304  if( db->mallocFailed ){
77305    p->rc = SQLITE_NOMEM;
77306    return SQLITE_NOMEM_BKPT;
77307  }
77308
77309  if( p->pc<=0 && p->expired ){
77310    p->rc = SQLITE_SCHEMA;
77311    rc = SQLITE_ERROR;
77312    goto end_of_step;
77313  }
77314  if( p->pc<0 ){
77315    /* If there are no other statements currently running, then
77316    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
77317    ** from interrupting a statement that has not yet started.
77318    */
77319    if( db->nVdbeActive==0 ){
77320      db->u1.isInterrupted = 0;
77321    }
77322
77323    assert( db->nVdbeWrite>0 || db->autoCommit==0
77324        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
77325    );
77326
77327#ifndef SQLITE_OMIT_TRACE
77328    if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
77329        && !db->init.busy && p->zSql ){
77330      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
77331    }else{
77332      assert( p->startTime==0 );
77333    }
77334#endif
77335
77336    db->nVdbeActive++;
77337    if( p->readOnly==0 ) db->nVdbeWrite++;
77338    if( p->bIsReader ) db->nVdbeRead++;
77339    p->pc = 0;
77340  }
77341#ifdef SQLITE_DEBUG
77342  p->rcApp = SQLITE_OK;
77343#endif
77344#ifndef SQLITE_OMIT_EXPLAIN
77345  if( p->explain ){
77346    rc = sqlite3VdbeList(p);
77347  }else
77348#endif /* SQLITE_OMIT_EXPLAIN */
77349  {
77350    db->nVdbeExec++;
77351    rc = sqlite3VdbeExec(p);
77352    db->nVdbeExec--;
77353  }
77354
77355#ifndef SQLITE_OMIT_TRACE
77356  /* If the statement completed successfully, invoke the profile callback */
77357  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
77358#endif
77359
77360  if( rc==SQLITE_DONE ){
77361    assert( p->rc==SQLITE_OK );
77362    p->rc = doWalCallbacks(db);
77363    if( p->rc!=SQLITE_OK ){
77364      rc = SQLITE_ERROR;
77365    }
77366  }
77367
77368  db->errCode = rc;
77369  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
77370    p->rc = SQLITE_NOMEM_BKPT;
77371  }
77372end_of_step:
77373  /* At this point local variable rc holds the value that should be
77374  ** returned if this statement was compiled using the legacy
77375  ** sqlite3_prepare() interface. According to the docs, this can only
77376  ** be one of the values in the first assert() below. Variable p->rc
77377  ** contains the value that would be returned if sqlite3_finalize()
77378  ** were called on statement p.
77379  */
77380  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
77381       || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
77382  );
77383  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
77384  if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
77385   && rc!=SQLITE_ROW
77386   && rc!=SQLITE_DONE
77387  ){
77388    /* If this statement was prepared using saved SQL and an
77389    ** error has occurred, then return the error code in p->rc to the
77390    ** caller. Set the error code in the database handle to the same value.
77391    */
77392    rc = sqlite3VdbeTransferError(p);
77393  }
77394  return (rc&db->errMask);
77395}
77396
77397/*
77398** This is the top-level implementation of sqlite3_step().  Call
77399** sqlite3Step() to do most of the work.  If a schema error occurs,
77400** call sqlite3Reprepare() and try again.
77401*/
77402SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
77403  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
77404  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
77405  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
77406  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
77407  sqlite3 *db;             /* The database connection */
77408
77409  if( vdbeSafetyNotNull(v) ){
77410    return SQLITE_MISUSE_BKPT;
77411  }
77412  db = v->db;
77413  sqlite3_mutex_enter(db->mutex);
77414  v->doingRerun = 0;
77415  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
77416         && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
77417    int savedPc = v->pc;
77418    rc2 = rc = sqlite3Reprepare(v);
77419    if( rc!=SQLITE_OK) break;
77420    sqlite3_reset(pStmt);
77421    if( savedPc>=0 ) v->doingRerun = 1;
77422    assert( v->expired==0 );
77423  }
77424  if( rc2!=SQLITE_OK ){
77425    /* This case occurs after failing to recompile an sql statement.
77426    ** The error message from the SQL compiler has already been loaded
77427    ** into the database handle. This block copies the error message
77428    ** from the database handle into the statement and sets the statement
77429    ** program counter to 0 to ensure that when the statement is
77430    ** finalized or reset the parser error message is available via
77431    ** sqlite3_errmsg() and sqlite3_errcode().
77432    */
77433    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
77434    sqlite3DbFree(db, v->zErrMsg);
77435    if( !db->mallocFailed ){
77436      v->zErrMsg = sqlite3DbStrDup(db, zErr);
77437      v->rc = rc2;
77438    } else {
77439      v->zErrMsg = 0;
77440      v->rc = rc = SQLITE_NOMEM_BKPT;
77441    }
77442  }
77443  rc = sqlite3ApiExit(db, rc);
77444  sqlite3_mutex_leave(db->mutex);
77445  return rc;
77446}
77447
77448
77449/*
77450** Extract the user data from a sqlite3_context structure and return a
77451** pointer to it.
77452*/
77453SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
77454  assert( p && p->pFunc );
77455  return p->pFunc->pUserData;
77456}
77457
77458/*
77459** Extract the user data from a sqlite3_context structure and return a
77460** pointer to it.
77461**
77462** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
77463** returns a copy of the pointer to the database connection (the 1st
77464** parameter) of the sqlite3_create_function() and
77465** sqlite3_create_function16() routines that originally registered the
77466** application defined function.
77467*/
77468SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
77469  assert( p && p->pOut );
77470  return p->pOut->db;
77471}
77472
77473/*
77474** Return the current time for a statement.  If the current time
77475** is requested more than once within the same run of a single prepared
77476** statement, the exact same time is returned for each invocation regardless
77477** of the amount of time that elapses between invocations.  In other words,
77478** the time returned is always the time of the first call.
77479*/
77480SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
77481  int rc;
77482#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
77483  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
77484  assert( p->pVdbe!=0 );
77485#else
77486  sqlite3_int64 iTime = 0;
77487  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
77488#endif
77489  if( *piTime==0 ){
77490    rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
77491    if( rc ) *piTime = 0;
77492  }
77493  return *piTime;
77494}
77495
77496/*
77497** The following is the implementation of an SQL function that always
77498** fails with an error message stating that the function is used in the
77499** wrong context.  The sqlite3_overload_function() API might construct
77500** SQL function that use this routine so that the functions will exist
77501** for name resolution but are actually overloaded by the xFindFunction
77502** method of virtual tables.
77503*/
77504SQLITE_PRIVATE void sqlite3InvalidFunction(
77505  sqlite3_context *context,  /* The function calling context */
77506  int NotUsed,               /* Number of arguments to the function */
77507  sqlite3_value **NotUsed2   /* Value of each argument */
77508){
77509  const char *zName = context->pFunc->zName;
77510  char *zErr;
77511  UNUSED_PARAMETER2(NotUsed, NotUsed2);
77512  zErr = sqlite3_mprintf(
77513      "unable to use function %s in the requested context", zName);
77514  sqlite3_result_error(context, zErr, -1);
77515  sqlite3_free(zErr);
77516}
77517
77518/*
77519** Create a new aggregate context for p and return a pointer to
77520** its pMem->z element.
77521*/
77522static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
77523  Mem *pMem = p->pMem;
77524  assert( (pMem->flags & MEM_Agg)==0 );
77525  if( nByte<=0 ){
77526    sqlite3VdbeMemSetNull(pMem);
77527    pMem->z = 0;
77528  }else{
77529    sqlite3VdbeMemClearAndResize(pMem, nByte);
77530    pMem->flags = MEM_Agg;
77531    pMem->u.pDef = p->pFunc;
77532    if( pMem->z ){
77533      memset(pMem->z, 0, nByte);
77534    }
77535  }
77536  return (void*)pMem->z;
77537}
77538
77539/*
77540** Allocate or return the aggregate context for a user function.  A new
77541** context is allocated on the first call.  Subsequent calls return the
77542** same context that was returned on prior calls.
77543*/
77544SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
77545  assert( p && p->pFunc && p->pFunc->xFinalize );
77546  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
77547  testcase( nByte<0 );
77548  if( (p->pMem->flags & MEM_Agg)==0 ){
77549    return createAggContext(p, nByte);
77550  }else{
77551    return (void*)p->pMem->z;
77552  }
77553}
77554
77555/*
77556** Return the auxiliary data pointer, if any, for the iArg'th argument to
77557** the user-function defined by pCtx.
77558**
77559** The left-most argument is 0.
77560**
77561** Undocumented behavior:  If iArg is negative then access a cache of
77562** auxiliary data pointers that is available to all functions within a
77563** single prepared statement.  The iArg values must match.
77564*/
77565SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
77566  AuxData *pAuxData;
77567
77568  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77569#if SQLITE_ENABLE_STAT3_OR_STAT4
77570  if( pCtx->pVdbe==0 ) return 0;
77571#else
77572  assert( pCtx->pVdbe!=0 );
77573#endif
77574  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
77575    if(  pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
77576      return pAuxData->pAux;
77577    }
77578  }
77579  return 0;
77580}
77581
77582/*
77583** Set the auxiliary data pointer and delete function, for the iArg'th
77584** argument to the user-function defined by pCtx. Any previous value is
77585** deleted by calling the delete function specified when it was set.
77586**
77587** The left-most argument is 0.
77588**
77589** Undocumented behavior:  If iArg is negative then make the data available
77590** to all functions within the current prepared statement using iArg as an
77591** access code.
77592*/
77593SQLITE_API void sqlite3_set_auxdata(
77594  sqlite3_context *pCtx,
77595  int iArg,
77596  void *pAux,
77597  void (*xDelete)(void*)
77598){
77599  AuxData *pAuxData;
77600  Vdbe *pVdbe = pCtx->pVdbe;
77601
77602  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
77603#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
77604  if( pVdbe==0 ) goto failed;
77605#else
77606  assert( pVdbe!=0 );
77607#endif
77608
77609  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
77610    if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
77611      break;
77612    }
77613  }
77614  if( pAuxData==0 ){
77615    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
77616    if( !pAuxData ) goto failed;
77617    pAuxData->iAuxOp = pCtx->iOp;
77618    pAuxData->iAuxArg = iArg;
77619    pAuxData->pNextAux = pVdbe->pAuxData;
77620    pVdbe->pAuxData = pAuxData;
77621    if( pCtx->fErrorOrAux==0 ){
77622      pCtx->isError = 0;
77623      pCtx->fErrorOrAux = 1;
77624    }
77625  }else if( pAuxData->xDeleteAux ){
77626    pAuxData->xDeleteAux(pAuxData->pAux);
77627  }
77628
77629  pAuxData->pAux = pAux;
77630  pAuxData->xDeleteAux = xDelete;
77631  return;
77632
77633failed:
77634  if( xDelete ){
77635    xDelete(pAux);
77636  }
77637}
77638
77639#ifndef SQLITE_OMIT_DEPRECATED
77640/*
77641** Return the number of times the Step function of an aggregate has been
77642** called.
77643**
77644** This function is deprecated.  Do not use it for new code.  It is
77645** provide only to avoid breaking legacy code.  New aggregate function
77646** implementations should keep their own counts within their aggregate
77647** context.
77648*/
77649SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
77650  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
77651  return p->pMem->n;
77652}
77653#endif
77654
77655/*
77656** Return the number of columns in the result set for the statement pStmt.
77657*/
77658SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
77659  Vdbe *pVm = (Vdbe *)pStmt;
77660  return pVm ? pVm->nResColumn : 0;
77661}
77662
77663/*
77664** Return the number of values available from the current row of the
77665** currently executing statement pStmt.
77666*/
77667SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
77668  Vdbe *pVm = (Vdbe *)pStmt;
77669  if( pVm==0 || pVm->pResultSet==0 ) return 0;
77670  return pVm->nResColumn;
77671}
77672
77673/*
77674** Return a pointer to static memory containing an SQL NULL value.
77675*/
77676static const Mem *columnNullValue(void){
77677  /* Even though the Mem structure contains an element
77678  ** of type i64, on certain architectures (x86) with certain compiler
77679  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
77680  ** instead of an 8-byte one. This all works fine, except that when
77681  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
77682  ** that a Mem structure is located on an 8-byte boundary. To prevent
77683  ** these assert()s from failing, when building with SQLITE_DEBUG defined
77684  ** using gcc, we force nullMem to be 8-byte aligned using the magical
77685  ** __attribute__((aligned(8))) macro.  */
77686  static const Mem nullMem
77687#if defined(SQLITE_DEBUG) && defined(__GNUC__)
77688    __attribute__((aligned(8)))
77689#endif
77690    = {
77691        /* .u          = */ {0},
77692        /* .flags      = */ (u16)MEM_Null,
77693        /* .enc        = */ (u8)0,
77694        /* .eSubtype   = */ (u8)0,
77695        /* .n          = */ (int)0,
77696        /* .z          = */ (char*)0,
77697        /* .zMalloc    = */ (char*)0,
77698        /* .szMalloc   = */ (int)0,
77699        /* .uTemp      = */ (u32)0,
77700        /* .db         = */ (sqlite3*)0,
77701        /* .xDel       = */ (void(*)(void*))0,
77702#ifdef SQLITE_DEBUG
77703        /* .pScopyFrom = */ (Mem*)0,
77704        /* .pFiller    = */ (void*)0,
77705#endif
77706      };
77707  return &nullMem;
77708}
77709
77710/*
77711** Check to see if column iCol of the given statement is valid.  If
77712** it is, return a pointer to the Mem for the value of that column.
77713** If iCol is not valid, return a pointer to a Mem which has a value
77714** of NULL.
77715*/
77716static Mem *columnMem(sqlite3_stmt *pStmt, int i){
77717  Vdbe *pVm;
77718  Mem *pOut;
77719
77720  pVm = (Vdbe *)pStmt;
77721  if( pVm==0 ) return (Mem*)columnNullValue();
77722  assert( pVm->db );
77723  sqlite3_mutex_enter(pVm->db->mutex);
77724  if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
77725    pOut = &pVm->pResultSet[i];
77726  }else{
77727    sqlite3Error(pVm->db, SQLITE_RANGE);
77728    pOut = (Mem*)columnNullValue();
77729  }
77730  return pOut;
77731}
77732
77733/*
77734** This function is called after invoking an sqlite3_value_XXX function on a
77735** column value (i.e. a value returned by evaluating an SQL expression in the
77736** select list of a SELECT statement) that may cause a malloc() failure. If
77737** malloc() has failed, the threads mallocFailed flag is cleared and the result
77738** code of statement pStmt set to SQLITE_NOMEM.
77739**
77740** Specifically, this is called from within:
77741**
77742**     sqlite3_column_int()
77743**     sqlite3_column_int64()
77744**     sqlite3_column_text()
77745**     sqlite3_column_text16()
77746**     sqlite3_column_real()
77747**     sqlite3_column_bytes()
77748**     sqlite3_column_bytes16()
77749**     sqiite3_column_blob()
77750*/
77751static void columnMallocFailure(sqlite3_stmt *pStmt)
77752{
77753  /* If malloc() failed during an encoding conversion within an
77754  ** sqlite3_column_XXX API, then set the return code of the statement to
77755  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
77756  ** and _finalize() will return NOMEM.
77757  */
77758  Vdbe *p = (Vdbe *)pStmt;
77759  if( p ){
77760    assert( p->db!=0 );
77761    assert( sqlite3_mutex_held(p->db->mutex) );
77762    p->rc = sqlite3ApiExit(p->db, p->rc);
77763    sqlite3_mutex_leave(p->db->mutex);
77764  }
77765}
77766
77767/**************************** sqlite3_column_  *******************************
77768** The following routines are used to access elements of the current row
77769** in the result set.
77770*/
77771SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
77772  const void *val;
77773  val = sqlite3_value_blob( columnMem(pStmt,i) );
77774  /* Even though there is no encoding conversion, value_blob() might
77775  ** need to call malloc() to expand the result of a zeroblob()
77776  ** expression.
77777  */
77778  columnMallocFailure(pStmt);
77779  return val;
77780}
77781SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
77782  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
77783  columnMallocFailure(pStmt);
77784  return val;
77785}
77786SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
77787  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
77788  columnMallocFailure(pStmt);
77789  return val;
77790}
77791SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
77792  double val = sqlite3_value_double( columnMem(pStmt,i) );
77793  columnMallocFailure(pStmt);
77794  return val;
77795}
77796SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
77797  int val = sqlite3_value_int( columnMem(pStmt,i) );
77798  columnMallocFailure(pStmt);
77799  return val;
77800}
77801SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
77802  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
77803  columnMallocFailure(pStmt);
77804  return val;
77805}
77806SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
77807  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
77808  columnMallocFailure(pStmt);
77809  return val;
77810}
77811SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
77812  Mem *pOut = columnMem(pStmt, i);
77813  if( pOut->flags&MEM_Static ){
77814    pOut->flags &= ~MEM_Static;
77815    pOut->flags |= MEM_Ephem;
77816  }
77817  columnMallocFailure(pStmt);
77818  return (sqlite3_value *)pOut;
77819}
77820#ifndef SQLITE_OMIT_UTF16
77821SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
77822  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
77823  columnMallocFailure(pStmt);
77824  return val;
77825}
77826#endif /* SQLITE_OMIT_UTF16 */
77827SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
77828  int iType = sqlite3_value_type( columnMem(pStmt,i) );
77829  columnMallocFailure(pStmt);
77830  return iType;
77831}
77832
77833/*
77834** Convert the N-th element of pStmt->pColName[] into a string using
77835** xFunc() then return that string.  If N is out of range, return 0.
77836**
77837** There are up to 5 names for each column.  useType determines which
77838** name is returned.  Here are the names:
77839**
77840**    0      The column name as it should be displayed for output
77841**    1      The datatype name for the column
77842**    2      The name of the database that the column derives from
77843**    3      The name of the table that the column derives from
77844**    4      The name of the table column that the result column derives from
77845**
77846** If the result is not a simple column reference (if it is an expression
77847** or a constant) then useTypes 2, 3, and 4 return NULL.
77848*/
77849static const void *columnName(
77850  sqlite3_stmt *pStmt,
77851  int N,
77852  const void *(*xFunc)(Mem*),
77853  int useType
77854){
77855  const void *ret;
77856  Vdbe *p;
77857  int n;
77858  sqlite3 *db;
77859#ifdef SQLITE_ENABLE_API_ARMOR
77860  if( pStmt==0 ){
77861    (void)SQLITE_MISUSE_BKPT;
77862    return 0;
77863  }
77864#endif
77865  ret = 0;
77866  p = (Vdbe *)pStmt;
77867  db = p->db;
77868  assert( db!=0 );
77869  n = sqlite3_column_count(pStmt);
77870  if( N<n && N>=0 ){
77871    N += useType*n;
77872    sqlite3_mutex_enter(db->mutex);
77873    assert( db->mallocFailed==0 );
77874    ret = xFunc(&p->aColName[N]);
77875     /* A malloc may have failed inside of the xFunc() call. If this
77876    ** is the case, clear the mallocFailed flag and return NULL.
77877    */
77878    if( db->mallocFailed ){
77879      sqlite3OomClear(db);
77880      ret = 0;
77881    }
77882    sqlite3_mutex_leave(db->mutex);
77883  }
77884  return ret;
77885}
77886
77887/*
77888** Return the name of the Nth column of the result set returned by SQL
77889** statement pStmt.
77890*/
77891SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
77892  return columnName(
77893      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
77894}
77895#ifndef SQLITE_OMIT_UTF16
77896SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
77897  return columnName(
77898      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
77899}
77900#endif
77901
77902/*
77903** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
77904** not define OMIT_DECLTYPE.
77905*/
77906#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
77907# error "Must not define both SQLITE_OMIT_DECLTYPE \
77908         and SQLITE_ENABLE_COLUMN_METADATA"
77909#endif
77910
77911#ifndef SQLITE_OMIT_DECLTYPE
77912/*
77913** Return the column declaration type (if applicable) of the 'i'th column
77914** of the result set of SQL statement pStmt.
77915*/
77916SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
77917  return columnName(
77918      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
77919}
77920#ifndef SQLITE_OMIT_UTF16
77921SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
77922  return columnName(
77923      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
77924}
77925#endif /* SQLITE_OMIT_UTF16 */
77926#endif /* SQLITE_OMIT_DECLTYPE */
77927
77928#ifdef SQLITE_ENABLE_COLUMN_METADATA
77929/*
77930** Return the name of the database from which a result column derives.
77931** NULL is returned if the result column is an expression or constant or
77932** anything else which is not an unambiguous reference to a database column.
77933*/
77934SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
77935  return columnName(
77936      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
77937}
77938#ifndef SQLITE_OMIT_UTF16
77939SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
77940  return columnName(
77941      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
77942}
77943#endif /* SQLITE_OMIT_UTF16 */
77944
77945/*
77946** Return the name of the table from which a result column derives.
77947** NULL is returned if the result column is an expression or constant or
77948** anything else which is not an unambiguous reference to a database column.
77949*/
77950SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
77951  return columnName(
77952      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
77953}
77954#ifndef SQLITE_OMIT_UTF16
77955SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
77956  return columnName(
77957      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
77958}
77959#endif /* SQLITE_OMIT_UTF16 */
77960
77961/*
77962** Return the name of the table column from which a result column derives.
77963** NULL is returned if the result column is an expression or constant or
77964** anything else which is not an unambiguous reference to a database column.
77965*/
77966SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
77967  return columnName(
77968      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
77969}
77970#ifndef SQLITE_OMIT_UTF16
77971SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
77972  return columnName(
77973      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
77974}
77975#endif /* SQLITE_OMIT_UTF16 */
77976#endif /* SQLITE_ENABLE_COLUMN_METADATA */
77977
77978
77979/******************************* sqlite3_bind_  ***************************
77980**
77981** Routines used to attach values to wildcards in a compiled SQL statement.
77982*/
77983/*
77984** Unbind the value bound to variable i in virtual machine p. This is the
77985** the same as binding a NULL value to the column. If the "i" parameter is
77986** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
77987**
77988** A successful evaluation of this routine acquires the mutex on p.
77989** the mutex is released if any kind of error occurs.
77990**
77991** The error code stored in database p->db is overwritten with the return
77992** value in any case.
77993*/
77994static int vdbeUnbind(Vdbe *p, int i){
77995  Mem *pVar;
77996  if( vdbeSafetyNotNull(p) ){
77997    return SQLITE_MISUSE_BKPT;
77998  }
77999  sqlite3_mutex_enter(p->db->mutex);
78000  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
78001    sqlite3Error(p->db, SQLITE_MISUSE);
78002    sqlite3_mutex_leave(p->db->mutex);
78003    sqlite3_log(SQLITE_MISUSE,
78004        "bind on a busy prepared statement: [%s]", p->zSql);
78005    return SQLITE_MISUSE_BKPT;
78006  }
78007  if( i<1 || i>p->nVar ){
78008    sqlite3Error(p->db, SQLITE_RANGE);
78009    sqlite3_mutex_leave(p->db->mutex);
78010    return SQLITE_RANGE;
78011  }
78012  i--;
78013  pVar = &p->aVar[i];
78014  sqlite3VdbeMemRelease(pVar);
78015  pVar->flags = MEM_Null;
78016  sqlite3Error(p->db, SQLITE_OK);
78017
78018  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
78019  ** binding a new value to this variable invalidates the current query plan.
78020  **
78021  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
78022  ** parameter in the WHERE clause might influence the choice of query plan
78023  ** for a statement, then the statement will be automatically recompiled,
78024  ** as if there had been a schema change, on the first sqlite3_step() call
78025  ** following any change to the bindings of that parameter.
78026  */
78027  assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
78028  if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
78029    p->expired = 1;
78030  }
78031  return SQLITE_OK;
78032}
78033
78034/*
78035** Bind a text or BLOB value.
78036*/
78037static int bindText(
78038  sqlite3_stmt *pStmt,   /* The statement to bind against */
78039  int i,                 /* Index of the parameter to bind */
78040  const void *zData,     /* Pointer to the data to be bound */
78041  int nData,             /* Number of bytes of data to be bound */
78042  void (*xDel)(void*),   /* Destructor for the data */
78043  u8 encoding            /* Encoding for the data */
78044){
78045  Vdbe *p = (Vdbe *)pStmt;
78046  Mem *pVar;
78047  int rc;
78048
78049  rc = vdbeUnbind(p, i);
78050  if( rc==SQLITE_OK ){
78051    if( zData!=0 ){
78052      pVar = &p->aVar[i-1];
78053      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
78054      if( rc==SQLITE_OK && encoding!=0 ){
78055        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
78056      }
78057      if( rc ){
78058        sqlite3Error(p->db, rc);
78059        rc = sqlite3ApiExit(p->db, rc);
78060      }
78061    }
78062    sqlite3_mutex_leave(p->db->mutex);
78063  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
78064    xDel((void*)zData);
78065  }
78066  return rc;
78067}
78068
78069
78070/*
78071** Bind a blob value to an SQL statement variable.
78072*/
78073SQLITE_API int sqlite3_bind_blob(
78074  sqlite3_stmt *pStmt,
78075  int i,
78076  const void *zData,
78077  int nData,
78078  void (*xDel)(void*)
78079){
78080#ifdef SQLITE_ENABLE_API_ARMOR
78081  if( nData<0 ) return SQLITE_MISUSE_BKPT;
78082#endif
78083  return bindText(pStmt, i, zData, nData, xDel, 0);
78084}
78085SQLITE_API int sqlite3_bind_blob64(
78086  sqlite3_stmt *pStmt,
78087  int i,
78088  const void *zData,
78089  sqlite3_uint64 nData,
78090  void (*xDel)(void*)
78091){
78092  assert( xDel!=SQLITE_DYNAMIC );
78093  if( nData>0x7fffffff ){
78094    return invokeValueDestructor(zData, xDel, 0);
78095  }else{
78096    return bindText(pStmt, i, zData, (int)nData, xDel, 0);
78097  }
78098}
78099SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
78100  int rc;
78101  Vdbe *p = (Vdbe *)pStmt;
78102  rc = vdbeUnbind(p, i);
78103  if( rc==SQLITE_OK ){
78104    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
78105    sqlite3_mutex_leave(p->db->mutex);
78106  }
78107  return rc;
78108}
78109SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
78110  return sqlite3_bind_int64(p, i, (i64)iValue);
78111}
78112SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
78113  int rc;
78114  Vdbe *p = (Vdbe *)pStmt;
78115  rc = vdbeUnbind(p, i);
78116  if( rc==SQLITE_OK ){
78117    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
78118    sqlite3_mutex_leave(p->db->mutex);
78119  }
78120  return rc;
78121}
78122SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
78123  int rc;
78124  Vdbe *p = (Vdbe*)pStmt;
78125  rc = vdbeUnbind(p, i);
78126  if( rc==SQLITE_OK ){
78127    sqlite3_mutex_leave(p->db->mutex);
78128  }
78129  return rc;
78130}
78131SQLITE_API int sqlite3_bind_pointer(
78132  sqlite3_stmt *pStmt,
78133  int i,
78134  void *pPtr,
78135  const char *zPTtype,
78136  void (*xDestructor)(void*)
78137){
78138  int rc;
78139  Vdbe *p = (Vdbe*)pStmt;
78140  rc = vdbeUnbind(p, i);
78141  if( rc==SQLITE_OK ){
78142    sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
78143    sqlite3_mutex_leave(p->db->mutex);
78144  }else if( xDestructor ){
78145    xDestructor(pPtr);
78146  }
78147  return rc;
78148}
78149SQLITE_API int sqlite3_bind_text(
78150  sqlite3_stmt *pStmt,
78151  int i,
78152  const char *zData,
78153  int nData,
78154  void (*xDel)(void*)
78155){
78156  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
78157}
78158SQLITE_API int sqlite3_bind_text64(
78159  sqlite3_stmt *pStmt,
78160  int i,
78161  const char *zData,
78162  sqlite3_uint64 nData,
78163  void (*xDel)(void*),
78164  unsigned char enc
78165){
78166  assert( xDel!=SQLITE_DYNAMIC );
78167  if( nData>0x7fffffff ){
78168    return invokeValueDestructor(zData, xDel, 0);
78169  }else{
78170    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
78171    return bindText(pStmt, i, zData, (int)nData, xDel, enc);
78172  }
78173}
78174#ifndef SQLITE_OMIT_UTF16
78175SQLITE_API int sqlite3_bind_text16(
78176  sqlite3_stmt *pStmt,
78177  int i,
78178  const void *zData,
78179  int nData,
78180  void (*xDel)(void*)
78181){
78182  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
78183}
78184#endif /* SQLITE_OMIT_UTF16 */
78185SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
78186  int rc;
78187  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
78188    case SQLITE_INTEGER: {
78189      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
78190      break;
78191    }
78192    case SQLITE_FLOAT: {
78193      rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
78194      break;
78195    }
78196    case SQLITE_BLOB: {
78197      if( pValue->flags & MEM_Zero ){
78198        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
78199      }else{
78200        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
78201      }
78202      break;
78203    }
78204    case SQLITE_TEXT: {
78205      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
78206                              pValue->enc);
78207      break;
78208    }
78209    default: {
78210      rc = sqlite3_bind_null(pStmt, i);
78211      break;
78212    }
78213  }
78214  return rc;
78215}
78216SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
78217  int rc;
78218  Vdbe *p = (Vdbe *)pStmt;
78219  rc = vdbeUnbind(p, i);
78220  if( rc==SQLITE_OK ){
78221    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
78222    sqlite3_mutex_leave(p->db->mutex);
78223  }
78224  return rc;
78225}
78226SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
78227  int rc;
78228  Vdbe *p = (Vdbe *)pStmt;
78229  sqlite3_mutex_enter(p->db->mutex);
78230  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
78231    rc = SQLITE_TOOBIG;
78232  }else{
78233    assert( (n & 0x7FFFFFFF)==n );
78234    rc = sqlite3_bind_zeroblob(pStmt, i, n);
78235  }
78236  rc = sqlite3ApiExit(p->db, rc);
78237  sqlite3_mutex_leave(p->db->mutex);
78238  return rc;
78239}
78240
78241/*
78242** Return the number of wildcards that can be potentially bound to.
78243** This routine is added to support DBD::SQLite.
78244*/
78245SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
78246  Vdbe *p = (Vdbe*)pStmt;
78247  return p ? p->nVar : 0;
78248}
78249
78250/*
78251** Return the name of a wildcard parameter.  Return NULL if the index
78252** is out of range or if the wildcard is unnamed.
78253**
78254** The result is always UTF-8.
78255*/
78256SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
78257  Vdbe *p = (Vdbe*)pStmt;
78258  if( p==0 ) return 0;
78259  return sqlite3VListNumToName(p->pVList, i);
78260}
78261
78262/*
78263** Given a wildcard parameter name, return the index of the variable
78264** with that name.  If there is no variable with the given name,
78265** return 0.
78266*/
78267SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
78268  if( p==0 || zName==0 ) return 0;
78269  return sqlite3VListNameToNum(p->pVList, zName, nName);
78270}
78271SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
78272  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
78273}
78274
78275/*
78276** Transfer all bindings from the first statement over to the second.
78277*/
78278SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
78279  Vdbe *pFrom = (Vdbe*)pFromStmt;
78280  Vdbe *pTo = (Vdbe*)pToStmt;
78281  int i;
78282  assert( pTo->db==pFrom->db );
78283  assert( pTo->nVar==pFrom->nVar );
78284  sqlite3_mutex_enter(pTo->db->mutex);
78285  for(i=0; i<pFrom->nVar; i++){
78286    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
78287  }
78288  sqlite3_mutex_leave(pTo->db->mutex);
78289  return SQLITE_OK;
78290}
78291
78292#ifndef SQLITE_OMIT_DEPRECATED
78293/*
78294** Deprecated external interface.  Internal/core SQLite code
78295** should call sqlite3TransferBindings.
78296**
78297** It is misuse to call this routine with statements from different
78298** database connections.  But as this is a deprecated interface, we
78299** will not bother to check for that condition.
78300**
78301** If the two statements contain a different number of bindings, then
78302** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
78303** SQLITE_OK is returned.
78304*/
78305SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
78306  Vdbe *pFrom = (Vdbe*)pFromStmt;
78307  Vdbe *pTo = (Vdbe*)pToStmt;
78308  if( pFrom->nVar!=pTo->nVar ){
78309    return SQLITE_ERROR;
78310  }
78311  assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
78312  if( pTo->expmask ){
78313    pTo->expired = 1;
78314  }
78315  assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
78316  if( pFrom->expmask ){
78317    pFrom->expired = 1;
78318  }
78319  return sqlite3TransferBindings(pFromStmt, pToStmt);
78320}
78321#endif
78322
78323/*
78324** Return the sqlite3* database handle to which the prepared statement given
78325** in the argument belongs.  This is the same database handle that was
78326** the first argument to the sqlite3_prepare() that was used to create
78327** the statement in the first place.
78328*/
78329SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
78330  return pStmt ? ((Vdbe*)pStmt)->db : 0;
78331}
78332
78333/*
78334** Return true if the prepared statement is guaranteed to not modify the
78335** database.
78336*/
78337SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
78338  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
78339}
78340
78341/*
78342** Return true if the prepared statement is in need of being reset.
78343*/
78344SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
78345  Vdbe *v = (Vdbe*)pStmt;
78346  return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
78347}
78348
78349/*
78350** Return a pointer to the next prepared statement after pStmt associated
78351** with database connection pDb.  If pStmt is NULL, return the first
78352** prepared statement for the database connection.  Return NULL if there
78353** are no more.
78354*/
78355SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
78356  sqlite3_stmt *pNext;
78357#ifdef SQLITE_ENABLE_API_ARMOR
78358  if( !sqlite3SafetyCheckOk(pDb) ){
78359    (void)SQLITE_MISUSE_BKPT;
78360    return 0;
78361  }
78362#endif
78363  sqlite3_mutex_enter(pDb->mutex);
78364  if( pStmt==0 ){
78365    pNext = (sqlite3_stmt*)pDb->pVdbe;
78366  }else{
78367    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
78368  }
78369  sqlite3_mutex_leave(pDb->mutex);
78370  return pNext;
78371}
78372
78373/*
78374** Return the value of a status counter for a prepared statement
78375*/
78376SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
78377  Vdbe *pVdbe = (Vdbe*)pStmt;
78378  u32 v;
78379#ifdef SQLITE_ENABLE_API_ARMOR
78380  if( !pStmt ){
78381    (void)SQLITE_MISUSE_BKPT;
78382    return 0;
78383  }
78384#endif
78385  if( op==SQLITE_STMTSTATUS_MEMUSED ){
78386    sqlite3 *db = pVdbe->db;
78387    sqlite3_mutex_enter(db->mutex);
78388    v = 0;
78389    db->pnBytesFreed = (int*)&v;
78390    sqlite3VdbeClearObject(db, pVdbe);
78391    sqlite3DbFree(db, pVdbe);
78392    db->pnBytesFreed = 0;
78393    sqlite3_mutex_leave(db->mutex);
78394  }else{
78395    v = pVdbe->aCounter[op];
78396    if( resetFlag ) pVdbe->aCounter[op] = 0;
78397  }
78398  return (int)v;
78399}
78400
78401/*
78402** Return the SQL associated with a prepared statement
78403*/
78404SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
78405  Vdbe *p = (Vdbe *)pStmt;
78406  return p ? p->zSql : 0;
78407}
78408
78409/*
78410** Return the SQL associated with a prepared statement with
78411** bound parameters expanded.  Space to hold the returned string is
78412** obtained from sqlite3_malloc().  The caller is responsible for
78413** freeing the returned string by passing it to sqlite3_free().
78414**
78415** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
78416** expanded bound parameters.
78417*/
78418SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
78419#ifdef SQLITE_OMIT_TRACE
78420  return 0;
78421#else
78422  char *z = 0;
78423  const char *zSql = sqlite3_sql(pStmt);
78424  if( zSql ){
78425    Vdbe *p = (Vdbe *)pStmt;
78426    sqlite3_mutex_enter(p->db->mutex);
78427    z = sqlite3VdbeExpandSql(p, zSql);
78428    sqlite3_mutex_leave(p->db->mutex);
78429  }
78430  return z;
78431#endif
78432}
78433
78434#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78435/*
78436** Allocate and populate an UnpackedRecord structure based on the serialized
78437** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
78438** if successful, or a NULL pointer if an OOM error is encountered.
78439*/
78440static UnpackedRecord *vdbeUnpackRecord(
78441  KeyInfo *pKeyInfo,
78442  int nKey,
78443  const void *pKey
78444){
78445  UnpackedRecord *pRet;           /* Return value */
78446
78447  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
78448  if( pRet ){
78449    memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
78450    sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
78451  }
78452  return pRet;
78453}
78454
78455/*
78456** This function is called from within a pre-update callback to retrieve
78457** a field of the row currently being updated or deleted.
78458*/
78459SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
78460  PreUpdate *p = db->pPreUpdate;
78461  Mem *pMem;
78462  int rc = SQLITE_OK;
78463
78464  /* Test that this call is being made from within an SQLITE_DELETE or
78465  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
78466  if( !p || p->op==SQLITE_INSERT ){
78467    rc = SQLITE_MISUSE_BKPT;
78468    goto preupdate_old_out;
78469  }
78470  if( p->pPk ){
78471    iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
78472  }
78473  if( iIdx>=p->pCsr->nField || iIdx<0 ){
78474    rc = SQLITE_RANGE;
78475    goto preupdate_old_out;
78476  }
78477
78478  /* If the old.* record has not yet been loaded into memory, do so now. */
78479  if( p->pUnpacked==0 ){
78480    u32 nRec;
78481    u8 *aRec;
78482
78483    nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
78484    aRec = sqlite3DbMallocRaw(db, nRec);
78485    if( !aRec ) goto preupdate_old_out;
78486    rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
78487    if( rc==SQLITE_OK ){
78488      p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
78489      if( !p->pUnpacked ) rc = SQLITE_NOMEM;
78490    }
78491    if( rc!=SQLITE_OK ){
78492      sqlite3DbFree(db, aRec);
78493      goto preupdate_old_out;
78494    }
78495    p->aRecord = aRec;
78496  }
78497
78498  pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
78499  if( iIdx==p->pTab->iPKey ){
78500    sqlite3VdbeMemSetInt64(pMem, p->iKey1);
78501  }else if( iIdx>=p->pUnpacked->nField ){
78502    *ppValue = (sqlite3_value *)columnNullValue();
78503  }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
78504    if( pMem->flags & MEM_Int ){
78505      sqlite3VdbeMemRealify(pMem);
78506    }
78507  }
78508
78509 preupdate_old_out:
78510  sqlite3Error(db, rc);
78511  return sqlite3ApiExit(db, rc);
78512}
78513#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
78514
78515#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78516/*
78517** This function is called from within a pre-update callback to retrieve
78518** the number of columns in the row being updated, deleted or inserted.
78519*/
78520SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
78521  PreUpdate *p = db->pPreUpdate;
78522  return (p ? p->keyinfo.nField : 0);
78523}
78524#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
78525
78526#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78527/*
78528** This function is designed to be called from within a pre-update callback
78529** only. It returns zero if the change that caused the callback was made
78530** immediately by a user SQL statement. Or, if the change was made by a
78531** trigger program, it returns the number of trigger programs currently
78532** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
78533** top-level trigger etc.).
78534**
78535** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
78536** or SET DEFAULT action is considered a trigger.
78537*/
78538SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
78539  PreUpdate *p = db->pPreUpdate;
78540  return (p ? p->v->nFrame : 0);
78541}
78542#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
78543
78544#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78545/*
78546** This function is called from within a pre-update callback to retrieve
78547** a field of the row currently being updated or inserted.
78548*/
78549SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
78550  PreUpdate *p = db->pPreUpdate;
78551  int rc = SQLITE_OK;
78552  Mem *pMem;
78553
78554  if( !p || p->op==SQLITE_DELETE ){
78555    rc = SQLITE_MISUSE_BKPT;
78556    goto preupdate_new_out;
78557  }
78558  if( p->pPk && p->op!=SQLITE_UPDATE ){
78559    iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
78560  }
78561  if( iIdx>=p->pCsr->nField || iIdx<0 ){
78562    rc = SQLITE_RANGE;
78563    goto preupdate_new_out;
78564  }
78565
78566  if( p->op==SQLITE_INSERT ){
78567    /* For an INSERT, memory cell p->iNewReg contains the serialized record
78568    ** that is being inserted. Deserialize it. */
78569    UnpackedRecord *pUnpack = p->pNewUnpacked;
78570    if( !pUnpack ){
78571      Mem *pData = &p->v->aMem[p->iNewReg];
78572      rc = ExpandBlob(pData);
78573      if( rc!=SQLITE_OK ) goto preupdate_new_out;
78574      pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
78575      if( !pUnpack ){
78576        rc = SQLITE_NOMEM;
78577        goto preupdate_new_out;
78578      }
78579      p->pNewUnpacked = pUnpack;
78580    }
78581    pMem = &pUnpack->aMem[iIdx];
78582    if( iIdx==p->pTab->iPKey ){
78583      sqlite3VdbeMemSetInt64(pMem, p->iKey2);
78584    }else if( iIdx>=pUnpack->nField ){
78585      pMem = (sqlite3_value *)columnNullValue();
78586    }
78587  }else{
78588    /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
78589    ** value. Make a copy of the cell contents and return a pointer to it.
78590    ** It is not safe to return a pointer to the memory cell itself as the
78591    ** caller may modify the value text encoding.
78592    */
78593    assert( p->op==SQLITE_UPDATE );
78594    if( !p->aNew ){
78595      p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
78596      if( !p->aNew ){
78597        rc = SQLITE_NOMEM;
78598        goto preupdate_new_out;
78599      }
78600    }
78601    assert( iIdx>=0 && iIdx<p->pCsr->nField );
78602    pMem = &p->aNew[iIdx];
78603    if( pMem->flags==0 ){
78604      if( iIdx==p->pTab->iPKey ){
78605        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
78606      }else{
78607        rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
78608        if( rc!=SQLITE_OK ) goto preupdate_new_out;
78609      }
78610    }
78611  }
78612  *ppValue = pMem;
78613
78614 preupdate_new_out:
78615  sqlite3Error(db, rc);
78616  return sqlite3ApiExit(db, rc);
78617}
78618#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
78619
78620#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
78621/*
78622** Return status data for a single loop within query pStmt.
78623*/
78624SQLITE_API int sqlite3_stmt_scanstatus(
78625  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
78626  int idx,                        /* Index of loop to report on */
78627  int iScanStatusOp,              /* Which metric to return */
78628  void *pOut                      /* OUT: Write the answer here */
78629){
78630  Vdbe *p = (Vdbe*)pStmt;
78631  ScanStatus *pScan;
78632  if( idx<0 || idx>=p->nScan ) return 1;
78633  pScan = &p->aScan[idx];
78634  switch( iScanStatusOp ){
78635    case SQLITE_SCANSTAT_NLOOP: {
78636      *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
78637      break;
78638    }
78639    case SQLITE_SCANSTAT_NVISIT: {
78640      *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
78641      break;
78642    }
78643    case SQLITE_SCANSTAT_EST: {
78644      double r = 1.0;
78645      LogEst x = pScan->nEst;
78646      while( x<100 ){
78647        x += 10;
78648        r *= 0.5;
78649      }
78650      *(double*)pOut = r*sqlite3LogEstToInt(x);
78651      break;
78652    }
78653    case SQLITE_SCANSTAT_NAME: {
78654      *(const char**)pOut = pScan->zName;
78655      break;
78656    }
78657    case SQLITE_SCANSTAT_EXPLAIN: {
78658      if( pScan->addrExplain ){
78659        *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
78660      }else{
78661        *(const char**)pOut = 0;
78662      }
78663      break;
78664    }
78665    case SQLITE_SCANSTAT_SELECTID: {
78666      if( pScan->addrExplain ){
78667        *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
78668      }else{
78669        *(int*)pOut = -1;
78670      }
78671      break;
78672    }
78673    default: {
78674      return 1;
78675    }
78676  }
78677  return 0;
78678}
78679
78680/*
78681** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
78682*/
78683SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
78684  Vdbe *p = (Vdbe*)pStmt;
78685  memset(p->anExec, 0, p->nOp * sizeof(i64));
78686}
78687#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
78688
78689/************** End of vdbeapi.c *********************************************/
78690/************** Begin file vdbetrace.c ***************************************/
78691/*
78692** 2009 November 25
78693**
78694** The author disclaims copyright to this source code.  In place of
78695** a legal notice, here is a blessing:
78696**
78697**    May you do good and not evil.
78698**    May you find forgiveness for yourself and forgive others.
78699**    May you share freely, never taking more than you give.
78700**
78701*************************************************************************
78702**
78703** This file contains code used to insert the values of host parameters
78704** (aka "wildcards") into the SQL text output by sqlite3_trace().
78705**
78706** The Vdbe parse-tree explainer is also found here.
78707*/
78708/* #include "sqliteInt.h" */
78709/* #include "vdbeInt.h" */
78710
78711#ifndef SQLITE_OMIT_TRACE
78712
78713/*
78714** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
78715** bytes in this text up to but excluding the first character in
78716** a host parameter.  If the text contains no host parameters, return
78717** the total number of bytes in the text.
78718*/
78719static int findNextHostParameter(const char *zSql, int *pnToken){
78720  int tokenType;
78721  int nTotal = 0;
78722  int n;
78723
78724  *pnToken = 0;
78725  while( zSql[0] ){
78726    n = sqlite3GetToken((u8*)zSql, &tokenType);
78727    assert( n>0 && tokenType!=TK_ILLEGAL );
78728    if( tokenType==TK_VARIABLE ){
78729      *pnToken = n;
78730      break;
78731    }
78732    nTotal += n;
78733    zSql += n;
78734  }
78735  return nTotal;
78736}
78737
78738/*
78739** This function returns a pointer to a nul-terminated string in memory
78740** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
78741** string contains a copy of zRawSql but with host parameters expanded to
78742** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
78743** then the returned string holds a copy of zRawSql with "-- " prepended
78744** to each line of text.
78745**
78746** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
78747** then long strings and blobs are truncated to that many bytes.  This
78748** can be used to prevent unreasonably large trace strings when dealing
78749** with large (multi-megabyte) strings and blobs.
78750**
78751** The calling function is responsible for making sure the memory returned
78752** is eventually freed.
78753**
78754** ALGORITHM:  Scan the input string looking for host parameters in any of
78755** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
78756** string literals, quoted identifier names, and comments.  For text forms,
78757** the host parameter index is found by scanning the prepared
78758** statement for the corresponding OP_Variable opcode.  Once the host
78759** parameter index is known, locate the value in p->aVar[].  Then render
78760** the value as a literal in place of the host parameter name.
78761*/
78762SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
78763  Vdbe *p,                 /* The prepared statement being evaluated */
78764  const char *zRawSql      /* Raw text of the SQL statement */
78765){
78766  sqlite3 *db;             /* The database connection */
78767  int idx = 0;             /* Index of a host parameter */
78768  int nextIndex = 1;       /* Index of next ? host parameter */
78769  int n;                   /* Length of a token prefix */
78770  int nToken;              /* Length of the parameter token */
78771  int i;                   /* Loop counter */
78772  Mem *pVar;               /* Value of a host parameter */
78773  StrAccum out;            /* Accumulate the output here */
78774#ifndef SQLITE_OMIT_UTF16
78775  Mem utf8;                /* Used to convert UTF16 parameters into UTF8 for display */
78776#endif
78777  char zBase[100];         /* Initial working space */
78778
78779  db = p->db;
78780  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
78781                      db->aLimit[SQLITE_LIMIT_LENGTH]);
78782  if( db->nVdbeExec>1 ){
78783    while( *zRawSql ){
78784      const char *zStart = zRawSql;
78785      while( *(zRawSql++)!='\n' && *zRawSql );
78786      sqlite3StrAccumAppend(&out, "-- ", 3);
78787      assert( (zRawSql - zStart) > 0 );
78788      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
78789    }
78790  }else if( p->nVar==0 ){
78791    sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
78792  }else{
78793    while( zRawSql[0] ){
78794      n = findNextHostParameter(zRawSql, &nToken);
78795      assert( n>0 );
78796      sqlite3StrAccumAppend(&out, zRawSql, n);
78797      zRawSql += n;
78798      assert( zRawSql[0] || nToken==0 );
78799      if( nToken==0 ) break;
78800      if( zRawSql[0]=='?' ){
78801        if( nToken>1 ){
78802          assert( sqlite3Isdigit(zRawSql[1]) );
78803          sqlite3GetInt32(&zRawSql[1], &idx);
78804        }else{
78805          idx = nextIndex;
78806        }
78807      }else{
78808        assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
78809                zRawSql[0]=='@' || zRawSql[0]=='#' );
78810        testcase( zRawSql[0]==':' );
78811        testcase( zRawSql[0]=='$' );
78812        testcase( zRawSql[0]=='@' );
78813        testcase( zRawSql[0]=='#' );
78814        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
78815        assert( idx>0 );
78816      }
78817      zRawSql += nToken;
78818      nextIndex = idx + 1;
78819      assert( idx>0 && idx<=p->nVar );
78820      pVar = &p->aVar[idx-1];
78821      if( pVar->flags & MEM_Null ){
78822        sqlite3StrAccumAppend(&out, "NULL", 4);
78823      }else if( pVar->flags & MEM_Int ){
78824        sqlite3XPrintf(&out, "%lld", pVar->u.i);
78825      }else if( pVar->flags & MEM_Real ){
78826        sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
78827      }else if( pVar->flags & MEM_Str ){
78828        int nOut;  /* Number of bytes of the string text to include in output */
78829#ifndef SQLITE_OMIT_UTF16
78830        u8 enc = ENC(db);
78831        if( enc!=SQLITE_UTF8 ){
78832          memset(&utf8, 0, sizeof(utf8));
78833          utf8.db = db;
78834          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
78835          if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
78836            out.accError = STRACCUM_NOMEM;
78837            out.nAlloc = 0;
78838          }
78839          pVar = &utf8;
78840        }
78841#endif
78842        nOut = pVar->n;
78843#ifdef SQLITE_TRACE_SIZE_LIMIT
78844        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
78845          nOut = SQLITE_TRACE_SIZE_LIMIT;
78846          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
78847        }
78848#endif
78849        sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
78850#ifdef SQLITE_TRACE_SIZE_LIMIT
78851        if( nOut<pVar->n ){
78852          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
78853        }
78854#endif
78855#ifndef SQLITE_OMIT_UTF16
78856        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
78857#endif
78858      }else if( pVar->flags & MEM_Zero ){
78859        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
78860      }else{
78861        int nOut;  /* Number of bytes of the blob to include in output */
78862        assert( pVar->flags & MEM_Blob );
78863        sqlite3StrAccumAppend(&out, "x'", 2);
78864        nOut = pVar->n;
78865#ifdef SQLITE_TRACE_SIZE_LIMIT
78866        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
78867#endif
78868        for(i=0; i<nOut; i++){
78869          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
78870        }
78871        sqlite3StrAccumAppend(&out, "'", 1);
78872#ifdef SQLITE_TRACE_SIZE_LIMIT
78873        if( nOut<pVar->n ){
78874          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
78875        }
78876#endif
78877      }
78878    }
78879  }
78880  if( out.accError ) sqlite3StrAccumReset(&out);
78881  return sqlite3StrAccumFinish(&out);
78882}
78883
78884#endif /* #ifndef SQLITE_OMIT_TRACE */
78885
78886/************** End of vdbetrace.c *******************************************/
78887/************** Begin file vdbe.c ********************************************/
78888/*
78889** 2001 September 15
78890**
78891** The author disclaims copyright to this source code.  In place of
78892** a legal notice, here is a blessing:
78893**
78894**    May you do good and not evil.
78895**    May you find forgiveness for yourself and forgive others.
78896**    May you share freely, never taking more than you give.
78897**
78898*************************************************************************
78899** The code in this file implements the function that runs the
78900** bytecode of a prepared statement.
78901**
78902** Various scripts scan this source file in order to generate HTML
78903** documentation, headers files, or other derived files.  The formatting
78904** of the code in this file is, therefore, important.  See other comments
78905** in this file for details.  If in doubt, do not deviate from existing
78906** commenting and indentation practices when changing or adding code.
78907*/
78908/* #include "sqliteInt.h" */
78909/* #include "vdbeInt.h" */
78910
78911/*
78912** Invoke this macro on memory cells just prior to changing the
78913** value of the cell.  This macro verifies that shallow copies are
78914** not misused.  A shallow copy of a string or blob just copies a
78915** pointer to the string or blob, not the content.  If the original
78916** is changed while the copy is still in use, the string or blob might
78917** be changed out from under the copy.  This macro verifies that nothing
78918** like that ever happens.
78919*/
78920#ifdef SQLITE_DEBUG
78921# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
78922#else
78923# define memAboutToChange(P,M)
78924#endif
78925
78926/*
78927** The following global variable is incremented every time a cursor
78928** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
78929** procedures use this information to make sure that indices are
78930** working correctly.  This variable has no function other than to
78931** help verify the correct operation of the library.
78932*/
78933#ifdef SQLITE_TEST
78934SQLITE_API int sqlite3_search_count = 0;
78935#endif
78936
78937/*
78938** When this global variable is positive, it gets decremented once before
78939** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
78940** field of the sqlite3 structure is set in order to simulate an interrupt.
78941**
78942** This facility is used for testing purposes only.  It does not function
78943** in an ordinary build.
78944*/
78945#ifdef SQLITE_TEST
78946SQLITE_API int sqlite3_interrupt_count = 0;
78947#endif
78948
78949/*
78950** The next global variable is incremented each type the OP_Sort opcode
78951** is executed.  The test procedures use this information to make sure that
78952** sorting is occurring or not occurring at appropriate times.   This variable
78953** has no function other than to help verify the correct operation of the
78954** library.
78955*/
78956#ifdef SQLITE_TEST
78957SQLITE_API int sqlite3_sort_count = 0;
78958#endif
78959
78960/*
78961** The next global variable records the size of the largest MEM_Blob
78962** or MEM_Str that has been used by a VDBE opcode.  The test procedures
78963** use this information to make sure that the zero-blob functionality
78964** is working correctly.   This variable has no function other than to
78965** help verify the correct operation of the library.
78966*/
78967#ifdef SQLITE_TEST
78968SQLITE_API int sqlite3_max_blobsize = 0;
78969static void updateMaxBlobsize(Mem *p){
78970  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
78971    sqlite3_max_blobsize = p->n;
78972  }
78973}
78974#endif
78975
78976/*
78977** This macro evaluates to true if either the update hook or the preupdate
78978** hook are enabled for database connect DB.
78979*/
78980#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
78981# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
78982#else
78983# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
78984#endif
78985
78986/*
78987** The next global variable is incremented each time the OP_Found opcode
78988** is executed. This is used to test whether or not the foreign key
78989** operation implemented using OP_FkIsZero is working. This variable
78990** has no function other than to help verify the correct operation of the
78991** library.
78992*/
78993#ifdef SQLITE_TEST
78994SQLITE_API int sqlite3_found_count = 0;
78995#endif
78996
78997/*
78998** Test a register to see if it exceeds the current maximum blob size.
78999** If it does, record the new maximum blob size.
79000*/
79001#if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
79002# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
79003#else
79004# define UPDATE_MAX_BLOBSIZE(P)
79005#endif
79006
79007/*
79008** Invoke the VDBE coverage callback, if that callback is defined.  This
79009** feature is used for test suite validation only and does not appear an
79010** production builds.
79011**
79012** M is an integer, 2 or 3, that indices how many different ways the
79013** branch can go.  It is usually 2.  "I" is the direction the branch
79014** goes.  0 means falls through.  1 means branch is taken.  2 means the
79015** second alternative branch is taken.
79016**
79017** iSrcLine is the source code line (from the __LINE__ macro) that
79018** generated the VDBE instruction.  This instrumentation assumes that all
79019** source code is in a single file (the amalgamation).  Special values 1
79020** and 2 for the iSrcLine parameter mean that this particular branch is
79021** always taken or never taken, respectively.
79022*/
79023#if !defined(SQLITE_VDBE_COVERAGE)
79024# define VdbeBranchTaken(I,M)
79025#else
79026# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
79027  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
79028    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
79029      M = iSrcLine;
79030      /* Assert the truth of VdbeCoverageAlwaysTaken() and
79031      ** VdbeCoverageNeverTaken() */
79032      assert( (M & I)==I );
79033    }else{
79034      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
79035      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
79036                                      iSrcLine,I,M);
79037    }
79038  }
79039#endif
79040
79041/*
79042** Convert the given register into a string if it isn't one
79043** already. Return non-zero if a malloc() fails.
79044*/
79045#define Stringify(P, enc) \
79046   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
79047     { goto no_mem; }
79048
79049/*
79050** An ephemeral string value (signified by the MEM_Ephem flag) contains
79051** a pointer to a dynamically allocated string where some other entity
79052** is responsible for deallocating that string.  Because the register
79053** does not control the string, it might be deleted without the register
79054** knowing it.
79055**
79056** This routine converts an ephemeral string into a dynamically allocated
79057** string that the register itself controls.  In other words, it
79058** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
79059*/
79060#define Deephemeralize(P) \
79061   if( ((P)->flags&MEM_Ephem)!=0 \
79062       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
79063
79064/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
79065#define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
79066
79067/*
79068** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
79069** if we run out of memory.
79070*/
79071static VdbeCursor *allocateCursor(
79072  Vdbe *p,              /* The virtual machine */
79073  int iCur,             /* Index of the new VdbeCursor */
79074  int nField,           /* Number of fields in the table or index */
79075  int iDb,              /* Database the cursor belongs to, or -1 */
79076  u8 eCurType           /* Type of the new cursor */
79077){
79078  /* Find the memory cell that will be used to store the blob of memory
79079  ** required for this VdbeCursor structure. It is convenient to use a
79080  ** vdbe memory cell to manage the memory allocation required for a
79081  ** VdbeCursor structure for the following reasons:
79082  **
79083  **   * Sometimes cursor numbers are used for a couple of different
79084  **     purposes in a vdbe program. The different uses might require
79085  **     different sized allocations. Memory cells provide growable
79086  **     allocations.
79087  **
79088  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
79089  **     be freed lazily via the sqlite3_release_memory() API. This
79090  **     minimizes the number of malloc calls made by the system.
79091  **
79092  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
79093  ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
79094  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
79095  */
79096  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
79097
79098  int nByte;
79099  VdbeCursor *pCx = 0;
79100  nByte =
79101      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
79102      (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
79103
79104  assert( iCur>=0 && iCur<p->nCursor );
79105  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
79106    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
79107    p->apCsr[iCur] = 0;
79108  }
79109  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
79110    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
79111    memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
79112    pCx->eCurType = eCurType;
79113    pCx->iDb = iDb;
79114    pCx->nField = nField;
79115    pCx->aOffset = &pCx->aType[nField];
79116    if( eCurType==CURTYPE_BTREE ){
79117      pCx->uc.pCursor = (BtCursor*)
79118          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
79119      sqlite3BtreeCursorZero(pCx->uc.pCursor);
79120    }
79121  }
79122  return pCx;
79123}
79124
79125/*
79126** Try to convert a value into a numeric representation if we can
79127** do so without loss of information.  In other words, if the string
79128** looks like a number, convert it into a number.  If it does not
79129** look like a number, leave it alone.
79130**
79131** If the bTryForInt flag is true, then extra effort is made to give
79132** an integer representation.  Strings that look like floating point
79133** values but which have no fractional component (example: '48.00')
79134** will have a MEM_Int representation when bTryForInt is true.
79135**
79136** If bTryForInt is false, then if the input string contains a decimal
79137** point or exponential notation, the result is only MEM_Real, even
79138** if there is an exact integer representation of the quantity.
79139*/
79140static void applyNumericAffinity(Mem *pRec, int bTryForInt){
79141  double rValue;
79142  i64 iValue;
79143  u8 enc = pRec->enc;
79144  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
79145  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
79146  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
79147    pRec->u.i = iValue;
79148    pRec->flags |= MEM_Int;
79149  }else{
79150    pRec->u.r = rValue;
79151    pRec->flags |= MEM_Real;
79152    if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
79153  }
79154}
79155
79156/*
79157** Processing is determine by the affinity parameter:
79158**
79159** SQLITE_AFF_INTEGER:
79160** SQLITE_AFF_REAL:
79161** SQLITE_AFF_NUMERIC:
79162**    Try to convert pRec to an integer representation or a
79163**    floating-point representation if an integer representation
79164**    is not possible.  Note that the integer representation is
79165**    always preferred, even if the affinity is REAL, because
79166**    an integer representation is more space efficient on disk.
79167**
79168** SQLITE_AFF_TEXT:
79169**    Convert pRec to a text representation.
79170**
79171** SQLITE_AFF_BLOB:
79172**    No-op.  pRec is unchanged.
79173*/
79174static void applyAffinity(
79175  Mem *pRec,          /* The value to apply affinity to */
79176  char affinity,      /* The affinity to be applied */
79177  u8 enc              /* Use this text encoding */
79178){
79179  if( affinity>=SQLITE_AFF_NUMERIC ){
79180    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
79181             || affinity==SQLITE_AFF_NUMERIC );
79182    if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
79183      if( (pRec->flags & MEM_Real)==0 ){
79184        if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
79185      }else{
79186        sqlite3VdbeIntegerAffinity(pRec);
79187      }
79188    }
79189  }else if( affinity==SQLITE_AFF_TEXT ){
79190    /* Only attempt the conversion to TEXT if there is an integer or real
79191    ** representation (blob and NULL do not get converted) but no string
79192    ** representation.  It would be harmless to repeat the conversion if
79193    ** there is already a string rep, but it is pointless to waste those
79194    ** CPU cycles. */
79195    if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
79196      if( (pRec->flags&(MEM_Real|MEM_Int)) ){
79197        sqlite3VdbeMemStringify(pRec, enc, 1);
79198      }
79199    }
79200    pRec->flags &= ~(MEM_Real|MEM_Int);
79201  }
79202}
79203
79204/*
79205** Try to convert the type of a function argument or a result column
79206** into a numeric representation.  Use either INTEGER or REAL whichever
79207** is appropriate.  But only do the conversion if it is possible without
79208** loss of information and return the revised type of the argument.
79209*/
79210SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
79211  int eType = sqlite3_value_type(pVal);
79212  if( eType==SQLITE_TEXT ){
79213    Mem *pMem = (Mem*)pVal;
79214    applyNumericAffinity(pMem, 0);
79215    eType = sqlite3_value_type(pVal);
79216  }
79217  return eType;
79218}
79219
79220/*
79221** Exported version of applyAffinity(). This one works on sqlite3_value*,
79222** not the internal Mem* type.
79223*/
79224SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
79225  sqlite3_value *pVal,
79226  u8 affinity,
79227  u8 enc
79228){
79229  applyAffinity((Mem *)pVal, affinity, enc);
79230}
79231
79232/*
79233** pMem currently only holds a string type (or maybe a BLOB that we can
79234** interpret as a string if we want to).  Compute its corresponding
79235** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
79236** accordingly.
79237*/
79238static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
79239  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
79240  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
79241  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
79242    return 0;
79243  }
79244  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
79245    return MEM_Int;
79246  }
79247  return MEM_Real;
79248}
79249
79250/*
79251** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
79252** none.
79253**
79254** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
79255** But it does set pMem->u.r and pMem->u.i appropriately.
79256*/
79257static u16 numericType(Mem *pMem){
79258  if( pMem->flags & (MEM_Int|MEM_Real) ){
79259    return pMem->flags & (MEM_Int|MEM_Real);
79260  }
79261  if( pMem->flags & (MEM_Str|MEM_Blob) ){
79262    return computeNumericType(pMem);
79263  }
79264  return 0;
79265}
79266
79267#ifdef SQLITE_DEBUG
79268/*
79269** Write a nice string representation of the contents of cell pMem
79270** into buffer zBuf, length nBuf.
79271*/
79272SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
79273  char *zCsr = zBuf;
79274  int f = pMem->flags;
79275
79276  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
79277
79278  if( f&MEM_Blob ){
79279    int i;
79280    char c;
79281    if( f & MEM_Dyn ){
79282      c = 'z';
79283      assert( (f & (MEM_Static|MEM_Ephem))==0 );
79284    }else if( f & MEM_Static ){
79285      c = 't';
79286      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
79287    }else if( f & MEM_Ephem ){
79288      c = 'e';
79289      assert( (f & (MEM_Static|MEM_Dyn))==0 );
79290    }else{
79291      c = 's';
79292    }
79293    *(zCsr++) = c;
79294    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
79295    zCsr += sqlite3Strlen30(zCsr);
79296    for(i=0; i<16 && i<pMem->n; i++){
79297      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
79298      zCsr += sqlite3Strlen30(zCsr);
79299    }
79300    for(i=0; i<16 && i<pMem->n; i++){
79301      char z = pMem->z[i];
79302      if( z<32 || z>126 ) *zCsr++ = '.';
79303      else *zCsr++ = z;
79304    }
79305    *(zCsr++) = ']';
79306    if( f & MEM_Zero ){
79307      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
79308      zCsr += sqlite3Strlen30(zCsr);
79309    }
79310    *zCsr = '\0';
79311  }else if( f & MEM_Str ){
79312    int j, k;
79313    zBuf[0] = ' ';
79314    if( f & MEM_Dyn ){
79315      zBuf[1] = 'z';
79316      assert( (f & (MEM_Static|MEM_Ephem))==0 );
79317    }else if( f & MEM_Static ){
79318      zBuf[1] = 't';
79319      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
79320    }else if( f & MEM_Ephem ){
79321      zBuf[1] = 'e';
79322      assert( (f & (MEM_Static|MEM_Dyn))==0 );
79323    }else{
79324      zBuf[1] = 's';
79325    }
79326    k = 2;
79327    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
79328    k += sqlite3Strlen30(&zBuf[k]);
79329    zBuf[k++] = '[';
79330    for(j=0; j<15 && j<pMem->n; j++){
79331      u8 c = pMem->z[j];
79332      if( c>=0x20 && c<0x7f ){
79333        zBuf[k++] = c;
79334      }else{
79335        zBuf[k++] = '.';
79336      }
79337    }
79338    zBuf[k++] = ']';
79339    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
79340    k += sqlite3Strlen30(&zBuf[k]);
79341    zBuf[k++] = 0;
79342  }
79343}
79344#endif
79345
79346#ifdef SQLITE_DEBUG
79347/*
79348** Print the value of a register for tracing purposes:
79349*/
79350static void memTracePrint(Mem *p){
79351  if( p->flags & MEM_Undefined ){
79352    printf(" undefined");
79353  }else if( p->flags & MEM_Null ){
79354    printf(" NULL");
79355  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
79356    printf(" si:%lld", p->u.i);
79357  }else if( p->flags & MEM_Int ){
79358    printf(" i:%lld", p->u.i);
79359#ifndef SQLITE_OMIT_FLOATING_POINT
79360  }else if( p->flags & MEM_Real ){
79361    printf(" r:%g", p->u.r);
79362#endif
79363  }else if( p->flags & MEM_RowSet ){
79364    printf(" (rowset)");
79365  }else{
79366    char zBuf[200];
79367    sqlite3VdbeMemPrettyPrint(p, zBuf);
79368    printf(" %s", zBuf);
79369  }
79370  if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
79371}
79372static void registerTrace(int iReg, Mem *p){
79373  printf("REG[%d] = ", iReg);
79374  memTracePrint(p);
79375  printf("\n");
79376  sqlite3VdbeCheckMemInvariants(p);
79377}
79378#endif
79379
79380#ifdef SQLITE_DEBUG
79381#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
79382#else
79383#  define REGISTER_TRACE(R,M)
79384#endif
79385
79386
79387#ifdef VDBE_PROFILE
79388
79389/*
79390** hwtime.h contains inline assembler code for implementing
79391** high-performance timing routines.
79392*/
79393/************** Include hwtime.h in the middle of vdbe.c *********************/
79394/************** Begin file hwtime.h ******************************************/
79395/*
79396** 2008 May 27
79397**
79398** The author disclaims copyright to this source code.  In place of
79399** a legal notice, here is a blessing:
79400**
79401**    May you do good and not evil.
79402**    May you find forgiveness for yourself and forgive others.
79403**    May you share freely, never taking more than you give.
79404**
79405******************************************************************************
79406**
79407** This file contains inline asm code for retrieving "high-performance"
79408** counters for x86 class CPUs.
79409*/
79410#ifndef SQLITE_HWTIME_H
79411#define SQLITE_HWTIME_H
79412
79413/*
79414** The following routine only works on pentium-class (or newer) processors.
79415** It uses the RDTSC opcode to read the cycle count value out of the
79416** processor and returns that value.  This can be used for high-res
79417** profiling.
79418*/
79419#if (defined(__GNUC__) || defined(_MSC_VER)) && \
79420      (defined(i386) || defined(__i386__) || defined(_M_IX86))
79421
79422  #if defined(__GNUC__)
79423
79424  __inline__ sqlite_uint64 sqlite3Hwtime(void){
79425     unsigned int lo, hi;
79426     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
79427     return (sqlite_uint64)hi << 32 | lo;
79428  }
79429
79430  #elif defined(_MSC_VER)
79431
79432  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
79433     __asm {
79434        rdtsc
79435        ret       ; return value at EDX:EAX
79436     }
79437  }
79438
79439  #endif
79440
79441#elif (defined(__GNUC__) && defined(__x86_64__))
79442
79443  __inline__ sqlite_uint64 sqlite3Hwtime(void){
79444      unsigned long val;
79445      __asm__ __volatile__ ("rdtsc" : "=A" (val));
79446      return val;
79447  }
79448
79449#elif (defined(__GNUC__) && defined(__ppc__))
79450
79451  __inline__ sqlite_uint64 sqlite3Hwtime(void){
79452      unsigned long long retval;
79453      unsigned long junk;
79454      __asm__ __volatile__ ("\n\
79455          1:      mftbu   %1\n\
79456                  mftb    %L0\n\
79457                  mftbu   %0\n\
79458                  cmpw    %0,%1\n\
79459                  bne     1b"
79460                  : "=r" (retval), "=r" (junk));
79461      return retval;
79462  }
79463
79464#else
79465
79466  #error Need implementation of sqlite3Hwtime() for your platform.
79467
79468  /*
79469  ** To compile without implementing sqlite3Hwtime() for your platform,
79470  ** you can remove the above #error and use the following
79471  ** stub function.  You will lose timing support for many
79472  ** of the debugging and testing utilities, but it should at
79473  ** least compile and run.
79474  */
79475SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
79476
79477#endif
79478
79479#endif /* !defined(SQLITE_HWTIME_H) */
79480
79481/************** End of hwtime.h **********************************************/
79482/************** Continuing where we left off in vdbe.c ***********************/
79483
79484#endif
79485
79486#ifndef NDEBUG
79487/*
79488** This function is only called from within an assert() expression. It
79489** checks that the sqlite3.nTransaction variable is correctly set to
79490** the number of non-transaction savepoints currently in the
79491** linked list starting at sqlite3.pSavepoint.
79492**
79493** Usage:
79494**
79495**     assert( checkSavepointCount(db) );
79496*/
79497static int checkSavepointCount(sqlite3 *db){
79498  int n = 0;
79499  Savepoint *p;
79500  for(p=db->pSavepoint; p; p=p->pNext) n++;
79501  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
79502  return 1;
79503}
79504#endif
79505
79506/*
79507** Return the register of pOp->p2 after first preparing it to be
79508** overwritten with an integer value.
79509*/
79510static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
79511  sqlite3VdbeMemSetNull(pOut);
79512  pOut->flags = MEM_Int;
79513  return pOut;
79514}
79515static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
79516  Mem *pOut;
79517  assert( pOp->p2>0 );
79518  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
79519  pOut = &p->aMem[pOp->p2];
79520  memAboutToChange(p, pOut);
79521  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
79522    return out2PrereleaseWithClear(pOut);
79523  }else{
79524    pOut->flags = MEM_Int;
79525    return pOut;
79526  }
79527}
79528
79529
79530/*
79531** Execute as much of a VDBE program as we can.
79532** This is the core of sqlite3_step().
79533*/
79534SQLITE_PRIVATE int sqlite3VdbeExec(
79535  Vdbe *p                    /* The VDBE */
79536){
79537  Op *aOp = p->aOp;          /* Copy of p->aOp */
79538  Op *pOp = aOp;             /* Current operation */
79539#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
79540  Op *pOrigOp;               /* Value of pOp at the top of the loop */
79541#endif
79542#ifdef SQLITE_DEBUG
79543  int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
79544#endif
79545  int rc = SQLITE_OK;        /* Value to return */
79546  sqlite3 *db = p->db;       /* The database */
79547  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
79548  u8 encoding = ENC(db);     /* The database encoding */
79549  int iCompare = 0;          /* Result of last comparison */
79550  unsigned nVmStep = 0;      /* Number of virtual machine steps */
79551#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
79552  unsigned nProgressLimit;   /* Invoke xProgress() when nVmStep reaches this */
79553#endif
79554  Mem *aMem = p->aMem;       /* Copy of p->aMem */
79555  Mem *pIn1 = 0;             /* 1st input operand */
79556  Mem *pIn2 = 0;             /* 2nd input operand */
79557  Mem *pIn3 = 0;             /* 3rd input operand */
79558  Mem *pOut = 0;             /* Output operand */
79559#ifdef VDBE_PROFILE
79560  u64 start;                 /* CPU clock count at start of opcode */
79561#endif
79562  /*** INSERT STACK UNION HERE ***/
79563
79564  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
79565  sqlite3VdbeEnter(p);
79566  if( p->rc==SQLITE_NOMEM ){
79567    /* This happens if a malloc() inside a call to sqlite3_column_text() or
79568    ** sqlite3_column_text16() failed.  */
79569    goto no_mem;
79570  }
79571  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
79572  assert( p->bIsReader || p->readOnly!=0 );
79573  p->iCurrentTime = 0;
79574  assert( p->explain==0 );
79575  p->pResultSet = 0;
79576  db->busyHandler.nBusy = 0;
79577  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
79578  sqlite3VdbeIOTraceSql(p);
79579#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
79580  if( db->xProgress ){
79581    u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
79582    assert( 0 < db->nProgressOps );
79583    nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
79584  }else{
79585    nProgressLimit = 0xffffffff;
79586  }
79587#endif
79588#ifdef SQLITE_DEBUG
79589  sqlite3BeginBenignMalloc();
79590  if( p->pc==0
79591   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
79592  ){
79593    int i;
79594    int once = 1;
79595    sqlite3VdbePrintSql(p);
79596    if( p->db->flags & SQLITE_VdbeListing ){
79597      printf("VDBE Program Listing:\n");
79598      for(i=0; i<p->nOp; i++){
79599        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
79600      }
79601    }
79602    if( p->db->flags & SQLITE_VdbeEQP ){
79603      for(i=0; i<p->nOp; i++){
79604        if( aOp[i].opcode==OP_Explain ){
79605          if( once ) printf("VDBE Query Plan:\n");
79606          printf("%s\n", aOp[i].p4.z);
79607          once = 0;
79608        }
79609      }
79610    }
79611    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
79612  }
79613  sqlite3EndBenignMalloc();
79614#endif
79615  for(pOp=&aOp[p->pc]; 1; pOp++){
79616    /* Errors are detected by individual opcodes, with an immediate
79617    ** jumps to abort_due_to_error. */
79618    assert( rc==SQLITE_OK );
79619
79620    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
79621#ifdef VDBE_PROFILE
79622    start = sqlite3Hwtime();
79623#endif
79624    nVmStep++;
79625#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
79626    if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
79627#endif
79628
79629    /* Only allow tracing if SQLITE_DEBUG is defined.
79630    */
79631#ifdef SQLITE_DEBUG
79632    if( db->flags & SQLITE_VdbeTrace ){
79633      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
79634    }
79635#endif
79636
79637
79638    /* Check to see if we need to simulate an interrupt.  This only happens
79639    ** if we have a special test build.
79640    */
79641#ifdef SQLITE_TEST
79642    if( sqlite3_interrupt_count>0 ){
79643      sqlite3_interrupt_count--;
79644      if( sqlite3_interrupt_count==0 ){
79645        sqlite3_interrupt(db);
79646      }
79647    }
79648#endif
79649
79650    /* Sanity checking on other operands */
79651#ifdef SQLITE_DEBUG
79652    {
79653      u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
79654      if( (opProperty & OPFLG_IN1)!=0 ){
79655        assert( pOp->p1>0 );
79656        assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
79657        assert( memIsValid(&aMem[pOp->p1]) );
79658        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
79659        REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
79660      }
79661      if( (opProperty & OPFLG_IN2)!=0 ){
79662        assert( pOp->p2>0 );
79663        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
79664        assert( memIsValid(&aMem[pOp->p2]) );
79665        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
79666        REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
79667      }
79668      if( (opProperty & OPFLG_IN3)!=0 ){
79669        assert( pOp->p3>0 );
79670        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
79671        assert( memIsValid(&aMem[pOp->p3]) );
79672        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
79673        REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
79674      }
79675      if( (opProperty & OPFLG_OUT2)!=0 ){
79676        assert( pOp->p2>0 );
79677        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
79678        memAboutToChange(p, &aMem[pOp->p2]);
79679      }
79680      if( (opProperty & OPFLG_OUT3)!=0 ){
79681        assert( pOp->p3>0 );
79682        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
79683        memAboutToChange(p, &aMem[pOp->p3]);
79684      }
79685    }
79686#endif
79687#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
79688    pOrigOp = pOp;
79689#endif
79690
79691    switch( pOp->opcode ){
79692
79693/*****************************************************************************
79694** What follows is a massive switch statement where each case implements a
79695** separate instruction in the virtual machine.  If we follow the usual
79696** indentation conventions, each case should be indented by 6 spaces.  But
79697** that is a lot of wasted space on the left margin.  So the code within
79698** the switch statement will break with convention and be flush-left. Another
79699** big comment (similar to this one) will mark the point in the code where
79700** we transition back to normal indentation.
79701**
79702** The formatting of each case is important.  The makefile for SQLite
79703** generates two C files "opcodes.h" and "opcodes.c" by scanning this
79704** file looking for lines that begin with "case OP_".  The opcodes.h files
79705** will be filled with #defines that give unique integer values to each
79706** opcode and the opcodes.c file is filled with an array of strings where
79707** each string is the symbolic name for the corresponding opcode.  If the
79708** case statement is followed by a comment of the form "/# same as ... #/"
79709** that comment is used to determine the particular value of the opcode.
79710**
79711** Other keywords in the comment that follows each case are used to
79712** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
79713** Keywords include: in1, in2, in3, out2, out3.  See
79714** the mkopcodeh.awk script for additional information.
79715**
79716** Documentation about VDBE opcodes is generated by scanning this file
79717** for lines of that contain "Opcode:".  That line and all subsequent
79718** comment lines are used in the generation of the opcode.html documentation
79719** file.
79720**
79721** SUMMARY:
79722**
79723**     Formatting is important to scripts that scan this file.
79724**     Do not deviate from the formatting style currently in use.
79725**
79726*****************************************************************************/
79727
79728/* Opcode:  Goto * P2 * * *
79729**
79730** An unconditional jump to address P2.
79731** The next instruction executed will be
79732** the one at index P2 from the beginning of
79733** the program.
79734**
79735** The P1 parameter is not actually used by this opcode.  However, it
79736** is sometimes set to 1 instead of 0 as a hint to the command-line shell
79737** that this Goto is the bottom of a loop and that the lines from P2 down
79738** to the current line should be indented for EXPLAIN output.
79739*/
79740case OP_Goto: {             /* jump */
79741jump_to_p2_and_check_for_interrupt:
79742  pOp = &aOp[pOp->p2 - 1];
79743
79744  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
79745  ** OP_VNext, or OP_SorterNext) all jump here upon
79746  ** completion.  Check to see if sqlite3_interrupt() has been called
79747  ** or if the progress callback needs to be invoked.
79748  **
79749  ** This code uses unstructured "goto" statements and does not look clean.
79750  ** But that is not due to sloppy coding habits. The code is written this
79751  ** way for performance, to avoid having to run the interrupt and progress
79752  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
79753  ** faster according to "valgrind --tool=cachegrind" */
79754check_for_interrupt:
79755  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
79756#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
79757  /* Call the progress callback if it is configured and the required number
79758  ** of VDBE ops have been executed (either since this invocation of
79759  ** sqlite3VdbeExec() or since last time the progress callback was called).
79760  ** If the progress callback returns non-zero, exit the virtual machine with
79761  ** a return code SQLITE_ABORT.
79762  */
79763  if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
79764    assert( db->nProgressOps!=0 );
79765    nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
79766    if( db->xProgress(db->pProgressArg) ){
79767      rc = SQLITE_INTERRUPT;
79768      goto abort_due_to_error;
79769    }
79770  }
79771#endif
79772
79773  break;
79774}
79775
79776/* Opcode:  Gosub P1 P2 * * *
79777**
79778** Write the current address onto register P1
79779** and then jump to address P2.
79780*/
79781case OP_Gosub: {            /* jump */
79782  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
79783  pIn1 = &aMem[pOp->p1];
79784  assert( VdbeMemDynamic(pIn1)==0 );
79785  memAboutToChange(p, pIn1);
79786  pIn1->flags = MEM_Int;
79787  pIn1->u.i = (int)(pOp-aOp);
79788  REGISTER_TRACE(pOp->p1, pIn1);
79789
79790  /* Most jump operations do a goto to this spot in order to update
79791  ** the pOp pointer. */
79792jump_to_p2:
79793  pOp = &aOp[pOp->p2 - 1];
79794  break;
79795}
79796
79797/* Opcode:  Return P1 * * * *
79798**
79799** Jump to the next instruction after the address in register P1.  After
79800** the jump, register P1 becomes undefined.
79801*/
79802case OP_Return: {           /* in1 */
79803  pIn1 = &aMem[pOp->p1];
79804  assert( pIn1->flags==MEM_Int );
79805  pOp = &aOp[pIn1->u.i];
79806  pIn1->flags = MEM_Undefined;
79807  break;
79808}
79809
79810/* Opcode: InitCoroutine P1 P2 P3 * *
79811**
79812** Set up register P1 so that it will Yield to the coroutine
79813** located at address P3.
79814**
79815** If P2!=0 then the coroutine implementation immediately follows
79816** this opcode.  So jump over the coroutine implementation to
79817** address P2.
79818**
79819** See also: EndCoroutine
79820*/
79821case OP_InitCoroutine: {     /* jump */
79822  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
79823  assert( pOp->p2>=0 && pOp->p2<p->nOp );
79824  assert( pOp->p3>=0 && pOp->p3<p->nOp );
79825  pOut = &aMem[pOp->p1];
79826  assert( !VdbeMemDynamic(pOut) );
79827  pOut->u.i = pOp->p3 - 1;
79828  pOut->flags = MEM_Int;
79829  if( pOp->p2 ) goto jump_to_p2;
79830  break;
79831}
79832
79833/* Opcode:  EndCoroutine P1 * * * *
79834**
79835** The instruction at the address in register P1 is a Yield.
79836** Jump to the P2 parameter of that Yield.
79837** After the jump, register P1 becomes undefined.
79838**
79839** See also: InitCoroutine
79840*/
79841case OP_EndCoroutine: {           /* in1 */
79842  VdbeOp *pCaller;
79843  pIn1 = &aMem[pOp->p1];
79844  assert( pIn1->flags==MEM_Int );
79845  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
79846  pCaller = &aOp[pIn1->u.i];
79847  assert( pCaller->opcode==OP_Yield );
79848  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
79849  pOp = &aOp[pCaller->p2 - 1];
79850  pIn1->flags = MEM_Undefined;
79851  break;
79852}
79853
79854/* Opcode:  Yield P1 P2 * * *
79855**
79856** Swap the program counter with the value in register P1.  This
79857** has the effect of yielding to a coroutine.
79858**
79859** If the coroutine that is launched by this instruction ends with
79860** Yield or Return then continue to the next instruction.  But if
79861** the coroutine launched by this instruction ends with
79862** EndCoroutine, then jump to P2 rather than continuing with the
79863** next instruction.
79864**
79865** See also: InitCoroutine
79866*/
79867case OP_Yield: {            /* in1, jump */
79868  int pcDest;
79869  pIn1 = &aMem[pOp->p1];
79870  assert( VdbeMemDynamic(pIn1)==0 );
79871  pIn1->flags = MEM_Int;
79872  pcDest = (int)pIn1->u.i;
79873  pIn1->u.i = (int)(pOp - aOp);
79874  REGISTER_TRACE(pOp->p1, pIn1);
79875  pOp = &aOp[pcDest];
79876  break;
79877}
79878
79879/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
79880** Synopsis: if r[P3]=null halt
79881**
79882** Check the value in register P3.  If it is NULL then Halt using
79883** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
79884** value in register P3 is not NULL, then this routine is a no-op.
79885** The P5 parameter should be 1.
79886*/
79887case OP_HaltIfNull: {      /* in3 */
79888  pIn3 = &aMem[pOp->p3];
79889  if( (pIn3->flags & MEM_Null)==0 ) break;
79890  /* Fall through into OP_Halt */
79891}
79892
79893/* Opcode:  Halt P1 P2 * P4 P5
79894**
79895** Exit immediately.  All open cursors, etc are closed
79896** automatically.
79897**
79898** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
79899** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
79900** For errors, it can be some other value.  If P1!=0 then P2 will determine
79901** whether or not to rollback the current transaction.  Do not rollback
79902** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
79903** then back out all changes that have occurred during this execution of the
79904** VDBE, but do not rollback the transaction.
79905**
79906** If P4 is not null then it is an error message string.
79907**
79908** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
79909**
79910**    0:  (no change)
79911**    1:  NOT NULL contraint failed: P4
79912**    2:  UNIQUE constraint failed: P4
79913**    3:  CHECK constraint failed: P4
79914**    4:  FOREIGN KEY constraint failed: P4
79915**
79916** If P5 is not zero and P4 is NULL, then everything after the ":" is
79917** omitted.
79918**
79919** There is an implied "Halt 0 0 0" instruction inserted at the very end of
79920** every program.  So a jump past the last instruction of the program
79921** is the same as executing Halt.
79922*/
79923case OP_Halt: {
79924  VdbeFrame *pFrame;
79925  int pcx;
79926
79927  pcx = (int)(pOp - aOp);
79928  if( pOp->p1==SQLITE_OK && p->pFrame ){
79929    /* Halt the sub-program. Return control to the parent frame. */
79930    pFrame = p->pFrame;
79931    p->pFrame = pFrame->pParent;
79932    p->nFrame--;
79933    sqlite3VdbeSetChanges(db, p->nChange);
79934    pcx = sqlite3VdbeFrameRestore(pFrame);
79935    if( pOp->p2==OE_Ignore ){
79936      /* Instruction pcx is the OP_Program that invoked the sub-program
79937      ** currently being halted. If the p2 instruction of this OP_Halt
79938      ** instruction is set to OE_Ignore, then the sub-program is throwing
79939      ** an IGNORE exception. In this case jump to the address specified
79940      ** as the p2 of the calling OP_Program.  */
79941      pcx = p->aOp[pcx].p2-1;
79942    }
79943    aOp = p->aOp;
79944    aMem = p->aMem;
79945    pOp = &aOp[pcx];
79946    break;
79947  }
79948  p->rc = pOp->p1;
79949  p->errorAction = (u8)pOp->p2;
79950  p->pc = pcx;
79951  assert( pOp->p5<=4 );
79952  if( p->rc ){
79953    if( pOp->p5 ){
79954      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
79955                                             "FOREIGN KEY" };
79956      testcase( pOp->p5==1 );
79957      testcase( pOp->p5==2 );
79958      testcase( pOp->p5==3 );
79959      testcase( pOp->p5==4 );
79960      sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
79961      if( pOp->p4.z ){
79962        p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
79963      }
79964    }else{
79965      sqlite3VdbeError(p, "%s", pOp->p4.z);
79966    }
79967    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
79968  }
79969  rc = sqlite3VdbeHalt(p);
79970  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
79971  if( rc==SQLITE_BUSY ){
79972    p->rc = SQLITE_BUSY;
79973  }else{
79974    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
79975    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
79976    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
79977  }
79978  goto vdbe_return;
79979}
79980
79981/* Opcode: Integer P1 P2 * * *
79982** Synopsis: r[P2]=P1
79983**
79984** The 32-bit integer value P1 is written into register P2.
79985*/
79986case OP_Integer: {         /* out2 */
79987  pOut = out2Prerelease(p, pOp);
79988  pOut->u.i = pOp->p1;
79989  break;
79990}
79991
79992/* Opcode: Int64 * P2 * P4 *
79993** Synopsis: r[P2]=P4
79994**
79995** P4 is a pointer to a 64-bit integer value.
79996** Write that value into register P2.
79997*/
79998case OP_Int64: {           /* out2 */
79999  pOut = out2Prerelease(p, pOp);
80000  assert( pOp->p4.pI64!=0 );
80001  pOut->u.i = *pOp->p4.pI64;
80002  break;
80003}
80004
80005#ifndef SQLITE_OMIT_FLOATING_POINT
80006/* Opcode: Real * P2 * P4 *
80007** Synopsis: r[P2]=P4
80008**
80009** P4 is a pointer to a 64-bit floating point value.
80010** Write that value into register P2.
80011*/
80012case OP_Real: {            /* same as TK_FLOAT, out2 */
80013  pOut = out2Prerelease(p, pOp);
80014  pOut->flags = MEM_Real;
80015  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
80016  pOut->u.r = *pOp->p4.pReal;
80017  break;
80018}
80019#endif
80020
80021/* Opcode: String8 * P2 * P4 *
80022** Synopsis: r[P2]='P4'
80023**
80024** P4 points to a nul terminated UTF-8 string. This opcode is transformed
80025** into a String opcode before it is executed for the first time.  During
80026** this transformation, the length of string P4 is computed and stored
80027** as the P1 parameter.
80028*/
80029case OP_String8: {         /* same as TK_STRING, out2 */
80030  assert( pOp->p4.z!=0 );
80031  pOut = out2Prerelease(p, pOp);
80032  pOp->opcode = OP_String;
80033  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
80034
80035#ifndef SQLITE_OMIT_UTF16
80036  if( encoding!=SQLITE_UTF8 ){
80037    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
80038    assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
80039    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
80040    assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
80041    assert( VdbeMemDynamic(pOut)==0 );
80042    pOut->szMalloc = 0;
80043    pOut->flags |= MEM_Static;
80044    if( pOp->p4type==P4_DYNAMIC ){
80045      sqlite3DbFree(db, pOp->p4.z);
80046    }
80047    pOp->p4type = P4_DYNAMIC;
80048    pOp->p4.z = pOut->z;
80049    pOp->p1 = pOut->n;
80050  }
80051  testcase( rc==SQLITE_TOOBIG );
80052#endif
80053  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80054    goto too_big;
80055  }
80056  assert( rc==SQLITE_OK );
80057  /* Fall through to the next case, OP_String */
80058}
80059
80060/* Opcode: String P1 P2 P3 P4 P5
80061** Synopsis: r[P2]='P4' (len=P1)
80062**
80063** The string value P4 of length P1 (bytes) is stored in register P2.
80064**
80065** If P3 is not zero and the content of register P3 is equal to P5, then
80066** the datatype of the register P2 is converted to BLOB.  The content is
80067** the same sequence of bytes, it is merely interpreted as a BLOB instead
80068** of a string, as if it had been CAST.  In other words:
80069**
80070** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
80071*/
80072case OP_String: {          /* out2 */
80073  assert( pOp->p4.z!=0 );
80074  pOut = out2Prerelease(p, pOp);
80075  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
80076  pOut->z = pOp->p4.z;
80077  pOut->n = pOp->p1;
80078  pOut->enc = encoding;
80079  UPDATE_MAX_BLOBSIZE(pOut);
80080#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
80081  if( pOp->p3>0 ){
80082    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
80083    pIn3 = &aMem[pOp->p3];
80084    assert( pIn3->flags & MEM_Int );
80085    if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
80086  }
80087#endif
80088  break;
80089}
80090
80091/* Opcode: Null P1 P2 P3 * *
80092** Synopsis: r[P2..P3]=NULL
80093**
80094** Write a NULL into registers P2.  If P3 greater than P2, then also write
80095** NULL into register P3 and every register in between P2 and P3.  If P3
80096** is less than P2 (typically P3 is zero) then only register P2 is
80097** set to NULL.
80098**
80099** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
80100** NULL values will not compare equal even if SQLITE_NULLEQ is set on
80101** OP_Ne or OP_Eq.
80102*/
80103case OP_Null: {           /* out2 */
80104  int cnt;
80105  u16 nullFlag;
80106  pOut = out2Prerelease(p, pOp);
80107  cnt = pOp->p3-pOp->p2;
80108  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
80109  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
80110  pOut->n = 0;
80111  while( cnt>0 ){
80112    pOut++;
80113    memAboutToChange(p, pOut);
80114    sqlite3VdbeMemSetNull(pOut);
80115    pOut->flags = nullFlag;
80116    pOut->n = 0;
80117    cnt--;
80118  }
80119  break;
80120}
80121
80122/* Opcode: SoftNull P1 * * * *
80123** Synopsis: r[P1]=NULL
80124**
80125** Set register P1 to have the value NULL as seen by the OP_MakeRecord
80126** instruction, but do not free any string or blob memory associated with
80127** the register, so that if the value was a string or blob that was
80128** previously copied using OP_SCopy, the copies will continue to be valid.
80129*/
80130case OP_SoftNull: {
80131  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
80132  pOut = &aMem[pOp->p1];
80133  pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
80134  break;
80135}
80136
80137/* Opcode: Blob P1 P2 * P4 *
80138** Synopsis: r[P2]=P4 (len=P1)
80139**
80140** P4 points to a blob of data P1 bytes long.  Store this
80141** blob in register P2.
80142*/
80143case OP_Blob: {                /* out2 */
80144  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
80145  pOut = out2Prerelease(p, pOp);
80146  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
80147  pOut->enc = encoding;
80148  UPDATE_MAX_BLOBSIZE(pOut);
80149  break;
80150}
80151
80152/* Opcode: Variable P1 P2 * P4 *
80153** Synopsis: r[P2]=parameter(P1,P4)
80154**
80155** Transfer the values of bound parameter P1 into register P2
80156**
80157** If the parameter is named, then its name appears in P4.
80158** The P4 value is used by sqlite3_bind_parameter_name().
80159*/
80160case OP_Variable: {            /* out2 */
80161  Mem *pVar;       /* Value being transferred */
80162
80163  assert( pOp->p1>0 && pOp->p1<=p->nVar );
80164  assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
80165  pVar = &p->aVar[pOp->p1 - 1];
80166  if( sqlite3VdbeMemTooBig(pVar) ){
80167    goto too_big;
80168  }
80169  pOut = &aMem[pOp->p2];
80170  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
80171  UPDATE_MAX_BLOBSIZE(pOut);
80172  break;
80173}
80174
80175/* Opcode: Move P1 P2 P3 * *
80176** Synopsis: r[P2@P3]=r[P1@P3]
80177**
80178** Move the P3 values in register P1..P1+P3-1 over into
80179** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
80180** left holding a NULL.  It is an error for register ranges
80181** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
80182** for P3 to be less than 1.
80183*/
80184case OP_Move: {
80185  int n;           /* Number of registers left to copy */
80186  int p1;          /* Register to copy from */
80187  int p2;          /* Register to copy to */
80188
80189  n = pOp->p3;
80190  p1 = pOp->p1;
80191  p2 = pOp->p2;
80192  assert( n>0 && p1>0 && p2>0 );
80193  assert( p1+n<=p2 || p2+n<=p1 );
80194
80195  pIn1 = &aMem[p1];
80196  pOut = &aMem[p2];
80197  do{
80198    assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
80199    assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
80200    assert( memIsValid(pIn1) );
80201    memAboutToChange(p, pOut);
80202    sqlite3VdbeMemMove(pOut, pIn1);
80203#ifdef SQLITE_DEBUG
80204    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
80205      pOut->pScopyFrom += pOp->p2 - p1;
80206    }
80207#endif
80208    Deephemeralize(pOut);
80209    REGISTER_TRACE(p2++, pOut);
80210    pIn1++;
80211    pOut++;
80212  }while( --n );
80213  break;
80214}
80215
80216/* Opcode: Copy P1 P2 P3 * *
80217** Synopsis: r[P2@P3+1]=r[P1@P3+1]
80218**
80219** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
80220**
80221** This instruction makes a deep copy of the value.  A duplicate
80222** is made of any string or blob constant.  See also OP_SCopy.
80223*/
80224case OP_Copy: {
80225  int n;
80226
80227  n = pOp->p3;
80228  pIn1 = &aMem[pOp->p1];
80229  pOut = &aMem[pOp->p2];
80230  assert( pOut!=pIn1 );
80231  while( 1 ){
80232    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
80233    Deephemeralize(pOut);
80234#ifdef SQLITE_DEBUG
80235    pOut->pScopyFrom = 0;
80236#endif
80237    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
80238    if( (n--)==0 ) break;
80239    pOut++;
80240    pIn1++;
80241  }
80242  break;
80243}
80244
80245/* Opcode: SCopy P1 P2 * * *
80246** Synopsis: r[P2]=r[P1]
80247**
80248** Make a shallow copy of register P1 into register P2.
80249**
80250** This instruction makes a shallow copy of the value.  If the value
80251** is a string or blob, then the copy is only a pointer to the
80252** original and hence if the original changes so will the copy.
80253** Worse, if the original is deallocated, the copy becomes invalid.
80254** Thus the program must guarantee that the original will not change
80255** during the lifetime of the copy.  Use OP_Copy to make a complete
80256** copy.
80257*/
80258case OP_SCopy: {            /* out2 */
80259  pIn1 = &aMem[pOp->p1];
80260  pOut = &aMem[pOp->p2];
80261  assert( pOut!=pIn1 );
80262  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
80263#ifdef SQLITE_DEBUG
80264  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
80265#endif
80266  break;
80267}
80268
80269/* Opcode: IntCopy P1 P2 * * *
80270** Synopsis: r[P2]=r[P1]
80271**
80272** Transfer the integer value held in register P1 into register P2.
80273**
80274** This is an optimized version of SCopy that works only for integer
80275** values.
80276*/
80277case OP_IntCopy: {            /* out2 */
80278  pIn1 = &aMem[pOp->p1];
80279  assert( (pIn1->flags & MEM_Int)!=0 );
80280  pOut = &aMem[pOp->p2];
80281  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
80282  break;
80283}
80284
80285/* Opcode: ResultRow P1 P2 * * *
80286** Synopsis: output=r[P1@P2]
80287**
80288** The registers P1 through P1+P2-1 contain a single row of
80289** results. This opcode causes the sqlite3_step() call to terminate
80290** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
80291** structure to provide access to the r(P1)..r(P1+P2-1) values as
80292** the result row.
80293*/
80294case OP_ResultRow: {
80295  Mem *pMem;
80296  int i;
80297  assert( p->nResColumn==pOp->p2 );
80298  assert( pOp->p1>0 );
80299  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
80300
80301#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
80302  /* Run the progress counter just before returning.
80303  */
80304  if( db->xProgress!=0
80305   && nVmStep>=nProgressLimit
80306   && db->xProgress(db->pProgressArg)!=0
80307  ){
80308    rc = SQLITE_INTERRUPT;
80309    goto abort_due_to_error;
80310  }
80311#endif
80312
80313  /* If this statement has violated immediate foreign key constraints, do
80314  ** not return the number of rows modified. And do not RELEASE the statement
80315  ** transaction. It needs to be rolled back.  */
80316  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
80317    assert( db->flags&SQLITE_CountRows );
80318    assert( p->usesStmtJournal );
80319    goto abort_due_to_error;
80320  }
80321
80322  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
80323  ** DML statements invoke this opcode to return the number of rows
80324  ** modified to the user. This is the only way that a VM that
80325  ** opens a statement transaction may invoke this opcode.
80326  **
80327  ** In case this is such a statement, close any statement transaction
80328  ** opened by this VM before returning control to the user. This is to
80329  ** ensure that statement-transactions are always nested, not overlapping.
80330  ** If the open statement-transaction is not closed here, then the user
80331  ** may step another VM that opens its own statement transaction. This
80332  ** may lead to overlapping statement transactions.
80333  **
80334  ** The statement transaction is never a top-level transaction.  Hence
80335  ** the RELEASE call below can never fail.
80336  */
80337  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
80338  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
80339  assert( rc==SQLITE_OK );
80340
80341  /* Invalidate all ephemeral cursor row caches */
80342  p->cacheCtr = (p->cacheCtr + 2)|1;
80343
80344  /* Make sure the results of the current row are \000 terminated
80345  ** and have an assigned type.  The results are de-ephemeralized as
80346  ** a side effect.
80347  */
80348  pMem = p->pResultSet = &aMem[pOp->p1];
80349  for(i=0; i<pOp->p2; i++){
80350    assert( memIsValid(&pMem[i]) );
80351    Deephemeralize(&pMem[i]);
80352    assert( (pMem[i].flags & MEM_Ephem)==0
80353            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
80354    sqlite3VdbeMemNulTerminate(&pMem[i]);
80355    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
80356  }
80357  if( db->mallocFailed ) goto no_mem;
80358
80359  if( db->mTrace & SQLITE_TRACE_ROW ){
80360    db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
80361  }
80362
80363  /* Return SQLITE_ROW
80364  */
80365  p->pc = (int)(pOp - aOp) + 1;
80366  rc = SQLITE_ROW;
80367  goto vdbe_return;
80368}
80369
80370/* Opcode: Concat P1 P2 P3 * *
80371** Synopsis: r[P3]=r[P2]+r[P1]
80372**
80373** Add the text in register P1 onto the end of the text in
80374** register P2 and store the result in register P3.
80375** If either the P1 or P2 text are NULL then store NULL in P3.
80376**
80377**   P3 = P2 || P1
80378**
80379** It is illegal for P1 and P3 to be the same register. Sometimes,
80380** if P3 is the same register as P2, the implementation is able
80381** to avoid a memcpy().
80382*/
80383case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
80384  i64 nByte;
80385
80386  pIn1 = &aMem[pOp->p1];
80387  pIn2 = &aMem[pOp->p2];
80388  pOut = &aMem[pOp->p3];
80389  assert( pIn1!=pOut );
80390  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
80391    sqlite3VdbeMemSetNull(pOut);
80392    break;
80393  }
80394  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
80395  Stringify(pIn1, encoding);
80396  Stringify(pIn2, encoding);
80397  nByte = pIn1->n + pIn2->n;
80398  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80399    goto too_big;
80400  }
80401  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
80402    goto no_mem;
80403  }
80404  MemSetTypeFlag(pOut, MEM_Str);
80405  if( pOut!=pIn2 ){
80406    memcpy(pOut->z, pIn2->z, pIn2->n);
80407  }
80408  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
80409  pOut->z[nByte]=0;
80410  pOut->z[nByte+1] = 0;
80411  pOut->flags |= MEM_Term;
80412  pOut->n = (int)nByte;
80413  pOut->enc = encoding;
80414  UPDATE_MAX_BLOBSIZE(pOut);
80415  break;
80416}
80417
80418/* Opcode: Add P1 P2 P3 * *
80419** Synopsis: r[P3]=r[P1]+r[P2]
80420**
80421** Add the value in register P1 to the value in register P2
80422** and store the result in register P3.
80423** If either input is NULL, the result is NULL.
80424*/
80425/* Opcode: Multiply P1 P2 P3 * *
80426** Synopsis: r[P3]=r[P1]*r[P2]
80427**
80428**
80429** Multiply the value in register P1 by the value in register P2
80430** and store the result in register P3.
80431** If either input is NULL, the result is NULL.
80432*/
80433/* Opcode: Subtract P1 P2 P3 * *
80434** Synopsis: r[P3]=r[P2]-r[P1]
80435**
80436** Subtract the value in register P1 from the value in register P2
80437** and store the result in register P3.
80438** If either input is NULL, the result is NULL.
80439*/
80440/* Opcode: Divide P1 P2 P3 * *
80441** Synopsis: r[P3]=r[P2]/r[P1]
80442**
80443** Divide the value in register P1 by the value in register P2
80444** and store the result in register P3 (P3=P2/P1). If the value in
80445** register P1 is zero, then the result is NULL. If either input is
80446** NULL, the result is NULL.
80447*/
80448/* Opcode: Remainder P1 P2 P3 * *
80449** Synopsis: r[P3]=r[P2]%r[P1]
80450**
80451** Compute the remainder after integer register P2 is divided by
80452** register P1 and store the result in register P3.
80453** If the value in register P1 is zero the result is NULL.
80454** If either operand is NULL, the result is NULL.
80455*/
80456case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
80457case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
80458case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
80459case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
80460case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
80461  char bIntint;   /* Started out as two integer operands */
80462  u16 flags;      /* Combined MEM_* flags from both inputs */
80463  u16 type1;      /* Numeric type of left operand */
80464  u16 type2;      /* Numeric type of right operand */
80465  i64 iA;         /* Integer value of left operand */
80466  i64 iB;         /* Integer value of right operand */
80467  double rA;      /* Real value of left operand */
80468  double rB;      /* Real value of right operand */
80469
80470  pIn1 = &aMem[pOp->p1];
80471  type1 = numericType(pIn1);
80472  pIn2 = &aMem[pOp->p2];
80473  type2 = numericType(pIn2);
80474  pOut = &aMem[pOp->p3];
80475  flags = pIn1->flags | pIn2->flags;
80476  if( (type1 & type2 & MEM_Int)!=0 ){
80477    iA = pIn1->u.i;
80478    iB = pIn2->u.i;
80479    bIntint = 1;
80480    switch( pOp->opcode ){
80481      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
80482      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
80483      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
80484      case OP_Divide: {
80485        if( iA==0 ) goto arithmetic_result_is_null;
80486        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
80487        iB /= iA;
80488        break;
80489      }
80490      default: {
80491        if( iA==0 ) goto arithmetic_result_is_null;
80492        if( iA==-1 ) iA = 1;
80493        iB %= iA;
80494        break;
80495      }
80496    }
80497    pOut->u.i = iB;
80498    MemSetTypeFlag(pOut, MEM_Int);
80499  }else if( (flags & MEM_Null)!=0 ){
80500    goto arithmetic_result_is_null;
80501  }else{
80502    bIntint = 0;
80503fp_math:
80504    rA = sqlite3VdbeRealValue(pIn1);
80505    rB = sqlite3VdbeRealValue(pIn2);
80506    switch( pOp->opcode ){
80507      case OP_Add:         rB += rA;       break;
80508      case OP_Subtract:    rB -= rA;       break;
80509      case OP_Multiply:    rB *= rA;       break;
80510      case OP_Divide: {
80511        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
80512        if( rA==(double)0 ) goto arithmetic_result_is_null;
80513        rB /= rA;
80514        break;
80515      }
80516      default: {
80517        iA = (i64)rA;
80518        iB = (i64)rB;
80519        if( iA==0 ) goto arithmetic_result_is_null;
80520        if( iA==-1 ) iA = 1;
80521        rB = (double)(iB % iA);
80522        break;
80523      }
80524    }
80525#ifdef SQLITE_OMIT_FLOATING_POINT
80526    pOut->u.i = rB;
80527    MemSetTypeFlag(pOut, MEM_Int);
80528#else
80529    if( sqlite3IsNaN(rB) ){
80530      goto arithmetic_result_is_null;
80531    }
80532    pOut->u.r = rB;
80533    MemSetTypeFlag(pOut, MEM_Real);
80534    if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
80535      sqlite3VdbeIntegerAffinity(pOut);
80536    }
80537#endif
80538  }
80539  break;
80540
80541arithmetic_result_is_null:
80542  sqlite3VdbeMemSetNull(pOut);
80543  break;
80544}
80545
80546/* Opcode: CollSeq P1 * * P4
80547**
80548** P4 is a pointer to a CollSeq object. If the next call to a user function
80549** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
80550** be returned. This is used by the built-in min(), max() and nullif()
80551** functions.
80552**
80553** If P1 is not zero, then it is a register that a subsequent min() or
80554** max() aggregate will set to 1 if the current row is not the minimum or
80555** maximum.  The P1 register is initialized to 0 by this instruction.
80556**
80557** The interface used by the implementation of the aforementioned functions
80558** to retrieve the collation sequence set by this opcode is not available
80559** publicly.  Only built-in functions have access to this feature.
80560*/
80561case OP_CollSeq: {
80562  assert( pOp->p4type==P4_COLLSEQ );
80563  if( pOp->p1 ){
80564    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
80565  }
80566  break;
80567}
80568
80569/* Opcode: BitAnd P1 P2 P3 * *
80570** Synopsis: r[P3]=r[P1]&r[P2]
80571**
80572** Take the bit-wise AND of the values in register P1 and P2 and
80573** store the result in register P3.
80574** If either input is NULL, the result is NULL.
80575*/
80576/* Opcode: BitOr P1 P2 P3 * *
80577** Synopsis: r[P3]=r[P1]|r[P2]
80578**
80579** Take the bit-wise OR of the values in register P1 and P2 and
80580** store the result in register P3.
80581** If either input is NULL, the result is NULL.
80582*/
80583/* Opcode: ShiftLeft P1 P2 P3 * *
80584** Synopsis: r[P3]=r[P2]<<r[P1]
80585**
80586** Shift the integer value in register P2 to the left by the
80587** number of bits specified by the integer in register P1.
80588** Store the result in register P3.
80589** If either input is NULL, the result is NULL.
80590*/
80591/* Opcode: ShiftRight P1 P2 P3 * *
80592** Synopsis: r[P3]=r[P2]>>r[P1]
80593**
80594** Shift the integer value in register P2 to the right by the
80595** number of bits specified by the integer in register P1.
80596** Store the result in register P3.
80597** If either input is NULL, the result is NULL.
80598*/
80599case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
80600case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
80601case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
80602case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
80603  i64 iA;
80604  u64 uA;
80605  i64 iB;
80606  u8 op;
80607
80608  pIn1 = &aMem[pOp->p1];
80609  pIn2 = &aMem[pOp->p2];
80610  pOut = &aMem[pOp->p3];
80611  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
80612    sqlite3VdbeMemSetNull(pOut);
80613    break;
80614  }
80615  iA = sqlite3VdbeIntValue(pIn2);
80616  iB = sqlite3VdbeIntValue(pIn1);
80617  op = pOp->opcode;
80618  if( op==OP_BitAnd ){
80619    iA &= iB;
80620  }else if( op==OP_BitOr ){
80621    iA |= iB;
80622  }else if( iB!=0 ){
80623    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
80624
80625    /* If shifting by a negative amount, shift in the other direction */
80626    if( iB<0 ){
80627      assert( OP_ShiftRight==OP_ShiftLeft+1 );
80628      op = 2*OP_ShiftLeft + 1 - op;
80629      iB = iB>(-64) ? -iB : 64;
80630    }
80631
80632    if( iB>=64 ){
80633      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
80634    }else{
80635      memcpy(&uA, &iA, sizeof(uA));
80636      if( op==OP_ShiftLeft ){
80637        uA <<= iB;
80638      }else{
80639        uA >>= iB;
80640        /* Sign-extend on a right shift of a negative number */
80641        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
80642      }
80643      memcpy(&iA, &uA, sizeof(iA));
80644    }
80645  }
80646  pOut->u.i = iA;
80647  MemSetTypeFlag(pOut, MEM_Int);
80648  break;
80649}
80650
80651/* Opcode: AddImm  P1 P2 * * *
80652** Synopsis: r[P1]=r[P1]+P2
80653**
80654** Add the constant P2 to the value in register P1.
80655** The result is always an integer.
80656**
80657** To force any register to be an integer, just add 0.
80658*/
80659case OP_AddImm: {            /* in1 */
80660  pIn1 = &aMem[pOp->p1];
80661  memAboutToChange(p, pIn1);
80662  sqlite3VdbeMemIntegerify(pIn1);
80663  pIn1->u.i += pOp->p2;
80664  break;
80665}
80666
80667/* Opcode: MustBeInt P1 P2 * * *
80668**
80669** Force the value in register P1 to be an integer.  If the value
80670** in P1 is not an integer and cannot be converted into an integer
80671** without data loss, then jump immediately to P2, or if P2==0
80672** raise an SQLITE_MISMATCH exception.
80673*/
80674case OP_MustBeInt: {            /* jump, in1 */
80675  pIn1 = &aMem[pOp->p1];
80676  if( (pIn1->flags & MEM_Int)==0 ){
80677    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
80678    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
80679    if( (pIn1->flags & MEM_Int)==0 ){
80680      if( pOp->p2==0 ){
80681        rc = SQLITE_MISMATCH;
80682        goto abort_due_to_error;
80683      }else{
80684        goto jump_to_p2;
80685      }
80686    }
80687  }
80688  MemSetTypeFlag(pIn1, MEM_Int);
80689  break;
80690}
80691
80692#ifndef SQLITE_OMIT_FLOATING_POINT
80693/* Opcode: RealAffinity P1 * * * *
80694**
80695** If register P1 holds an integer convert it to a real value.
80696**
80697** This opcode is used when extracting information from a column that
80698** has REAL affinity.  Such column values may still be stored as
80699** integers, for space efficiency, but after extraction we want them
80700** to have only a real value.
80701*/
80702case OP_RealAffinity: {                  /* in1 */
80703  pIn1 = &aMem[pOp->p1];
80704  if( pIn1->flags & MEM_Int ){
80705    sqlite3VdbeMemRealify(pIn1);
80706  }
80707  break;
80708}
80709#endif
80710
80711#ifndef SQLITE_OMIT_CAST
80712/* Opcode: Cast P1 P2 * * *
80713** Synopsis: affinity(r[P1])
80714**
80715** Force the value in register P1 to be the type defined by P2.
80716**
80717** <ul>
80718** <li> P2=='A' &rarr; BLOB
80719** <li> P2=='B' &rarr; TEXT
80720** <li> P2=='C' &rarr; NUMERIC
80721** <li> P2=='D' &rarr; INTEGER
80722** <li> P2=='E' &rarr; REAL
80723** </ul>
80724**
80725** A NULL value is not changed by this routine.  It remains NULL.
80726*/
80727case OP_Cast: {                  /* in1 */
80728  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
80729  testcase( pOp->p2==SQLITE_AFF_TEXT );
80730  testcase( pOp->p2==SQLITE_AFF_BLOB );
80731  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
80732  testcase( pOp->p2==SQLITE_AFF_INTEGER );
80733  testcase( pOp->p2==SQLITE_AFF_REAL );
80734  pIn1 = &aMem[pOp->p1];
80735  memAboutToChange(p, pIn1);
80736  rc = ExpandBlob(pIn1);
80737  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
80738  UPDATE_MAX_BLOBSIZE(pIn1);
80739  if( rc ) goto abort_due_to_error;
80740  break;
80741}
80742#endif /* SQLITE_OMIT_CAST */
80743
80744/* Opcode: Eq P1 P2 P3 P4 P5
80745** Synopsis: IF r[P3]==r[P1]
80746**
80747** Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
80748** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5, then
80749** store the result of comparison in register P2.
80750**
80751** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
80752** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
80753** to coerce both inputs according to this affinity before the
80754** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
80755** affinity is used. Note that the affinity conversions are stored
80756** back into the input registers P1 and P3.  So this opcode can cause
80757** persistent changes to registers P1 and P3.
80758**
80759** Once any conversions have taken place, and neither value is NULL,
80760** the values are compared. If both values are blobs then memcmp() is
80761** used to determine the results of the comparison.  If both values
80762** are text, then the appropriate collating function specified in
80763** P4 is used to do the comparison.  If P4 is not specified then
80764** memcmp() is used to compare text string.  If both values are
80765** numeric, then a numeric comparison is used. If the two values
80766** are of different types, then numbers are considered less than
80767** strings and strings are considered less than blobs.
80768**
80769** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
80770** true or false and is never NULL.  If both operands are NULL then the result
80771** of comparison is true.  If either operand is NULL then the result is false.
80772** If neither operand is NULL the result is the same as it would be if
80773** the SQLITE_NULLEQ flag were omitted from P5.
80774**
80775** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
80776** content of r[P2] is only changed if the new value is NULL or 0 (false).
80777** In other words, a prior r[P2] value will not be overwritten by 1 (true).
80778*/
80779/* Opcode: Ne P1 P2 P3 P4 P5
80780** Synopsis: IF r[P3]!=r[P1]
80781**
80782** This works just like the Eq opcode except that the jump is taken if
80783** the operands in registers P1 and P3 are not equal.  See the Eq opcode for
80784** additional information.
80785**
80786** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
80787** content of r[P2] is only changed if the new value is NULL or 1 (true).
80788** In other words, a prior r[P2] value will not be overwritten by 0 (false).
80789*/
80790/* Opcode: Lt P1 P2 P3 P4 P5
80791** Synopsis: IF r[P3]<r[P1]
80792**
80793** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
80794** jump to address P2.  Or if the SQLITE_STOREP2 flag is set in P5 store
80795** the result of comparison (0 or 1 or NULL) into register P2.
80796**
80797** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
80798** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL
80799** bit is clear then fall through if either operand is NULL.
80800**
80801** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
80802** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
80803** to coerce both inputs according to this affinity before the
80804** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
80805** affinity is used. Note that the affinity conversions are stored
80806** back into the input registers P1 and P3.  So this opcode can cause
80807** persistent changes to registers P1 and P3.
80808**
80809** Once any conversions have taken place, and neither value is NULL,
80810** the values are compared. If both values are blobs then memcmp() is
80811** used to determine the results of the comparison.  If both values
80812** are text, then the appropriate collating function specified in
80813** P4 is  used to do the comparison.  If P4 is not specified then
80814** memcmp() is used to compare text string.  If both values are
80815** numeric, then a numeric comparison is used. If the two values
80816** are of different types, then numbers are considered less than
80817** strings and strings are considered less than blobs.
80818*/
80819/* Opcode: Le P1 P2 P3 P4 P5
80820** Synopsis: IF r[P3]<=r[P1]
80821**
80822** This works just like the Lt opcode except that the jump is taken if
80823** the content of register P3 is less than or equal to the content of
80824** register P1.  See the Lt opcode for additional information.
80825*/
80826/* Opcode: Gt P1 P2 P3 P4 P5
80827** Synopsis: IF r[P3]>r[P1]
80828**
80829** This works just like the Lt opcode except that the jump is taken if
80830** the content of register P3 is greater than the content of
80831** register P1.  See the Lt opcode for additional information.
80832*/
80833/* Opcode: Ge P1 P2 P3 P4 P5
80834** Synopsis: IF r[P3]>=r[P1]
80835**
80836** This works just like the Lt opcode except that the jump is taken if
80837** the content of register P3 is greater than or equal to the content of
80838** register P1.  See the Lt opcode for additional information.
80839*/
80840case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
80841case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
80842case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
80843case OP_Le:               /* same as TK_LE, jump, in1, in3 */
80844case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
80845case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
80846  int res, res2;      /* Result of the comparison of pIn1 against pIn3 */
80847  char affinity;      /* Affinity to use for comparison */
80848  u16 flags1;         /* Copy of initial value of pIn1->flags */
80849  u16 flags3;         /* Copy of initial value of pIn3->flags */
80850
80851  pIn1 = &aMem[pOp->p1];
80852  pIn3 = &aMem[pOp->p3];
80853  flags1 = pIn1->flags;
80854  flags3 = pIn3->flags;
80855  if( (flags1 | flags3)&MEM_Null ){
80856    /* One or both operands are NULL */
80857    if( pOp->p5 & SQLITE_NULLEQ ){
80858      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
80859      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
80860      ** or not both operands are null.
80861      */
80862      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
80863      assert( (flags1 & MEM_Cleared)==0 );
80864      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
80865      if( (flags1&flags3&MEM_Null)!=0
80866       && (flags3&MEM_Cleared)==0
80867      ){
80868        res = 0;  /* Operands are equal */
80869      }else{
80870        res = 1;  /* Operands are not equal */
80871      }
80872    }else{
80873      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
80874      ** then the result is always NULL.
80875      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
80876      */
80877      if( pOp->p5 & SQLITE_STOREP2 ){
80878        pOut = &aMem[pOp->p2];
80879        iCompare = 1;    /* Operands are not equal */
80880        memAboutToChange(p, pOut);
80881        MemSetTypeFlag(pOut, MEM_Null);
80882        REGISTER_TRACE(pOp->p2, pOut);
80883      }else{
80884        VdbeBranchTaken(2,3);
80885        if( pOp->p5 & SQLITE_JUMPIFNULL ){
80886          goto jump_to_p2;
80887        }
80888      }
80889      break;
80890    }
80891  }else{
80892    /* Neither operand is NULL.  Do a comparison. */
80893    affinity = pOp->p5 & SQLITE_AFF_MASK;
80894    if( affinity>=SQLITE_AFF_NUMERIC ){
80895      if( (flags1 | flags3)&MEM_Str ){
80896        if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
80897          applyNumericAffinity(pIn1,0);
80898          testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
80899          flags3 = pIn3->flags;
80900        }
80901        if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
80902          applyNumericAffinity(pIn3,0);
80903        }
80904      }
80905      /* Handle the common case of integer comparison here, as an
80906      ** optimization, to avoid a call to sqlite3MemCompare() */
80907      if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
80908        if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
80909        if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
80910        res = 0;
80911        goto compare_op;
80912      }
80913    }else if( affinity==SQLITE_AFF_TEXT ){
80914      if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
80915        testcase( pIn1->flags & MEM_Int );
80916        testcase( pIn1->flags & MEM_Real );
80917        sqlite3VdbeMemStringify(pIn1, encoding, 1);
80918        testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
80919        flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
80920        assert( pIn1!=pIn3 );
80921      }
80922      if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
80923        testcase( pIn3->flags & MEM_Int );
80924        testcase( pIn3->flags & MEM_Real );
80925        sqlite3VdbeMemStringify(pIn3, encoding, 1);
80926        testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
80927        flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
80928      }
80929    }
80930    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
80931    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
80932  }
80933compare_op:
80934  switch( pOp->opcode ){
80935    case OP_Eq:    res2 = res==0;     break;
80936    case OP_Ne:    res2 = res;        break;
80937    case OP_Lt:    res2 = res<0;      break;
80938    case OP_Le:    res2 = res<=0;     break;
80939    case OP_Gt:    res2 = res>0;      break;
80940    default:       res2 = res>=0;     break;
80941  }
80942
80943  /* Undo any changes made by applyAffinity() to the input registers. */
80944  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
80945  pIn1->flags = flags1;
80946  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
80947  pIn3->flags = flags3;
80948
80949  if( pOp->p5 & SQLITE_STOREP2 ){
80950    pOut = &aMem[pOp->p2];
80951    iCompare = res;
80952    res2 = res2!=0;  /* For this path res2 must be exactly 0 or 1 */
80953    if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
80954      /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
80955      ** and prevents OP_Ne from overwriting NULL with 0.  This flag
80956      ** is only used in contexts where either:
80957      **   (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
80958      **   (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
80959      ** Therefore it is not necessary to check the content of r[P2] for
80960      ** NULL. */
80961      assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
80962      assert( res2==0 || res2==1 );
80963      testcase( res2==0 && pOp->opcode==OP_Eq );
80964      testcase( res2==1 && pOp->opcode==OP_Eq );
80965      testcase( res2==0 && pOp->opcode==OP_Ne );
80966      testcase( res2==1 && pOp->opcode==OP_Ne );
80967      if( (pOp->opcode==OP_Eq)==res2 ) break;
80968    }
80969    memAboutToChange(p, pOut);
80970    MemSetTypeFlag(pOut, MEM_Int);
80971    pOut->u.i = res2;
80972    REGISTER_TRACE(pOp->p2, pOut);
80973  }else{
80974    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
80975    if( res2 ){
80976      goto jump_to_p2;
80977    }
80978  }
80979  break;
80980}
80981
80982/* Opcode: ElseNotEq * P2 * * *
80983**
80984** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
80985** If result of an OP_Eq comparison on the same two operands
80986** would have be NULL or false (0), then then jump to P2.
80987** If the result of an OP_Eq comparison on the two previous operands
80988** would have been true (1), then fall through.
80989*/
80990case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
80991  assert( pOp>aOp );
80992  assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
80993  assert( pOp[-1].p5 & SQLITE_STOREP2 );
80994  VdbeBranchTaken(iCompare!=0, 2);
80995  if( iCompare!=0 ) goto jump_to_p2;
80996  break;
80997}
80998
80999
81000/* Opcode: Permutation * * * P4 *
81001**
81002** Set the permutation used by the OP_Compare operator in the next
81003** instruction.  The permutation is stored in the P4 operand.
81004**
81005** The permutation is only valid until the next OP_Compare that has
81006** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
81007** occur immediately prior to the OP_Compare.
81008**
81009** The first integer in the P4 integer array is the length of the array
81010** and does not become part of the permutation.
81011*/
81012case OP_Permutation: {
81013  assert( pOp->p4type==P4_INTARRAY );
81014  assert( pOp->p4.ai );
81015  assert( pOp[1].opcode==OP_Compare );
81016  assert( pOp[1].p5 & OPFLAG_PERMUTE );
81017  break;
81018}
81019
81020/* Opcode: Compare P1 P2 P3 P4 P5
81021** Synopsis: r[P1@P3] <-> r[P2@P3]
81022**
81023** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
81024** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
81025** the comparison for use by the next OP_Jump instruct.
81026**
81027** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
81028** determined by the most recent OP_Permutation operator.  If the
81029** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
81030** order.
81031**
81032** P4 is a KeyInfo structure that defines collating sequences and sort
81033** orders for the comparison.  The permutation applies to registers
81034** only.  The KeyInfo elements are used sequentially.
81035**
81036** The comparison is a sort comparison, so NULLs compare equal,
81037** NULLs are less than numbers, numbers are less than strings,
81038** and strings are less than blobs.
81039*/
81040case OP_Compare: {
81041  int n;
81042  int i;
81043  int p1;
81044  int p2;
81045  const KeyInfo *pKeyInfo;
81046  int idx;
81047  CollSeq *pColl;    /* Collating sequence to use on this term */
81048  int bRev;          /* True for DESCENDING sort order */
81049  int *aPermute;     /* The permutation */
81050
81051  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
81052    aPermute = 0;
81053  }else{
81054    assert( pOp>aOp );
81055    assert( pOp[-1].opcode==OP_Permutation );
81056    assert( pOp[-1].p4type==P4_INTARRAY );
81057    aPermute = pOp[-1].p4.ai + 1;
81058    assert( aPermute!=0 );
81059  }
81060  n = pOp->p3;
81061  pKeyInfo = pOp->p4.pKeyInfo;
81062  assert( n>0 );
81063  assert( pKeyInfo!=0 );
81064  p1 = pOp->p1;
81065  p2 = pOp->p2;
81066#ifdef SQLITE_DEBUG
81067  if( aPermute ){
81068    int k, mx = 0;
81069    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
81070    assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
81071    assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
81072  }else{
81073    assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
81074    assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
81075  }
81076#endif /* SQLITE_DEBUG */
81077  for(i=0; i<n; i++){
81078    idx = aPermute ? aPermute[i] : i;
81079    assert( memIsValid(&aMem[p1+idx]) );
81080    assert( memIsValid(&aMem[p2+idx]) );
81081    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
81082    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
81083    assert( i<pKeyInfo->nField );
81084    pColl = pKeyInfo->aColl[i];
81085    bRev = pKeyInfo->aSortOrder[i];
81086    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
81087    if( iCompare ){
81088      if( bRev ) iCompare = -iCompare;
81089      break;
81090    }
81091  }
81092  break;
81093}
81094
81095/* Opcode: Jump P1 P2 P3 * *
81096**
81097** Jump to the instruction at address P1, P2, or P3 depending on whether
81098** in the most recent OP_Compare instruction the P1 vector was less than
81099** equal to, or greater than the P2 vector, respectively.
81100*/
81101case OP_Jump: {             /* jump */
81102  if( iCompare<0 ){
81103    VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
81104  }else if( iCompare==0 ){
81105    VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
81106  }else{
81107    VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
81108  }
81109  break;
81110}
81111
81112/* Opcode: And P1 P2 P3 * *
81113** Synopsis: r[P3]=(r[P1] && r[P2])
81114**
81115** Take the logical AND of the values in registers P1 and P2 and
81116** write the result into register P3.
81117**
81118** If either P1 or P2 is 0 (false) then the result is 0 even if
81119** the other input is NULL.  A NULL and true or two NULLs give
81120** a NULL output.
81121*/
81122/* Opcode: Or P1 P2 P3 * *
81123** Synopsis: r[P3]=(r[P1] || r[P2])
81124**
81125** Take the logical OR of the values in register P1 and P2 and
81126** store the answer in register P3.
81127**
81128** If either P1 or P2 is nonzero (true) then the result is 1 (true)
81129** even if the other input is NULL.  A NULL and false or two NULLs
81130** give a NULL output.
81131*/
81132case OP_And:              /* same as TK_AND, in1, in2, out3 */
81133case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
81134  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
81135  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
81136
81137  pIn1 = &aMem[pOp->p1];
81138  if( pIn1->flags & MEM_Null ){
81139    v1 = 2;
81140  }else{
81141    v1 = sqlite3VdbeIntValue(pIn1)!=0;
81142  }
81143  pIn2 = &aMem[pOp->p2];
81144  if( pIn2->flags & MEM_Null ){
81145    v2 = 2;
81146  }else{
81147    v2 = sqlite3VdbeIntValue(pIn2)!=0;
81148  }
81149  if( pOp->opcode==OP_And ){
81150    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
81151    v1 = and_logic[v1*3+v2];
81152  }else{
81153    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
81154    v1 = or_logic[v1*3+v2];
81155  }
81156  pOut = &aMem[pOp->p3];
81157  if( v1==2 ){
81158    MemSetTypeFlag(pOut, MEM_Null);
81159  }else{
81160    pOut->u.i = v1;
81161    MemSetTypeFlag(pOut, MEM_Int);
81162  }
81163  break;
81164}
81165
81166/* Opcode: Not P1 P2 * * *
81167** Synopsis: r[P2]= !r[P1]
81168**
81169** Interpret the value in register P1 as a boolean value.  Store the
81170** boolean complement in register P2.  If the value in register P1 is
81171** NULL, then a NULL is stored in P2.
81172*/
81173case OP_Not: {                /* same as TK_NOT, in1, out2 */
81174  pIn1 = &aMem[pOp->p1];
81175  pOut = &aMem[pOp->p2];
81176  sqlite3VdbeMemSetNull(pOut);
81177  if( (pIn1->flags & MEM_Null)==0 ){
81178    pOut->flags = MEM_Int;
81179    pOut->u.i = !sqlite3VdbeIntValue(pIn1);
81180  }
81181  break;
81182}
81183
81184/* Opcode: BitNot P1 P2 * * *
81185** Synopsis: r[P1]= ~r[P1]
81186**
81187** Interpret the content of register P1 as an integer.  Store the
81188** ones-complement of the P1 value into register P2.  If P1 holds
81189** a NULL then store a NULL in P2.
81190*/
81191case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
81192  pIn1 = &aMem[pOp->p1];
81193  pOut = &aMem[pOp->p2];
81194  sqlite3VdbeMemSetNull(pOut);
81195  if( (pIn1->flags & MEM_Null)==0 ){
81196    pOut->flags = MEM_Int;
81197    pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
81198  }
81199  break;
81200}
81201
81202/* Opcode: Once P1 P2 * * *
81203**
81204** Fall through to the next instruction the first time this opcode is
81205** encountered on each invocation of the byte-code program.  Jump to P2
81206** on the second and all subsequent encounters during the same invocation.
81207**
81208** Top-level programs determine first invocation by comparing the P1
81209** operand against the P1 operand on the OP_Init opcode at the beginning
81210** of the program.  If the P1 values differ, then fall through and make
81211** the P1 of this opcode equal to the P1 of OP_Init.  If P1 values are
81212** the same then take the jump.
81213**
81214** For subprograms, there is a bitmask in the VdbeFrame that determines
81215** whether or not the jump should be taken.  The bitmask is necessary
81216** because the self-altering code trick does not work for recursive
81217** triggers.
81218*/
81219case OP_Once: {             /* jump */
81220  u32 iAddr;                /* Address of this instruction */
81221  assert( p->aOp[0].opcode==OP_Init );
81222  if( p->pFrame ){
81223    iAddr = (int)(pOp - p->aOp);
81224    if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
81225      VdbeBranchTaken(1, 2);
81226      goto jump_to_p2;
81227    }
81228    p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
81229  }else{
81230    if( p->aOp[0].p1==pOp->p1 ){
81231      VdbeBranchTaken(1, 2);
81232      goto jump_to_p2;
81233    }
81234  }
81235  VdbeBranchTaken(0, 2);
81236  pOp->p1 = p->aOp[0].p1;
81237  break;
81238}
81239
81240/* Opcode: If P1 P2 P3 * *
81241**
81242** Jump to P2 if the value in register P1 is true.  The value
81243** is considered true if it is numeric and non-zero.  If the value
81244** in P1 is NULL then take the jump if and only if P3 is non-zero.
81245*/
81246/* Opcode: IfNot P1 P2 P3 * *
81247**
81248** Jump to P2 if the value in register P1 is False.  The value
81249** is considered false if it has a numeric value of zero.  If the value
81250** in P1 is NULL then take the jump if and only if P3 is non-zero.
81251*/
81252case OP_If:                 /* jump, in1 */
81253case OP_IfNot: {            /* jump, in1 */
81254  int c;
81255  pIn1 = &aMem[pOp->p1];
81256  if( pIn1->flags & MEM_Null ){
81257    c = pOp->p3;
81258  }else{
81259#ifdef SQLITE_OMIT_FLOATING_POINT
81260    c = sqlite3VdbeIntValue(pIn1)!=0;
81261#else
81262    c = sqlite3VdbeRealValue(pIn1)!=0.0;
81263#endif
81264    if( pOp->opcode==OP_IfNot ) c = !c;
81265  }
81266  VdbeBranchTaken(c!=0, 2);
81267  if( c ){
81268    goto jump_to_p2;
81269  }
81270  break;
81271}
81272
81273/* Opcode: IsNull P1 P2 * * *
81274** Synopsis: if r[P1]==NULL goto P2
81275**
81276** Jump to P2 if the value in register P1 is NULL.
81277*/
81278case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
81279  pIn1 = &aMem[pOp->p1];
81280  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
81281  if( (pIn1->flags & MEM_Null)!=0 ){
81282    goto jump_to_p2;
81283  }
81284  break;
81285}
81286
81287/* Opcode: NotNull P1 P2 * * *
81288** Synopsis: if r[P1]!=NULL goto P2
81289**
81290** Jump to P2 if the value in register P1 is not NULL.
81291*/
81292case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
81293  pIn1 = &aMem[pOp->p1];
81294  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
81295  if( (pIn1->flags & MEM_Null)==0 ){
81296    goto jump_to_p2;
81297  }
81298  break;
81299}
81300
81301/* Opcode: IfNullRow P1 P2 P3 * *
81302** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
81303**
81304** Check the cursor P1 to see if it is currently pointing at a NULL row.
81305** If it is, then set register P3 to NULL and jump immediately to P2.
81306** If P1 is not on a NULL row, then fall through without making any
81307** changes.
81308*/
81309case OP_IfNullRow: {         /* jump */
81310  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81311  assert( p->apCsr[pOp->p1]!=0 );
81312  if( p->apCsr[pOp->p1]->nullRow ){
81313    sqlite3VdbeMemSetNull(aMem + pOp->p3);
81314    goto jump_to_p2;
81315  }
81316  break;
81317}
81318
81319/* Opcode: Column P1 P2 P3 P4 P5
81320** Synopsis: r[P3]=PX
81321**
81322** Interpret the data that cursor P1 points to as a structure built using
81323** the MakeRecord instruction.  (See the MakeRecord opcode for additional
81324** information about the format of the data.)  Extract the P2-th column
81325** from this record.  If there are less that (P2+1)
81326** values in the record, extract a NULL.
81327**
81328** The value extracted is stored in register P3.
81329**
81330** If the record contains fewer than P2 fields, then extract a NULL.  Or,
81331** if the P4 argument is a P4_MEM use the value of the P4 argument as
81332** the result.
81333**
81334** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
81335** then the cache of the cursor is reset prior to extracting the column.
81336** The first OP_Column against a pseudo-table after the value of the content
81337** register has changed should have this bit set.
81338**
81339** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
81340** the result is guaranteed to only be used as the argument of a length()
81341** or typeof() function, respectively.  The loading of large blobs can be
81342** skipped for length() and all content loading can be skipped for typeof().
81343*/
81344case OP_Column: {
81345  int p2;            /* column number to retrieve */
81346  VdbeCursor *pC;    /* The VDBE cursor */
81347  BtCursor *pCrsr;   /* The BTree cursor */
81348  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
81349  int len;           /* The length of the serialized data for the column */
81350  int i;             /* Loop counter */
81351  Mem *pDest;        /* Where to write the extracted value */
81352  Mem sMem;          /* For storing the record being decoded */
81353  const u8 *zData;   /* Part of the record being decoded */
81354  const u8 *zHdr;    /* Next unparsed byte of the header */
81355  const u8 *zEndHdr; /* Pointer to first byte after the header */
81356  u32 offset;        /* Offset into the data */
81357  u64 offset64;      /* 64-bit offset */
81358  u32 avail;         /* Number of bytes of available data */
81359  u32 t;             /* A type code from the record header */
81360  Mem *pReg;         /* PseudoTable input register */
81361
81362  pC = p->apCsr[pOp->p1];
81363  p2 = pOp->p2;
81364
81365  /* If the cursor cache is stale (meaning it is not currently point at
81366  ** the correct row) then bring it up-to-date by doing the necessary
81367  ** B-Tree seek. */
81368  rc = sqlite3VdbeCursorMoveto(&pC, &p2);
81369  if( rc ) goto abort_due_to_error;
81370
81371  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
81372  pDest = &aMem[pOp->p3];
81373  memAboutToChange(p, pDest);
81374  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81375  assert( pC!=0 );
81376  assert( p2<pC->nField );
81377  aOffset = pC->aOffset;
81378  assert( pC->eCurType!=CURTYPE_VTAB );
81379  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
81380  assert( pC->eCurType!=CURTYPE_SORTER );
81381
81382  if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
81383    if( pC->nullRow ){
81384      if( pC->eCurType==CURTYPE_PSEUDO ){
81385        assert( pC->uc.pseudoTableReg>0 );
81386        pReg = &aMem[pC->uc.pseudoTableReg];
81387        assert( pReg->flags & MEM_Blob );
81388        assert( memIsValid(pReg) );
81389        pC->payloadSize = pC->szRow = avail = pReg->n;
81390        pC->aRow = (u8*)pReg->z;
81391      }else{
81392        sqlite3VdbeMemSetNull(pDest);
81393        goto op_column_out;
81394      }
81395    }else{
81396      pCrsr = pC->uc.pCursor;
81397      assert( pC->eCurType==CURTYPE_BTREE );
81398      assert( pCrsr );
81399      assert( sqlite3BtreeCursorIsValid(pCrsr) );
81400      pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
81401      pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
81402      assert( avail<=65536 );  /* Maximum page size is 64KiB */
81403      if( pC->payloadSize <= (u32)avail ){
81404        pC->szRow = pC->payloadSize;
81405      }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
81406        goto too_big;
81407      }else{
81408        pC->szRow = avail;
81409      }
81410    }
81411    pC->cacheStatus = p->cacheCtr;
81412    pC->iHdrOffset = getVarint32(pC->aRow, offset);
81413    pC->nHdrParsed = 0;
81414    aOffset[0] = offset;
81415
81416
81417    if( avail<offset ){      /*OPTIMIZATION-IF-FALSE*/
81418      /* pC->aRow does not have to hold the entire row, but it does at least
81419      ** need to cover the header of the record.  If pC->aRow does not contain
81420      ** the complete header, then set it to zero, forcing the header to be
81421      ** dynamically allocated. */
81422      pC->aRow = 0;
81423      pC->szRow = 0;
81424
81425      /* Make sure a corrupt database has not given us an oversize header.
81426      ** Do this now to avoid an oversize memory allocation.
81427      **
81428      ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
81429      ** types use so much data space that there can only be 4096 and 32 of
81430      ** them, respectively.  So the maximum header length results from a
81431      ** 3-byte type for each of the maximum of 32768 columns plus three
81432      ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
81433      */
81434      if( offset > 98307 || offset > pC->payloadSize ){
81435        rc = SQLITE_CORRUPT_BKPT;
81436        goto abort_due_to_error;
81437      }
81438    }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
81439      /* The following goto is an optimization.  It can be omitted and
81440      ** everything will still work.  But OP_Column is measurably faster
81441      ** by skipping the subsequent conditional, which is always true.
81442      */
81443      zData = pC->aRow;
81444      assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
81445      goto op_column_read_header;
81446    }
81447  }
81448
81449  /* Make sure at least the first p2+1 entries of the header have been
81450  ** parsed and valid information is in aOffset[] and pC->aType[].
81451  */
81452  if( pC->nHdrParsed<=p2 ){
81453    /* If there is more header available for parsing in the record, try
81454    ** to extract additional fields up through the p2+1-th field
81455    */
81456    if( pC->iHdrOffset<aOffset[0] ){
81457      /* Make sure zData points to enough of the record to cover the header. */
81458      if( pC->aRow==0 ){
81459        memset(&sMem, 0, sizeof(sMem));
81460        rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
81461        if( rc!=SQLITE_OK ) goto abort_due_to_error;
81462        zData = (u8*)sMem.z;
81463      }else{
81464        zData = pC->aRow;
81465      }
81466
81467      /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
81468    op_column_read_header:
81469      i = pC->nHdrParsed;
81470      offset64 = aOffset[i];
81471      zHdr = zData + pC->iHdrOffset;
81472      zEndHdr = zData + aOffset[0];
81473      do{
81474        if( (t = zHdr[0])<0x80 ){
81475          zHdr++;
81476          offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
81477        }else{
81478          zHdr += sqlite3GetVarint32(zHdr, &t);
81479          offset64 += sqlite3VdbeSerialTypeLen(t);
81480        }
81481        pC->aType[i++] = t;
81482        aOffset[i] = (u32)(offset64 & 0xffffffff);
81483      }while( i<=p2 && zHdr<zEndHdr );
81484
81485      /* The record is corrupt if any of the following are true:
81486      ** (1) the bytes of the header extend past the declared header size
81487      ** (2) the entire header was used but not all data was used
81488      ** (3) the end of the data extends beyond the end of the record.
81489      */
81490      if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
81491       || (offset64 > pC->payloadSize)
81492      ){
81493        if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
81494        rc = SQLITE_CORRUPT_BKPT;
81495        goto abort_due_to_error;
81496      }
81497
81498      pC->nHdrParsed = i;
81499      pC->iHdrOffset = (u32)(zHdr - zData);
81500      if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
81501    }else{
81502      t = 0;
81503    }
81504
81505    /* If after trying to extract new entries from the header, nHdrParsed is
81506    ** still not up to p2, that means that the record has fewer than p2
81507    ** columns.  So the result will be either the default value or a NULL.
81508    */
81509    if( pC->nHdrParsed<=p2 ){
81510      if( pOp->p4type==P4_MEM ){
81511        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
81512      }else{
81513        sqlite3VdbeMemSetNull(pDest);
81514      }
81515      goto op_column_out;
81516    }
81517  }else{
81518    t = pC->aType[p2];
81519  }
81520
81521  /* Extract the content for the p2+1-th column.  Control can only
81522  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
81523  ** all valid.
81524  */
81525  assert( p2<pC->nHdrParsed );
81526  assert( rc==SQLITE_OK );
81527  assert( sqlite3VdbeCheckMemInvariants(pDest) );
81528  if( VdbeMemDynamic(pDest) ){
81529    sqlite3VdbeMemSetNull(pDest);
81530  }
81531  assert( t==pC->aType[p2] );
81532  if( pC->szRow>=aOffset[p2+1] ){
81533    /* This is the common case where the desired content fits on the original
81534    ** page - where the content is not on an overflow page */
81535    zData = pC->aRow + aOffset[p2];
81536    if( t<12 ){
81537      sqlite3VdbeSerialGet(zData, t, pDest);
81538    }else{
81539      /* If the column value is a string, we need a persistent value, not
81540      ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
81541      ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
81542      */
81543      static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
81544      pDest->n = len = (t-12)/2;
81545      pDest->enc = encoding;
81546      if( pDest->szMalloc < len+2 ){
81547        pDest->flags = MEM_Null;
81548        if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
81549      }else{
81550        pDest->z = pDest->zMalloc;
81551      }
81552      memcpy(pDest->z, zData, len);
81553      pDest->z[len] = 0;
81554      pDest->z[len+1] = 0;
81555      pDest->flags = aFlag[t&1];
81556    }
81557  }else{
81558    pDest->enc = encoding;
81559    /* This branch happens only when content is on overflow pages */
81560    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
81561          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
81562     || (len = sqlite3VdbeSerialTypeLen(t))==0
81563    ){
81564      /* Content is irrelevant for
81565      **    1. the typeof() function,
81566      **    2. the length(X) function if X is a blob, and
81567      **    3. if the content length is zero.
81568      ** So we might as well use bogus content rather than reading
81569      ** content from disk.
81570      **
81571      ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
81572      ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
81573      ** read up to 16. So 16 bytes of bogus content is supplied.
81574      */
81575      static u8 aZero[16];  /* This is the bogus content */
81576      sqlite3VdbeSerialGet(aZero, t, pDest);
81577    }else{
81578      rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
81579      if( rc!=SQLITE_OK ) goto abort_due_to_error;
81580      sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
81581      pDest->flags &= ~MEM_Ephem;
81582    }
81583  }
81584
81585op_column_out:
81586  UPDATE_MAX_BLOBSIZE(pDest);
81587  REGISTER_TRACE(pOp->p3, pDest);
81588  break;
81589}
81590
81591/* Opcode: Affinity P1 P2 * P4 *
81592** Synopsis: affinity(r[P1@P2])
81593**
81594** Apply affinities to a range of P2 registers starting with P1.
81595**
81596** P4 is a string that is P2 characters long. The N-th character of the
81597** string indicates the column affinity that should be used for the N-th
81598** memory cell in the range.
81599*/
81600case OP_Affinity: {
81601  const char *zAffinity;   /* The affinity to be applied */
81602
81603  zAffinity = pOp->p4.z;
81604  assert( zAffinity!=0 );
81605  assert( pOp->p2>0 );
81606  assert( zAffinity[pOp->p2]==0 );
81607  pIn1 = &aMem[pOp->p1];
81608  do{
81609    assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
81610    assert( memIsValid(pIn1) );
81611    applyAffinity(pIn1, *(zAffinity++), encoding);
81612    pIn1++;
81613  }while( zAffinity[0] );
81614  break;
81615}
81616
81617/* Opcode: MakeRecord P1 P2 P3 P4 *
81618** Synopsis: r[P3]=mkrec(r[P1@P2])
81619**
81620** Convert P2 registers beginning with P1 into the [record format]
81621** use as a data record in a database table or as a key
81622** in an index.  The OP_Column opcode can decode the record later.
81623**
81624** P4 may be a string that is P2 characters long.  The N-th character of the
81625** string indicates the column affinity that should be used for the N-th
81626** field of the index key.
81627**
81628** The mapping from character to affinity is given by the SQLITE_AFF_
81629** macros defined in sqliteInt.h.
81630**
81631** If P4 is NULL then all index fields have the affinity BLOB.
81632*/
81633case OP_MakeRecord: {
81634  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
81635  Mem *pRec;             /* The new record */
81636  u64 nData;             /* Number of bytes of data space */
81637  int nHdr;              /* Number of bytes of header space */
81638  i64 nByte;             /* Data space required for this record */
81639  i64 nZero;             /* Number of zero bytes at the end of the record */
81640  int nVarint;           /* Number of bytes in a varint */
81641  u32 serial_type;       /* Type field */
81642  Mem *pData0;           /* First field to be combined into the record */
81643  Mem *pLast;            /* Last field of the record */
81644  int nField;            /* Number of fields in the record */
81645  char *zAffinity;       /* The affinity string for the record */
81646  int file_format;       /* File format to use for encoding */
81647  int i;                 /* Space used in zNewRecord[] header */
81648  int j;                 /* Space used in zNewRecord[] content */
81649  u32 len;               /* Length of a field */
81650
81651  /* Assuming the record contains N fields, the record format looks
81652  ** like this:
81653  **
81654  ** ------------------------------------------------------------------------
81655  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
81656  ** ------------------------------------------------------------------------
81657  **
81658  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
81659  ** and so forth.
81660  **
81661  ** Each type field is a varint representing the serial type of the
81662  ** corresponding data element (see sqlite3VdbeSerialType()). The
81663  ** hdr-size field is also a varint which is the offset from the beginning
81664  ** of the record to data0.
81665  */
81666  nData = 0;         /* Number of bytes of data space */
81667  nHdr = 0;          /* Number of bytes of header space */
81668  nZero = 0;         /* Number of zero bytes at the end of the record */
81669  nField = pOp->p1;
81670  zAffinity = pOp->p4.z;
81671  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
81672  pData0 = &aMem[nField];
81673  nField = pOp->p2;
81674  pLast = &pData0[nField-1];
81675  file_format = p->minWriteFileFormat;
81676
81677  /* Identify the output register */
81678  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
81679  pOut = &aMem[pOp->p3];
81680  memAboutToChange(p, pOut);
81681
81682  /* Apply the requested affinity to all inputs
81683  */
81684  assert( pData0<=pLast );
81685  if( zAffinity ){
81686    pRec = pData0;
81687    do{
81688      applyAffinity(pRec++, *(zAffinity++), encoding);
81689      assert( zAffinity[0]==0 || pRec<=pLast );
81690    }while( zAffinity[0] );
81691  }
81692
81693#ifdef SQLITE_ENABLE_NULL_TRIM
81694  /* NULLs can be safely trimmed from the end of the record, as long as
81695  ** as the schema format is 2 or more and none of the omitted columns
81696  ** have a non-NULL default value.  Also, the record must be left with
81697  ** at least one field.  If P5>0 then it will be one more than the
81698  ** index of the right-most column with a non-NULL default value */
81699  if( pOp->p5 ){
81700    while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
81701      pLast--;
81702      nField--;
81703    }
81704  }
81705#endif
81706
81707  /* Loop through the elements that will make up the record to figure
81708  ** out how much space is required for the new record.
81709  */
81710  pRec = pLast;
81711  do{
81712    assert( memIsValid(pRec) );
81713    pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
81714    if( pRec->flags & MEM_Zero ){
81715      if( nData ){
81716        if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
81717      }else{
81718        nZero += pRec->u.nZero;
81719        len -= pRec->u.nZero;
81720      }
81721    }
81722    nData += len;
81723    testcase( serial_type==127 );
81724    testcase( serial_type==128 );
81725    nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
81726    if( pRec==pData0 ) break;
81727    pRec--;
81728  }while(1);
81729
81730  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
81731  ** which determines the total number of bytes in the header. The varint
81732  ** value is the size of the header in bytes including the size varint
81733  ** itself. */
81734  testcase( nHdr==126 );
81735  testcase( nHdr==127 );
81736  if( nHdr<=126 ){
81737    /* The common case */
81738    nHdr += 1;
81739  }else{
81740    /* Rare case of a really large header */
81741    nVarint = sqlite3VarintLen(nHdr);
81742    nHdr += nVarint;
81743    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
81744  }
81745  nByte = nHdr+nData;
81746  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
81747    goto too_big;
81748  }
81749
81750  /* Make sure the output register has a buffer large enough to store
81751  ** the new record. The output register (pOp->p3) is not allowed to
81752  ** be one of the input registers (because the following call to
81753  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
81754  */
81755  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
81756    goto no_mem;
81757  }
81758  zNewRecord = (u8 *)pOut->z;
81759
81760  /* Write the record */
81761  i = putVarint32(zNewRecord, nHdr);
81762  j = nHdr;
81763  assert( pData0<=pLast );
81764  pRec = pData0;
81765  do{
81766    serial_type = pRec->uTemp;
81767    /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
81768    ** additional varints, one per column. */
81769    i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
81770    /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
81771    ** immediately follow the header. */
81772    j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
81773  }while( (++pRec)<=pLast );
81774  assert( i==nHdr );
81775  assert( j==nByte );
81776
81777  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
81778  pOut->n = (int)nByte;
81779  pOut->flags = MEM_Blob;
81780  if( nZero ){
81781    pOut->u.nZero = nZero;
81782    pOut->flags |= MEM_Zero;
81783  }
81784  REGISTER_TRACE(pOp->p3, pOut);
81785  UPDATE_MAX_BLOBSIZE(pOut);
81786  break;
81787}
81788
81789/* Opcode: Count P1 P2 * * *
81790** Synopsis: r[P2]=count()
81791**
81792** Store the number of entries (an integer value) in the table or index
81793** opened by cursor P1 in register P2
81794*/
81795#ifndef SQLITE_OMIT_BTREECOUNT
81796case OP_Count: {         /* out2 */
81797  i64 nEntry;
81798  BtCursor *pCrsr;
81799
81800  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
81801  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
81802  assert( pCrsr );
81803  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
81804  rc = sqlite3BtreeCount(pCrsr, &nEntry);
81805  if( rc ) goto abort_due_to_error;
81806  pOut = out2Prerelease(p, pOp);
81807  pOut->u.i = nEntry;
81808  break;
81809}
81810#endif
81811
81812/* Opcode: Savepoint P1 * * P4 *
81813**
81814** Open, release or rollback the savepoint named by parameter P4, depending
81815** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
81816** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
81817*/
81818case OP_Savepoint: {
81819  int p1;                         /* Value of P1 operand */
81820  char *zName;                    /* Name of savepoint */
81821  int nName;
81822  Savepoint *pNew;
81823  Savepoint *pSavepoint;
81824  Savepoint *pTmp;
81825  int iSavepoint;
81826  int ii;
81827
81828  p1 = pOp->p1;
81829  zName = pOp->p4.z;
81830
81831  /* Assert that the p1 parameter is valid. Also that if there is no open
81832  ** transaction, then there cannot be any savepoints.
81833  */
81834  assert( db->pSavepoint==0 || db->autoCommit==0 );
81835  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
81836  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
81837  assert( checkSavepointCount(db) );
81838  assert( p->bIsReader );
81839
81840  if( p1==SAVEPOINT_BEGIN ){
81841    if( db->nVdbeWrite>0 ){
81842      /* A new savepoint cannot be created if there are active write
81843      ** statements (i.e. open read/write incremental blob handles).
81844      */
81845      sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
81846      rc = SQLITE_BUSY;
81847    }else{
81848      nName = sqlite3Strlen30(zName);
81849
81850#ifndef SQLITE_OMIT_VIRTUALTABLE
81851      /* This call is Ok even if this savepoint is actually a transaction
81852      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
81853      ** If this is a transaction savepoint being opened, it is guaranteed
81854      ** that the db->aVTrans[] array is empty.  */
81855      assert( db->autoCommit==0 || db->nVTrans==0 );
81856      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
81857                                db->nStatement+db->nSavepoint);
81858      if( rc!=SQLITE_OK ) goto abort_due_to_error;
81859#endif
81860
81861      /* Create a new savepoint structure. */
81862      pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
81863      if( pNew ){
81864        pNew->zName = (char *)&pNew[1];
81865        memcpy(pNew->zName, zName, nName+1);
81866
81867        /* If there is no open transaction, then mark this as a special
81868        ** "transaction savepoint". */
81869        if( db->autoCommit ){
81870          db->autoCommit = 0;
81871          db->isTransactionSavepoint = 1;
81872        }else{
81873          db->nSavepoint++;
81874        }
81875
81876        /* Link the new savepoint into the database handle's list. */
81877        pNew->pNext = db->pSavepoint;
81878        db->pSavepoint = pNew;
81879        pNew->nDeferredCons = db->nDeferredCons;
81880        pNew->nDeferredImmCons = db->nDeferredImmCons;
81881      }
81882    }
81883  }else{
81884    iSavepoint = 0;
81885
81886    /* Find the named savepoint. If there is no such savepoint, then an
81887    ** an error is returned to the user.  */
81888    for(
81889      pSavepoint = db->pSavepoint;
81890      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
81891      pSavepoint = pSavepoint->pNext
81892    ){
81893      iSavepoint++;
81894    }
81895    if( !pSavepoint ){
81896      sqlite3VdbeError(p, "no such savepoint: %s", zName);
81897      rc = SQLITE_ERROR;
81898    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
81899      /* It is not possible to release (commit) a savepoint if there are
81900      ** active write statements.
81901      */
81902      sqlite3VdbeError(p, "cannot release savepoint - "
81903                          "SQL statements in progress");
81904      rc = SQLITE_BUSY;
81905    }else{
81906
81907      /* Determine whether or not this is a transaction savepoint. If so,
81908      ** and this is a RELEASE command, then the current transaction
81909      ** is committed.
81910      */
81911      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
81912      if( isTransaction && p1==SAVEPOINT_RELEASE ){
81913        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
81914          goto vdbe_return;
81915        }
81916        db->autoCommit = 1;
81917        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
81918          p->pc = (int)(pOp - aOp);
81919          db->autoCommit = 0;
81920          p->rc = rc = SQLITE_BUSY;
81921          goto vdbe_return;
81922        }
81923        db->isTransactionSavepoint = 0;
81924        rc = p->rc;
81925      }else{
81926        int isSchemaChange;
81927        iSavepoint = db->nSavepoint - iSavepoint - 1;
81928        if( p1==SAVEPOINT_ROLLBACK ){
81929          isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
81930          for(ii=0; ii<db->nDb; ii++){
81931            rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
81932                                       SQLITE_ABORT_ROLLBACK,
81933                                       isSchemaChange==0);
81934            if( rc!=SQLITE_OK ) goto abort_due_to_error;
81935          }
81936        }else{
81937          isSchemaChange = 0;
81938        }
81939        for(ii=0; ii<db->nDb; ii++){
81940          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
81941          if( rc!=SQLITE_OK ){
81942            goto abort_due_to_error;
81943          }
81944        }
81945        if( isSchemaChange ){
81946          sqlite3ExpirePreparedStatements(db);
81947          sqlite3ResetAllSchemasOfConnection(db);
81948          db->flags = (db->flags | SQLITE_InternChanges);
81949        }
81950      }
81951
81952      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
81953      ** savepoints nested inside of the savepoint being operated on. */
81954      while( db->pSavepoint!=pSavepoint ){
81955        pTmp = db->pSavepoint;
81956        db->pSavepoint = pTmp->pNext;
81957        sqlite3DbFree(db, pTmp);
81958        db->nSavepoint--;
81959      }
81960
81961      /* If it is a RELEASE, then destroy the savepoint being operated on
81962      ** too. If it is a ROLLBACK TO, then set the number of deferred
81963      ** constraint violations present in the database to the value stored
81964      ** when the savepoint was created.  */
81965      if( p1==SAVEPOINT_RELEASE ){
81966        assert( pSavepoint==db->pSavepoint );
81967        db->pSavepoint = pSavepoint->pNext;
81968        sqlite3DbFree(db, pSavepoint);
81969        if( !isTransaction ){
81970          db->nSavepoint--;
81971        }
81972      }else{
81973        db->nDeferredCons = pSavepoint->nDeferredCons;
81974        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
81975      }
81976
81977      if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
81978        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
81979        if( rc!=SQLITE_OK ) goto abort_due_to_error;
81980      }
81981    }
81982  }
81983  if( rc ) goto abort_due_to_error;
81984
81985  break;
81986}
81987
81988/* Opcode: AutoCommit P1 P2 * * *
81989**
81990** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
81991** back any currently active btree transactions. If there are any active
81992** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
81993** there are active writing VMs or active VMs that use shared cache.
81994**
81995** This instruction causes the VM to halt.
81996*/
81997case OP_AutoCommit: {
81998  int desiredAutoCommit;
81999  int iRollback;
82000
82001  desiredAutoCommit = pOp->p1;
82002  iRollback = pOp->p2;
82003  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
82004  assert( desiredAutoCommit==1 || iRollback==0 );
82005  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
82006  assert( p->bIsReader );
82007
82008  if( desiredAutoCommit!=db->autoCommit ){
82009    if( iRollback ){
82010      assert( desiredAutoCommit==1 );
82011      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
82012      db->autoCommit = 1;
82013    }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
82014      /* If this instruction implements a COMMIT and other VMs are writing
82015      ** return an error indicating that the other VMs must complete first.
82016      */
82017      sqlite3VdbeError(p, "cannot commit transaction - "
82018                          "SQL statements in progress");
82019      rc = SQLITE_BUSY;
82020      goto abort_due_to_error;
82021    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
82022      goto vdbe_return;
82023    }else{
82024      db->autoCommit = (u8)desiredAutoCommit;
82025    }
82026    if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
82027      p->pc = (int)(pOp - aOp);
82028      db->autoCommit = (u8)(1-desiredAutoCommit);
82029      p->rc = rc = SQLITE_BUSY;
82030      goto vdbe_return;
82031    }
82032    assert( db->nStatement==0 );
82033    sqlite3CloseSavepoints(db);
82034    if( p->rc==SQLITE_OK ){
82035      rc = SQLITE_DONE;
82036    }else{
82037      rc = SQLITE_ERROR;
82038    }
82039    goto vdbe_return;
82040  }else{
82041    sqlite3VdbeError(p,
82042        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
82043        (iRollback)?"cannot rollback - no transaction is active":
82044                   "cannot commit - no transaction is active"));
82045
82046    rc = SQLITE_ERROR;
82047    goto abort_due_to_error;
82048  }
82049  break;
82050}
82051
82052/* Opcode: Transaction P1 P2 P3 P4 P5
82053**
82054** Begin a transaction on database P1 if a transaction is not already
82055** active.
82056** If P2 is non-zero, then a write-transaction is started, or if a
82057** read-transaction is already active, it is upgraded to a write-transaction.
82058** If P2 is zero, then a read-transaction is started.
82059**
82060** P1 is the index of the database file on which the transaction is
82061** started.  Index 0 is the main database file and index 1 is the
82062** file used for temporary tables.  Indices of 2 or more are used for
82063** attached databases.
82064**
82065** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
82066** true (this flag is set if the Vdbe may modify more than one row and may
82067** throw an ABORT exception), a statement transaction may also be opened.
82068** More specifically, a statement transaction is opened iff the database
82069** connection is currently not in autocommit mode, or if there are other
82070** active statements. A statement transaction allows the changes made by this
82071** VDBE to be rolled back after an error without having to roll back the
82072** entire transaction. If no error is encountered, the statement transaction
82073** will automatically commit when the VDBE halts.
82074**
82075** If P5!=0 then this opcode also checks the schema cookie against P3
82076** and the schema generation counter against P4.
82077** The cookie changes its value whenever the database schema changes.
82078** This operation is used to detect when that the cookie has changed
82079** and that the current process needs to reread the schema.  If the schema
82080** cookie in P3 differs from the schema cookie in the database header or
82081** if the schema generation counter in P4 differs from the current
82082** generation counter, then an SQLITE_SCHEMA error is raised and execution
82083** halts.  The sqlite3_step() wrapper function might then reprepare the
82084** statement and rerun it from the beginning.
82085*/
82086case OP_Transaction: {
82087  Btree *pBt;
82088  int iMeta;
82089  int iGen;
82090
82091  assert( p->bIsReader );
82092  assert( p->readOnly==0 || pOp->p2==0 );
82093  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82094  assert( DbMaskTest(p->btreeMask, pOp->p1) );
82095  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
82096    rc = SQLITE_READONLY;
82097    goto abort_due_to_error;
82098  }
82099  pBt = db->aDb[pOp->p1].pBt;
82100
82101  if( pBt ){
82102    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
82103    testcase( rc==SQLITE_BUSY_SNAPSHOT );
82104    testcase( rc==SQLITE_BUSY_RECOVERY );
82105    if( rc!=SQLITE_OK ){
82106      if( (rc&0xff)==SQLITE_BUSY ){
82107        p->pc = (int)(pOp - aOp);
82108        p->rc = rc;
82109        goto vdbe_return;
82110      }
82111      goto abort_due_to_error;
82112    }
82113
82114    if( pOp->p2 && p->usesStmtJournal
82115     && (db->autoCommit==0 || db->nVdbeRead>1)
82116    ){
82117      assert( sqlite3BtreeIsInTrans(pBt) );
82118      if( p->iStatement==0 ){
82119        assert( db->nStatement>=0 && db->nSavepoint>=0 );
82120        db->nStatement++;
82121        p->iStatement = db->nSavepoint + db->nStatement;
82122      }
82123
82124      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
82125      if( rc==SQLITE_OK ){
82126        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
82127      }
82128
82129      /* Store the current value of the database handles deferred constraint
82130      ** counter. If the statement transaction needs to be rolled back,
82131      ** the value of this counter needs to be restored too.  */
82132      p->nStmtDefCons = db->nDeferredCons;
82133      p->nStmtDefImmCons = db->nDeferredImmCons;
82134    }
82135
82136    /* Gather the schema version number for checking:
82137    ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
82138    ** version is checked to ensure that the schema has not changed since the
82139    ** SQL statement was prepared.
82140    */
82141    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
82142    iGen = db->aDb[pOp->p1].pSchema->iGeneration;
82143  }else{
82144    iGen = iMeta = 0;
82145  }
82146  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
82147  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
82148    sqlite3DbFree(db, p->zErrMsg);
82149    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
82150    /* If the schema-cookie from the database file matches the cookie
82151    ** stored with the in-memory representation of the schema, do
82152    ** not reload the schema from the database file.
82153    **
82154    ** If virtual-tables are in use, this is not just an optimization.
82155    ** Often, v-tables store their data in other SQLite tables, which
82156    ** are queried from within xNext() and other v-table methods using
82157    ** prepared queries. If such a query is out-of-date, we do not want to
82158    ** discard the database schema, as the user code implementing the
82159    ** v-table would have to be ready for the sqlite3_vtab structure itself
82160    ** to be invalidated whenever sqlite3_step() is called from within
82161    ** a v-table method.
82162    */
82163    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
82164      sqlite3ResetOneSchema(db, pOp->p1);
82165    }
82166    p->expired = 1;
82167    rc = SQLITE_SCHEMA;
82168  }
82169  if( rc ) goto abort_due_to_error;
82170  break;
82171}
82172
82173/* Opcode: ReadCookie P1 P2 P3 * *
82174**
82175** Read cookie number P3 from database P1 and write it into register P2.
82176** P3==1 is the schema version.  P3==2 is the database format.
82177** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
82178** the main database file and P1==1 is the database file used to store
82179** temporary tables.
82180**
82181** There must be a read-lock on the database (either a transaction
82182** must be started or there must be an open cursor) before
82183** executing this instruction.
82184*/
82185case OP_ReadCookie: {               /* out2 */
82186  int iMeta;
82187  int iDb;
82188  int iCookie;
82189
82190  assert( p->bIsReader );
82191  iDb = pOp->p1;
82192  iCookie = pOp->p3;
82193  assert( pOp->p3<SQLITE_N_BTREE_META );
82194  assert( iDb>=0 && iDb<db->nDb );
82195  assert( db->aDb[iDb].pBt!=0 );
82196  assert( DbMaskTest(p->btreeMask, iDb) );
82197
82198  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
82199  pOut = out2Prerelease(p, pOp);
82200  pOut->u.i = iMeta;
82201  break;
82202}
82203
82204/* Opcode: SetCookie P1 P2 P3 * *
82205**
82206** Write the integer value P3 into cookie number P2 of database P1.
82207** P2==1 is the schema version.  P2==2 is the database format.
82208** P2==3 is the recommended pager cache
82209** size, and so forth.  P1==0 is the main database file and P1==1 is the
82210** database file used to store temporary tables.
82211**
82212** A transaction must be started before executing this opcode.
82213*/
82214case OP_SetCookie: {
82215  Db *pDb;
82216  assert( pOp->p2<SQLITE_N_BTREE_META );
82217  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82218  assert( DbMaskTest(p->btreeMask, pOp->p1) );
82219  assert( p->readOnly==0 );
82220  pDb = &db->aDb[pOp->p1];
82221  assert( pDb->pBt!=0 );
82222  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
82223  /* See note about index shifting on OP_ReadCookie */
82224  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
82225  if( pOp->p2==BTREE_SCHEMA_VERSION ){
82226    /* When the schema cookie changes, record the new cookie internally */
82227    pDb->pSchema->schema_cookie = pOp->p3;
82228    db->flags |= SQLITE_InternChanges;
82229  }else if( pOp->p2==BTREE_FILE_FORMAT ){
82230    /* Record changes in the file format */
82231    pDb->pSchema->file_format = pOp->p3;
82232  }
82233  if( pOp->p1==1 ){
82234    /* Invalidate all prepared statements whenever the TEMP database
82235    ** schema is changed.  Ticket #1644 */
82236    sqlite3ExpirePreparedStatements(db);
82237    p->expired = 0;
82238  }
82239  if( rc ) goto abort_due_to_error;
82240  break;
82241}
82242
82243/* Opcode: OpenRead P1 P2 P3 P4 P5
82244** Synopsis: root=P2 iDb=P3
82245**
82246** Open a read-only cursor for the database table whose root page is
82247** P2 in a database file.  The database file is determined by P3.
82248** P3==0 means the main database, P3==1 means the database used for
82249** temporary tables, and P3>1 means used the corresponding attached
82250** database.  Give the new cursor an identifier of P1.  The P1
82251** values need not be contiguous but all P1 values should be small integers.
82252** It is an error for P1 to be negative.
82253**
82254** If P5!=0 then use the content of register P2 as the root page, not
82255** the value of P2 itself.
82256**
82257** There will be a read lock on the database whenever there is an
82258** open cursor.  If the database was unlocked prior to this instruction
82259** then a read lock is acquired as part of this instruction.  A read
82260** lock allows other processes to read the database but prohibits
82261** any other process from modifying the database.  The read lock is
82262** released when all cursors are closed.  If this instruction attempts
82263** to get a read lock but fails, the script terminates with an
82264** SQLITE_BUSY error code.
82265**
82266** The P4 value may be either an integer (P4_INT32) or a pointer to
82267** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
82268** structure, then said structure defines the content and collating
82269** sequence of the index being opened. Otherwise, if P4 is an integer
82270** value, it is set to the number of columns in the table.
82271**
82272** See also: OpenWrite, ReopenIdx
82273*/
82274/* Opcode: ReopenIdx P1 P2 P3 P4 P5
82275** Synopsis: root=P2 iDb=P3
82276**
82277** The ReopenIdx opcode works exactly like ReadOpen except that it first
82278** checks to see if the cursor on P1 is already open with a root page
82279** number of P2 and if it is this opcode becomes a no-op.  In other words,
82280** if the cursor is already open, do not reopen it.
82281**
82282** The ReopenIdx opcode may only be used with P5==0 and with P4 being
82283** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
82284** every other ReopenIdx or OpenRead for the same cursor number.
82285**
82286** See the OpenRead opcode documentation for additional information.
82287*/
82288/* Opcode: OpenWrite P1 P2 P3 P4 P5
82289** Synopsis: root=P2 iDb=P3
82290**
82291** Open a read/write cursor named P1 on the table or index whose root
82292** page is P2.  Or if P5!=0 use the content of register P2 to find the
82293** root page.
82294**
82295** The P4 value may be either an integer (P4_INT32) or a pointer to
82296** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
82297** structure, then said structure defines the content and collating
82298** sequence of the index being opened. Otherwise, if P4 is an integer
82299** value, it is set to the number of columns in the table, or to the
82300** largest index of any column of the table that is actually used.
82301**
82302** This instruction works just like OpenRead except that it opens the cursor
82303** in read/write mode.  For a given table, there can be one or more read-only
82304** cursors or a single read/write cursor but not both.
82305**
82306** See also OpenRead.
82307*/
82308case OP_ReopenIdx: {
82309  int nField;
82310  KeyInfo *pKeyInfo;
82311  int p2;
82312  int iDb;
82313  int wrFlag;
82314  Btree *pX;
82315  VdbeCursor *pCur;
82316  Db *pDb;
82317
82318  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
82319  assert( pOp->p4type==P4_KEYINFO );
82320  pCur = p->apCsr[pOp->p1];
82321  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
82322    assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
82323    goto open_cursor_set_hints;
82324  }
82325  /* If the cursor is not currently open or is open on a different
82326  ** index, then fall through into OP_OpenRead to force a reopen */
82327case OP_OpenRead:
82328case OP_OpenWrite:
82329
82330  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
82331  assert( p->bIsReader );
82332  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
82333          || p->readOnly==0 );
82334
82335  if( p->expired ){
82336    rc = SQLITE_ABORT_ROLLBACK;
82337    goto abort_due_to_error;
82338  }
82339
82340  nField = 0;
82341  pKeyInfo = 0;
82342  p2 = pOp->p2;
82343  iDb = pOp->p3;
82344  assert( iDb>=0 && iDb<db->nDb );
82345  assert( DbMaskTest(p->btreeMask, iDb) );
82346  pDb = &db->aDb[iDb];
82347  pX = pDb->pBt;
82348  assert( pX!=0 );
82349  if( pOp->opcode==OP_OpenWrite ){
82350    assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
82351    wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
82352    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82353    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
82354      p->minWriteFileFormat = pDb->pSchema->file_format;
82355    }
82356  }else{
82357    wrFlag = 0;
82358  }
82359  if( pOp->p5 & OPFLAG_P2ISREG ){
82360    assert( p2>0 );
82361    assert( p2<=(p->nMem+1 - p->nCursor) );
82362    pIn2 = &aMem[p2];
82363    assert( memIsValid(pIn2) );
82364    assert( (pIn2->flags & MEM_Int)!=0 );
82365    sqlite3VdbeMemIntegerify(pIn2);
82366    p2 = (int)pIn2->u.i;
82367    /* The p2 value always comes from a prior OP_CreateTable opcode and
82368    ** that opcode will always set the p2 value to 2 or more or else fail.
82369    ** If there were a failure, the prepared statement would have halted
82370    ** before reaching this instruction. */
82371    assert( p2>=2 );
82372  }
82373  if( pOp->p4type==P4_KEYINFO ){
82374    pKeyInfo = pOp->p4.pKeyInfo;
82375    assert( pKeyInfo->enc==ENC(db) );
82376    assert( pKeyInfo->db==db );
82377    nField = pKeyInfo->nField+pKeyInfo->nXField;
82378  }else if( pOp->p4type==P4_INT32 ){
82379    nField = pOp->p4.i;
82380  }
82381  assert( pOp->p1>=0 );
82382  assert( nField>=0 );
82383  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
82384  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
82385  if( pCur==0 ) goto no_mem;
82386  pCur->nullRow = 1;
82387  pCur->isOrdered = 1;
82388  pCur->pgnoRoot = p2;
82389#ifdef SQLITE_DEBUG
82390  pCur->wrFlag = wrFlag;
82391#endif
82392  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
82393  pCur->pKeyInfo = pKeyInfo;
82394  /* Set the VdbeCursor.isTable variable. Previous versions of
82395  ** SQLite used to check if the root-page flags were sane at this point
82396  ** and report database corruption if they were not, but this check has
82397  ** since moved into the btree layer.  */
82398  pCur->isTable = pOp->p4type!=P4_KEYINFO;
82399
82400open_cursor_set_hints:
82401  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
82402  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
82403  testcase( pOp->p5 & OPFLAG_BULKCSR );
82404#ifdef SQLITE_ENABLE_CURSOR_HINTS
82405  testcase( pOp->p2 & OPFLAG_SEEKEQ );
82406#endif
82407  sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
82408                               (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
82409  if( rc ) goto abort_due_to_error;
82410  break;
82411}
82412
82413/* Opcode: OpenDup P1 P2 * * *
82414**
82415** Open a new cursor P1 that points to the same ephemeral table as
82416** cursor P2.  The P2 cursor must have been opened by a prior OP_OpenEphemeral
82417** opcode.  Only ephemeral cursors may be duplicated.
82418**
82419** Duplicate ephemeral cursors are used for self-joins of materialized views.
82420*/
82421case OP_OpenDup: {
82422  VdbeCursor *pOrig;    /* The original cursor to be duplicated */
82423  VdbeCursor *pCx;      /* The new cursor */
82424
82425  pOrig = p->apCsr[pOp->p2];
82426  assert( pOrig->pBtx!=0 );  /* Only ephemeral cursors can be duplicated */
82427
82428  pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
82429  if( pCx==0 ) goto no_mem;
82430  pCx->nullRow = 1;
82431  pCx->isEphemeral = 1;
82432  pCx->pKeyInfo = pOrig->pKeyInfo;
82433  pCx->isTable = pOrig->isTable;
82434  rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
82435                          pCx->pKeyInfo, pCx->uc.pCursor);
82436  /* The sqlite3BtreeCursor() routine can only fail for the first cursor
82437  ** opened for a database.  Since there is already an open cursor when this
82438  ** opcode is run, the sqlite3BtreeCursor() cannot fail */
82439  assert( rc==SQLITE_OK );
82440  break;
82441}
82442
82443
82444/* Opcode: OpenEphemeral P1 P2 * P4 P5
82445** Synopsis: nColumn=P2
82446**
82447** Open a new cursor P1 to a transient table.
82448** The cursor is always opened read/write even if
82449** the main database is read-only.  The ephemeral
82450** table is deleted automatically when the cursor is closed.
82451**
82452** P2 is the number of columns in the ephemeral table.
82453** The cursor points to a BTree table if P4==0 and to a BTree index
82454** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
82455** that defines the format of keys in the index.
82456**
82457** The P5 parameter can be a mask of the BTREE_* flags defined
82458** in btree.h.  These flags control aspects of the operation of
82459** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
82460** added automatically.
82461*/
82462/* Opcode: OpenAutoindex P1 P2 * P4 *
82463** Synopsis: nColumn=P2
82464**
82465** This opcode works the same as OP_OpenEphemeral.  It has a
82466** different name to distinguish its use.  Tables created using
82467** by this opcode will be used for automatically created transient
82468** indices in joins.
82469*/
82470case OP_OpenAutoindex:
82471case OP_OpenEphemeral: {
82472  VdbeCursor *pCx;
82473  KeyInfo *pKeyInfo;
82474
82475  static const int vfsFlags =
82476      SQLITE_OPEN_READWRITE |
82477      SQLITE_OPEN_CREATE |
82478      SQLITE_OPEN_EXCLUSIVE |
82479      SQLITE_OPEN_DELETEONCLOSE |
82480      SQLITE_OPEN_TRANSIENT_DB;
82481  assert( pOp->p1>=0 );
82482  assert( pOp->p2>=0 );
82483  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
82484  if( pCx==0 ) goto no_mem;
82485  pCx->nullRow = 1;
82486  pCx->isEphemeral = 1;
82487  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
82488                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
82489  if( rc==SQLITE_OK ){
82490    rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
82491  }
82492  if( rc==SQLITE_OK ){
82493    /* If a transient index is required, create it by calling
82494    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
82495    ** opening it. If a transient table is required, just use the
82496    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
82497    */
82498    if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
82499      int pgno;
82500      assert( pOp->p4type==P4_KEYINFO );
82501      rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
82502      if( rc==SQLITE_OK ){
82503        assert( pgno==MASTER_ROOT+1 );
82504        assert( pKeyInfo->db==db );
82505        assert( pKeyInfo->enc==ENC(db) );
82506        rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
82507                                pKeyInfo, pCx->uc.pCursor);
82508      }
82509      pCx->isTable = 0;
82510    }else{
82511      rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
82512                              0, pCx->uc.pCursor);
82513      pCx->isTable = 1;
82514    }
82515  }
82516  if( rc ) goto abort_due_to_error;
82517  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
82518  break;
82519}
82520
82521/* Opcode: SorterOpen P1 P2 P3 P4 *
82522**
82523** This opcode works like OP_OpenEphemeral except that it opens
82524** a transient index that is specifically designed to sort large
82525** tables using an external merge-sort algorithm.
82526**
82527** If argument P3 is non-zero, then it indicates that the sorter may
82528** assume that a stable sort considering the first P3 fields of each
82529** key is sufficient to produce the required results.
82530*/
82531case OP_SorterOpen: {
82532  VdbeCursor *pCx;
82533
82534  assert( pOp->p1>=0 );
82535  assert( pOp->p2>=0 );
82536  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
82537  if( pCx==0 ) goto no_mem;
82538  pCx->pKeyInfo = pOp->p4.pKeyInfo;
82539  assert( pCx->pKeyInfo->db==db );
82540  assert( pCx->pKeyInfo->enc==ENC(db) );
82541  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
82542  if( rc ) goto abort_due_to_error;
82543  break;
82544}
82545
82546/* Opcode: SequenceTest P1 P2 * * *
82547** Synopsis: if( cursor[P1].ctr++ ) pc = P2
82548**
82549** P1 is a sorter cursor. If the sequence counter is currently zero, jump
82550** to P2. Regardless of whether or not the jump is taken, increment the
82551** the sequence value.
82552*/
82553case OP_SequenceTest: {
82554  VdbeCursor *pC;
82555  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82556  pC = p->apCsr[pOp->p1];
82557  assert( isSorter(pC) );
82558  if( (pC->seqCount++)==0 ){
82559    goto jump_to_p2;
82560  }
82561  break;
82562}
82563
82564/* Opcode: OpenPseudo P1 P2 P3 * *
82565** Synopsis: P3 columns in r[P2]
82566**
82567** Open a new cursor that points to a fake table that contains a single
82568** row of data.  The content of that one row is the content of memory
82569** register P2.  In other words, cursor P1 becomes an alias for the
82570** MEM_Blob content contained in register P2.
82571**
82572** A pseudo-table created by this opcode is used to hold a single
82573** row output from the sorter so that the row can be decomposed into
82574** individual columns using the OP_Column opcode.  The OP_Column opcode
82575** is the only cursor opcode that works with a pseudo-table.
82576**
82577** P3 is the number of fields in the records that will be stored by
82578** the pseudo-table.
82579*/
82580case OP_OpenPseudo: {
82581  VdbeCursor *pCx;
82582
82583  assert( pOp->p1>=0 );
82584  assert( pOp->p3>=0 );
82585  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
82586  if( pCx==0 ) goto no_mem;
82587  pCx->nullRow = 1;
82588  pCx->uc.pseudoTableReg = pOp->p2;
82589  pCx->isTable = 1;
82590  assert( pOp->p5==0 );
82591  break;
82592}
82593
82594/* Opcode: Close P1 * * * *
82595**
82596** Close a cursor previously opened as P1.  If P1 is not
82597** currently open, this instruction is a no-op.
82598*/
82599case OP_Close: {
82600  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82601  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
82602  p->apCsr[pOp->p1] = 0;
82603  break;
82604}
82605
82606#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
82607/* Opcode: ColumnsUsed P1 * * P4 *
82608**
82609** This opcode (which only exists if SQLite was compiled with
82610** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
82611** table or index for cursor P1 are used.  P4 is a 64-bit integer
82612** (P4_INT64) in which the first 63 bits are one for each of the
82613** first 63 columns of the table or index that are actually used
82614** by the cursor.  The high-order bit is set if any column after
82615** the 64th is used.
82616*/
82617case OP_ColumnsUsed: {
82618  VdbeCursor *pC;
82619  pC = p->apCsr[pOp->p1];
82620  assert( pC->eCurType==CURTYPE_BTREE );
82621  pC->maskUsed = *(u64*)pOp->p4.pI64;
82622  break;
82623}
82624#endif
82625
82626/* Opcode: SeekGE P1 P2 P3 P4 *
82627** Synopsis: key=r[P3@P4]
82628**
82629** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
82630** use the value in register P3 as the key.  If cursor P1 refers
82631** to an SQL index, then P3 is the first in an array of P4 registers
82632** that are used as an unpacked index key.
82633**
82634** Reposition cursor P1 so that  it points to the smallest entry that
82635** is greater than or equal to the key value. If there are no records
82636** greater than or equal to the key and P2 is not zero, then jump to P2.
82637**
82638** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
82639** opcode will always land on a record that equally equals the key, or
82640** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
82641** opcode must be followed by an IdxLE opcode with the same arguments.
82642** The IdxLE opcode will be skipped if this opcode succeeds, but the
82643** IdxLE opcode will be used on subsequent loop iterations.
82644**
82645** This opcode leaves the cursor configured to move in forward order,
82646** from the beginning toward the end.  In other words, the cursor is
82647** configured to use Next, not Prev.
82648**
82649** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
82650*/
82651/* Opcode: SeekGT P1 P2 P3 P4 *
82652** Synopsis: key=r[P3@P4]
82653**
82654** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
82655** use the value in register P3 as a key. If cursor P1 refers
82656** to an SQL index, then P3 is the first in an array of P4 registers
82657** that are used as an unpacked index key.
82658**
82659** Reposition cursor P1 so that  it points to the smallest entry that
82660** is greater than the key value. If there are no records greater than
82661** the key and P2 is not zero, then jump to P2.
82662**
82663** This opcode leaves the cursor configured to move in forward order,
82664** from the beginning toward the end.  In other words, the cursor is
82665** configured to use Next, not Prev.
82666**
82667** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
82668*/
82669/* Opcode: SeekLT P1 P2 P3 P4 *
82670** Synopsis: key=r[P3@P4]
82671**
82672** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
82673** use the value in register P3 as a key. If cursor P1 refers
82674** to an SQL index, then P3 is the first in an array of P4 registers
82675** that are used as an unpacked index key.
82676**
82677** Reposition cursor P1 so that  it points to the largest entry that
82678** is less than the key value. If there are no records less than
82679** the key and P2 is not zero, then jump to P2.
82680**
82681** This opcode leaves the cursor configured to move in reverse order,
82682** from the end toward the beginning.  In other words, the cursor is
82683** configured to use Prev, not Next.
82684**
82685** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
82686*/
82687/* Opcode: SeekLE P1 P2 P3 P4 *
82688** Synopsis: key=r[P3@P4]
82689**
82690** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
82691** use the value in register P3 as a key. If cursor P1 refers
82692** to an SQL index, then P3 is the first in an array of P4 registers
82693** that are used as an unpacked index key.
82694**
82695** Reposition cursor P1 so that it points to the largest entry that
82696** is less than or equal to the key value. If there are no records
82697** less than or equal to the key and P2 is not zero, then jump to P2.
82698**
82699** This opcode leaves the cursor configured to move in reverse order,
82700** from the end toward the beginning.  In other words, the cursor is
82701** configured to use Prev, not Next.
82702**
82703** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
82704** opcode will always land on a record that equally equals the key, or
82705** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
82706** opcode must be followed by an IdxGE opcode with the same arguments.
82707** The IdxGE opcode will be skipped if this opcode succeeds, but the
82708** IdxGE opcode will be used on subsequent loop iterations.
82709**
82710** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
82711*/
82712case OP_SeekLT:         /* jump, in3 */
82713case OP_SeekLE:         /* jump, in3 */
82714case OP_SeekGE:         /* jump, in3 */
82715case OP_SeekGT: {       /* jump, in3 */
82716  int res;           /* Comparison result */
82717  int oc;            /* Opcode */
82718  VdbeCursor *pC;    /* The cursor to seek */
82719  UnpackedRecord r;  /* The key to seek for */
82720  int nField;        /* Number of columns or fields in the key */
82721  i64 iKey;          /* The rowid we are to seek to */
82722  int eqOnly;        /* Only interested in == results */
82723
82724  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82725  assert( pOp->p2!=0 );
82726  pC = p->apCsr[pOp->p1];
82727  assert( pC!=0 );
82728  assert( pC->eCurType==CURTYPE_BTREE );
82729  assert( OP_SeekLE == OP_SeekLT+1 );
82730  assert( OP_SeekGE == OP_SeekLT+2 );
82731  assert( OP_SeekGT == OP_SeekLT+3 );
82732  assert( pC->isOrdered );
82733  assert( pC->uc.pCursor!=0 );
82734  oc = pOp->opcode;
82735  eqOnly = 0;
82736  pC->nullRow = 0;
82737#ifdef SQLITE_DEBUG
82738  pC->seekOp = pOp->opcode;
82739#endif
82740
82741  if( pC->isTable ){
82742    /* The BTREE_SEEK_EQ flag is only set on index cursors */
82743    assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
82744              || CORRUPT_DB );
82745
82746    /* The input value in P3 might be of any type: integer, real, string,
82747    ** blob, or NULL.  But it needs to be an integer before we can do
82748    ** the seek, so convert it. */
82749    pIn3 = &aMem[pOp->p3];
82750    if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
82751      applyNumericAffinity(pIn3, 0);
82752    }
82753    iKey = sqlite3VdbeIntValue(pIn3);
82754
82755    /* If the P3 value could not be converted into an integer without
82756    ** loss of information, then special processing is required... */
82757    if( (pIn3->flags & MEM_Int)==0 ){
82758      if( (pIn3->flags & MEM_Real)==0 ){
82759        /* If the P3 value cannot be converted into any kind of a number,
82760        ** then the seek is not possible, so jump to P2 */
82761        VdbeBranchTaken(1,2); goto jump_to_p2;
82762        break;
82763      }
82764
82765      /* If the approximation iKey is larger than the actual real search
82766      ** term, substitute >= for > and < for <=. e.g. if the search term
82767      ** is 4.9 and the integer approximation 5:
82768      **
82769      **        (x >  4.9)    ->     (x >= 5)
82770      **        (x <= 4.9)    ->     (x <  5)
82771      */
82772      if( pIn3->u.r<(double)iKey ){
82773        assert( OP_SeekGE==(OP_SeekGT-1) );
82774        assert( OP_SeekLT==(OP_SeekLE-1) );
82775        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
82776        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
82777      }
82778
82779      /* If the approximation iKey is smaller than the actual real search
82780      ** term, substitute <= for < and > for >=.  */
82781      else if( pIn3->u.r>(double)iKey ){
82782        assert( OP_SeekLE==(OP_SeekLT+1) );
82783        assert( OP_SeekGT==(OP_SeekGE+1) );
82784        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
82785        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
82786      }
82787    }
82788    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
82789    pC->movetoTarget = iKey;  /* Used by OP_Delete */
82790    if( rc!=SQLITE_OK ){
82791      goto abort_due_to_error;
82792    }
82793  }else{
82794    /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
82795    ** OP_SeekLE opcodes are allowed, and these must be immediately followed
82796    ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
82797    */
82798    if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
82799      eqOnly = 1;
82800      assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
82801      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
82802      assert( pOp[1].p1==pOp[0].p1 );
82803      assert( pOp[1].p2==pOp[0].p2 );
82804      assert( pOp[1].p3==pOp[0].p3 );
82805      assert( pOp[1].p4.i==pOp[0].p4.i );
82806    }
82807
82808    nField = pOp->p4.i;
82809    assert( pOp->p4type==P4_INT32 );
82810    assert( nField>0 );
82811    r.pKeyInfo = pC->pKeyInfo;
82812    r.nField = (u16)nField;
82813
82814    /* The next line of code computes as follows, only faster:
82815    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
82816    **     r.default_rc = -1;
82817    **   }else{
82818    **     r.default_rc = +1;
82819    **   }
82820    */
82821    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
82822    assert( oc!=OP_SeekGT || r.default_rc==-1 );
82823    assert( oc!=OP_SeekLE || r.default_rc==-1 );
82824    assert( oc!=OP_SeekGE || r.default_rc==+1 );
82825    assert( oc!=OP_SeekLT || r.default_rc==+1 );
82826
82827    r.aMem = &aMem[pOp->p3];
82828#ifdef SQLITE_DEBUG
82829    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
82830#endif
82831    r.eqSeen = 0;
82832    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
82833    if( rc!=SQLITE_OK ){
82834      goto abort_due_to_error;
82835    }
82836    if( eqOnly && r.eqSeen==0 ){
82837      assert( res!=0 );
82838      goto seek_not_found;
82839    }
82840  }
82841  pC->deferredMoveto = 0;
82842  pC->cacheStatus = CACHE_STALE;
82843#ifdef SQLITE_TEST
82844  sqlite3_search_count++;
82845#endif
82846  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
82847    if( res<0 || (res==0 && oc==OP_SeekGT) ){
82848      res = 0;
82849      rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
82850      if( rc!=SQLITE_OK ){
82851        if( rc==SQLITE_DONE ){
82852          rc = SQLITE_OK;
82853          res = 1;
82854        }else{
82855          goto abort_due_to_error;
82856        }
82857      }
82858    }else{
82859      res = 0;
82860    }
82861  }else{
82862    assert( oc==OP_SeekLT || oc==OP_SeekLE );
82863    if( res>0 || (res==0 && oc==OP_SeekLT) ){
82864      res = 0;
82865      rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
82866      if( rc!=SQLITE_OK ){
82867        if( rc==SQLITE_DONE ){
82868          rc = SQLITE_OK;
82869          res = 1;
82870        }else{
82871          goto abort_due_to_error;
82872        }
82873      }
82874    }else{
82875      /* res might be negative because the table is empty.  Check to
82876      ** see if this is the case.
82877      */
82878      res = sqlite3BtreeEof(pC->uc.pCursor);
82879    }
82880  }
82881seek_not_found:
82882  assert( pOp->p2>0 );
82883  VdbeBranchTaken(res!=0,2);
82884  if( res ){
82885    goto jump_to_p2;
82886  }else if( eqOnly ){
82887    assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
82888    pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
82889  }
82890  break;
82891}
82892
82893/* Opcode: Found P1 P2 P3 P4 *
82894** Synopsis: key=r[P3@P4]
82895**
82896** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
82897** P4>0 then register P3 is the first of P4 registers that form an unpacked
82898** record.
82899**
82900** Cursor P1 is on an index btree.  If the record identified by P3 and P4
82901** is a prefix of any entry in P1 then a jump is made to P2 and
82902** P1 is left pointing at the matching entry.
82903**
82904** This operation leaves the cursor in a state where it can be
82905** advanced in the forward direction.  The Next instruction will work,
82906** but not the Prev instruction.
82907**
82908** See also: NotFound, NoConflict, NotExists. SeekGe
82909*/
82910/* Opcode: NotFound P1 P2 P3 P4 *
82911** Synopsis: key=r[P3@P4]
82912**
82913** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
82914** P4>0 then register P3 is the first of P4 registers that form an unpacked
82915** record.
82916**
82917** Cursor P1 is on an index btree.  If the record identified by P3 and P4
82918** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
82919** does contain an entry whose prefix matches the P3/P4 record then control
82920** falls through to the next instruction and P1 is left pointing at the
82921** matching entry.
82922**
82923** This operation leaves the cursor in a state where it cannot be
82924** advanced in either direction.  In other words, the Next and Prev
82925** opcodes do not work after this operation.
82926**
82927** See also: Found, NotExists, NoConflict
82928*/
82929/* Opcode: NoConflict P1 P2 P3 P4 *
82930** Synopsis: key=r[P3@P4]
82931**
82932** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
82933** P4>0 then register P3 is the first of P4 registers that form an unpacked
82934** record.
82935**
82936** Cursor P1 is on an index btree.  If the record identified by P3 and P4
82937** contains any NULL value, jump immediately to P2.  If all terms of the
82938** record are not-NULL then a check is done to determine if any row in the
82939** P1 index btree has a matching key prefix.  If there are no matches, jump
82940** immediately to P2.  If there is a match, fall through and leave the P1
82941** cursor pointing to the matching row.
82942**
82943** This opcode is similar to OP_NotFound with the exceptions that the
82944** branch is always taken if any part of the search key input is NULL.
82945**
82946** This operation leaves the cursor in a state where it cannot be
82947** advanced in either direction.  In other words, the Next and Prev
82948** opcodes do not work after this operation.
82949**
82950** See also: NotFound, Found, NotExists
82951*/
82952case OP_NoConflict:     /* jump, in3 */
82953case OP_NotFound:       /* jump, in3 */
82954case OP_Found: {        /* jump, in3 */
82955  int alreadyExists;
82956  int takeJump;
82957  int ii;
82958  VdbeCursor *pC;
82959  int res;
82960  UnpackedRecord *pFree;
82961  UnpackedRecord *pIdxKey;
82962  UnpackedRecord r;
82963
82964#ifdef SQLITE_TEST
82965  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
82966#endif
82967
82968  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82969  assert( pOp->p4type==P4_INT32 );
82970  pC = p->apCsr[pOp->p1];
82971  assert( pC!=0 );
82972#ifdef SQLITE_DEBUG
82973  pC->seekOp = pOp->opcode;
82974#endif
82975  pIn3 = &aMem[pOp->p3];
82976  assert( pC->eCurType==CURTYPE_BTREE );
82977  assert( pC->uc.pCursor!=0 );
82978  assert( pC->isTable==0 );
82979  if( pOp->p4.i>0 ){
82980    r.pKeyInfo = pC->pKeyInfo;
82981    r.nField = (u16)pOp->p4.i;
82982    r.aMem = pIn3;
82983#ifdef SQLITE_DEBUG
82984    for(ii=0; ii<r.nField; ii++){
82985      assert( memIsValid(&r.aMem[ii]) );
82986      assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
82987      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
82988    }
82989#endif
82990    pIdxKey = &r;
82991    pFree = 0;
82992  }else{
82993    assert( pIn3->flags & MEM_Blob );
82994    rc = ExpandBlob(pIn3);
82995    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
82996    if( rc ) goto no_mem;
82997    pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
82998    if( pIdxKey==0 ) goto no_mem;
82999    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
83000  }
83001  pIdxKey->default_rc = 0;
83002  takeJump = 0;
83003  if( pOp->opcode==OP_NoConflict ){
83004    /* For the OP_NoConflict opcode, take the jump if any of the
83005    ** input fields are NULL, since any key with a NULL will not
83006    ** conflict */
83007    for(ii=0; ii<pIdxKey->nField; ii++){
83008      if( pIdxKey->aMem[ii].flags & MEM_Null ){
83009        takeJump = 1;
83010        break;
83011      }
83012    }
83013  }
83014  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
83015  if( pFree ) sqlite3DbFreeNN(db, pFree);
83016  if( rc!=SQLITE_OK ){
83017    goto abort_due_to_error;
83018  }
83019  pC->seekResult = res;
83020  alreadyExists = (res==0);
83021  pC->nullRow = 1-alreadyExists;
83022  pC->deferredMoveto = 0;
83023  pC->cacheStatus = CACHE_STALE;
83024  if( pOp->opcode==OP_Found ){
83025    VdbeBranchTaken(alreadyExists!=0,2);
83026    if( alreadyExists ) goto jump_to_p2;
83027  }else{
83028    VdbeBranchTaken(takeJump||alreadyExists==0,2);
83029    if( takeJump || !alreadyExists ) goto jump_to_p2;
83030  }
83031  break;
83032}
83033
83034/* Opcode: SeekRowid P1 P2 P3 * *
83035** Synopsis: intkey=r[P3]
83036**
83037** P1 is the index of a cursor open on an SQL table btree (with integer
83038** keys).  If register P3 does not contain an integer or if P1 does not
83039** contain a record with rowid P3 then jump immediately to P2.
83040** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
83041** a record with rowid P3 then
83042** leave the cursor pointing at that record and fall through to the next
83043** instruction.
83044**
83045** The OP_NotExists opcode performs the same operation, but with OP_NotExists
83046** the P3 register must be guaranteed to contain an integer value.  With this
83047** opcode, register P3 might not contain an integer.
83048**
83049** The OP_NotFound opcode performs the same operation on index btrees
83050** (with arbitrary multi-value keys).
83051**
83052** This opcode leaves the cursor in a state where it cannot be advanced
83053** in either direction.  In other words, the Next and Prev opcodes will
83054** not work following this opcode.
83055**
83056** See also: Found, NotFound, NoConflict, SeekRowid
83057*/
83058/* Opcode: NotExists P1 P2 P3 * *
83059** Synopsis: intkey=r[P3]
83060**
83061** P1 is the index of a cursor open on an SQL table btree (with integer
83062** keys).  P3 is an integer rowid.  If P1 does not contain a record with
83063** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
83064** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
83065** leave the cursor pointing at that record and fall through to the next
83066** instruction.
83067**
83068** The OP_SeekRowid opcode performs the same operation but also allows the
83069** P3 register to contain a non-integer value, in which case the jump is
83070** always taken.  This opcode requires that P3 always contain an integer.
83071**
83072** The OP_NotFound opcode performs the same operation on index btrees
83073** (with arbitrary multi-value keys).
83074**
83075** This opcode leaves the cursor in a state where it cannot be advanced
83076** in either direction.  In other words, the Next and Prev opcodes will
83077** not work following this opcode.
83078**
83079** See also: Found, NotFound, NoConflict, SeekRowid
83080*/
83081case OP_SeekRowid: {        /* jump, in3 */
83082  VdbeCursor *pC;
83083  BtCursor *pCrsr;
83084  int res;
83085  u64 iKey;
83086
83087  pIn3 = &aMem[pOp->p3];
83088  if( (pIn3->flags & MEM_Int)==0 ){
83089    applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
83090    if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
83091  }
83092  /* Fall through into OP_NotExists */
83093case OP_NotExists:          /* jump, in3 */
83094  pIn3 = &aMem[pOp->p3];
83095  assert( pIn3->flags & MEM_Int );
83096  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83097  pC = p->apCsr[pOp->p1];
83098  assert( pC!=0 );
83099#ifdef SQLITE_DEBUG
83100  pC->seekOp = 0;
83101#endif
83102  assert( pC->isTable );
83103  assert( pC->eCurType==CURTYPE_BTREE );
83104  pCrsr = pC->uc.pCursor;
83105  assert( pCrsr!=0 );
83106  res = 0;
83107  iKey = pIn3->u.i;
83108  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
83109  assert( rc==SQLITE_OK || res==0 );
83110  pC->movetoTarget = iKey;  /* Used by OP_Delete */
83111  pC->nullRow = 0;
83112  pC->cacheStatus = CACHE_STALE;
83113  pC->deferredMoveto = 0;
83114  VdbeBranchTaken(res!=0,2);
83115  pC->seekResult = res;
83116  if( res!=0 ){
83117    assert( rc==SQLITE_OK );
83118    if( pOp->p2==0 ){
83119      rc = SQLITE_CORRUPT_BKPT;
83120    }else{
83121      goto jump_to_p2;
83122    }
83123  }
83124  if( rc ) goto abort_due_to_error;
83125  break;
83126}
83127
83128/* Opcode: Sequence P1 P2 * * *
83129** Synopsis: r[P2]=cursor[P1].ctr++
83130**
83131** Find the next available sequence number for cursor P1.
83132** Write the sequence number into register P2.
83133** The sequence number on the cursor is incremented after this
83134** instruction.
83135*/
83136case OP_Sequence: {           /* out2 */
83137  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83138  assert( p->apCsr[pOp->p1]!=0 );
83139  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
83140  pOut = out2Prerelease(p, pOp);
83141  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
83142  break;
83143}
83144
83145
83146/* Opcode: NewRowid P1 P2 P3 * *
83147** Synopsis: r[P2]=rowid
83148**
83149** Get a new integer record number (a.k.a "rowid") used as the key to a table.
83150** The record number is not previously used as a key in the database
83151** table that cursor P1 points to.  The new record number is written
83152** written to register P2.
83153**
83154** If P3>0 then P3 is a register in the root frame of this VDBE that holds
83155** the largest previously generated record number. No new record numbers are
83156** allowed to be less than this value. When this value reaches its maximum,
83157** an SQLITE_FULL error is generated. The P3 register is updated with the '
83158** generated record number. This P3 mechanism is used to help implement the
83159** AUTOINCREMENT feature.
83160*/
83161case OP_NewRowid: {           /* out2 */
83162  i64 v;                 /* The new rowid */
83163  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
83164  int res;               /* Result of an sqlite3BtreeLast() */
83165  int cnt;               /* Counter to limit the number of searches */
83166  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
83167  VdbeFrame *pFrame;     /* Root frame of VDBE */
83168
83169  v = 0;
83170  res = 0;
83171  pOut = out2Prerelease(p, pOp);
83172  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83173  pC = p->apCsr[pOp->p1];
83174  assert( pC!=0 );
83175  assert( pC->eCurType==CURTYPE_BTREE );
83176  assert( pC->uc.pCursor!=0 );
83177  {
83178    /* The next rowid or record number (different terms for the same
83179    ** thing) is obtained in a two-step algorithm.
83180    **
83181    ** First we attempt to find the largest existing rowid and add one
83182    ** to that.  But if the largest existing rowid is already the maximum
83183    ** positive integer, we have to fall through to the second
83184    ** probabilistic algorithm
83185    **
83186    ** The second algorithm is to select a rowid at random and see if
83187    ** it already exists in the table.  If it does not exist, we have
83188    ** succeeded.  If the random rowid does exist, we select a new one
83189    ** and try again, up to 100 times.
83190    */
83191    assert( pC->isTable );
83192
83193#ifdef SQLITE_32BIT_ROWID
83194#   define MAX_ROWID 0x7fffffff
83195#else
83196    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
83197    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
83198    ** to provide the constant while making all compilers happy.
83199    */
83200#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
83201#endif
83202
83203    if( !pC->useRandomRowid ){
83204      rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
83205      if( rc!=SQLITE_OK ){
83206        goto abort_due_to_error;
83207      }
83208      if( res ){
83209        v = 1;   /* IMP: R-61914-48074 */
83210      }else{
83211        assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
83212        v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
83213        if( v>=MAX_ROWID ){
83214          pC->useRandomRowid = 1;
83215        }else{
83216          v++;   /* IMP: R-29538-34987 */
83217        }
83218      }
83219    }
83220
83221#ifndef SQLITE_OMIT_AUTOINCREMENT
83222    if( pOp->p3 ){
83223      /* Assert that P3 is a valid memory cell. */
83224      assert( pOp->p3>0 );
83225      if( p->pFrame ){
83226        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
83227        /* Assert that P3 is a valid memory cell. */
83228        assert( pOp->p3<=pFrame->nMem );
83229        pMem = &pFrame->aMem[pOp->p3];
83230      }else{
83231        /* Assert that P3 is a valid memory cell. */
83232        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
83233        pMem = &aMem[pOp->p3];
83234        memAboutToChange(p, pMem);
83235      }
83236      assert( memIsValid(pMem) );
83237
83238      REGISTER_TRACE(pOp->p3, pMem);
83239      sqlite3VdbeMemIntegerify(pMem);
83240      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
83241      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
83242        rc = SQLITE_FULL;   /* IMP: R-17817-00630 */
83243        goto abort_due_to_error;
83244      }
83245      if( v<pMem->u.i+1 ){
83246        v = pMem->u.i + 1;
83247      }
83248      pMem->u.i = v;
83249    }
83250#endif
83251    if( pC->useRandomRowid ){
83252      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
83253      ** largest possible integer (9223372036854775807) then the database
83254      ** engine starts picking positive candidate ROWIDs at random until
83255      ** it finds one that is not previously used. */
83256      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
83257                             ** an AUTOINCREMENT table. */
83258      cnt = 0;
83259      do{
83260        sqlite3_randomness(sizeof(v), &v);
83261        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
83262      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
83263                                                 0, &res))==SQLITE_OK)
83264            && (res==0)
83265            && (++cnt<100));
83266      if( rc ) goto abort_due_to_error;
83267      if( res==0 ){
83268        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
83269        goto abort_due_to_error;
83270      }
83271      assert( v>0 );  /* EV: R-40812-03570 */
83272    }
83273    pC->deferredMoveto = 0;
83274    pC->cacheStatus = CACHE_STALE;
83275  }
83276  pOut->u.i = v;
83277  break;
83278}
83279
83280/* Opcode: Insert P1 P2 P3 P4 P5
83281** Synopsis: intkey=r[P3] data=r[P2]
83282**
83283** Write an entry into the table of cursor P1.  A new entry is
83284** created if it doesn't already exist or the data for an existing
83285** entry is overwritten.  The data is the value MEM_Blob stored in register
83286** number P2. The key is stored in register P3. The key must
83287** be a MEM_Int.
83288**
83289** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
83290** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
83291** then rowid is stored for subsequent return by the
83292** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
83293**
83294** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
83295** run faster by avoiding an unnecessary seek on cursor P1.  However,
83296** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
83297** seeks on the cursor or if the most recent seek used a key equal to P3.
83298**
83299** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
83300** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
83301** is part of an INSERT operation.  The difference is only important to
83302** the update hook.
83303**
83304** Parameter P4 may point to a Table structure, or may be NULL. If it is
83305** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
83306** following a successful insert.
83307**
83308** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
83309** allocated, then ownership of P2 is transferred to the pseudo-cursor
83310** and register P2 becomes ephemeral.  If the cursor is changed, the
83311** value of register P2 will then change.  Make sure this does not
83312** cause any problems.)
83313**
83314** This instruction only works on tables.  The equivalent instruction
83315** for indices is OP_IdxInsert.
83316*/
83317/* Opcode: InsertInt P1 P2 P3 P4 P5
83318** Synopsis: intkey=P3 data=r[P2]
83319**
83320** This works exactly like OP_Insert except that the key is the
83321** integer value P3, not the value of the integer stored in register P3.
83322*/
83323case OP_Insert:
83324case OP_InsertInt: {
83325  Mem *pData;       /* MEM cell holding data for the record to be inserted */
83326  Mem *pKey;        /* MEM cell holding key  for the record */
83327  VdbeCursor *pC;   /* Cursor to table into which insert is written */
83328  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
83329  const char *zDb;  /* database name - used by the update hook */
83330  Table *pTab;      /* Table structure - used by update and pre-update hooks */
83331  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
83332  BtreePayload x;   /* Payload to be inserted */
83333
83334  op = 0;
83335  pData = &aMem[pOp->p2];
83336  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83337  assert( memIsValid(pData) );
83338  pC = p->apCsr[pOp->p1];
83339  assert( pC!=0 );
83340  assert( pC->eCurType==CURTYPE_BTREE );
83341  assert( pC->uc.pCursor!=0 );
83342  assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
83343  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
83344  REGISTER_TRACE(pOp->p2, pData);
83345
83346  if( pOp->opcode==OP_Insert ){
83347    pKey = &aMem[pOp->p3];
83348    assert( pKey->flags & MEM_Int );
83349    assert( memIsValid(pKey) );
83350    REGISTER_TRACE(pOp->p3, pKey);
83351    x.nKey = pKey->u.i;
83352  }else{
83353    assert( pOp->opcode==OP_InsertInt );
83354    x.nKey = pOp->p3;
83355  }
83356
83357  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
83358    assert( pC->iDb>=0 );
83359    zDb = db->aDb[pC->iDb].zDbSName;
83360    pTab = pOp->p4.pTab;
83361    assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
83362    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
83363  }else{
83364    pTab = 0; /* Not needed.  Silence a compiler warning. */
83365    zDb = 0;  /* Not needed.  Silence a compiler warning. */
83366  }
83367
83368#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
83369  /* Invoke the pre-update hook, if any */
83370  if( db->xPreUpdateCallback
83371   && pOp->p4type==P4_TABLE
83372   && !(pOp->p5 & OPFLAG_ISUPDATE)
83373  ){
83374    sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
83375  }
83376  if( pOp->p5 & OPFLAG_ISNOOP ) break;
83377#endif
83378
83379  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
83380  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
83381  if( pData->flags & MEM_Null ){
83382    x.pData = 0;
83383    x.nData = 0;
83384  }else{
83385    assert( pData->flags & (MEM_Blob|MEM_Str) );
83386    x.pData = pData->z;
83387    x.nData = pData->n;
83388  }
83389  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
83390  if( pData->flags & MEM_Zero ){
83391    x.nZero = pData->u.nZero;
83392  }else{
83393    x.nZero = 0;
83394  }
83395  x.pKey = 0;
83396  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
83397      (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
83398  );
83399  pC->deferredMoveto = 0;
83400  pC->cacheStatus = CACHE_STALE;
83401
83402  /* Invoke the update-hook if required. */
83403  if( rc ) goto abort_due_to_error;
83404  if( db->xUpdateCallback && op ){
83405    db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
83406  }
83407  break;
83408}
83409
83410/* Opcode: Delete P1 P2 P3 P4 P5
83411**
83412** Delete the record at which the P1 cursor is currently pointing.
83413**
83414** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
83415** the cursor will be left pointing at  either the next or the previous
83416** record in the table. If it is left pointing at the next record, then
83417** the next Next instruction will be a no-op. As a result, in this case
83418** it is ok to delete a record from within a Next loop. If
83419** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
83420** left in an undefined state.
83421**
83422** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
83423** delete one of several associated with deleting a table row and all its
83424** associated index entries.  Exactly one of those deletes is the "primary"
83425** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
83426** marked with the AUXDELETE flag.
83427**
83428** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
83429** change count is incremented (otherwise not).
83430**
83431** P1 must not be pseudo-table.  It has to be a real table with
83432** multiple rows.
83433**
83434** If P4 is not NULL then it points to a Table object. In this case either
83435** the update or pre-update hook, or both, may be invoked. The P1 cursor must
83436** have been positioned using OP_NotFound prior to invoking this opcode in
83437** this case. Specifically, if one is configured, the pre-update hook is
83438** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
83439** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
83440**
83441** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
83442** of the memory cell that contains the value that the rowid of the row will
83443** be set to by the update.
83444*/
83445case OP_Delete: {
83446  VdbeCursor *pC;
83447  const char *zDb;
83448  Table *pTab;
83449  int opflags;
83450
83451  opflags = pOp->p2;
83452  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83453  pC = p->apCsr[pOp->p1];
83454  assert( pC!=0 );
83455  assert( pC->eCurType==CURTYPE_BTREE );
83456  assert( pC->uc.pCursor!=0 );
83457  assert( pC->deferredMoveto==0 );
83458
83459#ifdef SQLITE_DEBUG
83460  if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
83461    /* If p5 is zero, the seek operation that positioned the cursor prior to
83462    ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
83463    ** the row that is being deleted */
83464    i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
83465    assert( pC->movetoTarget==iKey );
83466  }
83467#endif
83468
83469  /* If the update-hook or pre-update-hook will be invoked, set zDb to
83470  ** the name of the db to pass as to it. Also set local pTab to a copy
83471  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
83472  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
83473  ** VdbeCursor.movetoTarget to the current rowid.  */
83474  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
83475    assert( pC->iDb>=0 );
83476    assert( pOp->p4.pTab!=0 );
83477    zDb = db->aDb[pC->iDb].zDbSName;
83478    pTab = pOp->p4.pTab;
83479    if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
83480      pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
83481    }
83482  }else{
83483    zDb = 0;   /* Not needed.  Silence a compiler warning. */
83484    pTab = 0;  /* Not needed.  Silence a compiler warning. */
83485  }
83486
83487#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
83488  /* Invoke the pre-update-hook if required. */
83489  if( db->xPreUpdateCallback && pOp->p4.pTab ){
83490    assert( !(opflags & OPFLAG_ISUPDATE)
83491         || HasRowid(pTab)==0
83492         || (aMem[pOp->p3].flags & MEM_Int)
83493    );
83494    sqlite3VdbePreUpdateHook(p, pC,
83495        (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
83496        zDb, pTab, pC->movetoTarget,
83497        pOp->p3
83498    );
83499  }
83500  if( opflags & OPFLAG_ISNOOP ) break;
83501#endif
83502
83503  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
83504  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
83505  assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
83506  assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
83507
83508#ifdef SQLITE_DEBUG
83509  if( p->pFrame==0 ){
83510    if( pC->isEphemeral==0
83511        && (pOp->p5 & OPFLAG_AUXDELETE)==0
83512        && (pC->wrFlag & OPFLAG_FORDELETE)==0
83513      ){
83514      nExtraDelete++;
83515    }
83516    if( pOp->p2 & OPFLAG_NCHANGE ){
83517      nExtraDelete--;
83518    }
83519  }
83520#endif
83521
83522  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
83523  pC->cacheStatus = CACHE_STALE;
83524  pC->seekResult = 0;
83525  if( rc ) goto abort_due_to_error;
83526
83527  /* Invoke the update-hook if required. */
83528  if( opflags & OPFLAG_NCHANGE ){
83529    p->nChange++;
83530    if( db->xUpdateCallback && HasRowid(pTab) ){
83531      db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
83532          pC->movetoTarget);
83533      assert( pC->iDb>=0 );
83534    }
83535  }
83536
83537  break;
83538}
83539/* Opcode: ResetCount * * * * *
83540**
83541** The value of the change counter is copied to the database handle
83542** change counter (returned by subsequent calls to sqlite3_changes()).
83543** Then the VMs internal change counter resets to 0.
83544** This is used by trigger programs.
83545*/
83546case OP_ResetCount: {
83547  sqlite3VdbeSetChanges(db, p->nChange);
83548  p->nChange = 0;
83549  break;
83550}
83551
83552/* Opcode: SorterCompare P1 P2 P3 P4
83553** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
83554**
83555** P1 is a sorter cursor. This instruction compares a prefix of the
83556** record blob in register P3 against a prefix of the entry that
83557** the sorter cursor currently points to.  Only the first P4 fields
83558** of r[P3] and the sorter record are compared.
83559**
83560** If either P3 or the sorter contains a NULL in one of their significant
83561** fields (not counting the P4 fields at the end which are ignored) then
83562** the comparison is assumed to be equal.
83563**
83564** Fall through to next instruction if the two records compare equal to
83565** each other.  Jump to P2 if they are different.
83566*/
83567case OP_SorterCompare: {
83568  VdbeCursor *pC;
83569  int res;
83570  int nKeyCol;
83571
83572  pC = p->apCsr[pOp->p1];
83573  assert( isSorter(pC) );
83574  assert( pOp->p4type==P4_INT32 );
83575  pIn3 = &aMem[pOp->p3];
83576  nKeyCol = pOp->p4.i;
83577  res = 0;
83578  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
83579  VdbeBranchTaken(res!=0,2);
83580  if( rc ) goto abort_due_to_error;
83581  if( res ) goto jump_to_p2;
83582  break;
83583};
83584
83585/* Opcode: SorterData P1 P2 P3 * *
83586** Synopsis: r[P2]=data
83587**
83588** Write into register P2 the current sorter data for sorter cursor P1.
83589** Then clear the column header cache on cursor P3.
83590**
83591** This opcode is normally use to move a record out of the sorter and into
83592** a register that is the source for a pseudo-table cursor created using
83593** OpenPseudo.  That pseudo-table cursor is the one that is identified by
83594** parameter P3.  Clearing the P3 column cache as part of this opcode saves
83595** us from having to issue a separate NullRow instruction to clear that cache.
83596*/
83597case OP_SorterData: {
83598  VdbeCursor *pC;
83599
83600  pOut = &aMem[pOp->p2];
83601  pC = p->apCsr[pOp->p1];
83602  assert( isSorter(pC) );
83603  rc = sqlite3VdbeSorterRowkey(pC, pOut);
83604  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
83605  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83606  if( rc ) goto abort_due_to_error;
83607  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
83608  break;
83609}
83610
83611/* Opcode: RowData P1 P2 P3 * *
83612** Synopsis: r[P2]=data
83613**
83614** Write into register P2 the complete row content for the row at
83615** which cursor P1 is currently pointing.
83616** There is no interpretation of the data.
83617** It is just copied onto the P2 register exactly as
83618** it is found in the database file.
83619**
83620** If cursor P1 is an index, then the content is the key of the row.
83621** If cursor P2 is a table, then the content extracted is the data.
83622**
83623** If the P1 cursor must be pointing to a valid row (not a NULL row)
83624** of a real table, not a pseudo-table.
83625**
83626** If P3!=0 then this opcode is allowed to make an ephermeral pointer
83627** into the database page.  That means that the content of the output
83628** register will be invalidated as soon as the cursor moves - including
83629** moves caused by other cursors that "save" the the current cursors
83630** position in order that they can write to the same table.  If P3==0
83631** then a copy of the data is made into memory.  P3!=0 is faster, but
83632** P3==0 is safer.
83633**
83634** If P3!=0 then the content of the P2 register is unsuitable for use
83635** in OP_Result and any OP_Result will invalidate the P2 register content.
83636** The P2 register content is invalidated by opcodes like OP_Function or
83637** by any use of another cursor pointing to the same table.
83638*/
83639case OP_RowData: {
83640  VdbeCursor *pC;
83641  BtCursor *pCrsr;
83642  u32 n;
83643
83644  pOut = out2Prerelease(p, pOp);
83645
83646  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83647  pC = p->apCsr[pOp->p1];
83648  assert( pC!=0 );
83649  assert( pC->eCurType==CURTYPE_BTREE );
83650  assert( isSorter(pC)==0 );
83651  assert( pC->nullRow==0 );
83652  assert( pC->uc.pCursor!=0 );
83653  pCrsr = pC->uc.pCursor;
83654
83655  /* The OP_RowData opcodes always follow OP_NotExists or
83656  ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
83657  ** that might invalidate the cursor.
83658  ** If this where not the case, on of the following assert()s
83659  ** would fail.  Should this ever change (because of changes in the code
83660  ** generator) then the fix would be to insert a call to
83661  ** sqlite3VdbeCursorMoveto().
83662  */
83663  assert( pC->deferredMoveto==0 );
83664  assert( sqlite3BtreeCursorIsValid(pCrsr) );
83665#if 0  /* Not required due to the previous to assert() statements */
83666  rc = sqlite3VdbeCursorMoveto(pC);
83667  if( rc!=SQLITE_OK ) goto abort_due_to_error;
83668#endif
83669
83670  n = sqlite3BtreePayloadSize(pCrsr);
83671  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
83672    goto too_big;
83673  }
83674  testcase( n==0 );
83675  rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
83676  if( rc ) goto abort_due_to_error;
83677  if( !pOp->p3 ) Deephemeralize(pOut);
83678  UPDATE_MAX_BLOBSIZE(pOut);
83679  REGISTER_TRACE(pOp->p2, pOut);
83680  break;
83681}
83682
83683/* Opcode: Rowid P1 P2 * * *
83684** Synopsis: r[P2]=rowid
83685**
83686** Store in register P2 an integer which is the key of the table entry that
83687** P1 is currently point to.
83688**
83689** P1 can be either an ordinary table or a virtual table.  There used to
83690** be a separate OP_VRowid opcode for use with virtual tables, but this
83691** one opcode now works for both table types.
83692*/
83693case OP_Rowid: {                 /* out2 */
83694  VdbeCursor *pC;
83695  i64 v;
83696  sqlite3_vtab *pVtab;
83697  const sqlite3_module *pModule;
83698
83699  pOut = out2Prerelease(p, pOp);
83700  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83701  pC = p->apCsr[pOp->p1];
83702  assert( pC!=0 );
83703  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
83704  if( pC->nullRow ){
83705    pOut->flags = MEM_Null;
83706    break;
83707  }else if( pC->deferredMoveto ){
83708    v = pC->movetoTarget;
83709#ifndef SQLITE_OMIT_VIRTUALTABLE
83710  }else if( pC->eCurType==CURTYPE_VTAB ){
83711    assert( pC->uc.pVCur!=0 );
83712    pVtab = pC->uc.pVCur->pVtab;
83713    pModule = pVtab->pModule;
83714    assert( pModule->xRowid );
83715    rc = pModule->xRowid(pC->uc.pVCur, &v);
83716    sqlite3VtabImportErrmsg(p, pVtab);
83717    if( rc ) goto abort_due_to_error;
83718#endif /* SQLITE_OMIT_VIRTUALTABLE */
83719  }else{
83720    assert( pC->eCurType==CURTYPE_BTREE );
83721    assert( pC->uc.pCursor!=0 );
83722    rc = sqlite3VdbeCursorRestore(pC);
83723    if( rc ) goto abort_due_to_error;
83724    if( pC->nullRow ){
83725      pOut->flags = MEM_Null;
83726      break;
83727    }
83728    v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
83729  }
83730  pOut->u.i = v;
83731  break;
83732}
83733
83734/* Opcode: NullRow P1 * * * *
83735**
83736** Move the cursor P1 to a null row.  Any OP_Column operations
83737** that occur while the cursor is on the null row will always
83738** write a NULL.
83739*/
83740case OP_NullRow: {
83741  VdbeCursor *pC;
83742
83743  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83744  pC = p->apCsr[pOp->p1];
83745  assert( pC!=0 );
83746  pC->nullRow = 1;
83747  pC->cacheStatus = CACHE_STALE;
83748  if( pC->eCurType==CURTYPE_BTREE ){
83749    assert( pC->uc.pCursor!=0 );
83750    sqlite3BtreeClearCursor(pC->uc.pCursor);
83751  }
83752  break;
83753}
83754
83755/* Opcode: Last P1 P2 P3 * *
83756**
83757** The next use of the Rowid or Column or Prev instruction for P1
83758** will refer to the last entry in the database table or index.
83759** If the table or index is empty and P2>0, then jump immediately to P2.
83760** If P2 is 0 or if the table or index is not empty, fall through
83761** to the following instruction.
83762**
83763** This opcode leaves the cursor configured to move in reverse order,
83764** from the end toward the beginning.  In other words, the cursor is
83765** configured to use Prev, not Next.
83766**
83767** If P3 is -1, then the cursor is positioned at the end of the btree
83768** for the purpose of appending a new entry onto the btree.  In that
83769** case P2 must be 0.  It is assumed that the cursor is used only for
83770** appending and so if the cursor is valid, then the cursor must already
83771** be pointing at the end of the btree and so no changes are made to
83772** the cursor.
83773*/
83774case OP_Last: {        /* jump */
83775  VdbeCursor *pC;
83776  BtCursor *pCrsr;
83777  int res;
83778
83779  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83780  pC = p->apCsr[pOp->p1];
83781  assert( pC!=0 );
83782  assert( pC->eCurType==CURTYPE_BTREE );
83783  pCrsr = pC->uc.pCursor;
83784  res = 0;
83785  assert( pCrsr!=0 );
83786  pC->seekResult = pOp->p3;
83787#ifdef SQLITE_DEBUG
83788  pC->seekOp = OP_Last;
83789#endif
83790  if( pOp->p3==0 || !sqlite3BtreeCursorIsValidNN(pCrsr) ){
83791    rc = sqlite3BtreeLast(pCrsr, &res);
83792    pC->nullRow = (u8)res;
83793    pC->deferredMoveto = 0;
83794    pC->cacheStatus = CACHE_STALE;
83795    if( rc ) goto abort_due_to_error;
83796    if( pOp->p2>0 ){
83797      VdbeBranchTaken(res!=0,2);
83798      if( res ) goto jump_to_p2;
83799    }
83800  }else{
83801    assert( pOp->p2==0 );
83802  }
83803  break;
83804}
83805
83806/* Opcode: IfSmaller P1 P2 P3 * *
83807**
83808** Estimate the number of rows in the table P1.  Jump to P2 if that
83809** estimate is less than approximately 2**(0.1*P3).
83810*/
83811case OP_IfSmaller: {        /* jump */
83812  VdbeCursor *pC;
83813  BtCursor *pCrsr;
83814  int res;
83815  i64 sz;
83816
83817  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83818  pC = p->apCsr[pOp->p1];
83819  assert( pC!=0 );
83820  pCrsr = pC->uc.pCursor;
83821  assert( pCrsr );
83822  rc = sqlite3BtreeFirst(pCrsr, &res);
83823  if( rc ) goto abort_due_to_error;
83824  if( res==0 ){
83825    sz = sqlite3BtreeRowCountEst(pCrsr);
83826    if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
83827  }
83828  VdbeBranchTaken(res!=0,2);
83829  if( res ) goto jump_to_p2;
83830  break;
83831}
83832
83833
83834/* Opcode: SorterSort P1 P2 * * *
83835**
83836** After all records have been inserted into the Sorter object
83837** identified by P1, invoke this opcode to actually do the sorting.
83838** Jump to P2 if there are no records to be sorted.
83839**
83840** This opcode is an alias for OP_Sort and OP_Rewind that is used
83841** for Sorter objects.
83842*/
83843/* Opcode: Sort P1 P2 * * *
83844**
83845** This opcode does exactly the same thing as OP_Rewind except that
83846** it increments an undocumented global variable used for testing.
83847**
83848** Sorting is accomplished by writing records into a sorting index,
83849** then rewinding that index and playing it back from beginning to
83850** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
83851** rewinding so that the global variable will be incremented and
83852** regression tests can determine whether or not the optimizer is
83853** correctly optimizing out sorts.
83854*/
83855case OP_SorterSort:    /* jump */
83856case OP_Sort: {        /* jump */
83857#ifdef SQLITE_TEST
83858  sqlite3_sort_count++;
83859  sqlite3_search_count--;
83860#endif
83861  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
83862  /* Fall through into OP_Rewind */
83863}
83864/* Opcode: Rewind P1 P2 * * *
83865**
83866** The next use of the Rowid or Column or Next instruction for P1
83867** will refer to the first entry in the database table or index.
83868** If the table or index is empty, jump immediately to P2.
83869** If the table or index is not empty, fall through to the following
83870** instruction.
83871**
83872** This opcode leaves the cursor configured to move in forward order,
83873** from the beginning toward the end.  In other words, the cursor is
83874** configured to use Next, not Prev.
83875*/
83876case OP_Rewind: {        /* jump */
83877  VdbeCursor *pC;
83878  BtCursor *pCrsr;
83879  int res;
83880
83881  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83882  pC = p->apCsr[pOp->p1];
83883  assert( pC!=0 );
83884  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
83885  res = 1;
83886#ifdef SQLITE_DEBUG
83887  pC->seekOp = OP_Rewind;
83888#endif
83889  if( isSorter(pC) ){
83890    rc = sqlite3VdbeSorterRewind(pC, &res);
83891  }else{
83892    assert( pC->eCurType==CURTYPE_BTREE );
83893    pCrsr = pC->uc.pCursor;
83894    assert( pCrsr );
83895    rc = sqlite3BtreeFirst(pCrsr, &res);
83896    pC->deferredMoveto = 0;
83897    pC->cacheStatus = CACHE_STALE;
83898  }
83899  if( rc ) goto abort_due_to_error;
83900  pC->nullRow = (u8)res;
83901  assert( pOp->p2>0 && pOp->p2<p->nOp );
83902  VdbeBranchTaken(res!=0,2);
83903  if( res ) goto jump_to_p2;
83904  break;
83905}
83906
83907/* Opcode: Next P1 P2 P3 P4 P5
83908**
83909** Advance cursor P1 so that it points to the next key/data pair in its
83910** table or index.  If there are no more key/value pairs then fall through
83911** to the following instruction.  But if the cursor advance was successful,
83912** jump immediately to P2.
83913**
83914** The Next opcode is only valid following an SeekGT, SeekGE, or
83915** OP_Rewind opcode used to position the cursor.  Next is not allowed
83916** to follow SeekLT, SeekLE, or OP_Last.
83917**
83918** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
83919** been opened prior to this opcode or the program will segfault.
83920**
83921** The P3 value is a hint to the btree implementation. If P3==1, that
83922** means P1 is an SQL index and that this instruction could have been
83923** omitted if that index had been unique.  P3 is usually 0.  P3 is
83924** always either 0 or 1.
83925**
83926** P4 is always of type P4_ADVANCE. The function pointer points to
83927** sqlite3BtreeNext().
83928**
83929** If P5 is positive and the jump is taken, then event counter
83930** number P5-1 in the prepared statement is incremented.
83931**
83932** See also: Prev, NextIfOpen
83933*/
83934/* Opcode: NextIfOpen P1 P2 P3 P4 P5
83935**
83936** This opcode works just like Next except that if cursor P1 is not
83937** open it behaves a no-op.
83938*/
83939/* Opcode: Prev P1 P2 P3 P4 P5
83940**
83941** Back up cursor P1 so that it points to the previous key/data pair in its
83942** table or index.  If there is no previous key/value pairs then fall through
83943** to the following instruction.  But if the cursor backup was successful,
83944** jump immediately to P2.
83945**
83946**
83947** The Prev opcode is only valid following an SeekLT, SeekLE, or
83948** OP_Last opcode used to position the cursor.  Prev is not allowed
83949** to follow SeekGT, SeekGE, or OP_Rewind.
83950**
83951** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
83952** not open then the behavior is undefined.
83953**
83954** The P3 value is a hint to the btree implementation. If P3==1, that
83955** means P1 is an SQL index and that this instruction could have been
83956** omitted if that index had been unique.  P3 is usually 0.  P3 is
83957** always either 0 or 1.
83958**
83959** P4 is always of type P4_ADVANCE. The function pointer points to
83960** sqlite3BtreePrevious().
83961**
83962** If P5 is positive and the jump is taken, then event counter
83963** number P5-1 in the prepared statement is incremented.
83964*/
83965/* Opcode: PrevIfOpen P1 P2 P3 P4 P5
83966**
83967** This opcode works just like Prev except that if cursor P1 is not
83968** open it behaves a no-op.
83969*/
83970/* Opcode: SorterNext P1 P2 * * P5
83971**
83972** This opcode works just like OP_Next except that P1 must be a
83973** sorter object for which the OP_SorterSort opcode has been
83974** invoked.  This opcode advances the cursor to the next sorted
83975** record, or jumps to P2 if there are no more sorted records.
83976*/
83977case OP_SorterNext: {  /* jump */
83978  VdbeCursor *pC;
83979
83980  pC = p->apCsr[pOp->p1];
83981  assert( isSorter(pC) );
83982  rc = sqlite3VdbeSorterNext(db, pC);
83983  goto next_tail;
83984case OP_PrevIfOpen:    /* jump */
83985case OP_NextIfOpen:    /* jump */
83986  if( p->apCsr[pOp->p1]==0 ) break;
83987  /* Fall through */
83988case OP_Prev:          /* jump */
83989case OP_Next:          /* jump */
83990  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83991  assert( pOp->p5<ArraySize(p->aCounter) );
83992  pC = p->apCsr[pOp->p1];
83993  assert( pC!=0 );
83994  assert( pC->deferredMoveto==0 );
83995  assert( pC->eCurType==CURTYPE_BTREE );
83996  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
83997  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
83998  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
83999  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
84000
84001  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
84002  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
84003  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
84004       || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
84005       || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
84006  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
84007       || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
84008       || pC->seekOp==OP_Last );
84009
84010  rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
84011next_tail:
84012  pC->cacheStatus = CACHE_STALE;
84013  VdbeBranchTaken(rc==SQLITE_OK,2);
84014  if( rc==SQLITE_OK ){
84015    pC->nullRow = 0;
84016    p->aCounter[pOp->p5]++;
84017#ifdef SQLITE_TEST
84018    sqlite3_search_count++;
84019#endif
84020    goto jump_to_p2_and_check_for_interrupt;
84021  }
84022  if( rc!=SQLITE_DONE ) goto abort_due_to_error;
84023  rc = SQLITE_OK;
84024  pC->nullRow = 1;
84025  goto check_for_interrupt;
84026}
84027
84028/* Opcode: IdxInsert P1 P2 P3 P4 P5
84029** Synopsis: key=r[P2]
84030**
84031** Register P2 holds an SQL index key made using the
84032** MakeRecord instructions.  This opcode writes that key
84033** into the index P1.  Data for the entry is nil.
84034**
84035** If P4 is not zero, then it is the number of values in the unpacked
84036** key of reg(P2).  In that case, P3 is the index of the first register
84037** for the unpacked key.  The availability of the unpacked key can sometimes
84038** be an optimization.
84039**
84040** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
84041** that this insert is likely to be an append.
84042**
84043** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
84044** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
84045** then the change counter is unchanged.
84046**
84047** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
84048** run faster by avoiding an unnecessary seek on cursor P1.  However,
84049** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
84050** seeks on the cursor or if the most recent seek used a key equivalent
84051** to P2.
84052**
84053** This instruction only works for indices.  The equivalent instruction
84054** for tables is OP_Insert.
84055*/
84056/* Opcode: SorterInsert P1 P2 * * *
84057** Synopsis: key=r[P2]
84058**
84059** Register P2 holds an SQL index key made using the
84060** MakeRecord instructions.  This opcode writes that key
84061** into the sorter P1.  Data for the entry is nil.
84062*/
84063case OP_SorterInsert:       /* in2 */
84064case OP_IdxInsert: {        /* in2 */
84065  VdbeCursor *pC;
84066  BtreePayload x;
84067
84068  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84069  pC = p->apCsr[pOp->p1];
84070  assert( pC!=0 );
84071  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
84072  pIn2 = &aMem[pOp->p2];
84073  assert( pIn2->flags & MEM_Blob );
84074  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
84075  assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
84076  assert( pC->isTable==0 );
84077  rc = ExpandBlob(pIn2);
84078  if( rc ) goto abort_due_to_error;
84079  if( pOp->opcode==OP_SorterInsert ){
84080    rc = sqlite3VdbeSorterWrite(pC, pIn2);
84081  }else{
84082    x.nKey = pIn2->n;
84083    x.pKey = pIn2->z;
84084    x.aMem = aMem + pOp->p3;
84085    x.nMem = (u16)pOp->p4.i;
84086    rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
84087         (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
84088        ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
84089        );
84090    assert( pC->deferredMoveto==0 );
84091    pC->cacheStatus = CACHE_STALE;
84092  }
84093  if( rc) goto abort_due_to_error;
84094  break;
84095}
84096
84097/* Opcode: IdxDelete P1 P2 P3 * *
84098** Synopsis: key=r[P2@P3]
84099**
84100** The content of P3 registers starting at register P2 form
84101** an unpacked index key. This opcode removes that entry from the
84102** index opened by cursor P1.
84103*/
84104case OP_IdxDelete: {
84105  VdbeCursor *pC;
84106  BtCursor *pCrsr;
84107  int res;
84108  UnpackedRecord r;
84109
84110  assert( pOp->p3>0 );
84111  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
84112  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84113  pC = p->apCsr[pOp->p1];
84114  assert( pC!=0 );
84115  assert( pC->eCurType==CURTYPE_BTREE );
84116  pCrsr = pC->uc.pCursor;
84117  assert( pCrsr!=0 );
84118  assert( pOp->p5==0 );
84119  r.pKeyInfo = pC->pKeyInfo;
84120  r.nField = (u16)pOp->p3;
84121  r.default_rc = 0;
84122  r.aMem = &aMem[pOp->p2];
84123  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
84124  if( rc ) goto abort_due_to_error;
84125  if( res==0 ){
84126    rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
84127    if( rc ) goto abort_due_to_error;
84128  }
84129  assert( pC->deferredMoveto==0 );
84130  pC->cacheStatus = CACHE_STALE;
84131  pC->seekResult = 0;
84132  break;
84133}
84134
84135/* Opcode: DeferredSeek P1 * P3 P4 *
84136** Synopsis: Move P3 to P1.rowid if needed
84137**
84138** P1 is an open index cursor and P3 is a cursor on the corresponding
84139** table.  This opcode does a deferred seek of the P3 table cursor
84140** to the row that corresponds to the current row of P1.
84141**
84142** This is a deferred seek.  Nothing actually happens until
84143** the cursor is used to read a record.  That way, if no reads
84144** occur, no unnecessary I/O happens.
84145**
84146** P4 may be an array of integers (type P4_INTARRAY) containing
84147** one entry for each column in the P3 table.  If array entry a(i)
84148** is non-zero, then reading column a(i)-1 from cursor P3 is
84149** equivalent to performing the deferred seek and then reading column i
84150** from P1.  This information is stored in P3 and used to redirect
84151** reads against P3 over to P1, thus possibly avoiding the need to
84152** seek and read cursor P3.
84153*/
84154/* Opcode: IdxRowid P1 P2 * * *
84155** Synopsis: r[P2]=rowid
84156**
84157** Write into register P2 an integer which is the last entry in the record at
84158** the end of the index key pointed to by cursor P1.  This integer should be
84159** the rowid of the table entry to which this index entry points.
84160**
84161** See also: Rowid, MakeRecord.
84162*/
84163case OP_DeferredSeek:
84164case OP_IdxRowid: {           /* out2 */
84165  VdbeCursor *pC;             /* The P1 index cursor */
84166  VdbeCursor *pTabCur;        /* The P2 table cursor (OP_DeferredSeek only) */
84167  i64 rowid;                  /* Rowid that P1 current points to */
84168
84169  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84170  pC = p->apCsr[pOp->p1];
84171  assert( pC!=0 );
84172  assert( pC->eCurType==CURTYPE_BTREE );
84173  assert( pC->uc.pCursor!=0 );
84174  assert( pC->isTable==0 );
84175  assert( pC->deferredMoveto==0 );
84176  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
84177
84178  /* The IdxRowid and Seek opcodes are combined because of the commonality
84179  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
84180  rc = sqlite3VdbeCursorRestore(pC);
84181
84182  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
84183  ** out from under the cursor.  That will never happens for an IdxRowid
84184  ** or Seek opcode */
84185  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
84186
84187  if( !pC->nullRow ){
84188    rowid = 0;  /* Not needed.  Only used to silence a warning. */
84189    rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
84190    if( rc!=SQLITE_OK ){
84191      goto abort_due_to_error;
84192    }
84193    if( pOp->opcode==OP_DeferredSeek ){
84194      assert( pOp->p3>=0 && pOp->p3<p->nCursor );
84195      pTabCur = p->apCsr[pOp->p3];
84196      assert( pTabCur!=0 );
84197      assert( pTabCur->eCurType==CURTYPE_BTREE );
84198      assert( pTabCur->uc.pCursor!=0 );
84199      assert( pTabCur->isTable );
84200      pTabCur->nullRow = 0;
84201      pTabCur->movetoTarget = rowid;
84202      pTabCur->deferredMoveto = 1;
84203      assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
84204      pTabCur->aAltMap = pOp->p4.ai;
84205      pTabCur->pAltCursor = pC;
84206    }else{
84207      pOut = out2Prerelease(p, pOp);
84208      pOut->u.i = rowid;
84209    }
84210  }else{
84211    assert( pOp->opcode==OP_IdxRowid );
84212    sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
84213  }
84214  break;
84215}
84216
84217/* Opcode: IdxGE P1 P2 P3 P4 P5
84218** Synopsis: key=r[P3@P4]
84219**
84220** The P4 register values beginning with P3 form an unpacked index
84221** key that omits the PRIMARY KEY.  Compare this key value against the index
84222** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
84223** fields at the end.
84224**
84225** If the P1 index entry is greater than or equal to the key value
84226** then jump to P2.  Otherwise fall through to the next instruction.
84227*/
84228/* Opcode: IdxGT P1 P2 P3 P4 P5
84229** Synopsis: key=r[P3@P4]
84230**
84231** The P4 register values beginning with P3 form an unpacked index
84232** key that omits the PRIMARY KEY.  Compare this key value against the index
84233** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
84234** fields at the end.
84235**
84236** If the P1 index entry is greater than the key value
84237** then jump to P2.  Otherwise fall through to the next instruction.
84238*/
84239/* Opcode: IdxLT P1 P2 P3 P4 P5
84240** Synopsis: key=r[P3@P4]
84241**
84242** The P4 register values beginning with P3 form an unpacked index
84243** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
84244** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
84245** ROWID on the P1 index.
84246**
84247** If the P1 index entry is less than the key value then jump to P2.
84248** Otherwise fall through to the next instruction.
84249*/
84250/* Opcode: IdxLE P1 P2 P3 P4 P5
84251** Synopsis: key=r[P3@P4]
84252**
84253** The P4 register values beginning with P3 form an unpacked index
84254** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
84255** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
84256** ROWID on the P1 index.
84257**
84258** If the P1 index entry is less than or equal to the key value then jump
84259** to P2. Otherwise fall through to the next instruction.
84260*/
84261case OP_IdxLE:          /* jump */
84262case OP_IdxGT:          /* jump */
84263case OP_IdxLT:          /* jump */
84264case OP_IdxGE:  {       /* jump */
84265  VdbeCursor *pC;
84266  int res;
84267  UnpackedRecord r;
84268
84269  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84270  pC = p->apCsr[pOp->p1];
84271  assert( pC!=0 );
84272  assert( pC->isOrdered );
84273  assert( pC->eCurType==CURTYPE_BTREE );
84274  assert( pC->uc.pCursor!=0);
84275  assert( pC->deferredMoveto==0 );
84276  assert( pOp->p5==0 || pOp->p5==1 );
84277  assert( pOp->p4type==P4_INT32 );
84278  r.pKeyInfo = pC->pKeyInfo;
84279  r.nField = (u16)pOp->p4.i;
84280  if( pOp->opcode<OP_IdxLT ){
84281    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
84282    r.default_rc = -1;
84283  }else{
84284    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
84285    r.default_rc = 0;
84286  }
84287  r.aMem = &aMem[pOp->p3];
84288#ifdef SQLITE_DEBUG
84289  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
84290#endif
84291  res = 0;  /* Not needed.  Only used to silence a warning. */
84292  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
84293  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
84294  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
84295    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
84296    res = -res;
84297  }else{
84298    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
84299    res++;
84300  }
84301  VdbeBranchTaken(res>0,2);
84302  if( rc ) goto abort_due_to_error;
84303  if( res>0 ) goto jump_to_p2;
84304  break;
84305}
84306
84307/* Opcode: Destroy P1 P2 P3 * *
84308**
84309** Delete an entire database table or index whose root page in the database
84310** file is given by P1.
84311**
84312** The table being destroyed is in the main database file if P3==0.  If
84313** P3==1 then the table to be clear is in the auxiliary database file
84314** that is used to store tables create using CREATE TEMPORARY TABLE.
84315**
84316** If AUTOVACUUM is enabled then it is possible that another root page
84317** might be moved into the newly deleted root page in order to keep all
84318** root pages contiguous at the beginning of the database.  The former
84319** value of the root page that moved - its value before the move occurred -
84320** is stored in register P2. If no page movement was required (because the
84321** table being dropped was already the last one in the database) then a
84322** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero
84323** is stored in register P2.
84324**
84325** This opcode throws an error if there are any active reader VMs when
84326** it is invoked. This is done to avoid the difficulty associated with
84327** updating existing cursors when a root page is moved in an AUTOVACUUM
84328** database. This error is thrown even if the database is not an AUTOVACUUM
84329** db in order to avoid introducing an incompatibility between autovacuum
84330** and non-autovacuum modes.
84331**
84332** See also: Clear
84333*/
84334case OP_Destroy: {     /* out2 */
84335  int iMoved;
84336  int iDb;
84337
84338  assert( p->readOnly==0 );
84339  assert( pOp->p1>1 );
84340  pOut = out2Prerelease(p, pOp);
84341  pOut->flags = MEM_Null;
84342  if( db->nVdbeRead > db->nVDestroy+1 ){
84343    rc = SQLITE_LOCKED;
84344    p->errorAction = OE_Abort;
84345    goto abort_due_to_error;
84346  }else{
84347    iDb = pOp->p3;
84348    assert( DbMaskTest(p->btreeMask, iDb) );
84349    iMoved = 0;  /* Not needed.  Only to silence a warning. */
84350    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
84351    pOut->flags = MEM_Int;
84352    pOut->u.i = iMoved;
84353    if( rc ) goto abort_due_to_error;
84354#ifndef SQLITE_OMIT_AUTOVACUUM
84355    if( iMoved!=0 ){
84356      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
84357      /* All OP_Destroy operations occur on the same btree */
84358      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
84359      resetSchemaOnFault = iDb+1;
84360    }
84361#endif
84362  }
84363  break;
84364}
84365
84366/* Opcode: Clear P1 P2 P3
84367**
84368** Delete all contents of the database table or index whose root page
84369** in the database file is given by P1.  But, unlike Destroy, do not
84370** remove the table or index from the database file.
84371**
84372** The table being clear is in the main database file if P2==0.  If
84373** P2==1 then the table to be clear is in the auxiliary database file
84374** that is used to store tables create using CREATE TEMPORARY TABLE.
84375**
84376** If the P3 value is non-zero, then the table referred to must be an
84377** intkey table (an SQL table, not an index). In this case the row change
84378** count is incremented by the number of rows in the table being cleared.
84379** If P3 is greater than zero, then the value stored in register P3 is
84380** also incremented by the number of rows in the table being cleared.
84381**
84382** See also: Destroy
84383*/
84384case OP_Clear: {
84385  int nChange;
84386
84387  nChange = 0;
84388  assert( p->readOnly==0 );
84389  assert( DbMaskTest(p->btreeMask, pOp->p2) );
84390  rc = sqlite3BtreeClearTable(
84391      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
84392  );
84393  if( pOp->p3 ){
84394    p->nChange += nChange;
84395    if( pOp->p3>0 ){
84396      assert( memIsValid(&aMem[pOp->p3]) );
84397      memAboutToChange(p, &aMem[pOp->p3]);
84398      aMem[pOp->p3].u.i += nChange;
84399    }
84400  }
84401  if( rc ) goto abort_due_to_error;
84402  break;
84403}
84404
84405/* Opcode: ResetSorter P1 * * * *
84406**
84407** Delete all contents from the ephemeral table or sorter
84408** that is open on cursor P1.
84409**
84410** This opcode only works for cursors used for sorting and
84411** opened with OP_OpenEphemeral or OP_SorterOpen.
84412*/
84413case OP_ResetSorter: {
84414  VdbeCursor *pC;
84415
84416  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84417  pC = p->apCsr[pOp->p1];
84418  assert( pC!=0 );
84419  if( isSorter(pC) ){
84420    sqlite3VdbeSorterReset(db, pC->uc.pSorter);
84421  }else{
84422    assert( pC->eCurType==CURTYPE_BTREE );
84423    assert( pC->isEphemeral );
84424    rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
84425    if( rc ) goto abort_due_to_error;
84426  }
84427  break;
84428}
84429
84430/* Opcode: CreateTable P1 P2 * * *
84431** Synopsis: r[P2]=root iDb=P1
84432**
84433** Allocate a new table in the main database file if P1==0 or in the
84434** auxiliary database file if P1==1 or in an attached database if
84435** P1>1.  Write the root page number of the new table into
84436** register P2
84437**
84438** The difference between a table and an index is this:  A table must
84439** have a 4-byte integer key and can have arbitrary data.  An index
84440** has an arbitrary key but no data.
84441**
84442** See also: CreateIndex
84443*/
84444/* Opcode: CreateIndex P1 P2 * * *
84445** Synopsis: r[P2]=root iDb=P1
84446**
84447** Allocate a new index in the main database file if P1==0 or in the
84448** auxiliary database file if P1==1 or in an attached database if
84449** P1>1.  Write the root page number of the new table into
84450** register P2.
84451**
84452** See documentation on OP_CreateTable for additional information.
84453*/
84454case OP_CreateIndex:            /* out2 */
84455case OP_CreateTable: {          /* out2 */
84456  int pgno;
84457  int flags;
84458  Db *pDb;
84459
84460  pOut = out2Prerelease(p, pOp);
84461  pgno = 0;
84462  assert( pOp->p1>=0 && pOp->p1<db->nDb );
84463  assert( DbMaskTest(p->btreeMask, pOp->p1) );
84464  assert( p->readOnly==0 );
84465  pDb = &db->aDb[pOp->p1];
84466  assert( pDb->pBt!=0 );
84467  if( pOp->opcode==OP_CreateTable ){
84468    /* flags = BTREE_INTKEY; */
84469    flags = BTREE_INTKEY;
84470  }else{
84471    flags = BTREE_BLOBKEY;
84472  }
84473  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
84474  if( rc ) goto abort_due_to_error;
84475  pOut->u.i = pgno;
84476  break;
84477}
84478
84479/* Opcode: SqlExec * * * P4 *
84480**
84481** Run the SQL statement or statements specified in the P4 string.
84482*/
84483case OP_SqlExec: {
84484  db->nSqlExec++;
84485  rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
84486  db->nSqlExec--;
84487  if( rc ) goto abort_due_to_error;
84488  break;
84489}
84490
84491/* Opcode: ParseSchema P1 * * P4 *
84492**
84493** Read and parse all entries from the SQLITE_MASTER table of database P1
84494** that match the WHERE clause P4.
84495**
84496** This opcode invokes the parser to create a new virtual machine,
84497** then runs the new virtual machine.  It is thus a re-entrant opcode.
84498*/
84499case OP_ParseSchema: {
84500  int iDb;
84501  const char *zMaster;
84502  char *zSql;
84503  InitData initData;
84504
84505  /* Any prepared statement that invokes this opcode will hold mutexes
84506  ** on every btree.  This is a prerequisite for invoking
84507  ** sqlite3InitCallback().
84508  */
84509#ifdef SQLITE_DEBUG
84510  for(iDb=0; iDb<db->nDb; iDb++){
84511    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
84512  }
84513#endif
84514
84515  iDb = pOp->p1;
84516  assert( iDb>=0 && iDb<db->nDb );
84517  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
84518  /* Used to be a conditional */ {
84519    zMaster = MASTER_NAME;
84520    initData.db = db;
84521    initData.iDb = pOp->p1;
84522    initData.pzErrMsg = &p->zErrMsg;
84523    zSql = sqlite3MPrintf(db,
84524       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
84525       db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
84526    if( zSql==0 ){
84527      rc = SQLITE_NOMEM_BKPT;
84528    }else{
84529      assert( db->init.busy==0 );
84530      db->init.busy = 1;
84531      initData.rc = SQLITE_OK;
84532      assert( !db->mallocFailed );
84533      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
84534      if( rc==SQLITE_OK ) rc = initData.rc;
84535      sqlite3DbFreeNN(db, zSql);
84536      db->init.busy = 0;
84537    }
84538  }
84539  if( rc ){
84540    sqlite3ResetAllSchemasOfConnection(db);
84541    if( rc==SQLITE_NOMEM ){
84542      goto no_mem;
84543    }
84544    goto abort_due_to_error;
84545  }
84546  break;
84547}
84548
84549#if !defined(SQLITE_OMIT_ANALYZE)
84550/* Opcode: LoadAnalysis P1 * * * *
84551**
84552** Read the sqlite_stat1 table for database P1 and load the content
84553** of that table into the internal index hash table.  This will cause
84554** the analysis to be used when preparing all subsequent queries.
84555*/
84556case OP_LoadAnalysis: {
84557  assert( pOp->p1>=0 && pOp->p1<db->nDb );
84558  rc = sqlite3AnalysisLoad(db, pOp->p1);
84559  if( rc ) goto abort_due_to_error;
84560  break;
84561}
84562#endif /* !defined(SQLITE_OMIT_ANALYZE) */
84563
84564/* Opcode: DropTable P1 * * P4 *
84565**
84566** Remove the internal (in-memory) data structures that describe
84567** the table named P4 in database P1.  This is called after a table
84568** is dropped from disk (using the Destroy opcode) in order to keep
84569** the internal representation of the
84570** schema consistent with what is on disk.
84571*/
84572case OP_DropTable: {
84573  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
84574  break;
84575}
84576
84577/* Opcode: DropIndex P1 * * P4 *
84578**
84579** Remove the internal (in-memory) data structures that describe
84580** the index named P4 in database P1.  This is called after an index
84581** is dropped from disk (using the Destroy opcode)
84582** in order to keep the internal representation of the
84583** schema consistent with what is on disk.
84584*/
84585case OP_DropIndex: {
84586  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
84587  break;
84588}
84589
84590/* Opcode: DropTrigger P1 * * P4 *
84591**
84592** Remove the internal (in-memory) data structures that describe
84593** the trigger named P4 in database P1.  This is called after a trigger
84594** is dropped from disk (using the Destroy opcode) in order to keep
84595** the internal representation of the
84596** schema consistent with what is on disk.
84597*/
84598case OP_DropTrigger: {
84599  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
84600  break;
84601}
84602
84603
84604#ifndef SQLITE_OMIT_INTEGRITY_CHECK
84605/* Opcode: IntegrityCk P1 P2 P3 P4 P5
84606**
84607** Do an analysis of the currently open database.  Store in
84608** register P1 the text of an error message describing any problems.
84609** If no problems are found, store a NULL in register P1.
84610**
84611** The register P3 contains one less than the maximum number of allowed errors.
84612** At most reg(P3) errors will be reported.
84613** In other words, the analysis stops as soon as reg(P1) errors are
84614** seen.  Reg(P1) is updated with the number of errors remaining.
84615**
84616** The root page numbers of all tables in the database are integers
84617** stored in P4_INTARRAY argument.
84618**
84619** If P5 is not zero, the check is done on the auxiliary database
84620** file, not the main database file.
84621**
84622** This opcode is used to implement the integrity_check pragma.
84623*/
84624case OP_IntegrityCk: {
84625  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
84626  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
84627  int nErr;       /* Number of errors reported */
84628  char *z;        /* Text of the error report */
84629  Mem *pnErr;     /* Register keeping track of errors remaining */
84630
84631  assert( p->bIsReader );
84632  nRoot = pOp->p2;
84633  aRoot = pOp->p4.ai;
84634  assert( nRoot>0 );
84635  assert( aRoot[nRoot]==0 );
84636  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
84637  pnErr = &aMem[pOp->p3];
84638  assert( (pnErr->flags & MEM_Int)!=0 );
84639  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
84640  pIn1 = &aMem[pOp->p1];
84641  assert( pOp->p5<db->nDb );
84642  assert( DbMaskTest(p->btreeMask, pOp->p5) );
84643  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
84644                                 (int)pnErr->u.i+1, &nErr);
84645  sqlite3VdbeMemSetNull(pIn1);
84646  if( nErr==0 ){
84647    assert( z==0 );
84648  }else if( z==0 ){
84649    goto no_mem;
84650  }else{
84651    pnErr->u.i -= nErr-1;
84652    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
84653  }
84654  UPDATE_MAX_BLOBSIZE(pIn1);
84655  sqlite3VdbeChangeEncoding(pIn1, encoding);
84656  break;
84657}
84658#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
84659
84660/* Opcode: RowSetAdd P1 P2 * * *
84661** Synopsis: rowset(P1)=r[P2]
84662**
84663** Insert the integer value held by register P2 into a RowSet object
84664** held in register P1.
84665**
84666** An assertion fails if P2 is not an integer.
84667*/
84668case OP_RowSetAdd: {       /* in1, in2 */
84669  pIn1 = &aMem[pOp->p1];
84670  pIn2 = &aMem[pOp->p2];
84671  assert( (pIn2->flags & MEM_Int)!=0 );
84672  if( (pIn1->flags & MEM_RowSet)==0 ){
84673    sqlite3VdbeMemSetRowSet(pIn1);
84674    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
84675  }
84676  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
84677  break;
84678}
84679
84680/* Opcode: RowSetRead P1 P2 P3 * *
84681** Synopsis: r[P3]=rowset(P1)
84682**
84683** Extract the smallest value from the RowSet object in P1
84684** and put that value into register P3.
84685** Or, if RowSet object P1 is initially empty, leave P3
84686** unchanged and jump to instruction P2.
84687*/
84688case OP_RowSetRead: {       /* jump, in1, out3 */
84689  i64 val;
84690
84691  pIn1 = &aMem[pOp->p1];
84692  if( (pIn1->flags & MEM_RowSet)==0
84693   || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
84694  ){
84695    /* The boolean index is empty */
84696    sqlite3VdbeMemSetNull(pIn1);
84697    VdbeBranchTaken(1,2);
84698    goto jump_to_p2_and_check_for_interrupt;
84699  }else{
84700    /* A value was pulled from the index */
84701    VdbeBranchTaken(0,2);
84702    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
84703  }
84704  goto check_for_interrupt;
84705}
84706
84707/* Opcode: RowSetTest P1 P2 P3 P4
84708** Synopsis: if r[P3] in rowset(P1) goto P2
84709**
84710** Register P3 is assumed to hold a 64-bit integer value. If register P1
84711** contains a RowSet object and that RowSet object contains
84712** the value held in P3, jump to register P2. Otherwise, insert the
84713** integer in P3 into the RowSet and continue on to the
84714** next opcode.
84715**
84716** The RowSet object is optimized for the case where sets of integers
84717** are inserted in distinct phases, which each set contains no duplicates.
84718** Each set is identified by a unique P4 value. The first set
84719** must have P4==0, the final set must have P4==-1, and for all other sets
84720** must have P4>0.
84721**
84722** This allows optimizations: (a) when P4==0 there is no need to test
84723** the RowSet object for P3, as it is guaranteed not to contain it,
84724** (b) when P4==-1 there is no need to insert the value, as it will
84725** never be tested for, and (c) when a value that is part of set X is
84726** inserted, there is no need to search to see if the same value was
84727** previously inserted as part of set X (only if it was previously
84728** inserted as part of some other set).
84729*/
84730case OP_RowSetTest: {                     /* jump, in1, in3 */
84731  int iSet;
84732  int exists;
84733
84734  pIn1 = &aMem[pOp->p1];
84735  pIn3 = &aMem[pOp->p3];
84736  iSet = pOp->p4.i;
84737  assert( pIn3->flags&MEM_Int );
84738
84739  /* If there is anything other than a rowset object in memory cell P1,
84740  ** delete it now and initialize P1 with an empty rowset
84741  */
84742  if( (pIn1->flags & MEM_RowSet)==0 ){
84743    sqlite3VdbeMemSetRowSet(pIn1);
84744    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
84745  }
84746
84747  assert( pOp->p4type==P4_INT32 );
84748  assert( iSet==-1 || iSet>=0 );
84749  if( iSet ){
84750    exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
84751    VdbeBranchTaken(exists!=0,2);
84752    if( exists ) goto jump_to_p2;
84753  }
84754  if( iSet>=0 ){
84755    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
84756  }
84757  break;
84758}
84759
84760
84761#ifndef SQLITE_OMIT_TRIGGER
84762
84763/* Opcode: Program P1 P2 P3 P4 P5
84764**
84765** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
84766**
84767** P1 contains the address of the memory cell that contains the first memory
84768** cell in an array of values used as arguments to the sub-program. P2
84769** contains the address to jump to if the sub-program throws an IGNORE
84770** exception using the RAISE() function. Register P3 contains the address
84771** of a memory cell in this (the parent) VM that is used to allocate the
84772** memory required by the sub-vdbe at runtime.
84773**
84774** P4 is a pointer to the VM containing the trigger program.
84775**
84776** If P5 is non-zero, then recursive program invocation is enabled.
84777*/
84778case OP_Program: {        /* jump */
84779  int nMem;               /* Number of memory registers for sub-program */
84780  int nByte;              /* Bytes of runtime space required for sub-program */
84781  Mem *pRt;               /* Register to allocate runtime space */
84782  Mem *pMem;              /* Used to iterate through memory cells */
84783  Mem *pEnd;              /* Last memory cell in new array */
84784  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
84785  SubProgram *pProgram;   /* Sub-program to execute */
84786  void *t;                /* Token identifying trigger */
84787
84788  pProgram = pOp->p4.pProgram;
84789  pRt = &aMem[pOp->p3];
84790  assert( pProgram->nOp>0 );
84791
84792  /* If the p5 flag is clear, then recursive invocation of triggers is
84793  ** disabled for backwards compatibility (p5 is set if this sub-program
84794  ** is really a trigger, not a foreign key action, and the flag set
84795  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
84796  **
84797  ** It is recursive invocation of triggers, at the SQL level, that is
84798  ** disabled. In some cases a single trigger may generate more than one
84799  ** SubProgram (if the trigger may be executed with more than one different
84800  ** ON CONFLICT algorithm). SubProgram structures associated with a
84801  ** single trigger all have the same value for the SubProgram.token
84802  ** variable.  */
84803  if( pOp->p5 ){
84804    t = pProgram->token;
84805    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
84806    if( pFrame ) break;
84807  }
84808
84809  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
84810    rc = SQLITE_ERROR;
84811    sqlite3VdbeError(p, "too many levels of trigger recursion");
84812    goto abort_due_to_error;
84813  }
84814
84815  /* Register pRt is used to store the memory required to save the state
84816  ** of the current program, and the memory required at runtime to execute
84817  ** the trigger program. If this trigger has been fired before, then pRt
84818  ** is already allocated. Otherwise, it must be initialized.  */
84819  if( (pRt->flags&MEM_Frame)==0 ){
84820    /* SubProgram.nMem is set to the number of memory cells used by the
84821    ** program stored in SubProgram.aOp. As well as these, one memory
84822    ** cell is required for each cursor used by the program. Set local
84823    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
84824    */
84825    nMem = pProgram->nMem + pProgram->nCsr;
84826    assert( nMem>0 );
84827    if( pProgram->nCsr==0 ) nMem++;
84828    nByte = ROUND8(sizeof(VdbeFrame))
84829              + nMem * sizeof(Mem)
84830              + pProgram->nCsr * sizeof(VdbeCursor*)
84831              + (pProgram->nOp + 7)/8;
84832    pFrame = sqlite3DbMallocZero(db, nByte);
84833    if( !pFrame ){
84834      goto no_mem;
84835    }
84836    sqlite3VdbeMemRelease(pRt);
84837    pRt->flags = MEM_Frame;
84838    pRt->u.pFrame = pFrame;
84839
84840    pFrame->v = p;
84841    pFrame->nChildMem = nMem;
84842    pFrame->nChildCsr = pProgram->nCsr;
84843    pFrame->pc = (int)(pOp - aOp);
84844    pFrame->aMem = p->aMem;
84845    pFrame->nMem = p->nMem;
84846    pFrame->apCsr = p->apCsr;
84847    pFrame->nCursor = p->nCursor;
84848    pFrame->aOp = p->aOp;
84849    pFrame->nOp = p->nOp;
84850    pFrame->token = pProgram->token;
84851#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
84852    pFrame->anExec = p->anExec;
84853#endif
84854
84855    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
84856    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
84857      pMem->flags = MEM_Undefined;
84858      pMem->db = db;
84859    }
84860  }else{
84861    pFrame = pRt->u.pFrame;
84862    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
84863        || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
84864    assert( pProgram->nCsr==pFrame->nChildCsr );
84865    assert( (int)(pOp - aOp)==pFrame->pc );
84866  }
84867
84868  p->nFrame++;
84869  pFrame->pParent = p->pFrame;
84870  pFrame->lastRowid = db->lastRowid;
84871  pFrame->nChange = p->nChange;
84872  pFrame->nDbChange = p->db->nChange;
84873  assert( pFrame->pAuxData==0 );
84874  pFrame->pAuxData = p->pAuxData;
84875  p->pAuxData = 0;
84876  p->nChange = 0;
84877  p->pFrame = pFrame;
84878  p->aMem = aMem = VdbeFrameMem(pFrame);
84879  p->nMem = pFrame->nChildMem;
84880  p->nCursor = (u16)pFrame->nChildCsr;
84881  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
84882  pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
84883  memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
84884  p->aOp = aOp = pProgram->aOp;
84885  p->nOp = pProgram->nOp;
84886#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
84887  p->anExec = 0;
84888#endif
84889  pOp = &aOp[-1];
84890
84891  break;
84892}
84893
84894/* Opcode: Param P1 P2 * * *
84895**
84896** This opcode is only ever present in sub-programs called via the
84897** OP_Program instruction. Copy a value currently stored in a memory
84898** cell of the calling (parent) frame to cell P2 in the current frames
84899** address space. This is used by trigger programs to access the new.*
84900** and old.* values.
84901**
84902** The address of the cell in the parent frame is determined by adding
84903** the value of the P1 argument to the value of the P1 argument to the
84904** calling OP_Program instruction.
84905*/
84906case OP_Param: {           /* out2 */
84907  VdbeFrame *pFrame;
84908  Mem *pIn;
84909  pOut = out2Prerelease(p, pOp);
84910  pFrame = p->pFrame;
84911  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
84912  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
84913  break;
84914}
84915
84916#endif /* #ifndef SQLITE_OMIT_TRIGGER */
84917
84918#ifndef SQLITE_OMIT_FOREIGN_KEY
84919/* Opcode: FkCounter P1 P2 * * *
84920** Synopsis: fkctr[P1]+=P2
84921**
84922** Increment a "constraint counter" by P2 (P2 may be negative or positive).
84923** If P1 is non-zero, the database constraint counter is incremented
84924** (deferred foreign key constraints). Otherwise, if P1 is zero, the
84925** statement counter is incremented (immediate foreign key constraints).
84926*/
84927case OP_FkCounter: {
84928  if( db->flags & SQLITE_DeferFKs ){
84929    db->nDeferredImmCons += pOp->p2;
84930  }else if( pOp->p1 ){
84931    db->nDeferredCons += pOp->p2;
84932  }else{
84933    p->nFkConstraint += pOp->p2;
84934  }
84935  break;
84936}
84937
84938/* Opcode: FkIfZero P1 P2 * * *
84939** Synopsis: if fkctr[P1]==0 goto P2
84940**
84941** This opcode tests if a foreign key constraint-counter is currently zero.
84942** If so, jump to instruction P2. Otherwise, fall through to the next
84943** instruction.
84944**
84945** If P1 is non-zero, then the jump is taken if the database constraint-counter
84946** is zero (the one that counts deferred constraint violations). If P1 is
84947** zero, the jump is taken if the statement constraint-counter is zero
84948** (immediate foreign key constraint violations).
84949*/
84950case OP_FkIfZero: {         /* jump */
84951  if( pOp->p1 ){
84952    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
84953    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
84954  }else{
84955    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
84956    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
84957  }
84958  break;
84959}
84960#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
84961
84962#ifndef SQLITE_OMIT_AUTOINCREMENT
84963/* Opcode: MemMax P1 P2 * * *
84964** Synopsis: r[P1]=max(r[P1],r[P2])
84965**
84966** P1 is a register in the root frame of this VM (the root frame is
84967** different from the current frame if this instruction is being executed
84968** within a sub-program). Set the value of register P1 to the maximum of
84969** its current value and the value in register P2.
84970**
84971** This instruction throws an error if the memory cell is not initially
84972** an integer.
84973*/
84974case OP_MemMax: {        /* in2 */
84975  VdbeFrame *pFrame;
84976  if( p->pFrame ){
84977    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
84978    pIn1 = &pFrame->aMem[pOp->p1];
84979  }else{
84980    pIn1 = &aMem[pOp->p1];
84981  }
84982  assert( memIsValid(pIn1) );
84983  sqlite3VdbeMemIntegerify(pIn1);
84984  pIn2 = &aMem[pOp->p2];
84985  sqlite3VdbeMemIntegerify(pIn2);
84986  if( pIn1->u.i<pIn2->u.i){
84987    pIn1->u.i = pIn2->u.i;
84988  }
84989  break;
84990}
84991#endif /* SQLITE_OMIT_AUTOINCREMENT */
84992
84993/* Opcode: IfPos P1 P2 P3 * *
84994** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
84995**
84996** Register P1 must contain an integer.
84997** If the value of register P1 is 1 or greater, subtract P3 from the
84998** value in P1 and jump to P2.
84999**
85000** If the initial value of register P1 is less than 1, then the
85001** value is unchanged and control passes through to the next instruction.
85002*/
85003case OP_IfPos: {        /* jump, in1 */
85004  pIn1 = &aMem[pOp->p1];
85005  assert( pIn1->flags&MEM_Int );
85006  VdbeBranchTaken( pIn1->u.i>0, 2);
85007  if( pIn1->u.i>0 ){
85008    pIn1->u.i -= pOp->p3;
85009    goto jump_to_p2;
85010  }
85011  break;
85012}
85013
85014/* Opcode: OffsetLimit P1 P2 P3 * *
85015** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
85016**
85017** This opcode performs a commonly used computation associated with
85018** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
85019** holds the offset counter.  The opcode computes the combined value
85020** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
85021** value computed is the total number of rows that will need to be
85022** visited in order to complete the query.
85023**
85024** If r[P3] is zero or negative, that means there is no OFFSET
85025** and r[P2] is set to be the value of the LIMIT, r[P1].
85026**
85027** if r[P1] is zero or negative, that means there is no LIMIT
85028** and r[P2] is set to -1.
85029**
85030** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
85031*/
85032case OP_OffsetLimit: {    /* in1, out2, in3 */
85033  i64 x;
85034  pIn1 = &aMem[pOp->p1];
85035  pIn3 = &aMem[pOp->p3];
85036  pOut = out2Prerelease(p, pOp);
85037  assert( pIn1->flags & MEM_Int );
85038  assert( pIn3->flags & MEM_Int );
85039  x = pIn1->u.i;
85040  if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
85041    /* If the LIMIT is less than or equal to zero, loop forever.  This
85042    ** is documented.  But also, if the LIMIT+OFFSET exceeds 2^63 then
85043    ** also loop forever.  This is undocumented.  In fact, one could argue
85044    ** that the loop should terminate.  But assuming 1 billion iterations
85045    ** per second (far exceeding the capabilities of any current hardware)
85046    ** it would take nearly 300 years to actually reach the limit.  So
85047    ** looping forever is a reasonable approximation. */
85048    pOut->u.i = -1;
85049  }else{
85050    pOut->u.i = x;
85051  }
85052  break;
85053}
85054
85055/* Opcode: IfNotZero P1 P2 * * *
85056** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
85057**
85058** Register P1 must contain an integer.  If the content of register P1 is
85059** initially greater than zero, then decrement the value in register P1.
85060** If it is non-zero (negative or positive) and then also jump to P2.
85061** If register P1 is initially zero, leave it unchanged and fall through.
85062*/
85063case OP_IfNotZero: {        /* jump, in1 */
85064  pIn1 = &aMem[pOp->p1];
85065  assert( pIn1->flags&MEM_Int );
85066  VdbeBranchTaken(pIn1->u.i<0, 2);
85067  if( pIn1->u.i ){
85068     if( pIn1->u.i>0 ) pIn1->u.i--;
85069     goto jump_to_p2;
85070  }
85071  break;
85072}
85073
85074/* Opcode: DecrJumpZero P1 P2 * * *
85075** Synopsis: if (--r[P1])==0 goto P2
85076**
85077** Register P1 must hold an integer.  Decrement the value in P1
85078** and jump to P2 if the new value is exactly zero.
85079*/
85080case OP_DecrJumpZero: {      /* jump, in1 */
85081  pIn1 = &aMem[pOp->p1];
85082  assert( pIn1->flags&MEM_Int );
85083  if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
85084  VdbeBranchTaken(pIn1->u.i==0, 2);
85085  if( pIn1->u.i==0 ) goto jump_to_p2;
85086  break;
85087}
85088
85089
85090/* Opcode: AggStep0 * P2 P3 P4 P5
85091** Synopsis: accum=r[P3] step(r[P2@P5])
85092**
85093** Execute the step function for an aggregate.  The
85094** function has P5 arguments.   P4 is a pointer to the FuncDef
85095** structure that specifies the function.  Register P3 is the
85096** accumulator.
85097**
85098** The P5 arguments are taken from register P2 and its
85099** successors.
85100*/
85101/* Opcode: AggStep * P2 P3 P4 P5
85102** Synopsis: accum=r[P3] step(r[P2@P5])
85103**
85104** Execute the step function for an aggregate.  The
85105** function has P5 arguments.   P4 is a pointer to an sqlite3_context
85106** object that is used to run the function.  Register P3 is
85107** as the accumulator.
85108**
85109** The P5 arguments are taken from register P2 and its
85110** successors.
85111**
85112** This opcode is initially coded as OP_AggStep0.  On first evaluation,
85113** the FuncDef stored in P4 is converted into an sqlite3_context and
85114** the opcode is changed.  In this way, the initialization of the
85115** sqlite3_context only happens once, instead of on each call to the
85116** step function.
85117*/
85118case OP_AggStep0: {
85119  int n;
85120  sqlite3_context *pCtx;
85121
85122  assert( pOp->p4type==P4_FUNCDEF );
85123  n = pOp->p5;
85124  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
85125  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
85126  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
85127  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
85128  if( pCtx==0 ) goto no_mem;
85129  pCtx->pMem = 0;
85130  pCtx->pFunc = pOp->p4.pFunc;
85131  pCtx->iOp = (int)(pOp - aOp);
85132  pCtx->pVdbe = p;
85133  pCtx->argc = n;
85134  pOp->p4type = P4_FUNCCTX;
85135  pOp->p4.pCtx = pCtx;
85136  pOp->opcode = OP_AggStep;
85137  /* Fall through into OP_AggStep */
85138}
85139case OP_AggStep: {
85140  int i;
85141  sqlite3_context *pCtx;
85142  Mem *pMem;
85143  Mem t;
85144
85145  assert( pOp->p4type==P4_FUNCCTX );
85146  pCtx = pOp->p4.pCtx;
85147  pMem = &aMem[pOp->p3];
85148
85149  /* If this function is inside of a trigger, the register array in aMem[]
85150  ** might change from one evaluation to the next.  The next block of code
85151  ** checks to see if the register array has changed, and if so it
85152  ** reinitializes the relavant parts of the sqlite3_context object */
85153  if( pCtx->pMem != pMem ){
85154    pCtx->pMem = pMem;
85155    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
85156  }
85157
85158#ifdef SQLITE_DEBUG
85159  for(i=0; i<pCtx->argc; i++){
85160    assert( memIsValid(pCtx->argv[i]) );
85161    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
85162  }
85163#endif
85164
85165  pMem->n++;
85166  sqlite3VdbeMemInit(&t, db, MEM_Null);
85167  pCtx->pOut = &t;
85168  pCtx->fErrorOrAux = 0;
85169  pCtx->skipFlag = 0;
85170  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
85171  if( pCtx->fErrorOrAux ){
85172    if( pCtx->isError ){
85173      sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
85174      rc = pCtx->isError;
85175    }
85176    sqlite3VdbeMemRelease(&t);
85177    if( rc ) goto abort_due_to_error;
85178  }else{
85179    assert( t.flags==MEM_Null );
85180  }
85181  if( pCtx->skipFlag ){
85182    assert( pOp[-1].opcode==OP_CollSeq );
85183    i = pOp[-1].p1;
85184    if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
85185  }
85186  break;
85187}
85188
85189/* Opcode: AggFinal P1 P2 * P4 *
85190** Synopsis: accum=r[P1] N=P2
85191**
85192** Execute the finalizer function for an aggregate.  P1 is
85193** the memory location that is the accumulator for the aggregate.
85194**
85195** P2 is the number of arguments that the step function takes and
85196** P4 is a pointer to the FuncDef for this function.  The P2
85197** argument is not used by this opcode.  It is only there to disambiguate
85198** functions that can take varying numbers of arguments.  The
85199** P4 argument is only needed for the degenerate case where
85200** the step function was not previously called.
85201*/
85202case OP_AggFinal: {
85203  Mem *pMem;
85204  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
85205  pMem = &aMem[pOp->p1];
85206  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
85207  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
85208  if( rc ){
85209    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
85210    goto abort_due_to_error;
85211  }
85212  sqlite3VdbeChangeEncoding(pMem, encoding);
85213  UPDATE_MAX_BLOBSIZE(pMem);
85214  if( sqlite3VdbeMemTooBig(pMem) ){
85215    goto too_big;
85216  }
85217  break;
85218}
85219
85220#ifndef SQLITE_OMIT_WAL
85221/* Opcode: Checkpoint P1 P2 P3 * *
85222**
85223** Checkpoint database P1. This is a no-op if P1 is not currently in
85224** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
85225** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
85226** SQLITE_BUSY or not, respectively.  Write the number of pages in the
85227** WAL after the checkpoint into mem[P3+1] and the number of pages
85228** in the WAL that have been checkpointed after the checkpoint
85229** completes into mem[P3+2].  However on an error, mem[P3+1] and
85230** mem[P3+2] are initialized to -1.
85231*/
85232case OP_Checkpoint: {
85233  int i;                          /* Loop counter */
85234  int aRes[3];                    /* Results */
85235  Mem *pMem;                      /* Write results here */
85236
85237  assert( p->readOnly==0 );
85238  aRes[0] = 0;
85239  aRes[1] = aRes[2] = -1;
85240  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
85241       || pOp->p2==SQLITE_CHECKPOINT_FULL
85242       || pOp->p2==SQLITE_CHECKPOINT_RESTART
85243       || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
85244  );
85245  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
85246  if( rc ){
85247    if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
85248    rc = SQLITE_OK;
85249    aRes[0] = 1;
85250  }
85251  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
85252    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
85253  }
85254  break;
85255};
85256#endif
85257
85258#ifndef SQLITE_OMIT_PRAGMA
85259/* Opcode: JournalMode P1 P2 P3 * *
85260**
85261** Change the journal mode of database P1 to P3. P3 must be one of the
85262** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
85263** modes (delete, truncate, persist, off and memory), this is a simple
85264** operation. No IO is required.
85265**
85266** If changing into or out of WAL mode the procedure is more complicated.
85267**
85268** Write a string containing the final journal-mode to register P2.
85269*/
85270case OP_JournalMode: {    /* out2 */
85271  Btree *pBt;                     /* Btree to change journal mode of */
85272  Pager *pPager;                  /* Pager associated with pBt */
85273  int eNew;                       /* New journal mode */
85274  int eOld;                       /* The old journal mode */
85275#ifndef SQLITE_OMIT_WAL
85276  const char *zFilename;          /* Name of database file for pPager */
85277#endif
85278
85279  pOut = out2Prerelease(p, pOp);
85280  eNew = pOp->p3;
85281  assert( eNew==PAGER_JOURNALMODE_DELETE
85282       || eNew==PAGER_JOURNALMODE_TRUNCATE
85283       || eNew==PAGER_JOURNALMODE_PERSIST
85284       || eNew==PAGER_JOURNALMODE_OFF
85285       || eNew==PAGER_JOURNALMODE_MEMORY
85286       || eNew==PAGER_JOURNALMODE_WAL
85287       || eNew==PAGER_JOURNALMODE_QUERY
85288  );
85289  assert( pOp->p1>=0 && pOp->p1<db->nDb );
85290  assert( p->readOnly==0 );
85291
85292  pBt = db->aDb[pOp->p1].pBt;
85293  pPager = sqlite3BtreePager(pBt);
85294  eOld = sqlite3PagerGetJournalMode(pPager);
85295  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
85296  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
85297
85298#ifndef SQLITE_OMIT_WAL
85299  zFilename = sqlite3PagerFilename(pPager, 1);
85300
85301  /* Do not allow a transition to journal_mode=WAL for a database
85302  ** in temporary storage or if the VFS does not support shared memory
85303  */
85304  if( eNew==PAGER_JOURNALMODE_WAL
85305   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
85306       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
85307  ){
85308    eNew = eOld;
85309  }
85310
85311  if( (eNew!=eOld)
85312   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
85313  ){
85314    if( !db->autoCommit || db->nVdbeRead>1 ){
85315      rc = SQLITE_ERROR;
85316      sqlite3VdbeError(p,
85317          "cannot change %s wal mode from within a transaction",
85318          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
85319      );
85320      goto abort_due_to_error;
85321    }else{
85322
85323      if( eOld==PAGER_JOURNALMODE_WAL ){
85324        /* If leaving WAL mode, close the log file. If successful, the call
85325        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
85326        ** file. An EXCLUSIVE lock may still be held on the database file
85327        ** after a successful return.
85328        */
85329        rc = sqlite3PagerCloseWal(pPager, db);
85330        if( rc==SQLITE_OK ){
85331          sqlite3PagerSetJournalMode(pPager, eNew);
85332        }
85333      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
85334        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
85335        ** as an intermediate */
85336        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
85337      }
85338
85339      /* Open a transaction on the database file. Regardless of the journal
85340      ** mode, this transaction always uses a rollback journal.
85341      */
85342      assert( sqlite3BtreeIsInTrans(pBt)==0 );
85343      if( rc==SQLITE_OK ){
85344        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
85345      }
85346    }
85347  }
85348#endif /* ifndef SQLITE_OMIT_WAL */
85349
85350  if( rc ) eNew = eOld;
85351  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
85352
85353  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
85354  pOut->z = (char *)sqlite3JournalModename(eNew);
85355  pOut->n = sqlite3Strlen30(pOut->z);
85356  pOut->enc = SQLITE_UTF8;
85357  sqlite3VdbeChangeEncoding(pOut, encoding);
85358  if( rc ) goto abort_due_to_error;
85359  break;
85360};
85361#endif /* SQLITE_OMIT_PRAGMA */
85362
85363#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
85364/* Opcode: Vacuum P1 * * * *
85365**
85366** Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
85367** for an attached database.  The "temp" database may not be vacuumed.
85368*/
85369case OP_Vacuum: {
85370  assert( p->readOnly==0 );
85371  rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
85372  if( rc ) goto abort_due_to_error;
85373  break;
85374}
85375#endif
85376
85377#if !defined(SQLITE_OMIT_AUTOVACUUM)
85378/* Opcode: IncrVacuum P1 P2 * * *
85379**
85380** Perform a single step of the incremental vacuum procedure on
85381** the P1 database. If the vacuum has finished, jump to instruction
85382** P2. Otherwise, fall through to the next instruction.
85383*/
85384case OP_IncrVacuum: {        /* jump */
85385  Btree *pBt;
85386
85387  assert( pOp->p1>=0 && pOp->p1<db->nDb );
85388  assert( DbMaskTest(p->btreeMask, pOp->p1) );
85389  assert( p->readOnly==0 );
85390  pBt = db->aDb[pOp->p1].pBt;
85391  rc = sqlite3BtreeIncrVacuum(pBt);
85392  VdbeBranchTaken(rc==SQLITE_DONE,2);
85393  if( rc ){
85394    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
85395    rc = SQLITE_OK;
85396    goto jump_to_p2;
85397  }
85398  break;
85399}
85400#endif
85401
85402/* Opcode: Expire P1 * * * *
85403**
85404** Cause precompiled statements to expire.  When an expired statement
85405** is executed using sqlite3_step() it will either automatically
85406** reprepare itself (if it was originally created using sqlite3_prepare_v2())
85407** or it will fail with SQLITE_SCHEMA.
85408**
85409** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
85410** then only the currently executing statement is expired.
85411*/
85412case OP_Expire: {
85413  if( !pOp->p1 ){
85414    sqlite3ExpirePreparedStatements(db);
85415  }else{
85416    p->expired = 1;
85417  }
85418  break;
85419}
85420
85421#ifndef SQLITE_OMIT_SHARED_CACHE
85422/* Opcode: TableLock P1 P2 P3 P4 *
85423** Synopsis: iDb=P1 root=P2 write=P3
85424**
85425** Obtain a lock on a particular table. This instruction is only used when
85426** the shared-cache feature is enabled.
85427**
85428** P1 is the index of the database in sqlite3.aDb[] of the database
85429** on which the lock is acquired.  A readlock is obtained if P3==0 or
85430** a write lock if P3==1.
85431**
85432** P2 contains the root-page of the table to lock.
85433**
85434** P4 contains a pointer to the name of the table being locked. This is only
85435** used to generate an error message if the lock cannot be obtained.
85436*/
85437case OP_TableLock: {
85438  u8 isWriteLock = (u8)pOp->p3;
85439  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
85440    int p1 = pOp->p1;
85441    assert( p1>=0 && p1<db->nDb );
85442    assert( DbMaskTest(p->btreeMask, p1) );
85443    assert( isWriteLock==0 || isWriteLock==1 );
85444    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
85445    if( rc ){
85446      if( (rc&0xFF)==SQLITE_LOCKED ){
85447        const char *z = pOp->p4.z;
85448        sqlite3VdbeError(p, "database table is locked: %s", z);
85449      }
85450      goto abort_due_to_error;
85451    }
85452  }
85453  break;
85454}
85455#endif /* SQLITE_OMIT_SHARED_CACHE */
85456
85457#ifndef SQLITE_OMIT_VIRTUALTABLE
85458/* Opcode: VBegin * * * P4 *
85459**
85460** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
85461** xBegin method for that table.
85462**
85463** Also, whether or not P4 is set, check that this is not being called from
85464** within a callback to a virtual table xSync() method. If it is, the error
85465** code will be set to SQLITE_LOCKED.
85466*/
85467case OP_VBegin: {
85468  VTable *pVTab;
85469  pVTab = pOp->p4.pVtab;
85470  rc = sqlite3VtabBegin(db, pVTab);
85471  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
85472  if( rc ) goto abort_due_to_error;
85473  break;
85474}
85475#endif /* SQLITE_OMIT_VIRTUALTABLE */
85476
85477#ifndef SQLITE_OMIT_VIRTUALTABLE
85478/* Opcode: VCreate P1 P2 * * *
85479**
85480** P2 is a register that holds the name of a virtual table in database
85481** P1. Call the xCreate method for that table.
85482*/
85483case OP_VCreate: {
85484  Mem sMem;          /* For storing the record being decoded */
85485  const char *zTab;  /* Name of the virtual table */
85486
85487  memset(&sMem, 0, sizeof(sMem));
85488  sMem.db = db;
85489  /* Because P2 is always a static string, it is impossible for the
85490  ** sqlite3VdbeMemCopy() to fail */
85491  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
85492  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
85493  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
85494  assert( rc==SQLITE_OK );
85495  zTab = (const char*)sqlite3_value_text(&sMem);
85496  assert( zTab || db->mallocFailed );
85497  if( zTab ){
85498    rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
85499  }
85500  sqlite3VdbeMemRelease(&sMem);
85501  if( rc ) goto abort_due_to_error;
85502  break;
85503}
85504#endif /* SQLITE_OMIT_VIRTUALTABLE */
85505
85506#ifndef SQLITE_OMIT_VIRTUALTABLE
85507/* Opcode: VDestroy P1 * * P4 *
85508**
85509** P4 is the name of a virtual table in database P1.  Call the xDestroy method
85510** of that table.
85511*/
85512case OP_VDestroy: {
85513  db->nVDestroy++;
85514  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
85515  db->nVDestroy--;
85516  if( rc ) goto abort_due_to_error;
85517  break;
85518}
85519#endif /* SQLITE_OMIT_VIRTUALTABLE */
85520
85521#ifndef SQLITE_OMIT_VIRTUALTABLE
85522/* Opcode: VOpen P1 * * P4 *
85523**
85524** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
85525** P1 is a cursor number.  This opcode opens a cursor to the virtual
85526** table and stores that cursor in P1.
85527*/
85528case OP_VOpen: {
85529  VdbeCursor *pCur;
85530  sqlite3_vtab_cursor *pVCur;
85531  sqlite3_vtab *pVtab;
85532  const sqlite3_module *pModule;
85533
85534  assert( p->bIsReader );
85535  pCur = 0;
85536  pVCur = 0;
85537  pVtab = pOp->p4.pVtab->pVtab;
85538  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
85539    rc = SQLITE_LOCKED;
85540    goto abort_due_to_error;
85541  }
85542  pModule = pVtab->pModule;
85543  rc = pModule->xOpen(pVtab, &pVCur);
85544  sqlite3VtabImportErrmsg(p, pVtab);
85545  if( rc ) goto abort_due_to_error;
85546
85547  /* Initialize sqlite3_vtab_cursor base class */
85548  pVCur->pVtab = pVtab;
85549
85550  /* Initialize vdbe cursor object */
85551  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
85552  if( pCur ){
85553    pCur->uc.pVCur = pVCur;
85554    pVtab->nRef++;
85555  }else{
85556    assert( db->mallocFailed );
85557    pModule->xClose(pVCur);
85558    goto no_mem;
85559  }
85560  break;
85561}
85562#endif /* SQLITE_OMIT_VIRTUALTABLE */
85563
85564#ifndef SQLITE_OMIT_VIRTUALTABLE
85565/* Opcode: VFilter P1 P2 P3 P4 *
85566** Synopsis: iplan=r[P3] zplan='P4'
85567**
85568** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
85569** the filtered result set is empty.
85570**
85571** P4 is either NULL or a string that was generated by the xBestIndex
85572** method of the module.  The interpretation of the P4 string is left
85573** to the module implementation.
85574**
85575** This opcode invokes the xFilter method on the virtual table specified
85576** by P1.  The integer query plan parameter to xFilter is stored in register
85577** P3. Register P3+1 stores the argc parameter to be passed to the
85578** xFilter method. Registers P3+2..P3+1+argc are the argc
85579** additional parameters which are passed to
85580** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
85581**
85582** A jump is made to P2 if the result set after filtering would be empty.
85583*/
85584case OP_VFilter: {   /* jump */
85585  int nArg;
85586  int iQuery;
85587  const sqlite3_module *pModule;
85588  Mem *pQuery;
85589  Mem *pArgc;
85590  sqlite3_vtab_cursor *pVCur;
85591  sqlite3_vtab *pVtab;
85592  VdbeCursor *pCur;
85593  int res;
85594  int i;
85595  Mem **apArg;
85596
85597  pQuery = &aMem[pOp->p3];
85598  pArgc = &pQuery[1];
85599  pCur = p->apCsr[pOp->p1];
85600  assert( memIsValid(pQuery) );
85601  REGISTER_TRACE(pOp->p3, pQuery);
85602  assert( pCur->eCurType==CURTYPE_VTAB );
85603  pVCur = pCur->uc.pVCur;
85604  pVtab = pVCur->pVtab;
85605  pModule = pVtab->pModule;
85606
85607  /* Grab the index number and argc parameters */
85608  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
85609  nArg = (int)pArgc->u.i;
85610  iQuery = (int)pQuery->u.i;
85611
85612  /* Invoke the xFilter method */
85613  res = 0;
85614  apArg = p->apArg;
85615  for(i = 0; i<nArg; i++){
85616    apArg[i] = &pArgc[i+1];
85617  }
85618  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
85619  sqlite3VtabImportErrmsg(p, pVtab);
85620  if( rc ) goto abort_due_to_error;
85621  res = pModule->xEof(pVCur);
85622  pCur->nullRow = 0;
85623  VdbeBranchTaken(res!=0,2);
85624  if( res ) goto jump_to_p2;
85625  break;
85626}
85627#endif /* SQLITE_OMIT_VIRTUALTABLE */
85628
85629#ifndef SQLITE_OMIT_VIRTUALTABLE
85630/* Opcode: VColumn P1 P2 P3 * *
85631** Synopsis: r[P3]=vcolumn(P2)
85632**
85633** Store the value of the P2-th column of
85634** the row of the virtual-table that the
85635** P1 cursor is pointing to into register P3.
85636*/
85637case OP_VColumn: {
85638  sqlite3_vtab *pVtab;
85639  const sqlite3_module *pModule;
85640  Mem *pDest;
85641  sqlite3_context sContext;
85642
85643  VdbeCursor *pCur = p->apCsr[pOp->p1];
85644  assert( pCur->eCurType==CURTYPE_VTAB );
85645  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
85646  pDest = &aMem[pOp->p3];
85647  memAboutToChange(p, pDest);
85648  if( pCur->nullRow ){
85649    sqlite3VdbeMemSetNull(pDest);
85650    break;
85651  }
85652  pVtab = pCur->uc.pVCur->pVtab;
85653  pModule = pVtab->pModule;
85654  assert( pModule->xColumn );
85655  memset(&sContext, 0, sizeof(sContext));
85656  sContext.pOut = pDest;
85657  MemSetTypeFlag(pDest, MEM_Null);
85658  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
85659  sqlite3VtabImportErrmsg(p, pVtab);
85660  if( sContext.isError ){
85661    rc = sContext.isError;
85662  }
85663  sqlite3VdbeChangeEncoding(pDest, encoding);
85664  REGISTER_TRACE(pOp->p3, pDest);
85665  UPDATE_MAX_BLOBSIZE(pDest);
85666
85667  if( sqlite3VdbeMemTooBig(pDest) ){
85668    goto too_big;
85669  }
85670  if( rc ) goto abort_due_to_error;
85671  break;
85672}
85673#endif /* SQLITE_OMIT_VIRTUALTABLE */
85674
85675#ifndef SQLITE_OMIT_VIRTUALTABLE
85676/* Opcode: VNext P1 P2 * * *
85677**
85678** Advance virtual table P1 to the next row in its result set and
85679** jump to instruction P2.  Or, if the virtual table has reached
85680** the end of its result set, then fall through to the next instruction.
85681*/
85682case OP_VNext: {   /* jump */
85683  sqlite3_vtab *pVtab;
85684  const sqlite3_module *pModule;
85685  int res;
85686  VdbeCursor *pCur;
85687
85688  res = 0;
85689  pCur = p->apCsr[pOp->p1];
85690  assert( pCur->eCurType==CURTYPE_VTAB );
85691  if( pCur->nullRow ){
85692    break;
85693  }
85694  pVtab = pCur->uc.pVCur->pVtab;
85695  pModule = pVtab->pModule;
85696  assert( pModule->xNext );
85697
85698  /* Invoke the xNext() method of the module. There is no way for the
85699  ** underlying implementation to return an error if one occurs during
85700  ** xNext(). Instead, if an error occurs, true is returned (indicating that
85701  ** data is available) and the error code returned when xColumn or
85702  ** some other method is next invoked on the save virtual table cursor.
85703  */
85704  rc = pModule->xNext(pCur->uc.pVCur);
85705  sqlite3VtabImportErrmsg(p, pVtab);
85706  if( rc ) goto abort_due_to_error;
85707  res = pModule->xEof(pCur->uc.pVCur);
85708  VdbeBranchTaken(!res,2);
85709  if( !res ){
85710    /* If there is data, jump to P2 */
85711    goto jump_to_p2_and_check_for_interrupt;
85712  }
85713  goto check_for_interrupt;
85714}
85715#endif /* SQLITE_OMIT_VIRTUALTABLE */
85716
85717#ifndef SQLITE_OMIT_VIRTUALTABLE
85718/* Opcode: VRename P1 * * P4 *
85719**
85720** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
85721** This opcode invokes the corresponding xRename method. The value
85722** in register P1 is passed as the zName argument to the xRename method.
85723*/
85724case OP_VRename: {
85725  sqlite3_vtab *pVtab;
85726  Mem *pName;
85727
85728  pVtab = pOp->p4.pVtab->pVtab;
85729  pName = &aMem[pOp->p1];
85730  assert( pVtab->pModule->xRename );
85731  assert( memIsValid(pName) );
85732  assert( p->readOnly==0 );
85733  REGISTER_TRACE(pOp->p1, pName);
85734  assert( pName->flags & MEM_Str );
85735  testcase( pName->enc==SQLITE_UTF8 );
85736  testcase( pName->enc==SQLITE_UTF16BE );
85737  testcase( pName->enc==SQLITE_UTF16LE );
85738  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
85739  if( rc ) goto abort_due_to_error;
85740  rc = pVtab->pModule->xRename(pVtab, pName->z);
85741  sqlite3VtabImportErrmsg(p, pVtab);
85742  p->expired = 0;
85743  if( rc ) goto abort_due_to_error;
85744  break;
85745}
85746#endif
85747
85748#ifndef SQLITE_OMIT_VIRTUALTABLE
85749/* Opcode: VUpdate P1 P2 P3 P4 P5
85750** Synopsis: data=r[P3@P2]
85751**
85752** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
85753** This opcode invokes the corresponding xUpdate method. P2 values
85754** are contiguous memory cells starting at P3 to pass to the xUpdate
85755** invocation. The value in register (P3+P2-1) corresponds to the
85756** p2th element of the argv array passed to xUpdate.
85757**
85758** The xUpdate method will do a DELETE or an INSERT or both.
85759** The argv[0] element (which corresponds to memory cell P3)
85760** is the rowid of a row to delete.  If argv[0] is NULL then no
85761** deletion occurs.  The argv[1] element is the rowid of the new
85762** row.  This can be NULL to have the virtual table select the new
85763** rowid for itself.  The subsequent elements in the array are
85764** the values of columns in the new row.
85765**
85766** If P2==1 then no insert is performed.  argv[0] is the rowid of
85767** a row to delete.
85768**
85769** P1 is a boolean flag. If it is set to true and the xUpdate call
85770** is successful, then the value returned by sqlite3_last_insert_rowid()
85771** is set to the value of the rowid for the row just inserted.
85772**
85773** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
85774** apply in the case of a constraint failure on an insert or update.
85775*/
85776case OP_VUpdate: {
85777  sqlite3_vtab *pVtab;
85778  const sqlite3_module *pModule;
85779  int nArg;
85780  int i;
85781  sqlite_int64 rowid;
85782  Mem **apArg;
85783  Mem *pX;
85784
85785  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
85786       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
85787  );
85788  assert( p->readOnly==0 );
85789  pVtab = pOp->p4.pVtab->pVtab;
85790  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
85791    rc = SQLITE_LOCKED;
85792    goto abort_due_to_error;
85793  }
85794  pModule = pVtab->pModule;
85795  nArg = pOp->p2;
85796  assert( pOp->p4type==P4_VTAB );
85797  if( ALWAYS(pModule->xUpdate) ){
85798    u8 vtabOnConflict = db->vtabOnConflict;
85799    apArg = p->apArg;
85800    pX = &aMem[pOp->p3];
85801    for(i=0; i<nArg; i++){
85802      assert( memIsValid(pX) );
85803      memAboutToChange(p, pX);
85804      apArg[i] = pX;
85805      pX++;
85806    }
85807    db->vtabOnConflict = pOp->p5;
85808    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
85809    db->vtabOnConflict = vtabOnConflict;
85810    sqlite3VtabImportErrmsg(p, pVtab);
85811    if( rc==SQLITE_OK && pOp->p1 ){
85812      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
85813      db->lastRowid = rowid;
85814    }
85815    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
85816      if( pOp->p5==OE_Ignore ){
85817        rc = SQLITE_OK;
85818      }else{
85819        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
85820      }
85821    }else{
85822      p->nChange++;
85823    }
85824    if( rc ) goto abort_due_to_error;
85825  }
85826  break;
85827}
85828#endif /* SQLITE_OMIT_VIRTUALTABLE */
85829
85830#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
85831/* Opcode: Pagecount P1 P2 * * *
85832**
85833** Write the current number of pages in database P1 to memory cell P2.
85834*/
85835case OP_Pagecount: {            /* out2 */
85836  pOut = out2Prerelease(p, pOp);
85837  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
85838  break;
85839}
85840#endif
85841
85842
85843#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
85844/* Opcode: MaxPgcnt P1 P2 P3 * *
85845**
85846** Try to set the maximum page count for database P1 to the value in P3.
85847** Do not let the maximum page count fall below the current page count and
85848** do not change the maximum page count value if P3==0.
85849**
85850** Store the maximum page count after the change in register P2.
85851*/
85852case OP_MaxPgcnt: {            /* out2 */
85853  unsigned int newMax;
85854  Btree *pBt;
85855
85856  pOut = out2Prerelease(p, pOp);
85857  pBt = db->aDb[pOp->p1].pBt;
85858  newMax = 0;
85859  if( pOp->p3 ){
85860    newMax = sqlite3BtreeLastPage(pBt);
85861    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
85862  }
85863  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
85864  break;
85865}
85866#endif
85867
85868/* Opcode: Function0 P1 P2 P3 P4 P5
85869** Synopsis: r[P3]=func(r[P2@P5])
85870**
85871** Invoke a user function (P4 is a pointer to a FuncDef object that
85872** defines the function) with P5 arguments taken from register P2 and
85873** successors.  The result of the function is stored in register P3.
85874** Register P3 must not be one of the function inputs.
85875**
85876** P1 is a 32-bit bitmask indicating whether or not each argument to the
85877** function was determined to be constant at compile time. If the first
85878** argument was constant then bit 0 of P1 is set. This is used to determine
85879** whether meta data associated with a user function argument using the
85880** sqlite3_set_auxdata() API may be safely retained until the next
85881** invocation of this opcode.
85882**
85883** See also: Function, AggStep, AggFinal
85884*/
85885/* Opcode: Function P1 P2 P3 P4 P5
85886** Synopsis: r[P3]=func(r[P2@P5])
85887**
85888** Invoke a user function (P4 is a pointer to an sqlite3_context object that
85889** contains a pointer to the function to be run) with P5 arguments taken
85890** from register P2 and successors.  The result of the function is stored
85891** in register P3.  Register P3 must not be one of the function inputs.
85892**
85893** P1 is a 32-bit bitmask indicating whether or not each argument to the
85894** function was determined to be constant at compile time. If the first
85895** argument was constant then bit 0 of P1 is set. This is used to determine
85896** whether meta data associated with a user function argument using the
85897** sqlite3_set_auxdata() API may be safely retained until the next
85898** invocation of this opcode.
85899**
85900** SQL functions are initially coded as OP_Function0 with P4 pointing
85901** to a FuncDef object.  But on first evaluation, the P4 operand is
85902** automatically converted into an sqlite3_context object and the operation
85903** changed to this OP_Function opcode.  In this way, the initialization of
85904** the sqlite3_context object occurs only once, rather than once for each
85905** evaluation of the function.
85906**
85907** See also: Function0, AggStep, AggFinal
85908*/
85909case OP_PureFunc0:
85910case OP_Function0: {
85911  int n;
85912  sqlite3_context *pCtx;
85913
85914  assert( pOp->p4type==P4_FUNCDEF );
85915  n = pOp->p5;
85916  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
85917  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
85918  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
85919  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
85920  if( pCtx==0 ) goto no_mem;
85921  pCtx->pOut = 0;
85922  pCtx->pFunc = pOp->p4.pFunc;
85923  pCtx->iOp = (int)(pOp - aOp);
85924  pCtx->pVdbe = p;
85925  pCtx->argc = n;
85926  pOp->p4type = P4_FUNCCTX;
85927  pOp->p4.pCtx = pCtx;
85928  assert( OP_PureFunc == OP_PureFunc0+2 );
85929  assert( OP_Function == OP_Function0+2 );
85930  pOp->opcode += 2;
85931  /* Fall through into OP_Function */
85932}
85933case OP_PureFunc:
85934case OP_Function: {
85935  int i;
85936  sqlite3_context *pCtx;
85937
85938  assert( pOp->p4type==P4_FUNCCTX );
85939  pCtx = pOp->p4.pCtx;
85940
85941  /* If this function is inside of a trigger, the register array in aMem[]
85942  ** might change from one evaluation to the next.  The next block of code
85943  ** checks to see if the register array has changed, and if so it
85944  ** reinitializes the relavant parts of the sqlite3_context object */
85945  pOut = &aMem[pOp->p3];
85946  if( pCtx->pOut != pOut ){
85947    pCtx->pOut = pOut;
85948    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
85949  }
85950
85951  memAboutToChange(p, pOut);
85952#ifdef SQLITE_DEBUG
85953  for(i=0; i<pCtx->argc; i++){
85954    assert( memIsValid(pCtx->argv[i]) );
85955    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
85956  }
85957#endif
85958  MemSetTypeFlag(pOut, MEM_Null);
85959  pCtx->fErrorOrAux = 0;
85960  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
85961
85962  /* If the function returned an error, throw an exception */
85963  if( pCtx->fErrorOrAux ){
85964    if( pCtx->isError ){
85965      sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
85966      rc = pCtx->isError;
85967    }
85968    sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
85969    if( rc ) goto abort_due_to_error;
85970  }
85971
85972  /* Copy the result of the function into register P3 */
85973  if( pOut->flags & (MEM_Str|MEM_Blob) ){
85974    sqlite3VdbeChangeEncoding(pOut, encoding);
85975    if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
85976  }
85977
85978  REGISTER_TRACE(pOp->p3, pOut);
85979  UPDATE_MAX_BLOBSIZE(pOut);
85980  break;
85981}
85982
85983
85984/* Opcode: Init P1 P2 * P4 *
85985** Synopsis: Start at P2
85986**
85987** Programs contain a single instance of this opcode as the very first
85988** opcode.
85989**
85990** If tracing is enabled (by the sqlite3_trace()) interface, then
85991** the UTF-8 string contained in P4 is emitted on the trace callback.
85992** Or if P4 is blank, use the string returned by sqlite3_sql().
85993**
85994** If P2 is not zero, jump to instruction P2.
85995**
85996** Increment the value of P1 so that OP_Once opcodes will jump the
85997** first time they are evaluated for this run.
85998*/
85999case OP_Init: {          /* jump */
86000  char *zTrace;
86001  int i;
86002
86003  /* If the P4 argument is not NULL, then it must be an SQL comment string.
86004  ** The "--" string is broken up to prevent false-positives with srcck1.c.
86005  **
86006  ** This assert() provides evidence for:
86007  ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
86008  ** would have been returned by the legacy sqlite3_trace() interface by
86009  ** using the X argument when X begins with "--" and invoking
86010  ** sqlite3_expanded_sql(P) otherwise.
86011  */
86012  assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
86013  assert( pOp==p->aOp );  /* Always instruction 0 */
86014
86015#ifndef SQLITE_OMIT_TRACE
86016  if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
86017   && !p->doingRerun
86018   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
86019  ){
86020#ifndef SQLITE_OMIT_DEPRECATED
86021    if( db->mTrace & SQLITE_TRACE_LEGACY ){
86022      void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
86023      char *z = sqlite3VdbeExpandSql(p, zTrace);
86024      x(db->pTraceArg, z);
86025      sqlite3_free(z);
86026    }else
86027#endif
86028    if( db->nVdbeExec>1 ){
86029      char *z = sqlite3MPrintf(db, "-- %s", zTrace);
86030      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
86031      sqlite3DbFree(db, z);
86032    }else{
86033      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
86034    }
86035  }
86036#ifdef SQLITE_USE_FCNTL_TRACE
86037  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
86038  if( zTrace ){
86039    int j;
86040    for(j=0; j<db->nDb; j++){
86041      if( DbMaskTest(p->btreeMask, j)==0 ) continue;
86042      sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
86043    }
86044  }
86045#endif /* SQLITE_USE_FCNTL_TRACE */
86046#ifdef SQLITE_DEBUG
86047  if( (db->flags & SQLITE_SqlTrace)!=0
86048   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
86049  ){
86050    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
86051  }
86052#endif /* SQLITE_DEBUG */
86053#endif /* SQLITE_OMIT_TRACE */
86054  assert( pOp->p2>0 );
86055  if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
86056    for(i=1; i<p->nOp; i++){
86057      if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
86058    }
86059    pOp->p1 = 0;
86060  }
86061  pOp->p1++;
86062  p->aCounter[SQLITE_STMTSTATUS_RUN]++;
86063  goto jump_to_p2;
86064}
86065
86066#ifdef SQLITE_ENABLE_CURSOR_HINTS
86067/* Opcode: CursorHint P1 * * P4 *
86068**
86069** Provide a hint to cursor P1 that it only needs to return rows that
86070** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
86071** to values currently held in registers.  TK_COLUMN terms in the P4
86072** expression refer to columns in the b-tree to which cursor P1 is pointing.
86073*/
86074case OP_CursorHint: {
86075  VdbeCursor *pC;
86076
86077  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
86078  assert( pOp->p4type==P4_EXPR );
86079  pC = p->apCsr[pOp->p1];
86080  if( pC ){
86081    assert( pC->eCurType==CURTYPE_BTREE );
86082    sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
86083                           pOp->p4.pExpr, aMem);
86084  }
86085  break;
86086}
86087#endif /* SQLITE_ENABLE_CURSOR_HINTS */
86088
86089/* Opcode: Noop * * * * *
86090**
86091** Do nothing.  This instruction is often useful as a jump
86092** destination.
86093*/
86094/*
86095** The magic Explain opcode are only inserted when explain==2 (which
86096** is to say when the EXPLAIN QUERY PLAN syntax is used.)
86097** This opcode records information from the optimizer.  It is the
86098** the same as a no-op.  This opcodesnever appears in a real VM program.
86099*/
86100default: {          /* This is really OP_Noop and OP_Explain */
86101  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
86102  break;
86103}
86104
86105/*****************************************************************************
86106** The cases of the switch statement above this line should all be indented
86107** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
86108** readability.  From this point on down, the normal indentation rules are
86109** restored.
86110*****************************************************************************/
86111    }
86112
86113#ifdef VDBE_PROFILE
86114    {
86115      u64 endTime = sqlite3Hwtime();
86116      if( endTime>start ) pOrigOp->cycles += endTime - start;
86117      pOrigOp->cnt++;
86118    }
86119#endif
86120
86121    /* The following code adds nothing to the actual functionality
86122    ** of the program.  It is only here for testing and debugging.
86123    ** On the other hand, it does burn CPU cycles every time through
86124    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
86125    */
86126#ifndef NDEBUG
86127    assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
86128
86129#ifdef SQLITE_DEBUG
86130    if( db->flags & SQLITE_VdbeTrace ){
86131      u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
86132      if( rc!=0 ) printf("rc=%d\n",rc);
86133      if( opProperty & (OPFLG_OUT2) ){
86134        registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
86135      }
86136      if( opProperty & OPFLG_OUT3 ){
86137        registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
86138      }
86139    }
86140#endif  /* SQLITE_DEBUG */
86141#endif  /* NDEBUG */
86142  }  /* The end of the for(;;) loop the loops through opcodes */
86143
86144  /* If we reach this point, it means that execution is finished with
86145  ** an error of some kind.
86146  */
86147abort_due_to_error:
86148  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
86149  assert( rc );
86150  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
86151    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
86152  }
86153  p->rc = rc;
86154  sqlite3SystemError(db, rc);
86155  testcase( sqlite3GlobalConfig.xLog!=0 );
86156  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
86157                   (int)(pOp - aOp), p->zSql, p->zErrMsg);
86158  sqlite3VdbeHalt(p);
86159  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
86160  rc = SQLITE_ERROR;
86161  if( resetSchemaOnFault>0 ){
86162    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
86163  }
86164
86165  /* This is the only way out of this procedure.  We have to
86166  ** release the mutexes on btrees that were acquired at the
86167  ** top. */
86168vdbe_return:
86169  testcase( nVmStep>0 );
86170  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
86171  sqlite3VdbeLeave(p);
86172  assert( rc!=SQLITE_OK || nExtraDelete==0
86173       || sqlite3_strlike("DELETE%",p->zSql,0)!=0
86174  );
86175  return rc;
86176
86177  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
86178  ** is encountered.
86179  */
86180too_big:
86181  sqlite3VdbeError(p, "string or blob too big");
86182  rc = SQLITE_TOOBIG;
86183  goto abort_due_to_error;
86184
86185  /* Jump to here if a malloc() fails.
86186  */
86187no_mem:
86188  sqlite3OomFault(db);
86189  sqlite3VdbeError(p, "out of memory");
86190  rc = SQLITE_NOMEM_BKPT;
86191  goto abort_due_to_error;
86192
86193  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
86194  ** flag.
86195  */
86196abort_due_to_interrupt:
86197  assert( db->u1.isInterrupted );
86198  rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
86199  p->rc = rc;
86200  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
86201  goto abort_due_to_error;
86202}
86203
86204
86205/************** End of vdbe.c ************************************************/
86206/************** Begin file vdbeblob.c ****************************************/
86207/*
86208** 2007 May 1
86209**
86210** The author disclaims copyright to this source code.  In place of
86211** a legal notice, here is a blessing:
86212**
86213**    May you do good and not evil.
86214**    May you find forgiveness for yourself and forgive others.
86215**    May you share freely, never taking more than you give.
86216**
86217*************************************************************************
86218**
86219** This file contains code used to implement incremental BLOB I/O.
86220*/
86221
86222/* #include "sqliteInt.h" */
86223/* #include "vdbeInt.h" */
86224
86225#ifndef SQLITE_OMIT_INCRBLOB
86226
86227/*
86228** Valid sqlite3_blob* handles point to Incrblob structures.
86229*/
86230typedef struct Incrblob Incrblob;
86231struct Incrblob {
86232  int nByte;              /* Size of open blob, in bytes */
86233  int iOffset;            /* Byte offset of blob in cursor data */
86234  u16 iCol;               /* Table column this handle is open on */
86235  BtCursor *pCsr;         /* Cursor pointing at blob row */
86236  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
86237  sqlite3 *db;            /* The associated database */
86238  char *zDb;              /* Database name */
86239  Table *pTab;            /* Table object */
86240};
86241
86242
86243/*
86244** This function is used by both blob_open() and blob_reopen(). It seeks
86245** the b-tree cursor associated with blob handle p to point to row iRow.
86246** If successful, SQLITE_OK is returned and subsequent calls to
86247** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
86248**
86249** If an error occurs, or if the specified row does not exist or does not
86250** contain a value of type TEXT or BLOB in the column nominated when the
86251** blob handle was opened, then an error code is returned and *pzErr may
86252** be set to point to a buffer containing an error message. It is the
86253** responsibility of the caller to free the error message buffer using
86254** sqlite3DbFree().
86255**
86256** If an error does occur, then the b-tree cursor is closed. All subsequent
86257** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
86258** immediately return SQLITE_ABORT.
86259*/
86260static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
86261  int rc;                         /* Error code */
86262  char *zErr = 0;                 /* Error message */
86263  Vdbe *v = (Vdbe *)p->pStmt;
86264
86265  /* Set the value of register r[1] in the SQL statement to integer iRow.
86266  ** This is done directly as a performance optimization
86267  */
86268  v->aMem[1].flags = MEM_Int;
86269  v->aMem[1].u.i = iRow;
86270
86271  /* If the statement has been run before (and is paused at the OP_ResultRow)
86272  ** then back it up to the point where it does the OP_SeekRowid.  This could
86273  ** have been down with an extra OP_Goto, but simply setting the program
86274  ** counter is faster. */
86275  if( v->pc>3 ){
86276    v->pc = 3;
86277    rc = sqlite3VdbeExec(v);
86278  }else{
86279    rc = sqlite3_step(p->pStmt);
86280  }
86281  if( rc==SQLITE_ROW ){
86282    VdbeCursor *pC = v->apCsr[0];
86283    u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
86284    testcase( pC->nHdrParsed==p->iCol );
86285    testcase( pC->nHdrParsed==p->iCol+1 );
86286    if( type<12 ){
86287      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
86288          type==0?"null": type==7?"real": "integer"
86289      );
86290      rc = SQLITE_ERROR;
86291      sqlite3_finalize(p->pStmt);
86292      p->pStmt = 0;
86293    }else{
86294      p->iOffset = pC->aType[p->iCol + pC->nField];
86295      p->nByte = sqlite3VdbeSerialTypeLen(type);
86296      p->pCsr =  pC->uc.pCursor;
86297      sqlite3BtreeIncrblobCursor(p->pCsr);
86298    }
86299  }
86300
86301  if( rc==SQLITE_ROW ){
86302    rc = SQLITE_OK;
86303  }else if( p->pStmt ){
86304    rc = sqlite3_finalize(p->pStmt);
86305    p->pStmt = 0;
86306    if( rc==SQLITE_OK ){
86307      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
86308      rc = SQLITE_ERROR;
86309    }else{
86310      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
86311    }
86312  }
86313
86314  assert( rc!=SQLITE_OK || zErr==0 );
86315  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
86316
86317  *pzErr = zErr;
86318  return rc;
86319}
86320
86321/*
86322** Open a blob handle.
86323*/
86324SQLITE_API int sqlite3_blob_open(
86325  sqlite3* db,            /* The database connection */
86326  const char *zDb,        /* The attached database containing the blob */
86327  const char *zTable,     /* The table containing the blob */
86328  const char *zColumn,    /* The column containing the blob */
86329  sqlite_int64 iRow,      /* The row containing the glob */
86330  int wrFlag,             /* True -> read/write access, false -> read-only */
86331  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
86332){
86333  int nAttempt = 0;
86334  int iCol;               /* Index of zColumn in row-record */
86335  int rc = SQLITE_OK;
86336  char *zErr = 0;
86337  Table *pTab;
86338  Parse *pParse = 0;
86339  Incrblob *pBlob = 0;
86340
86341#ifdef SQLITE_ENABLE_API_ARMOR
86342  if( ppBlob==0 ){
86343    return SQLITE_MISUSE_BKPT;
86344  }
86345#endif
86346  *ppBlob = 0;
86347#ifdef SQLITE_ENABLE_API_ARMOR
86348  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
86349    return SQLITE_MISUSE_BKPT;
86350  }
86351#endif
86352  wrFlag = !!wrFlag;                /* wrFlag = (wrFlag ? 1 : 0); */
86353
86354  sqlite3_mutex_enter(db->mutex);
86355
86356  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
86357  if( !pBlob ) goto blob_open_out;
86358  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
86359  if( !pParse ) goto blob_open_out;
86360
86361  do {
86362    memset(pParse, 0, sizeof(Parse));
86363    pParse->db = db;
86364    sqlite3DbFree(db, zErr);
86365    zErr = 0;
86366
86367    sqlite3BtreeEnterAll(db);
86368    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
86369    if( pTab && IsVirtual(pTab) ){
86370      pTab = 0;
86371      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
86372    }
86373    if( pTab && !HasRowid(pTab) ){
86374      pTab = 0;
86375      sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
86376    }
86377#ifndef SQLITE_OMIT_VIEW
86378    if( pTab && pTab->pSelect ){
86379      pTab = 0;
86380      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
86381    }
86382#endif
86383    if( !pTab ){
86384      if( pParse->zErrMsg ){
86385        sqlite3DbFree(db, zErr);
86386        zErr = pParse->zErrMsg;
86387        pParse->zErrMsg = 0;
86388      }
86389      rc = SQLITE_ERROR;
86390      sqlite3BtreeLeaveAll(db);
86391      goto blob_open_out;
86392    }
86393    pBlob->pTab = pTab;
86394    pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
86395
86396    /* Now search pTab for the exact column. */
86397    for(iCol=0; iCol<pTab->nCol; iCol++) {
86398      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
86399        break;
86400      }
86401    }
86402    if( iCol==pTab->nCol ){
86403      sqlite3DbFree(db, zErr);
86404      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
86405      rc = SQLITE_ERROR;
86406      sqlite3BtreeLeaveAll(db);
86407      goto blob_open_out;
86408    }
86409
86410    /* If the value is being opened for writing, check that the
86411    ** column is not indexed, and that it is not part of a foreign key.
86412    */
86413    if( wrFlag ){
86414      const char *zFault = 0;
86415      Index *pIdx;
86416#ifndef SQLITE_OMIT_FOREIGN_KEY
86417      if( db->flags&SQLITE_ForeignKeys ){
86418        /* Check that the column is not part of an FK child key definition. It
86419        ** is not necessary to check if it is part of a parent key, as parent
86420        ** key columns must be indexed. The check below will pick up this
86421        ** case.  */
86422        FKey *pFKey;
86423        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
86424          int j;
86425          for(j=0; j<pFKey->nCol; j++){
86426            if( pFKey->aCol[j].iFrom==iCol ){
86427              zFault = "foreign key";
86428            }
86429          }
86430        }
86431      }
86432#endif
86433      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86434        int j;
86435        for(j=0; j<pIdx->nKeyCol; j++){
86436          /* FIXME: Be smarter about indexes that use expressions */
86437          if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
86438            zFault = "indexed";
86439          }
86440        }
86441      }
86442      if( zFault ){
86443        sqlite3DbFree(db, zErr);
86444        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
86445        rc = SQLITE_ERROR;
86446        sqlite3BtreeLeaveAll(db);
86447        goto blob_open_out;
86448      }
86449    }
86450
86451    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
86452    assert( pBlob->pStmt || db->mallocFailed );
86453    if( pBlob->pStmt ){
86454
86455      /* This VDBE program seeks a btree cursor to the identified
86456      ** db/table/row entry. The reason for using a vdbe program instead
86457      ** of writing code to use the b-tree layer directly is that the
86458      ** vdbe program will take advantage of the various transaction,
86459      ** locking and error handling infrastructure built into the vdbe.
86460      **
86461      ** After seeking the cursor, the vdbe executes an OP_ResultRow.
86462      ** Code external to the Vdbe then "borrows" the b-tree cursor and
86463      ** uses it to implement the blob_read(), blob_write() and
86464      ** blob_bytes() functions.
86465      **
86466      ** The sqlite3_blob_close() function finalizes the vdbe program,
86467      ** which closes the b-tree cursor and (possibly) commits the
86468      ** transaction.
86469      */
86470      static const int iLn = VDBE_OFFSET_LINENO(2);
86471      static const VdbeOpList openBlob[] = {
86472        {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
86473        {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
86474        /* blobSeekToRow() will initialize r[1] to the desired rowid */
86475        {OP_NotExists,      0, 5, 1},  /* 2: Seek the cursor to rowid=r[1] */
86476        {OP_Column,         0, 0, 1},  /* 3  */
86477        {OP_ResultRow,      1, 0, 0},  /* 4  */
86478        {OP_Halt,           0, 0, 0},  /* 5  */
86479      };
86480      Vdbe *v = (Vdbe *)pBlob->pStmt;
86481      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86482      VdbeOp *aOp;
86483
86484      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
86485                           pTab->pSchema->schema_cookie,
86486                           pTab->pSchema->iGeneration);
86487      sqlite3VdbeChangeP5(v, 1);
86488      aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
86489
86490      /* Make sure a mutex is held on the table to be accessed */
86491      sqlite3VdbeUsesBtree(v, iDb);
86492
86493      if( db->mallocFailed==0 ){
86494        assert( aOp!=0 );
86495        /* Configure the OP_TableLock instruction */
86496#ifdef SQLITE_OMIT_SHARED_CACHE
86497        aOp[0].opcode = OP_Noop;
86498#else
86499        aOp[0].p1 = iDb;
86500        aOp[0].p2 = pTab->tnum;
86501        aOp[0].p3 = wrFlag;
86502        sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
86503      }
86504      if( db->mallocFailed==0 ){
86505#endif
86506
86507        /* Remove either the OP_OpenWrite or OpenRead. Set the P2
86508        ** parameter of the other to pTab->tnum.  */
86509        if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
86510        aOp[1].p2 = pTab->tnum;
86511        aOp[1].p3 = iDb;
86512
86513        /* Configure the number of columns. Configure the cursor to
86514        ** think that the table has one more column than it really
86515        ** does. An OP_Column to retrieve this imaginary column will
86516        ** always return an SQL NULL. This is useful because it means
86517        ** we can invoke OP_Column to fill in the vdbe cursors type
86518        ** and offset cache without causing any IO.
86519        */
86520        aOp[1].p4type = P4_INT32;
86521        aOp[1].p4.i = pTab->nCol+1;
86522        aOp[3].p2 = pTab->nCol;
86523
86524        pParse->nVar = 0;
86525        pParse->nMem = 1;
86526        pParse->nTab = 1;
86527        sqlite3VdbeMakeReady(v, pParse);
86528      }
86529    }
86530
86531    pBlob->iCol = iCol;
86532    pBlob->db = db;
86533    sqlite3BtreeLeaveAll(db);
86534    if( db->mallocFailed ){
86535      goto blob_open_out;
86536    }
86537    rc = blobSeekToRow(pBlob, iRow, &zErr);
86538  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
86539
86540blob_open_out:
86541  if( rc==SQLITE_OK && db->mallocFailed==0 ){
86542    *ppBlob = (sqlite3_blob *)pBlob;
86543  }else{
86544    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
86545    sqlite3DbFree(db, pBlob);
86546  }
86547  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
86548  sqlite3DbFree(db, zErr);
86549  sqlite3ParserReset(pParse);
86550  sqlite3StackFree(db, pParse);
86551  rc = sqlite3ApiExit(db, rc);
86552  sqlite3_mutex_leave(db->mutex);
86553  return rc;
86554}
86555
86556/*
86557** Close a blob handle that was previously created using
86558** sqlite3_blob_open().
86559*/
86560SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
86561  Incrblob *p = (Incrblob *)pBlob;
86562  int rc;
86563  sqlite3 *db;
86564
86565  if( p ){
86566    db = p->db;
86567    sqlite3_mutex_enter(db->mutex);
86568    rc = sqlite3_finalize(p->pStmt);
86569    sqlite3DbFree(db, p);
86570    sqlite3_mutex_leave(db->mutex);
86571  }else{
86572    rc = SQLITE_OK;
86573  }
86574  return rc;
86575}
86576
86577/*
86578** Perform a read or write operation on a blob
86579*/
86580static int blobReadWrite(
86581  sqlite3_blob *pBlob,
86582  void *z,
86583  int n,
86584  int iOffset,
86585  int (*xCall)(BtCursor*, u32, u32, void*)
86586){
86587  int rc;
86588  Incrblob *p = (Incrblob *)pBlob;
86589  Vdbe *v;
86590  sqlite3 *db;
86591
86592  if( p==0 ) return SQLITE_MISUSE_BKPT;
86593  db = p->db;
86594  sqlite3_mutex_enter(db->mutex);
86595  v = (Vdbe*)p->pStmt;
86596
86597  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
86598    /* Request is out of range. Return a transient error. */
86599    rc = SQLITE_ERROR;
86600  }else if( v==0 ){
86601    /* If there is no statement handle, then the blob-handle has
86602    ** already been invalidated. Return SQLITE_ABORT in this case.
86603    */
86604    rc = SQLITE_ABORT;
86605  }else{
86606    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
86607    ** returned, clean-up the statement handle.
86608    */
86609    assert( db == v->db );
86610    sqlite3BtreeEnterCursor(p->pCsr);
86611
86612#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
86613    if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
86614      /* If a pre-update hook is registered and this is a write cursor,
86615      ** invoke it here.
86616      **
86617      ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
86618      ** operation should really be an SQLITE_UPDATE. This is probably
86619      ** incorrect, but is convenient because at this point the new.* values
86620      ** are not easily obtainable. And for the sessions module, an
86621      ** SQLITE_UPDATE where the PK columns do not change is handled in the
86622      ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
86623      ** slightly more efficient). Since you cannot write to a PK column
86624      ** using the incremental-blob API, this works. For the sessions module
86625      ** anyhow.
86626      */
86627      sqlite3_int64 iKey;
86628      iKey = sqlite3BtreeIntegerKey(p->pCsr);
86629      sqlite3VdbePreUpdateHook(
86630          v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
86631      );
86632    }
86633#endif
86634
86635    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
86636    sqlite3BtreeLeaveCursor(p->pCsr);
86637    if( rc==SQLITE_ABORT ){
86638      sqlite3VdbeFinalize(v);
86639      p->pStmt = 0;
86640    }else{
86641      v->rc = rc;
86642    }
86643  }
86644  sqlite3Error(db, rc);
86645  rc = sqlite3ApiExit(db, rc);
86646  sqlite3_mutex_leave(db->mutex);
86647  return rc;
86648}
86649
86650/*
86651** Read data from a blob handle.
86652*/
86653SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
86654  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
86655}
86656
86657/*
86658** Write data to a blob handle.
86659*/
86660SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
86661  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
86662}
86663
86664/*
86665** Query a blob handle for the size of the data.
86666**
86667** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
86668** so no mutex is required for access.
86669*/
86670SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
86671  Incrblob *p = (Incrblob *)pBlob;
86672  return (p && p->pStmt) ? p->nByte : 0;
86673}
86674
86675/*
86676** Move an existing blob handle to point to a different row of the same
86677** database table.
86678**
86679** If an error occurs, or if the specified row does not exist or does not
86680** contain a blob or text value, then an error code is returned and the
86681** database handle error code and message set. If this happens, then all
86682** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
86683** immediately return SQLITE_ABORT.
86684*/
86685SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
86686  int rc;
86687  Incrblob *p = (Incrblob *)pBlob;
86688  sqlite3 *db;
86689
86690  if( p==0 ) return SQLITE_MISUSE_BKPT;
86691  db = p->db;
86692  sqlite3_mutex_enter(db->mutex);
86693
86694  if( p->pStmt==0 ){
86695    /* If there is no statement handle, then the blob-handle has
86696    ** already been invalidated. Return SQLITE_ABORT in this case.
86697    */
86698    rc = SQLITE_ABORT;
86699  }else{
86700    char *zErr;
86701    rc = blobSeekToRow(p, iRow, &zErr);
86702    if( rc!=SQLITE_OK ){
86703      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
86704      sqlite3DbFree(db, zErr);
86705    }
86706    assert( rc!=SQLITE_SCHEMA );
86707  }
86708
86709  rc = sqlite3ApiExit(db, rc);
86710  assert( rc==SQLITE_OK || p->pStmt==0 );
86711  sqlite3_mutex_leave(db->mutex);
86712  return rc;
86713}
86714
86715#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
86716
86717/************** End of vdbeblob.c ********************************************/
86718/************** Begin file vdbesort.c ****************************************/
86719/*
86720** 2011-07-09
86721**
86722** The author disclaims copyright to this source code.  In place of
86723** a legal notice, here is a blessing:
86724**
86725**    May you do good and not evil.
86726**    May you find forgiveness for yourself and forgive others.
86727**    May you share freely, never taking more than you give.
86728**
86729*************************************************************************
86730** This file contains code for the VdbeSorter object, used in concert with
86731** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
86732** or by SELECT statements with ORDER BY clauses that cannot be satisfied
86733** using indexes and without LIMIT clauses.
86734**
86735** The VdbeSorter object implements a multi-threaded external merge sort
86736** algorithm that is efficient even if the number of elements being sorted
86737** exceeds the available memory.
86738**
86739** Here is the (internal, non-API) interface between this module and the
86740** rest of the SQLite system:
86741**
86742**    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
86743**
86744**    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
86745**                                  object.  The row is a binary blob in the
86746**                                  OP_MakeRecord format that contains both
86747**                                  the ORDER BY key columns and result columns
86748**                                  in the case of a SELECT w/ ORDER BY, or
86749**                                  the complete record for an index entry
86750**                                  in the case of a CREATE INDEX.
86751**
86752**    sqlite3VdbeSorterRewind()     Sort all content previously added.
86753**                                  Position the read cursor on the
86754**                                  first sorted element.
86755**
86756**    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
86757**                                  element.
86758**
86759**    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
86760**                                  row currently under the read cursor.
86761**
86762**    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
86763**                                  currently under the read cursor against
86764**                                  another binary blob X and report if
86765**                                  X is strictly less than the read cursor.
86766**                                  Used to enforce uniqueness in a
86767**                                  CREATE UNIQUE INDEX statement.
86768**
86769**    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
86770**                                  all resources.
86771**
86772**    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
86773**                                  is like Close() followed by Init() only
86774**                                  much faster.
86775**
86776** The interfaces above must be called in a particular order.  Write() can
86777** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
86778** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
86779**
86780**   Init()
86781**   for each record: Write()
86782**   Rewind()
86783**     Rowkey()/Compare()
86784**   Next()
86785**   Close()
86786**
86787** Algorithm:
86788**
86789** Records passed to the sorter via calls to Write() are initially held
86790** unsorted in main memory. Assuming the amount of memory used never exceeds
86791** a threshold, when Rewind() is called the set of records is sorted using
86792** an in-memory merge sort. In this case, no temporary files are required
86793** and subsequent calls to Rowkey(), Next() and Compare() read records
86794** directly from main memory.
86795**
86796** If the amount of space used to store records in main memory exceeds the
86797** threshold, then the set of records currently in memory are sorted and
86798** written to a temporary file in "Packed Memory Array" (PMA) format.
86799** A PMA created at this point is known as a "level-0 PMA". Higher levels
86800** of PMAs may be created by merging existing PMAs together - for example
86801** merging two or more level-0 PMAs together creates a level-1 PMA.
86802**
86803** The threshold for the amount of main memory to use before flushing
86804** records to a PMA is roughly the same as the limit configured for the
86805** page-cache of the main database. Specifically, the threshold is set to
86806** the value returned by "PRAGMA main.page_size" multipled by
86807** that returned by "PRAGMA main.cache_size", in bytes.
86808**
86809** If the sorter is running in single-threaded mode, then all PMAs generated
86810** are appended to a single temporary file. Or, if the sorter is running in
86811** multi-threaded mode then up to (N+1) temporary files may be opened, where
86812** N is the configured number of worker threads. In this case, instead of
86813** sorting the records and writing the PMA to a temporary file itself, the
86814** calling thread usually launches a worker thread to do so. Except, if
86815** there are already N worker threads running, the main thread does the work
86816** itself.
86817**
86818** The sorter is running in multi-threaded mode if (a) the library was built
86819** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
86820** than zero, and (b) worker threads have been enabled at runtime by calling
86821** "PRAGMA threads=N" with some value of N greater than 0.
86822**
86823** When Rewind() is called, any data remaining in memory is flushed to a
86824** final PMA. So at this point the data is stored in some number of sorted
86825** PMAs within temporary files on disk.
86826**
86827** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
86828** sorter is running in single-threaded mode, then these PMAs are merged
86829** incrementally as keys are retreived from the sorter by the VDBE.  The
86830** MergeEngine object, described in further detail below, performs this
86831** merge.
86832**
86833** Or, if running in multi-threaded mode, then a background thread is
86834** launched to merge the existing PMAs. Once the background thread has
86835** merged T bytes of data into a single sorted PMA, the main thread
86836** begins reading keys from that PMA while the background thread proceeds
86837** with merging the next T bytes of data. And so on.
86838**
86839** Parameter T is set to half the value of the memory threshold used
86840** by Write() above to determine when to create a new PMA.
86841**
86842** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
86843** Rewind() is called, then a hierarchy of incremental-merges is used.
86844** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
86845** disk are merged together. Then T bytes of data from the second set, and
86846** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
86847** PMAs at a time. This done is to improve locality.
86848**
86849** If running in multi-threaded mode and there are more than
86850** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
86851** than one background thread may be created. Specifically, there may be
86852** one background thread for each temporary file on disk, and one background
86853** thread to merge the output of each of the others to a single PMA for
86854** the main thread to read from.
86855*/
86856/* #include "sqliteInt.h" */
86857/* #include "vdbeInt.h" */
86858
86859/*
86860** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
86861** messages to stderr that may be helpful in understanding the performance
86862** characteristics of the sorter in multi-threaded mode.
86863*/
86864#if 0
86865# define SQLITE_DEBUG_SORTER_THREADS 1
86866#endif
86867
86868/*
86869** Hard-coded maximum amount of data to accumulate in memory before flushing
86870** to a level 0 PMA. The purpose of this limit is to prevent various integer
86871** overflows. 512MiB.
86872*/
86873#define SQLITE_MAX_PMASZ    (1<<29)
86874
86875/*
86876** Private objects used by the sorter
86877*/
86878typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
86879typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
86880typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
86881typedef struct SorterRecord SorterRecord;   /* A record being sorted */
86882typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
86883typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
86884typedef struct SorterList SorterList;       /* In-memory list of records */
86885typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
86886
86887/*
86888** A container for a temp file handle and the current amount of data
86889** stored in the file.
86890*/
86891struct SorterFile {
86892  sqlite3_file *pFd;              /* File handle */
86893  i64 iEof;                       /* Bytes of data stored in pFd */
86894};
86895
86896/*
86897** An in-memory list of objects to be sorted.
86898**
86899** If aMemory==0 then each object is allocated separately and the objects
86900** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
86901** are stored in the aMemory[] bulk memory, one right after the other, and
86902** are connected using SorterRecord.u.iNext.
86903*/
86904struct SorterList {
86905  SorterRecord *pList;            /* Linked list of records */
86906  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
86907  int szPMA;                      /* Size of pList as PMA in bytes */
86908};
86909
86910/*
86911** The MergeEngine object is used to combine two or more smaller PMAs into
86912** one big PMA using a merge operation.  Separate PMAs all need to be
86913** combined into one big PMA in order to be able to step through the sorted
86914** records in order.
86915**
86916** The aReadr[] array contains a PmaReader object for each of the PMAs being
86917** merged.  An aReadr[] object either points to a valid key or else is at EOF.
86918** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
86919** For the purposes of the paragraphs below, we assume that the array is
86920** actually N elements in size, where N is the smallest power of 2 greater
86921** to or equal to the number of PMAs being merged. The extra aReadr[] elements
86922** are treated as if they are empty (always at EOF).
86923**
86924** The aTree[] array is also N elements in size. The value of N is stored in
86925** the MergeEngine.nTree variable.
86926**
86927** The final (N/2) elements of aTree[] contain the results of comparing
86928** pairs of PMA keys together. Element i contains the result of
86929** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
86930** aTree element is set to the index of it.
86931**
86932** For the purposes of this comparison, EOF is considered greater than any
86933** other key value. If the keys are equal (only possible with two EOF
86934** values), it doesn't matter which index is stored.
86935**
86936** The (N/4) elements of aTree[] that precede the final (N/2) described
86937** above contains the index of the smallest of each block of 4 PmaReaders
86938** And so on. So that aTree[1] contains the index of the PmaReader that
86939** currently points to the smallest key value. aTree[0] is unused.
86940**
86941** Example:
86942**
86943**     aReadr[0] -> Banana
86944**     aReadr[1] -> Feijoa
86945**     aReadr[2] -> Elderberry
86946**     aReadr[3] -> Currant
86947**     aReadr[4] -> Grapefruit
86948**     aReadr[5] -> Apple
86949**     aReadr[6] -> Durian
86950**     aReadr[7] -> EOF
86951**
86952**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
86953**
86954** The current element is "Apple" (the value of the key indicated by
86955** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
86956** be advanced to the next key in its segment. Say the next key is
86957** "Eggplant":
86958**
86959**     aReadr[5] -> Eggplant
86960**
86961** The contents of aTree[] are updated first by comparing the new PmaReader
86962** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
86963** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
86964** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
86965** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
86966** so the value written into element 1 of the array is 0. As follows:
86967**
86968**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
86969**
86970** In other words, each time we advance to the next sorter element, log2(N)
86971** key comparison operations are required, where N is the number of segments
86972** being merged (rounded up to the next power of 2).
86973*/
86974struct MergeEngine {
86975  int nTree;                 /* Used size of aTree/aReadr (power of 2) */
86976  SortSubtask *pTask;        /* Used by this thread only */
86977  int *aTree;                /* Current state of incremental merge */
86978  PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
86979};
86980
86981/*
86982** This object represents a single thread of control in a sort operation.
86983** Exactly VdbeSorter.nTask instances of this object are allocated
86984** as part of each VdbeSorter object. Instances are never allocated any
86985** other way. VdbeSorter.nTask is set to the number of worker threads allowed
86986** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
86987** single-threaded operation, there is exactly one instance of this object
86988** and for multi-threaded operation there are two or more instances.
86989**
86990** Essentially, this structure contains all those fields of the VdbeSorter
86991** structure for which each thread requires a separate instance. For example,
86992** each thread requries its own UnpackedRecord object to unpack records in
86993** as part of comparison operations.
86994**
86995** Before a background thread is launched, variable bDone is set to 0. Then,
86996** right before it exits, the thread itself sets bDone to 1. This is used for
86997** two purposes:
86998**
86999**   1. When flushing the contents of memory to a level-0 PMA on disk, to
87000**      attempt to select a SortSubtask for which there is not already an
87001**      active background thread (since doing so causes the main thread
87002**      to block until it finishes).
87003**
87004**   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
87005**      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
87006**      block provoke debugging output.
87007**
87008** In both cases, the effects of the main thread seeing (bDone==0) even
87009** after the thread has finished are not dire. So we don't worry about
87010** memory barriers and such here.
87011*/
87012typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
87013struct SortSubtask {
87014  SQLiteThread *pThread;          /* Background thread, if any */
87015  int bDone;                      /* Set if thread is finished but not joined */
87016  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
87017  UnpackedRecord *pUnpacked;      /* Space to unpack a record */
87018  SorterList list;                /* List for thread to write to a PMA */
87019  int nPMA;                       /* Number of PMAs currently in file */
87020  SorterCompare xCompare;         /* Compare function to use */
87021  SorterFile file;                /* Temp file for level-0 PMAs */
87022  SorterFile file2;               /* Space for other PMAs */
87023};
87024
87025
87026/*
87027** Main sorter structure. A single instance of this is allocated for each
87028** sorter cursor created by the VDBE.
87029**
87030** mxKeysize:
87031**   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
87032**   this variable is updated so as to be set to the size on disk of the
87033**   largest record in the sorter.
87034*/
87035struct VdbeSorter {
87036  int mnPmaSize;                  /* Minimum PMA size, in bytes */
87037  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
87038  int mxKeysize;                  /* Largest serialized key seen so far */
87039  int pgsz;                       /* Main database page size */
87040  PmaReader *pReader;             /* Readr data from here after Rewind() */
87041  MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
87042  sqlite3 *db;                    /* Database connection */
87043  KeyInfo *pKeyInfo;              /* How to compare records */
87044  UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
87045  SorterList list;                /* List of in-memory records */
87046  int iMemory;                    /* Offset of free space in list.aMemory */
87047  int nMemory;                    /* Size of list.aMemory allocation in bytes */
87048  u8 bUsePMA;                     /* True if one or more PMAs created */
87049  u8 bUseThreads;                 /* True to use background threads */
87050  u8 iPrev;                       /* Previous thread used to flush PMA */
87051  u8 nTask;                       /* Size of aTask[] array */
87052  u8 typeMask;
87053  SortSubtask aTask[1];           /* One or more subtasks */
87054};
87055
87056#define SORTER_TYPE_INTEGER 0x01
87057#define SORTER_TYPE_TEXT    0x02
87058
87059/*
87060** An instance of the following object is used to read records out of a
87061** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
87062** aKey might point into aMap or into aBuffer.  If neither of those locations
87063** contain a contiguous representation of the key, then aAlloc is allocated
87064** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
87065**
87066** pFd==0 at EOF.
87067*/
87068struct PmaReader {
87069  i64 iReadOff;               /* Current read offset */
87070  i64 iEof;                   /* 1 byte past EOF for this PmaReader */
87071  int nAlloc;                 /* Bytes of space at aAlloc */
87072  int nKey;                   /* Number of bytes in key */
87073  sqlite3_file *pFd;          /* File handle we are reading from */
87074  u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
87075  u8 *aKey;                   /* Pointer to current key */
87076  u8 *aBuffer;                /* Current read buffer */
87077  int nBuffer;                /* Size of read buffer in bytes */
87078  u8 *aMap;                   /* Pointer to mapping of entire file */
87079  IncrMerger *pIncr;          /* Incremental merger */
87080};
87081
87082/*
87083** Normally, a PmaReader object iterates through an existing PMA stored
87084** within a temp file. However, if the PmaReader.pIncr variable points to
87085** an object of the following type, it may be used to iterate/merge through
87086** multiple PMAs simultaneously.
87087**
87088** There are two types of IncrMerger object - single (bUseThread==0) and
87089** multi-threaded (bUseThread==1).
87090**
87091** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
87092** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
87093** size. When the IncrMerger is initialized, it reads enough data from
87094** pMerger to populate aFile[0]. It then sets variables within the
87095** corresponding PmaReader object to read from that file and kicks off
87096** a background thread to populate aFile[1] with the next mxSz bytes of
87097** sorted record data from pMerger.
87098**
87099** When the PmaReader reaches the end of aFile[0], it blocks until the
87100** background thread has finished populating aFile[1]. It then exchanges
87101** the contents of the aFile[0] and aFile[1] variables within this structure,
87102** sets the PmaReader fields to read from the new aFile[0] and kicks off
87103** another background thread to populate the new aFile[1]. And so on, until
87104** the contents of pMerger are exhausted.
87105**
87106** A single-threaded IncrMerger does not open any temporary files of its
87107** own. Instead, it has exclusive access to mxSz bytes of space beginning
87108** at offset iStartOff of file pTask->file2. And instead of using a
87109** background thread to prepare data for the PmaReader, with a single
87110** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
87111** keys from pMerger by the calling thread whenever the PmaReader runs out
87112** of data.
87113*/
87114struct IncrMerger {
87115  SortSubtask *pTask;             /* Task that owns this merger */
87116  MergeEngine *pMerger;           /* Merge engine thread reads data from */
87117  i64 iStartOff;                  /* Offset to start writing file at */
87118  int mxSz;                       /* Maximum bytes of data to store */
87119  int bEof;                       /* Set to true when merge is finished */
87120  int bUseThread;                 /* True to use a bg thread for this object */
87121  SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
87122};
87123
87124/*
87125** An instance of this object is used for writing a PMA.
87126**
87127** The PMA is written one record at a time.  Each record is of an arbitrary
87128** size.  But I/O is more efficient if it occurs in page-sized blocks where
87129** each block is aligned on a page boundary.  This object caches writes to
87130** the PMA so that aligned, page-size blocks are written.
87131*/
87132struct PmaWriter {
87133  int eFWErr;                     /* Non-zero if in an error state */
87134  u8 *aBuffer;                    /* Pointer to write buffer */
87135  int nBuffer;                    /* Size of write buffer in bytes */
87136  int iBufStart;                  /* First byte of buffer to write */
87137  int iBufEnd;                    /* Last byte of buffer to write */
87138  i64 iWriteOff;                  /* Offset of start of buffer in file */
87139  sqlite3_file *pFd;              /* File handle to write to */
87140};
87141
87142/*
87143** This object is the header on a single record while that record is being
87144** held in memory and prior to being written out as part of a PMA.
87145**
87146** How the linked list is connected depends on how memory is being managed
87147** by this module. If using a separate allocation for each in-memory record
87148** (VdbeSorter.list.aMemory==0), then the list is always connected using the
87149** SorterRecord.u.pNext pointers.
87150**
87151** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
87152** then while records are being accumulated the list is linked using the
87153** SorterRecord.u.iNext offset. This is because the aMemory[] array may
87154** be sqlite3Realloc()ed while records are being accumulated. Once the VM
87155** has finished passing records to the sorter, or when the in-memory buffer
87156** is full, the list is sorted. As part of the sorting process, it is
87157** converted to use the SorterRecord.u.pNext pointers. See function
87158** vdbeSorterSort() for details.
87159*/
87160struct SorterRecord {
87161  int nVal;                       /* Size of the record in bytes */
87162  union {
87163    SorterRecord *pNext;          /* Pointer to next record in list */
87164    int iNext;                    /* Offset within aMemory of next record */
87165  } u;
87166  /* The data for the record immediately follows this header */
87167};
87168
87169/* Return a pointer to the buffer containing the record data for SorterRecord
87170** object p. Should be used as if:
87171**
87172**   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
87173*/
87174#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
87175
87176
87177/* Maximum number of PMAs that a single MergeEngine can merge */
87178#define SORTER_MAX_MERGE_COUNT 16
87179
87180static int vdbeIncrSwap(IncrMerger*);
87181static void vdbeIncrFree(IncrMerger *);
87182
87183/*
87184** Free all memory belonging to the PmaReader object passed as the
87185** argument. All structure fields are set to zero before returning.
87186*/
87187static void vdbePmaReaderClear(PmaReader *pReadr){
87188  sqlite3_free(pReadr->aAlloc);
87189  sqlite3_free(pReadr->aBuffer);
87190  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
87191  vdbeIncrFree(pReadr->pIncr);
87192  memset(pReadr, 0, sizeof(PmaReader));
87193}
87194
87195/*
87196** Read the next nByte bytes of data from the PMA p.
87197** If successful, set *ppOut to point to a buffer containing the data
87198** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
87199** error code.
87200**
87201** The buffer returned in *ppOut is only valid until the
87202** next call to this function.
87203*/
87204static int vdbePmaReadBlob(
87205  PmaReader *p,                   /* PmaReader from which to take the blob */
87206  int nByte,                      /* Bytes of data to read */
87207  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
87208){
87209  int iBuf;                       /* Offset within buffer to read from */
87210  int nAvail;                     /* Bytes of data available in buffer */
87211
87212  if( p->aMap ){
87213    *ppOut = &p->aMap[p->iReadOff];
87214    p->iReadOff += nByte;
87215    return SQLITE_OK;
87216  }
87217
87218  assert( p->aBuffer );
87219
87220  /* If there is no more data to be read from the buffer, read the next
87221  ** p->nBuffer bytes of data from the file into it. Or, if there are less
87222  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
87223  iBuf = p->iReadOff % p->nBuffer;
87224  if( iBuf==0 ){
87225    int nRead;                    /* Bytes to read from disk */
87226    int rc;                       /* sqlite3OsRead() return code */
87227
87228    /* Determine how many bytes of data to read. */
87229    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
87230      nRead = p->nBuffer;
87231    }else{
87232      nRead = (int)(p->iEof - p->iReadOff);
87233    }
87234    assert( nRead>0 );
87235
87236    /* Readr data from the file. Return early if an error occurs. */
87237    rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
87238    assert( rc!=SQLITE_IOERR_SHORT_READ );
87239    if( rc!=SQLITE_OK ) return rc;
87240  }
87241  nAvail = p->nBuffer - iBuf;
87242
87243  if( nByte<=nAvail ){
87244    /* The requested data is available in the in-memory buffer. In this
87245    ** case there is no need to make a copy of the data, just return a
87246    ** pointer into the buffer to the caller.  */
87247    *ppOut = &p->aBuffer[iBuf];
87248    p->iReadOff += nByte;
87249  }else{
87250    /* The requested data is not all available in the in-memory buffer.
87251    ** In this case, allocate space at p->aAlloc[] to copy the requested
87252    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
87253    int nRem;                     /* Bytes remaining to copy */
87254
87255    /* Extend the p->aAlloc[] allocation if required. */
87256    if( p->nAlloc<nByte ){
87257      u8 *aNew;
87258      int nNew = MAX(128, p->nAlloc*2);
87259      while( nByte>nNew ) nNew = nNew*2;
87260      aNew = sqlite3Realloc(p->aAlloc, nNew);
87261      if( !aNew ) return SQLITE_NOMEM_BKPT;
87262      p->nAlloc = nNew;
87263      p->aAlloc = aNew;
87264    }
87265
87266    /* Copy as much data as is available in the buffer into the start of
87267    ** p->aAlloc[].  */
87268    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
87269    p->iReadOff += nAvail;
87270    nRem = nByte - nAvail;
87271
87272    /* The following loop copies up to p->nBuffer bytes per iteration into
87273    ** the p->aAlloc[] buffer.  */
87274    while( nRem>0 ){
87275      int rc;                     /* vdbePmaReadBlob() return code */
87276      int nCopy;                  /* Number of bytes to copy */
87277      u8 *aNext;                  /* Pointer to buffer to copy data from */
87278
87279      nCopy = nRem;
87280      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
87281      rc = vdbePmaReadBlob(p, nCopy, &aNext);
87282      if( rc!=SQLITE_OK ) return rc;
87283      assert( aNext!=p->aAlloc );
87284      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
87285      nRem -= nCopy;
87286    }
87287
87288    *ppOut = p->aAlloc;
87289  }
87290
87291  return SQLITE_OK;
87292}
87293
87294/*
87295** Read a varint from the stream of data accessed by p. Set *pnOut to
87296** the value read.
87297*/
87298static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
87299  int iBuf;
87300
87301  if( p->aMap ){
87302    p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
87303  }else{
87304    iBuf = p->iReadOff % p->nBuffer;
87305    if( iBuf && (p->nBuffer-iBuf)>=9 ){
87306      p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
87307    }else{
87308      u8 aVarint[16], *a;
87309      int i = 0, rc;
87310      do{
87311        rc = vdbePmaReadBlob(p, 1, &a);
87312        if( rc ) return rc;
87313        aVarint[(i++)&0xf] = a[0];
87314      }while( (a[0]&0x80)!=0 );
87315      sqlite3GetVarint(aVarint, pnOut);
87316    }
87317  }
87318
87319  return SQLITE_OK;
87320}
87321
87322/*
87323** Attempt to memory map file pFile. If successful, set *pp to point to the
87324** new mapping and return SQLITE_OK. If the mapping is not attempted
87325** (because the file is too large or the VFS layer is configured not to use
87326** mmap), return SQLITE_OK and set *pp to NULL.
87327**
87328** Or, if an error occurs, return an SQLite error code. The final value of
87329** *pp is undefined in this case.
87330*/
87331static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
87332  int rc = SQLITE_OK;
87333  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
87334    sqlite3_file *pFd = pFile->pFd;
87335    if( pFd->pMethods->iVersion>=3 ){
87336      rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
87337      testcase( rc!=SQLITE_OK );
87338    }
87339  }
87340  return rc;
87341}
87342
87343/*
87344** Attach PmaReader pReadr to file pFile (if it is not already attached to
87345** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
87346** if successful, or an SQLite error code if an error occurs.
87347*/
87348static int vdbePmaReaderSeek(
87349  SortSubtask *pTask,             /* Task context */
87350  PmaReader *pReadr,              /* Reader whose cursor is to be moved */
87351  SorterFile *pFile,              /* Sorter file to read from */
87352  i64 iOff                        /* Offset in pFile */
87353){
87354  int rc = SQLITE_OK;
87355
87356  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
87357
87358  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
87359  if( pReadr->aMap ){
87360    sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
87361    pReadr->aMap = 0;
87362  }
87363  pReadr->iReadOff = iOff;
87364  pReadr->iEof = pFile->iEof;
87365  pReadr->pFd = pFile->pFd;
87366
87367  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
87368  if( rc==SQLITE_OK && pReadr->aMap==0 ){
87369    int pgsz = pTask->pSorter->pgsz;
87370    int iBuf = pReadr->iReadOff % pgsz;
87371    if( pReadr->aBuffer==0 ){
87372      pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
87373      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
87374      pReadr->nBuffer = pgsz;
87375    }
87376    if( rc==SQLITE_OK && iBuf ){
87377      int nRead = pgsz - iBuf;
87378      if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
87379        nRead = (int)(pReadr->iEof - pReadr->iReadOff);
87380      }
87381      rc = sqlite3OsRead(
87382          pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
87383      );
87384      testcase( rc!=SQLITE_OK );
87385    }
87386  }
87387
87388  return rc;
87389}
87390
87391/*
87392** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
87393** no error occurs, or an SQLite error code if one does.
87394*/
87395static int vdbePmaReaderNext(PmaReader *pReadr){
87396  int rc = SQLITE_OK;             /* Return Code */
87397  u64 nRec = 0;                   /* Size of record in bytes */
87398
87399
87400  if( pReadr->iReadOff>=pReadr->iEof ){
87401    IncrMerger *pIncr = pReadr->pIncr;
87402    int bEof = 1;
87403    if( pIncr ){
87404      rc = vdbeIncrSwap(pIncr);
87405      if( rc==SQLITE_OK && pIncr->bEof==0 ){
87406        rc = vdbePmaReaderSeek(
87407            pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
87408        );
87409        bEof = 0;
87410      }
87411    }
87412
87413    if( bEof ){
87414      /* This is an EOF condition */
87415      vdbePmaReaderClear(pReadr);
87416      testcase( rc!=SQLITE_OK );
87417      return rc;
87418    }
87419  }
87420
87421  if( rc==SQLITE_OK ){
87422    rc = vdbePmaReadVarint(pReadr, &nRec);
87423  }
87424  if( rc==SQLITE_OK ){
87425    pReadr->nKey = (int)nRec;
87426    rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
87427    testcase( rc!=SQLITE_OK );
87428  }
87429
87430  return rc;
87431}
87432
87433/*
87434** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
87435** starting at offset iStart and ending at offset iEof-1. This function
87436** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
87437** PMA is empty).
87438**
87439** If the pnByte parameter is NULL, then it is assumed that the file
87440** contains a single PMA, and that that PMA omits the initial length varint.
87441*/
87442static int vdbePmaReaderInit(
87443  SortSubtask *pTask,             /* Task context */
87444  SorterFile *pFile,              /* Sorter file to read from */
87445  i64 iStart,                     /* Start offset in pFile */
87446  PmaReader *pReadr,              /* PmaReader to populate */
87447  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
87448){
87449  int rc;
87450
87451  assert( pFile->iEof>iStart );
87452  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
87453  assert( pReadr->aBuffer==0 );
87454  assert( pReadr->aMap==0 );
87455
87456  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
87457  if( rc==SQLITE_OK ){
87458    u64 nByte = 0;                 /* Size of PMA in bytes */
87459    rc = vdbePmaReadVarint(pReadr, &nByte);
87460    pReadr->iEof = pReadr->iReadOff + nByte;
87461    *pnByte += nByte;
87462  }
87463
87464  if( rc==SQLITE_OK ){
87465    rc = vdbePmaReaderNext(pReadr);
87466  }
87467  return rc;
87468}
87469
87470/*
87471** A version of vdbeSorterCompare() that assumes that it has already been
87472** determined that the first field of key1 is equal to the first field of
87473** key2.
87474*/
87475static int vdbeSorterCompareTail(
87476  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
87477  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
87478  const void *pKey1, int nKey1,   /* Left side of comparison */
87479  const void *pKey2, int nKey2    /* Right side of comparison */
87480){
87481  UnpackedRecord *r2 = pTask->pUnpacked;
87482  if( *pbKey2Cached==0 ){
87483    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
87484    *pbKey2Cached = 1;
87485  }
87486  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
87487}
87488
87489/*
87490** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
87491** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
87492** used by the comparison. Return the result of the comparison.
87493**
87494** If IN/OUT parameter *pbKey2Cached is true when this function is called,
87495** it is assumed that (pTask->pUnpacked) contains the unpacked version
87496** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
87497** version of key2 and *pbKey2Cached set to true before returning.
87498**
87499** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
87500** to SQLITE_NOMEM.
87501*/
87502static int vdbeSorterCompare(
87503  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
87504  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
87505  const void *pKey1, int nKey1,   /* Left side of comparison */
87506  const void *pKey2, int nKey2    /* Right side of comparison */
87507){
87508  UnpackedRecord *r2 = pTask->pUnpacked;
87509  if( !*pbKey2Cached ){
87510    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
87511    *pbKey2Cached = 1;
87512  }
87513  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
87514}
87515
87516/*
87517** A specially optimized version of vdbeSorterCompare() that assumes that
87518** the first field of each key is a TEXT value and that the collation
87519** sequence to compare them with is BINARY.
87520*/
87521static int vdbeSorterCompareText(
87522  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
87523  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
87524  const void *pKey1, int nKey1,   /* Left side of comparison */
87525  const void *pKey2, int nKey2    /* Right side of comparison */
87526){
87527  const u8 * const p1 = (const u8 * const)pKey1;
87528  const u8 * const p2 = (const u8 * const)pKey2;
87529  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
87530  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
87531
87532  int n1;
87533  int n2;
87534  int res;
87535
87536  getVarint32(&p1[1], n1);
87537  getVarint32(&p2[1], n2);
87538  res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
87539  if( res==0 ){
87540    res = n1 - n2;
87541  }
87542
87543  if( res==0 ){
87544    if( pTask->pSorter->pKeyInfo->nField>1 ){
87545      res = vdbeSorterCompareTail(
87546          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
87547      );
87548    }
87549  }else{
87550    if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
87551      res = res * -1;
87552    }
87553  }
87554
87555  return res;
87556}
87557
87558/*
87559** A specially optimized version of vdbeSorterCompare() that assumes that
87560** the first field of each key is an INTEGER value.
87561*/
87562static int vdbeSorterCompareInt(
87563  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
87564  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
87565  const void *pKey1, int nKey1,   /* Left side of comparison */
87566  const void *pKey2, int nKey2    /* Right side of comparison */
87567){
87568  const u8 * const p1 = (const u8 * const)pKey1;
87569  const u8 * const p2 = (const u8 * const)pKey2;
87570  const int s1 = p1[1];                 /* Left hand serial type */
87571  const int s2 = p2[1];                 /* Right hand serial type */
87572  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
87573  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
87574  int res;                              /* Return value */
87575
87576  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
87577  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
87578
87579  if( s1==s2 ){
87580    /* The two values have the same sign. Compare using memcmp(). */
87581    static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
87582    const u8 n = aLen[s1];
87583    int i;
87584    res = 0;
87585    for(i=0; i<n; i++){
87586      if( (res = v1[i] - v2[i])!=0 ){
87587        if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
87588          res = v1[0] & 0x80 ? -1 : +1;
87589        }
87590        break;
87591      }
87592    }
87593  }else if( s1>7 && s2>7 ){
87594    res = s1 - s2;
87595  }else{
87596    if( s2>7 ){
87597      res = +1;
87598    }else if( s1>7 ){
87599      res = -1;
87600    }else{
87601      res = s1 - s2;
87602    }
87603    assert( res!=0 );
87604
87605    if( res>0 ){
87606      if( *v1 & 0x80 ) res = -1;
87607    }else{
87608      if( *v2 & 0x80 ) res = +1;
87609    }
87610  }
87611
87612  if( res==0 ){
87613    if( pTask->pSorter->pKeyInfo->nField>1 ){
87614      res = vdbeSorterCompareTail(
87615          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
87616      );
87617    }
87618  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
87619    res = res * -1;
87620  }
87621
87622  return res;
87623}
87624
87625/*
87626** Initialize the temporary index cursor just opened as a sorter cursor.
87627**
87628** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
87629** to determine the number of fields that should be compared from the
87630** records being sorted. However, if the value passed as argument nField
87631** is non-zero and the sorter is able to guarantee a stable sort, nField
87632** is used instead. This is used when sorting records for a CREATE INDEX
87633** statement. In this case, keys are always delivered to the sorter in
87634** order of the primary key, which happens to be make up the final part
87635** of the records being sorted. So if the sort is stable, there is never
87636** any reason to compare PK fields and they can be ignored for a small
87637** performance boost.
87638**
87639** The sorter can guarantee a stable sort when running in single-threaded
87640** mode, but not in multi-threaded mode.
87641**
87642** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87643*/
87644SQLITE_PRIVATE int sqlite3VdbeSorterInit(
87645  sqlite3 *db,                    /* Database connection (for malloc()) */
87646  int nField,                     /* Number of key fields in each record */
87647  VdbeCursor *pCsr                /* Cursor that holds the new sorter */
87648){
87649  int pgsz;                       /* Page size of main database */
87650  int i;                          /* Used to iterate through aTask[] */
87651  VdbeSorter *pSorter;            /* The new sorter */
87652  KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
87653  int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
87654  int sz;                         /* Size of pSorter in bytes */
87655  int rc = SQLITE_OK;
87656#if SQLITE_MAX_WORKER_THREADS==0
87657# define nWorker 0
87658#else
87659  int nWorker;
87660#endif
87661
87662  /* Initialize the upper limit on the number of worker threads */
87663#if SQLITE_MAX_WORKER_THREADS>0
87664  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
87665    nWorker = 0;
87666  }else{
87667    nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
87668  }
87669#endif
87670
87671  /* Do not allow the total number of threads (main thread + all workers)
87672  ** to exceed the maximum merge count */
87673#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
87674  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
87675    nWorker = SORTER_MAX_MERGE_COUNT-1;
87676  }
87677#endif
87678
87679  assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
87680  assert( pCsr->eCurType==CURTYPE_SORTER );
87681  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
87682  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
87683
87684  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
87685  pCsr->uc.pSorter = pSorter;
87686  if( pSorter==0 ){
87687    rc = SQLITE_NOMEM_BKPT;
87688  }else{
87689    pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
87690    memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
87691    pKeyInfo->db = 0;
87692    if( nField && nWorker==0 ){
87693      pKeyInfo->nXField += (pKeyInfo->nField - nField);
87694      pKeyInfo->nField = nField;
87695    }
87696    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
87697    pSorter->nTask = nWorker + 1;
87698    pSorter->iPrev = (u8)(nWorker - 1);
87699    pSorter->bUseThreads = (pSorter->nTask>1);
87700    pSorter->db = db;
87701    for(i=0; i<pSorter->nTask; i++){
87702      SortSubtask *pTask = &pSorter->aTask[i];
87703      pTask->pSorter = pSorter;
87704    }
87705
87706    if( !sqlite3TempInMemory(db) ){
87707      i64 mxCache;                /* Cache size in bytes*/
87708      u32 szPma = sqlite3GlobalConfig.szPma;
87709      pSorter->mnPmaSize = szPma * pgsz;
87710
87711      mxCache = db->aDb[0].pSchema->cache_size;
87712      if( mxCache<0 ){
87713        /* A negative cache-size value C indicates that the cache is abs(C)
87714        ** KiB in size.  */
87715        mxCache = mxCache * -1024;
87716      }else{
87717        mxCache = mxCache * pgsz;
87718      }
87719      mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
87720      pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
87721
87722      /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
87723      ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
87724      ** large heap allocations.
87725      */
87726      if( sqlite3GlobalConfig.pScratch==0 ){
87727        assert( pSorter->iMemory==0 );
87728        pSorter->nMemory = pgsz;
87729        pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
87730        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
87731      }
87732    }
87733
87734    if( (pKeyInfo->nField+pKeyInfo->nXField)<13
87735     && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
87736    ){
87737      pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
87738    }
87739  }
87740
87741  return rc;
87742}
87743#undef nWorker   /* Defined at the top of this function */
87744
87745/*
87746** Free the list of sorted records starting at pRecord.
87747*/
87748static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
87749  SorterRecord *p;
87750  SorterRecord *pNext;
87751  for(p=pRecord; p; p=pNext){
87752    pNext = p->u.pNext;
87753    sqlite3DbFree(db, p);
87754  }
87755}
87756
87757/*
87758** Free all resources owned by the object indicated by argument pTask. All
87759** fields of *pTask are zeroed before returning.
87760*/
87761static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
87762  sqlite3DbFree(db, pTask->pUnpacked);
87763#if SQLITE_MAX_WORKER_THREADS>0
87764  /* pTask->list.aMemory can only be non-zero if it was handed memory
87765  ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
87766  if( pTask->list.aMemory ){
87767    sqlite3_free(pTask->list.aMemory);
87768  }else
87769#endif
87770  {
87771    assert( pTask->list.aMemory==0 );
87772    vdbeSorterRecordFree(0, pTask->list.pList);
87773  }
87774  if( pTask->file.pFd ){
87775    sqlite3OsCloseFree(pTask->file.pFd);
87776  }
87777  if( pTask->file2.pFd ){
87778    sqlite3OsCloseFree(pTask->file2.pFd);
87779  }
87780  memset(pTask, 0, sizeof(SortSubtask));
87781}
87782
87783#ifdef SQLITE_DEBUG_SORTER_THREADS
87784static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
87785  i64 t;
87786  int iTask = (pTask - pTask->pSorter->aTask);
87787  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
87788  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
87789}
87790static void vdbeSorterRewindDebug(const char *zEvent){
87791  i64 t;
87792  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
87793  fprintf(stderr, "%lld:X %s\n", t, zEvent);
87794}
87795static void vdbeSorterPopulateDebug(
87796  SortSubtask *pTask,
87797  const char *zEvent
87798){
87799  i64 t;
87800  int iTask = (pTask - pTask->pSorter->aTask);
87801  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
87802  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
87803}
87804static void vdbeSorterBlockDebug(
87805  SortSubtask *pTask,
87806  int bBlocked,
87807  const char *zEvent
87808){
87809  if( bBlocked ){
87810    i64 t;
87811    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
87812    fprintf(stderr, "%lld:main %s\n", t, zEvent);
87813  }
87814}
87815#else
87816# define vdbeSorterWorkDebug(x,y)
87817# define vdbeSorterRewindDebug(y)
87818# define vdbeSorterPopulateDebug(x,y)
87819# define vdbeSorterBlockDebug(x,y,z)
87820#endif
87821
87822#if SQLITE_MAX_WORKER_THREADS>0
87823/*
87824** Join thread pTask->thread.
87825*/
87826static int vdbeSorterJoinThread(SortSubtask *pTask){
87827  int rc = SQLITE_OK;
87828  if( pTask->pThread ){
87829#ifdef SQLITE_DEBUG_SORTER_THREADS
87830    int bDone = pTask->bDone;
87831#endif
87832    void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
87833    vdbeSorterBlockDebug(pTask, !bDone, "enter");
87834    (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
87835    vdbeSorterBlockDebug(pTask, !bDone, "exit");
87836    rc = SQLITE_PTR_TO_INT(pRet);
87837    assert( pTask->bDone==1 );
87838    pTask->bDone = 0;
87839    pTask->pThread = 0;
87840  }
87841  return rc;
87842}
87843
87844/*
87845** Launch a background thread to run xTask(pIn).
87846*/
87847static int vdbeSorterCreateThread(
87848  SortSubtask *pTask,             /* Thread will use this task object */
87849  void *(*xTask)(void*),          /* Routine to run in a separate thread */
87850  void *pIn                       /* Argument passed into xTask() */
87851){
87852  assert( pTask->pThread==0 && pTask->bDone==0 );
87853  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
87854}
87855
87856/*
87857** Join all outstanding threads launched by SorterWrite() to create
87858** level-0 PMAs.
87859*/
87860static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
87861  int rc = rcin;
87862  int i;
87863
87864  /* This function is always called by the main user thread.
87865  **
87866  ** If this function is being called after SorterRewind() has been called,
87867  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
87868  ** is currently attempt to join one of the other threads. To avoid a race
87869  ** condition where this thread also attempts to join the same object, join
87870  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
87871  for(i=pSorter->nTask-1; i>=0; i--){
87872    SortSubtask *pTask = &pSorter->aTask[i];
87873    int rc2 = vdbeSorterJoinThread(pTask);
87874    if( rc==SQLITE_OK ) rc = rc2;
87875  }
87876  return rc;
87877}
87878#else
87879# define vdbeSorterJoinAll(x,rcin) (rcin)
87880# define vdbeSorterJoinThread(pTask) SQLITE_OK
87881#endif
87882
87883/*
87884** Allocate a new MergeEngine object capable of handling up to
87885** nReader PmaReader inputs.
87886**
87887** nReader is automatically rounded up to the next power of two.
87888** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
87889*/
87890static MergeEngine *vdbeMergeEngineNew(int nReader){
87891  int N = 2;                      /* Smallest power of two >= nReader */
87892  int nByte;                      /* Total bytes of space to allocate */
87893  MergeEngine *pNew;              /* Pointer to allocated object to return */
87894
87895  assert( nReader<=SORTER_MAX_MERGE_COUNT );
87896
87897  while( N<nReader ) N += N;
87898  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
87899
87900  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
87901  if( pNew ){
87902    pNew->nTree = N;
87903    pNew->pTask = 0;
87904    pNew->aReadr = (PmaReader*)&pNew[1];
87905    pNew->aTree = (int*)&pNew->aReadr[N];
87906  }
87907  return pNew;
87908}
87909
87910/*
87911** Free the MergeEngine object passed as the only argument.
87912*/
87913static void vdbeMergeEngineFree(MergeEngine *pMerger){
87914  int i;
87915  if( pMerger ){
87916    for(i=0; i<pMerger->nTree; i++){
87917      vdbePmaReaderClear(&pMerger->aReadr[i]);
87918    }
87919  }
87920  sqlite3_free(pMerger);
87921}
87922
87923/*
87924** Free all resources associated with the IncrMerger object indicated by
87925** the first argument.
87926*/
87927static void vdbeIncrFree(IncrMerger *pIncr){
87928  if( pIncr ){
87929#if SQLITE_MAX_WORKER_THREADS>0
87930    if( pIncr->bUseThread ){
87931      vdbeSorterJoinThread(pIncr->pTask);
87932      if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
87933      if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
87934    }
87935#endif
87936    vdbeMergeEngineFree(pIncr->pMerger);
87937    sqlite3_free(pIncr);
87938  }
87939}
87940
87941/*
87942** Reset a sorting cursor back to its original empty state.
87943*/
87944SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
87945  int i;
87946  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
87947  assert( pSorter->bUseThreads || pSorter->pReader==0 );
87948#if SQLITE_MAX_WORKER_THREADS>0
87949  if( pSorter->pReader ){
87950    vdbePmaReaderClear(pSorter->pReader);
87951    sqlite3DbFree(db, pSorter->pReader);
87952    pSorter->pReader = 0;
87953  }
87954#endif
87955  vdbeMergeEngineFree(pSorter->pMerger);
87956  pSorter->pMerger = 0;
87957  for(i=0; i<pSorter->nTask; i++){
87958    SortSubtask *pTask = &pSorter->aTask[i];
87959    vdbeSortSubtaskCleanup(db, pTask);
87960    pTask->pSorter = pSorter;
87961  }
87962  if( pSorter->list.aMemory==0 ){
87963    vdbeSorterRecordFree(0, pSorter->list.pList);
87964  }
87965  pSorter->list.pList = 0;
87966  pSorter->list.szPMA = 0;
87967  pSorter->bUsePMA = 0;
87968  pSorter->iMemory = 0;
87969  pSorter->mxKeysize = 0;
87970  sqlite3DbFree(db, pSorter->pUnpacked);
87971  pSorter->pUnpacked = 0;
87972}
87973
87974/*
87975** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
87976*/
87977SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
87978  VdbeSorter *pSorter;
87979  assert( pCsr->eCurType==CURTYPE_SORTER );
87980  pSorter = pCsr->uc.pSorter;
87981  if( pSorter ){
87982    sqlite3VdbeSorterReset(db, pSorter);
87983    sqlite3_free(pSorter->list.aMemory);
87984    sqlite3DbFree(db, pSorter);
87985    pCsr->uc.pSorter = 0;
87986  }
87987}
87988
87989#if SQLITE_MAX_MMAP_SIZE>0
87990/*
87991** The first argument is a file-handle open on a temporary file. The file
87992** is guaranteed to be nByte bytes or smaller in size. This function
87993** attempts to extend the file to nByte bytes in size and to ensure that
87994** the VFS has memory mapped it.
87995**
87996** Whether or not the file does end up memory mapped of course depends on
87997** the specific VFS implementation.
87998*/
87999static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
88000  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
88001    void *p = 0;
88002    int chunksize = 4*1024;
88003    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
88004    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
88005    sqlite3OsFetch(pFd, 0, (int)nByte, &p);
88006    sqlite3OsUnfetch(pFd, 0, p);
88007  }
88008}
88009#else
88010# define vdbeSorterExtendFile(x,y,z)
88011#endif
88012
88013/*
88014** Allocate space for a file-handle and open a temporary file. If successful,
88015** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
88016** Otherwise, set *ppFd to 0 and return an SQLite error code.
88017*/
88018static int vdbeSorterOpenTempFile(
88019  sqlite3 *db,                    /* Database handle doing sort */
88020  i64 nExtend,                    /* Attempt to extend file to this size */
88021  sqlite3_file **ppFd
88022){
88023  int rc;
88024  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
88025  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
88026      SQLITE_OPEN_TEMP_JOURNAL |
88027      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
88028      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
88029  );
88030  if( rc==SQLITE_OK ){
88031    i64 max = SQLITE_MAX_MMAP_SIZE;
88032    sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
88033    if( nExtend>0 ){
88034      vdbeSorterExtendFile(db, *ppFd, nExtend);
88035    }
88036  }
88037  return rc;
88038}
88039
88040/*
88041** If it has not already been allocated, allocate the UnpackedRecord
88042** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
88043** if no allocation was required), or SQLITE_NOMEM otherwise.
88044*/
88045static int vdbeSortAllocUnpacked(SortSubtask *pTask){
88046  if( pTask->pUnpacked==0 ){
88047    pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
88048    if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
88049    pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
88050    pTask->pUnpacked->errCode = 0;
88051  }
88052  return SQLITE_OK;
88053}
88054
88055
88056/*
88057** Merge the two sorted lists p1 and p2 into a single list.
88058*/
88059static SorterRecord *vdbeSorterMerge(
88060  SortSubtask *pTask,             /* Calling thread context */
88061  SorterRecord *p1,               /* First list to merge */
88062  SorterRecord *p2                /* Second list to merge */
88063){
88064  SorterRecord *pFinal = 0;
88065  SorterRecord **pp = &pFinal;
88066  int bCached = 0;
88067
88068  assert( p1!=0 && p2!=0 );
88069  for(;;){
88070    int res;
88071    res = pTask->xCompare(
88072        pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
88073    );
88074
88075    if( res<=0 ){
88076      *pp = p1;
88077      pp = &p1->u.pNext;
88078      p1 = p1->u.pNext;
88079      if( p1==0 ){
88080        *pp = p2;
88081        break;
88082      }
88083    }else{
88084      *pp = p2;
88085      pp = &p2->u.pNext;
88086      p2 = p2->u.pNext;
88087      bCached = 0;
88088      if( p2==0 ){
88089        *pp = p1;
88090        break;
88091      }
88092    }
88093  }
88094  return pFinal;
88095}
88096
88097/*
88098** Return the SorterCompare function to compare values collected by the
88099** sorter object passed as the only argument.
88100*/
88101static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
88102  if( p->typeMask==SORTER_TYPE_INTEGER ){
88103    return vdbeSorterCompareInt;
88104  }else if( p->typeMask==SORTER_TYPE_TEXT ){
88105    return vdbeSorterCompareText;
88106  }
88107  return vdbeSorterCompare;
88108}
88109
88110/*
88111** Sort the linked list of records headed at pTask->pList. Return
88112** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
88113** an error occurs.
88114*/
88115static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
88116  int i;
88117  SorterRecord **aSlot;
88118  SorterRecord *p;
88119  int rc;
88120
88121  rc = vdbeSortAllocUnpacked(pTask);
88122  if( rc!=SQLITE_OK ) return rc;
88123
88124  p = pList->pList;
88125  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
88126
88127  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
88128  if( !aSlot ){
88129    return SQLITE_NOMEM_BKPT;
88130  }
88131
88132  while( p ){
88133    SorterRecord *pNext;
88134    if( pList->aMemory ){
88135      if( (u8*)p==pList->aMemory ){
88136        pNext = 0;
88137      }else{
88138        assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
88139        pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
88140      }
88141    }else{
88142      pNext = p->u.pNext;
88143    }
88144
88145    p->u.pNext = 0;
88146    for(i=0; aSlot[i]; i++){
88147      p = vdbeSorterMerge(pTask, p, aSlot[i]);
88148      aSlot[i] = 0;
88149    }
88150    aSlot[i] = p;
88151    p = pNext;
88152  }
88153
88154  p = 0;
88155  for(i=0; i<64; i++){
88156    if( aSlot[i]==0 ) continue;
88157    p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
88158  }
88159  pList->pList = p;
88160
88161  sqlite3_free(aSlot);
88162  assert( pTask->pUnpacked->errCode==SQLITE_OK
88163       || pTask->pUnpacked->errCode==SQLITE_NOMEM
88164  );
88165  return pTask->pUnpacked->errCode;
88166}
88167
88168/*
88169** Initialize a PMA-writer object.
88170*/
88171static void vdbePmaWriterInit(
88172  sqlite3_file *pFd,              /* File handle to write to */
88173  PmaWriter *p,                   /* Object to populate */
88174  int nBuf,                       /* Buffer size */
88175  i64 iStart                      /* Offset of pFd to begin writing at */
88176){
88177  memset(p, 0, sizeof(PmaWriter));
88178  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
88179  if( !p->aBuffer ){
88180    p->eFWErr = SQLITE_NOMEM_BKPT;
88181  }else{
88182    p->iBufEnd = p->iBufStart = (iStart % nBuf);
88183    p->iWriteOff = iStart - p->iBufStart;
88184    p->nBuffer = nBuf;
88185    p->pFd = pFd;
88186  }
88187}
88188
88189/*
88190** Write nData bytes of data to the PMA. Return SQLITE_OK
88191** if successful, or an SQLite error code if an error occurs.
88192*/
88193static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
88194  int nRem = nData;
88195  while( nRem>0 && p->eFWErr==0 ){
88196    int nCopy = nRem;
88197    if( nCopy>(p->nBuffer - p->iBufEnd) ){
88198      nCopy = p->nBuffer - p->iBufEnd;
88199    }
88200
88201    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
88202    p->iBufEnd += nCopy;
88203    if( p->iBufEnd==p->nBuffer ){
88204      p->eFWErr = sqlite3OsWrite(p->pFd,
88205          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
88206          p->iWriteOff + p->iBufStart
88207      );
88208      p->iBufStart = p->iBufEnd = 0;
88209      p->iWriteOff += p->nBuffer;
88210    }
88211    assert( p->iBufEnd<p->nBuffer );
88212
88213    nRem -= nCopy;
88214  }
88215}
88216
88217/*
88218** Flush any buffered data to disk and clean up the PMA-writer object.
88219** The results of using the PMA-writer after this call are undefined.
88220** Return SQLITE_OK if flushing the buffered data succeeds or is not
88221** required. Otherwise, return an SQLite error code.
88222**
88223** Before returning, set *piEof to the offset immediately following the
88224** last byte written to the file.
88225*/
88226static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
88227  int rc;
88228  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
88229    p->eFWErr = sqlite3OsWrite(p->pFd,
88230        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
88231        p->iWriteOff + p->iBufStart
88232    );
88233  }
88234  *piEof = (p->iWriteOff + p->iBufEnd);
88235  sqlite3_free(p->aBuffer);
88236  rc = p->eFWErr;
88237  memset(p, 0, sizeof(PmaWriter));
88238  return rc;
88239}
88240
88241/*
88242** Write value iVal encoded as a varint to the PMA. Return
88243** SQLITE_OK if successful, or an SQLite error code if an error occurs.
88244*/
88245static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
88246  int nByte;
88247  u8 aByte[10];
88248  nByte = sqlite3PutVarint(aByte, iVal);
88249  vdbePmaWriteBlob(p, aByte, nByte);
88250}
88251
88252/*
88253** Write the current contents of in-memory linked-list pList to a level-0
88254** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
88255** successful, or an SQLite error code otherwise.
88256**
88257** The format of a PMA is:
88258**
88259**     * A varint. This varint contains the total number of bytes of content
88260**       in the PMA (not including the varint itself).
88261**
88262**     * One or more records packed end-to-end in order of ascending keys.
88263**       Each record consists of a varint followed by a blob of data (the
88264**       key). The varint is the number of bytes in the blob of data.
88265*/
88266static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
88267  sqlite3 *db = pTask->pSorter->db;
88268  int rc = SQLITE_OK;             /* Return code */
88269  PmaWriter writer;               /* Object used to write to the file */
88270
88271#ifdef SQLITE_DEBUG
88272  /* Set iSz to the expected size of file pTask->file after writing the PMA.
88273  ** This is used by an assert() statement at the end of this function.  */
88274  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
88275#endif
88276
88277  vdbeSorterWorkDebug(pTask, "enter");
88278  memset(&writer, 0, sizeof(PmaWriter));
88279  assert( pList->szPMA>0 );
88280
88281  /* If the first temporary PMA file has not been opened, open it now. */
88282  if( pTask->file.pFd==0 ){
88283    rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
88284    assert( rc!=SQLITE_OK || pTask->file.pFd );
88285    assert( pTask->file.iEof==0 );
88286    assert( pTask->nPMA==0 );
88287  }
88288
88289  /* Try to get the file to memory map */
88290  if( rc==SQLITE_OK ){
88291    vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
88292  }
88293
88294  /* Sort the list */
88295  if( rc==SQLITE_OK ){
88296    rc = vdbeSorterSort(pTask, pList);
88297  }
88298
88299  if( rc==SQLITE_OK ){
88300    SorterRecord *p;
88301    SorterRecord *pNext = 0;
88302
88303    vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
88304                      pTask->file.iEof);
88305    pTask->nPMA++;
88306    vdbePmaWriteVarint(&writer, pList->szPMA);
88307    for(p=pList->pList; p; p=pNext){
88308      pNext = p->u.pNext;
88309      vdbePmaWriteVarint(&writer, p->nVal);
88310      vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
88311      if( pList->aMemory==0 ) sqlite3_free(p);
88312    }
88313    pList->pList = p;
88314    rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
88315  }
88316
88317  vdbeSorterWorkDebug(pTask, "exit");
88318  assert( rc!=SQLITE_OK || pList->pList==0 );
88319  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
88320  return rc;
88321}
88322
88323/*
88324** Advance the MergeEngine to its next entry.
88325** Set *pbEof to true there is no next entry because
88326** the MergeEngine has reached the end of all its inputs.
88327**
88328** Return SQLITE_OK if successful or an error code if an error occurs.
88329*/
88330static int vdbeMergeEngineStep(
88331  MergeEngine *pMerger,      /* The merge engine to advance to the next row */
88332  int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
88333){
88334  int rc;
88335  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
88336  SortSubtask *pTask = pMerger->pTask;
88337
88338  /* Advance the current PmaReader */
88339  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
88340
88341  /* Update contents of aTree[] */
88342  if( rc==SQLITE_OK ){
88343    int i;                      /* Index of aTree[] to recalculate */
88344    PmaReader *pReadr1;         /* First PmaReader to compare */
88345    PmaReader *pReadr2;         /* Second PmaReader to compare */
88346    int bCached = 0;
88347
88348    /* Find the first two PmaReaders to compare. The one that was just
88349    ** advanced (iPrev) and the one next to it in the array.  */
88350    pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
88351    pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
88352
88353    for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
88354      /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
88355      int iRes;
88356      if( pReadr1->pFd==0 ){
88357        iRes = +1;
88358      }else if( pReadr2->pFd==0 ){
88359        iRes = -1;
88360      }else{
88361        iRes = pTask->xCompare(pTask, &bCached,
88362            pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
88363        );
88364      }
88365
88366      /* If pReadr1 contained the smaller value, set aTree[i] to its index.
88367      ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
88368      ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
88369      ** pKey2 to point to the record belonging to pReadr2.
88370      **
88371      ** Alternatively, if pReadr2 contains the smaller of the two values,
88372      ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
88373      ** was actually called above, then pTask->pUnpacked now contains
88374      ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
88375      ** vdbeSorterCompare() from decoding pReadr2 again.
88376      **
88377      ** If the two values were equal, then the value from the oldest
88378      ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
88379      ** is sorted from oldest to newest, so pReadr1 contains older values
88380      ** than pReadr2 iff (pReadr1<pReadr2).  */
88381      if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
88382        pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
88383        pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
88384        bCached = 0;
88385      }else{
88386        if( pReadr1->pFd ) bCached = 0;
88387        pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
88388        pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
88389      }
88390    }
88391    *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
88392  }
88393
88394  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
88395}
88396
88397#if SQLITE_MAX_WORKER_THREADS>0
88398/*
88399** The main routine for background threads that write level-0 PMAs.
88400*/
88401static void *vdbeSorterFlushThread(void *pCtx){
88402  SortSubtask *pTask = (SortSubtask*)pCtx;
88403  int rc;                         /* Return code */
88404  assert( pTask->bDone==0 );
88405  rc = vdbeSorterListToPMA(pTask, &pTask->list);
88406  pTask->bDone = 1;
88407  return SQLITE_INT_TO_PTR(rc);
88408}
88409#endif /* SQLITE_MAX_WORKER_THREADS>0 */
88410
88411/*
88412** Flush the current contents of VdbeSorter.list to a new PMA, possibly
88413** using a background thread.
88414*/
88415static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
88416#if SQLITE_MAX_WORKER_THREADS==0
88417  pSorter->bUsePMA = 1;
88418  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
88419#else
88420  int rc = SQLITE_OK;
88421  int i;
88422  SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
88423  int nWorker = (pSorter->nTask-1);
88424
88425  /* Set the flag to indicate that at least one PMA has been written.
88426  ** Or will be, anyhow.  */
88427  pSorter->bUsePMA = 1;
88428
88429  /* Select a sub-task to sort and flush the current list of in-memory
88430  ** records to disk. If the sorter is running in multi-threaded mode,
88431  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
88432  ** the background thread from a sub-tasks previous turn is still running,
88433  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
88434  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
88435  ** sub-tasks are prefered as they use background threads - the final
88436  ** sub-task uses the main thread. */
88437  for(i=0; i<nWorker; i++){
88438    int iTest = (pSorter->iPrev + i + 1) % nWorker;
88439    pTask = &pSorter->aTask[iTest];
88440    if( pTask->bDone ){
88441      rc = vdbeSorterJoinThread(pTask);
88442    }
88443    if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
88444  }
88445
88446  if( rc==SQLITE_OK ){
88447    if( i==nWorker ){
88448      /* Use the foreground thread for this operation */
88449      rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
88450    }else{
88451      /* Launch a background thread for this operation */
88452      u8 *aMem = pTask->list.aMemory;
88453      void *pCtx = (void*)pTask;
88454
88455      assert( pTask->pThread==0 && pTask->bDone==0 );
88456      assert( pTask->list.pList==0 );
88457      assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
88458
88459      pSorter->iPrev = (u8)(pTask - pSorter->aTask);
88460      pTask->list = pSorter->list;
88461      pSorter->list.pList = 0;
88462      pSorter->list.szPMA = 0;
88463      if( aMem ){
88464        pSorter->list.aMemory = aMem;
88465        pSorter->nMemory = sqlite3MallocSize(aMem);
88466      }else if( pSorter->list.aMemory ){
88467        pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
88468        if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
88469      }
88470
88471      rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
88472    }
88473  }
88474
88475  return rc;
88476#endif /* SQLITE_MAX_WORKER_THREADS!=0 */
88477}
88478
88479/*
88480** Add a record to the sorter.
88481*/
88482SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
88483  const VdbeCursor *pCsr,         /* Sorter cursor */
88484  Mem *pVal                       /* Memory cell containing record */
88485){
88486  VdbeSorter *pSorter;
88487  int rc = SQLITE_OK;             /* Return Code */
88488  SorterRecord *pNew;             /* New list element */
88489  int bFlush;                     /* True to flush contents of memory to PMA */
88490  int nReq;                       /* Bytes of memory required */
88491  int nPMA;                       /* Bytes of PMA space required */
88492  int t;                          /* serial type of first record field */
88493
88494  assert( pCsr->eCurType==CURTYPE_SORTER );
88495  pSorter = pCsr->uc.pSorter;
88496  getVarint32((const u8*)&pVal->z[1], t);
88497  if( t>0 && t<10 && t!=7 ){
88498    pSorter->typeMask &= SORTER_TYPE_INTEGER;
88499  }else if( t>10 && (t & 0x01) ){
88500    pSorter->typeMask &= SORTER_TYPE_TEXT;
88501  }else{
88502    pSorter->typeMask = 0;
88503  }
88504
88505  assert( pSorter );
88506
88507  /* Figure out whether or not the current contents of memory should be
88508  ** flushed to a PMA before continuing. If so, do so.
88509  **
88510  ** If using the single large allocation mode (pSorter->aMemory!=0), then
88511  ** flush the contents of memory to a new PMA if (a) at least one value is
88512  ** already in memory and (b) the new value will not fit in memory.
88513  **
88514  ** Or, if using separate allocations for each record, flush the contents
88515  ** of memory to a PMA if either of the following are true:
88516  **
88517  **   * The total memory allocated for the in-memory list is greater
88518  **     than (page-size * cache-size), or
88519  **
88520  **   * The total memory allocated for the in-memory list is greater
88521  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
88522  */
88523  nReq = pVal->n + sizeof(SorterRecord);
88524  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
88525  if( pSorter->mxPmaSize ){
88526    if( pSorter->list.aMemory ){
88527      bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
88528    }else{
88529      bFlush = (
88530          (pSorter->list.szPMA > pSorter->mxPmaSize)
88531       || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
88532      );
88533    }
88534    if( bFlush ){
88535      rc = vdbeSorterFlushPMA(pSorter);
88536      pSorter->list.szPMA = 0;
88537      pSorter->iMemory = 0;
88538      assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
88539    }
88540  }
88541
88542  pSorter->list.szPMA += nPMA;
88543  if( nPMA>pSorter->mxKeysize ){
88544    pSorter->mxKeysize = nPMA;
88545  }
88546
88547  if( pSorter->list.aMemory ){
88548    int nMin = pSorter->iMemory + nReq;
88549
88550    if( nMin>pSorter->nMemory ){
88551      u8 *aNew;
88552      int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
88553      int nNew = pSorter->nMemory * 2;
88554      while( nNew < nMin ) nNew = nNew*2;
88555      if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
88556      if( nNew < nMin ) nNew = nMin;
88557
88558      aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
88559      if( !aNew ) return SQLITE_NOMEM_BKPT;
88560      pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
88561      pSorter->list.aMemory = aNew;
88562      pSorter->nMemory = nNew;
88563    }
88564
88565    pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
88566    pSorter->iMemory += ROUND8(nReq);
88567    if( pSorter->list.pList ){
88568      pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
88569    }
88570  }else{
88571    pNew = (SorterRecord *)sqlite3Malloc(nReq);
88572    if( pNew==0 ){
88573      return SQLITE_NOMEM_BKPT;
88574    }
88575    pNew->u.pNext = pSorter->list.pList;
88576  }
88577
88578  memcpy(SRVAL(pNew), pVal->z, pVal->n);
88579  pNew->nVal = pVal->n;
88580  pSorter->list.pList = pNew;
88581
88582  return rc;
88583}
88584
88585/*
88586** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
88587** of the data stored in aFile[1] is the same as that used by regular PMAs,
88588** except that the number-of-bytes varint is omitted from the start.
88589*/
88590static int vdbeIncrPopulate(IncrMerger *pIncr){
88591  int rc = SQLITE_OK;
88592  int rc2;
88593  i64 iStart = pIncr->iStartOff;
88594  SorterFile *pOut = &pIncr->aFile[1];
88595  SortSubtask *pTask = pIncr->pTask;
88596  MergeEngine *pMerger = pIncr->pMerger;
88597  PmaWriter writer;
88598  assert( pIncr->bEof==0 );
88599
88600  vdbeSorterPopulateDebug(pTask, "enter");
88601
88602  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
88603  while( rc==SQLITE_OK ){
88604    int dummy;
88605    PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
88606    int nKey = pReader->nKey;
88607    i64 iEof = writer.iWriteOff + writer.iBufEnd;
88608
88609    /* Check if the output file is full or if the input has been exhausted.
88610    ** In either case exit the loop. */
88611    if( pReader->pFd==0 ) break;
88612    if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
88613
88614    /* Write the next key to the output. */
88615    vdbePmaWriteVarint(&writer, nKey);
88616    vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
88617    assert( pIncr->pMerger->pTask==pTask );
88618    rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
88619  }
88620
88621  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
88622  if( rc==SQLITE_OK ) rc = rc2;
88623  vdbeSorterPopulateDebug(pTask, "exit");
88624  return rc;
88625}
88626
88627#if SQLITE_MAX_WORKER_THREADS>0
88628/*
88629** The main routine for background threads that populate aFile[1] of
88630** multi-threaded IncrMerger objects.
88631*/
88632static void *vdbeIncrPopulateThread(void *pCtx){
88633  IncrMerger *pIncr = (IncrMerger*)pCtx;
88634  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
88635  pIncr->pTask->bDone = 1;
88636  return pRet;
88637}
88638
88639/*
88640** Launch a background thread to populate aFile[1] of pIncr.
88641*/
88642static int vdbeIncrBgPopulate(IncrMerger *pIncr){
88643  void *p = (void*)pIncr;
88644  assert( pIncr->bUseThread );
88645  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
88646}
88647#endif
88648
88649/*
88650** This function is called when the PmaReader corresponding to pIncr has
88651** finished reading the contents of aFile[0]. Its purpose is to "refill"
88652** aFile[0] such that the PmaReader should start rereading it from the
88653** beginning.
88654**
88655** For single-threaded objects, this is accomplished by literally reading
88656** keys from pIncr->pMerger and repopulating aFile[0].
88657**
88658** For multi-threaded objects, all that is required is to wait until the
88659** background thread is finished (if it is not already) and then swap
88660** aFile[0] and aFile[1] in place. If the contents of pMerger have not
88661** been exhausted, this function also launches a new background thread
88662** to populate the new aFile[1].
88663**
88664** SQLITE_OK is returned on success, or an SQLite error code otherwise.
88665*/
88666static int vdbeIncrSwap(IncrMerger *pIncr){
88667  int rc = SQLITE_OK;
88668
88669#if SQLITE_MAX_WORKER_THREADS>0
88670  if( pIncr->bUseThread ){
88671    rc = vdbeSorterJoinThread(pIncr->pTask);
88672
88673    if( rc==SQLITE_OK ){
88674      SorterFile f0 = pIncr->aFile[0];
88675      pIncr->aFile[0] = pIncr->aFile[1];
88676      pIncr->aFile[1] = f0;
88677    }
88678
88679    if( rc==SQLITE_OK ){
88680      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
88681        pIncr->bEof = 1;
88682      }else{
88683        rc = vdbeIncrBgPopulate(pIncr);
88684      }
88685    }
88686  }else
88687#endif
88688  {
88689    rc = vdbeIncrPopulate(pIncr);
88690    pIncr->aFile[0] = pIncr->aFile[1];
88691    if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
88692      pIncr->bEof = 1;
88693    }
88694  }
88695
88696  return rc;
88697}
88698
88699/*
88700** Allocate and return a new IncrMerger object to read data from pMerger.
88701**
88702** If an OOM condition is encountered, return NULL. In this case free the
88703** pMerger argument before returning.
88704*/
88705static int vdbeIncrMergerNew(
88706  SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
88707  MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
88708  IncrMerger **ppOut      /* Write the new IncrMerger here */
88709){
88710  int rc = SQLITE_OK;
88711  IncrMerger *pIncr = *ppOut = (IncrMerger*)
88712       (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
88713  if( pIncr ){
88714    pIncr->pMerger = pMerger;
88715    pIncr->pTask = pTask;
88716    pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
88717    pTask->file2.iEof += pIncr->mxSz;
88718  }else{
88719    vdbeMergeEngineFree(pMerger);
88720    rc = SQLITE_NOMEM_BKPT;
88721  }
88722  return rc;
88723}
88724
88725#if SQLITE_MAX_WORKER_THREADS>0
88726/*
88727** Set the "use-threads" flag on object pIncr.
88728*/
88729static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
88730  pIncr->bUseThread = 1;
88731  pIncr->pTask->file2.iEof -= pIncr->mxSz;
88732}
88733#endif /* SQLITE_MAX_WORKER_THREADS>0 */
88734
88735
88736
88737/*
88738** Recompute pMerger->aTree[iOut] by comparing the next keys on the
88739** two PmaReaders that feed that entry.  Neither of the PmaReaders
88740** are advanced.  This routine merely does the comparison.
88741*/
88742static void vdbeMergeEngineCompare(
88743  MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
88744  int iOut               /* Store the result in pMerger->aTree[iOut] */
88745){
88746  int i1;
88747  int i2;
88748  int iRes;
88749  PmaReader *p1;
88750  PmaReader *p2;
88751
88752  assert( iOut<pMerger->nTree && iOut>0 );
88753
88754  if( iOut>=(pMerger->nTree/2) ){
88755    i1 = (iOut - pMerger->nTree/2) * 2;
88756    i2 = i1 + 1;
88757  }else{
88758    i1 = pMerger->aTree[iOut*2];
88759    i2 = pMerger->aTree[iOut*2+1];
88760  }
88761
88762  p1 = &pMerger->aReadr[i1];
88763  p2 = &pMerger->aReadr[i2];
88764
88765  if( p1->pFd==0 ){
88766    iRes = i2;
88767  }else if( p2->pFd==0 ){
88768    iRes = i1;
88769  }else{
88770    SortSubtask *pTask = pMerger->pTask;
88771    int bCached = 0;
88772    int res;
88773    assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
88774    res = pTask->xCompare(
88775        pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
88776    );
88777    if( res<=0 ){
88778      iRes = i1;
88779    }else{
88780      iRes = i2;
88781    }
88782  }
88783
88784  pMerger->aTree[iOut] = iRes;
88785}
88786
88787/*
88788** Allowed values for the eMode parameter to vdbeMergeEngineInit()
88789** and vdbePmaReaderIncrMergeInit().
88790**
88791** Only INCRINIT_NORMAL is valid in single-threaded builds (when
88792** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
88793** when there exists one or more separate worker threads.
88794*/
88795#define INCRINIT_NORMAL 0
88796#define INCRINIT_TASK   1
88797#define INCRINIT_ROOT   2
88798
88799/*
88800** Forward reference required as the vdbeIncrMergeInit() and
88801** vdbePmaReaderIncrInit() routines are called mutually recursively when
88802** building a merge tree.
88803*/
88804static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
88805
88806/*
88807** Initialize the MergeEngine object passed as the second argument. Once this
88808** function returns, the first key of merged data may be read from the
88809** MergeEngine object in the usual fashion.
88810**
88811** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
88812** objects attached to the PmaReader objects that the merger reads from have
88813** already been populated, but that they have not yet populated aFile[0] and
88814** set the PmaReader objects up to read from it. In this case all that is
88815** required is to call vdbePmaReaderNext() on each PmaReader to point it at
88816** its first key.
88817**
88818** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
88819** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
88820** to pMerger.
88821**
88822** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
88823*/
88824static int vdbeMergeEngineInit(
88825  SortSubtask *pTask,             /* Thread that will run pMerger */
88826  MergeEngine *pMerger,           /* MergeEngine to initialize */
88827  int eMode                       /* One of the INCRINIT_XXX constants */
88828){
88829  int rc = SQLITE_OK;             /* Return code */
88830  int i;                          /* For looping over PmaReader objects */
88831  int nTree = pMerger->nTree;
88832
88833  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
88834  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
88835
88836  /* Verify that the MergeEngine is assigned to a single thread */
88837  assert( pMerger->pTask==0 );
88838  pMerger->pTask = pTask;
88839
88840  for(i=0; i<nTree; i++){
88841    if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
88842      /* PmaReaders should be normally initialized in order, as if they are
88843      ** reading from the same temp file this makes for more linear file IO.
88844      ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
88845      ** in use it will block the vdbePmaReaderNext() call while it uses
88846      ** the main thread to fill its buffer. So calling PmaReaderNext()
88847      ** on this PmaReader before any of the multi-threaded PmaReaders takes
88848      ** better advantage of multi-processor hardware. */
88849      rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
88850    }else{
88851      rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
88852    }
88853    if( rc!=SQLITE_OK ) return rc;
88854  }
88855
88856  for(i=pMerger->nTree-1; i>0; i--){
88857    vdbeMergeEngineCompare(pMerger, i);
88858  }
88859  return pTask->pUnpacked->errCode;
88860}
88861
88862/*
88863** The PmaReader passed as the first argument is guaranteed to be an
88864** incremental-reader (pReadr->pIncr!=0). This function serves to open
88865** and/or initialize the temp file related fields of the IncrMerge
88866** object at (pReadr->pIncr).
88867**
88868** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
88869** in the sub-tree headed by pReadr are also initialized. Data is then
88870** loaded into the buffers belonging to pReadr and it is set to point to
88871** the first key in its range.
88872**
88873** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
88874** to be a multi-threaded PmaReader and this function is being called in a
88875** background thread. In this case all PmaReaders in the sub-tree are
88876** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
88877** pReadr is populated. However, pReadr itself is not set up to point
88878** to its first key. A call to vdbePmaReaderNext() is still required to do
88879** that.
88880**
88881** The reason this function does not call vdbePmaReaderNext() immediately
88882** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
88883** to block on thread (pTask->thread) before accessing aFile[1]. But, since
88884** this entire function is being run by thread (pTask->thread), that will
88885** lead to the current background thread attempting to join itself.
88886**
88887** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
88888** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
88889** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
88890** In this case vdbePmaReaderNext() is called on all child PmaReaders and
88891** the current PmaReader set to point to the first key in its range.
88892**
88893** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
88894*/
88895static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
88896  int rc = SQLITE_OK;
88897  IncrMerger *pIncr = pReadr->pIncr;
88898  SortSubtask *pTask = pIncr->pTask;
88899  sqlite3 *db = pTask->pSorter->db;
88900
88901  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
88902  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
88903
88904  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
88905
88906  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
88907  ** requires two temp files to itself, whereas a single-threaded object
88908  ** only requires a region of pTask->file2. */
88909  if( rc==SQLITE_OK ){
88910    int mxSz = pIncr->mxSz;
88911#if SQLITE_MAX_WORKER_THREADS>0
88912    if( pIncr->bUseThread ){
88913      rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
88914      if( rc==SQLITE_OK ){
88915        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
88916      }
88917    }else
88918#endif
88919    /*if( !pIncr->bUseThread )*/{
88920      if( pTask->file2.pFd==0 ){
88921        assert( pTask->file2.iEof>0 );
88922        rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
88923        pTask->file2.iEof = 0;
88924      }
88925      if( rc==SQLITE_OK ){
88926        pIncr->aFile[1].pFd = pTask->file2.pFd;
88927        pIncr->iStartOff = pTask->file2.iEof;
88928        pTask->file2.iEof += mxSz;
88929      }
88930    }
88931  }
88932
88933#if SQLITE_MAX_WORKER_THREADS>0
88934  if( rc==SQLITE_OK && pIncr->bUseThread ){
88935    /* Use the current thread to populate aFile[1], even though this
88936    ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
88937    ** then this function is already running in background thread
88938    ** pIncr->pTask->thread.
88939    **
88940    ** If this is the INCRINIT_ROOT object, then it is running in the
88941    ** main VDBE thread. But that is Ok, as that thread cannot return
88942    ** control to the VDBE or proceed with anything useful until the
88943    ** first results are ready from this merger object anyway.
88944    */
88945    assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
88946    rc = vdbeIncrPopulate(pIncr);
88947  }
88948#endif
88949
88950  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
88951    rc = vdbePmaReaderNext(pReadr);
88952  }
88953
88954  return rc;
88955}
88956
88957#if SQLITE_MAX_WORKER_THREADS>0
88958/*
88959** The main routine for vdbePmaReaderIncrMergeInit() operations run in
88960** background threads.
88961*/
88962static void *vdbePmaReaderBgIncrInit(void *pCtx){
88963  PmaReader *pReader = (PmaReader*)pCtx;
88964  void *pRet = SQLITE_INT_TO_PTR(
88965                  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
88966               );
88967  pReader->pIncr->pTask->bDone = 1;
88968  return pRet;
88969}
88970#endif
88971
88972/*
88973** If the PmaReader passed as the first argument is not an incremental-reader
88974** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
88975** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
88976** this routine to initialize the incremental merge.
88977**
88978** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
88979** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
88980** Or, if the IncrMerger is single threaded, the same function is called
88981** using the current thread.
88982*/
88983static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
88984  IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
88985  int rc = SQLITE_OK;                  /* Return code */
88986  if( pIncr ){
88987#if SQLITE_MAX_WORKER_THREADS>0
88988    assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
88989    if( pIncr->bUseThread ){
88990      void *pCtx = (void*)pReadr;
88991      rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
88992    }else
88993#endif
88994    {
88995      rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
88996    }
88997  }
88998  return rc;
88999}
89000
89001/*
89002** Allocate a new MergeEngine object to merge the contents of nPMA level-0
89003** PMAs from pTask->file. If no error occurs, set *ppOut to point to
89004** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
89005** to NULL and return an SQLite error code.
89006**
89007** When this function is called, *piOffset is set to the offset of the
89008** first PMA to read from pTask->file. Assuming no error occurs, it is
89009** set to the offset immediately following the last byte of the last
89010** PMA before returning. If an error does occur, then the final value of
89011** *piOffset is undefined.
89012*/
89013static int vdbeMergeEngineLevel0(
89014  SortSubtask *pTask,             /* Sorter task to read from */
89015  int nPMA,                       /* Number of PMAs to read */
89016  i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
89017  MergeEngine **ppOut             /* OUT: New merge-engine */
89018){
89019  MergeEngine *pNew;              /* Merge engine to return */
89020  i64 iOff = *piOffset;
89021  int i;
89022  int rc = SQLITE_OK;
89023
89024  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
89025  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
89026
89027  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
89028    i64 nDummy = 0;
89029    PmaReader *pReadr = &pNew->aReadr[i];
89030    rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
89031    iOff = pReadr->iEof;
89032  }
89033
89034  if( rc!=SQLITE_OK ){
89035    vdbeMergeEngineFree(pNew);
89036    *ppOut = 0;
89037  }
89038  *piOffset = iOff;
89039  return rc;
89040}
89041
89042/*
89043** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
89044** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
89045**
89046** i.e.
89047**
89048**   nPMA<=16    -> TreeDepth() == 0
89049**   nPMA<=256   -> TreeDepth() == 1
89050**   nPMA<=65536 -> TreeDepth() == 2
89051*/
89052static int vdbeSorterTreeDepth(int nPMA){
89053  int nDepth = 0;
89054  i64 nDiv = SORTER_MAX_MERGE_COUNT;
89055  while( nDiv < (i64)nPMA ){
89056    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
89057    nDepth++;
89058  }
89059  return nDepth;
89060}
89061
89062/*
89063** pRoot is the root of an incremental merge-tree with depth nDepth (according
89064** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
89065** tree, counting from zero. This function adds pLeaf to the tree.
89066**
89067** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
89068** code is returned and pLeaf is freed.
89069*/
89070static int vdbeSorterAddToTree(
89071  SortSubtask *pTask,             /* Task context */
89072  int nDepth,                     /* Depth of tree according to TreeDepth() */
89073  int iSeq,                       /* Sequence number of leaf within tree */
89074  MergeEngine *pRoot,             /* Root of tree */
89075  MergeEngine *pLeaf              /* Leaf to add to tree */
89076){
89077  int rc = SQLITE_OK;
89078  int nDiv = 1;
89079  int i;
89080  MergeEngine *p = pRoot;
89081  IncrMerger *pIncr;
89082
89083  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
89084
89085  for(i=1; i<nDepth; i++){
89086    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
89087  }
89088
89089  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
89090    int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
89091    PmaReader *pReadr = &p->aReadr[iIter];
89092
89093    if( pReadr->pIncr==0 ){
89094      MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
89095      if( pNew==0 ){
89096        rc = SQLITE_NOMEM_BKPT;
89097      }else{
89098        rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
89099      }
89100    }
89101    if( rc==SQLITE_OK ){
89102      p = pReadr->pIncr->pMerger;
89103      nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
89104    }
89105  }
89106
89107  if( rc==SQLITE_OK ){
89108    p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
89109  }else{
89110    vdbeIncrFree(pIncr);
89111  }
89112  return rc;
89113}
89114
89115/*
89116** This function is called as part of a SorterRewind() operation on a sorter
89117** that has already written two or more level-0 PMAs to one or more temp
89118** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
89119** can be used to incrementally merge all PMAs on disk.
89120**
89121** If successful, SQLITE_OK is returned and *ppOut set to point to the
89122** MergeEngine object at the root of the tree before returning. Or, if an
89123** error occurs, an SQLite error code is returned and the final value
89124** of *ppOut is undefined.
89125*/
89126static int vdbeSorterMergeTreeBuild(
89127  VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
89128  MergeEngine **ppOut        /* Write the MergeEngine here */
89129){
89130  MergeEngine *pMain = 0;
89131  int rc = SQLITE_OK;
89132  int iTask;
89133
89134#if SQLITE_MAX_WORKER_THREADS>0
89135  /* If the sorter uses more than one task, then create the top-level
89136  ** MergeEngine here. This MergeEngine will read data from exactly
89137  ** one PmaReader per sub-task.  */
89138  assert( pSorter->bUseThreads || pSorter->nTask==1 );
89139  if( pSorter->nTask>1 ){
89140    pMain = vdbeMergeEngineNew(pSorter->nTask);
89141    if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
89142  }
89143#endif
89144
89145  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
89146    SortSubtask *pTask = &pSorter->aTask[iTask];
89147    assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
89148    if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
89149      MergeEngine *pRoot = 0;     /* Root node of tree for this task */
89150      int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
89151      i64 iReadOff = 0;
89152
89153      if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
89154        rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
89155      }else{
89156        int i;
89157        int iSeq = 0;
89158        pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
89159        if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
89160        for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
89161          MergeEngine *pMerger = 0; /* New level-0 PMA merger */
89162          int nReader;              /* Number of level-0 PMAs to merge */
89163
89164          nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
89165          rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
89166          if( rc==SQLITE_OK ){
89167            rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
89168          }
89169        }
89170      }
89171
89172      if( rc==SQLITE_OK ){
89173#if SQLITE_MAX_WORKER_THREADS>0
89174        if( pMain!=0 ){
89175          rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
89176        }else
89177#endif
89178        {
89179          assert( pMain==0 );
89180          pMain = pRoot;
89181        }
89182      }else{
89183        vdbeMergeEngineFree(pRoot);
89184      }
89185    }
89186  }
89187
89188  if( rc!=SQLITE_OK ){
89189    vdbeMergeEngineFree(pMain);
89190    pMain = 0;
89191  }
89192  *ppOut = pMain;
89193  return rc;
89194}
89195
89196/*
89197** This function is called as part of an sqlite3VdbeSorterRewind() operation
89198** on a sorter that has written two or more PMAs to temporary files. It sets
89199** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
89200** (for multi-threaded sorters) so that it can be used to iterate through
89201** all records stored in the sorter.
89202**
89203** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
89204*/
89205static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
89206  int rc;                         /* Return code */
89207  SortSubtask *pTask0 = &pSorter->aTask[0];
89208  MergeEngine *pMain = 0;
89209#if SQLITE_MAX_WORKER_THREADS
89210  sqlite3 *db = pTask0->pSorter->db;
89211  int i;
89212  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
89213  for(i=0; i<pSorter->nTask; i++){
89214    pSorter->aTask[i].xCompare = xCompare;
89215  }
89216#endif
89217
89218  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
89219  if( rc==SQLITE_OK ){
89220#if SQLITE_MAX_WORKER_THREADS
89221    assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
89222    if( pSorter->bUseThreads ){
89223      int iTask;
89224      PmaReader *pReadr = 0;
89225      SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
89226      rc = vdbeSortAllocUnpacked(pLast);
89227      if( rc==SQLITE_OK ){
89228        pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
89229        pSorter->pReader = pReadr;
89230        if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
89231      }
89232      if( rc==SQLITE_OK ){
89233        rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
89234        if( rc==SQLITE_OK ){
89235          vdbeIncrMergerSetThreads(pReadr->pIncr);
89236          for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
89237            IncrMerger *pIncr;
89238            if( (pIncr = pMain->aReadr[iTask].pIncr) ){
89239              vdbeIncrMergerSetThreads(pIncr);
89240              assert( pIncr->pTask!=pLast );
89241            }
89242          }
89243          for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
89244            /* Check that:
89245            **
89246            **   a) The incremental merge object is configured to use the
89247            **      right task, and
89248            **   b) If it is using task (nTask-1), it is configured to run
89249            **      in single-threaded mode. This is important, as the
89250            **      root merge (INCRINIT_ROOT) will be using the same task
89251            **      object.
89252            */
89253            PmaReader *p = &pMain->aReadr[iTask];
89254            assert( p->pIncr==0 || (
89255                (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
89256             && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
89257            ));
89258            rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
89259          }
89260        }
89261        pMain = 0;
89262      }
89263      if( rc==SQLITE_OK ){
89264        rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
89265      }
89266    }else
89267#endif
89268    {
89269      rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
89270      pSorter->pMerger = pMain;
89271      pMain = 0;
89272    }
89273  }
89274
89275  if( rc!=SQLITE_OK ){
89276    vdbeMergeEngineFree(pMain);
89277  }
89278  return rc;
89279}
89280
89281
89282/*
89283** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
89284** this function is called to prepare for iterating through the records
89285** in sorted order.
89286*/
89287SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
89288  VdbeSorter *pSorter;
89289  int rc = SQLITE_OK;             /* Return code */
89290
89291  assert( pCsr->eCurType==CURTYPE_SORTER );
89292  pSorter = pCsr->uc.pSorter;
89293  assert( pSorter );
89294
89295  /* If no data has been written to disk, then do not do so now. Instead,
89296  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
89297  ** from the in-memory list.  */
89298  if( pSorter->bUsePMA==0 ){
89299    if( pSorter->list.pList ){
89300      *pbEof = 0;
89301      rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
89302    }else{
89303      *pbEof = 1;
89304    }
89305    return rc;
89306  }
89307
89308  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
89309  ** function flushes the contents of memory to disk, it immediately always
89310  ** creates a new list consisting of a single key immediately afterwards.
89311  ** So the list is never empty at this point.  */
89312  assert( pSorter->list.pList );
89313  rc = vdbeSorterFlushPMA(pSorter);
89314
89315  /* Join all threads */
89316  rc = vdbeSorterJoinAll(pSorter, rc);
89317
89318  vdbeSorterRewindDebug("rewind");
89319
89320  /* Assuming no errors have occurred, set up a merger structure to
89321  ** incrementally read and merge all remaining PMAs.  */
89322  assert( pSorter->pReader==0 );
89323  if( rc==SQLITE_OK ){
89324    rc = vdbeSorterSetupMerge(pSorter);
89325    *pbEof = 0;
89326  }
89327
89328  vdbeSorterRewindDebug("rewinddone");
89329  return rc;
89330}
89331
89332/*
89333** Advance to the next element in the sorter.  Return value:
89334**
89335**    SQLITE_OK     success
89336**    SQLITE_DONE   end of data
89337**    otherwise     some kind of error.
89338*/
89339SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
89340  VdbeSorter *pSorter;
89341  int rc;                         /* Return code */
89342
89343  assert( pCsr->eCurType==CURTYPE_SORTER );
89344  pSorter = pCsr->uc.pSorter;
89345  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
89346  if( pSorter->bUsePMA ){
89347    assert( pSorter->pReader==0 || pSorter->pMerger==0 );
89348    assert( pSorter->bUseThreads==0 || pSorter->pReader );
89349    assert( pSorter->bUseThreads==1 || pSorter->pMerger );
89350#if SQLITE_MAX_WORKER_THREADS>0
89351    if( pSorter->bUseThreads ){
89352      rc = vdbePmaReaderNext(pSorter->pReader);
89353      if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
89354    }else
89355#endif
89356    /*if( !pSorter->bUseThreads )*/ {
89357      int res = 0;
89358      assert( pSorter->pMerger!=0 );
89359      assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
89360      rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
89361      if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
89362    }
89363  }else{
89364    SorterRecord *pFree = pSorter->list.pList;
89365    pSorter->list.pList = pFree->u.pNext;
89366    pFree->u.pNext = 0;
89367    if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
89368    rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
89369  }
89370  return rc;
89371}
89372
89373/*
89374** Return a pointer to a buffer owned by the sorter that contains the
89375** current key.
89376*/
89377static void *vdbeSorterRowkey(
89378  const VdbeSorter *pSorter,      /* Sorter object */
89379  int *pnKey                      /* OUT: Size of current key in bytes */
89380){
89381  void *pKey;
89382  if( pSorter->bUsePMA ){
89383    PmaReader *pReader;
89384#if SQLITE_MAX_WORKER_THREADS>0
89385    if( pSorter->bUseThreads ){
89386      pReader = pSorter->pReader;
89387    }else
89388#endif
89389    /*if( !pSorter->bUseThreads )*/{
89390      pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
89391    }
89392    *pnKey = pReader->nKey;
89393    pKey = pReader->aKey;
89394  }else{
89395    *pnKey = pSorter->list.pList->nVal;
89396    pKey = SRVAL(pSorter->list.pList);
89397  }
89398  return pKey;
89399}
89400
89401/*
89402** Copy the current sorter key into the memory cell pOut.
89403*/
89404SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
89405  VdbeSorter *pSorter;
89406  void *pKey; int nKey;           /* Sorter key to copy into pOut */
89407
89408  assert( pCsr->eCurType==CURTYPE_SORTER );
89409  pSorter = pCsr->uc.pSorter;
89410  pKey = vdbeSorterRowkey(pSorter, &nKey);
89411  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
89412    return SQLITE_NOMEM_BKPT;
89413  }
89414  pOut->n = nKey;
89415  MemSetTypeFlag(pOut, MEM_Blob);
89416  memcpy(pOut->z, pKey, nKey);
89417
89418  return SQLITE_OK;
89419}
89420
89421/*
89422** Compare the key in memory cell pVal with the key that the sorter cursor
89423** passed as the first argument currently points to. For the purposes of
89424** the comparison, ignore the rowid field at the end of each record.
89425**
89426** If the sorter cursor key contains any NULL values, consider it to be
89427** less than pVal. Even if pVal also contains NULL values.
89428**
89429** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
89430** Otherwise, set *pRes to a negative, zero or positive value if the
89431** key in pVal is smaller than, equal to or larger than the current sorter
89432** key.
89433**
89434** This routine forms the core of the OP_SorterCompare opcode, which in
89435** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
89436*/
89437SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
89438  const VdbeCursor *pCsr,         /* Sorter cursor */
89439  Mem *pVal,                      /* Value to compare to current sorter key */
89440  int nKeyCol,                    /* Compare this many columns */
89441  int *pRes                       /* OUT: Result of comparison */
89442){
89443  VdbeSorter *pSorter;
89444  UnpackedRecord *r2;
89445  KeyInfo *pKeyInfo;
89446  int i;
89447  void *pKey; int nKey;           /* Sorter key to compare pVal with */
89448
89449  assert( pCsr->eCurType==CURTYPE_SORTER );
89450  pSorter = pCsr->uc.pSorter;
89451  r2 = pSorter->pUnpacked;
89452  pKeyInfo = pCsr->pKeyInfo;
89453  if( r2==0 ){
89454    r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
89455    if( r2==0 ) return SQLITE_NOMEM_BKPT;
89456    r2->nField = nKeyCol;
89457  }
89458  assert( r2->nField==nKeyCol );
89459
89460  pKey = vdbeSorterRowkey(pSorter, &nKey);
89461  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
89462  for(i=0; i<nKeyCol; i++){
89463    if( r2->aMem[i].flags & MEM_Null ){
89464      *pRes = -1;
89465      return SQLITE_OK;
89466    }
89467  }
89468
89469  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
89470  return SQLITE_OK;
89471}
89472
89473/************** End of vdbesort.c ********************************************/
89474/************** Begin file memjournal.c **************************************/
89475/*
89476** 2008 October 7
89477**
89478** The author disclaims copyright to this source code.  In place of
89479** a legal notice, here is a blessing:
89480**
89481**    May you do good and not evil.
89482**    May you find forgiveness for yourself and forgive others.
89483**    May you share freely, never taking more than you give.
89484**
89485*************************************************************************
89486**
89487** This file contains code use to implement an in-memory rollback journal.
89488** The in-memory rollback journal is used to journal transactions for
89489** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
89490**
89491** Update:  The in-memory journal is also used to temporarily cache
89492** smaller journals that are not critical for power-loss recovery.
89493** For example, statement journals that are not too big will be held
89494** entirely in memory, thus reducing the number of file I/O calls, and
89495** more importantly, reducing temporary file creation events.  If these
89496** journals become too large for memory, they are spilled to disk.  But
89497** in the common case, they are usually small and no file I/O needs to
89498** occur.
89499*/
89500/* #include "sqliteInt.h" */
89501
89502/* Forward references to internal structures */
89503typedef struct MemJournal MemJournal;
89504typedef struct FilePoint FilePoint;
89505typedef struct FileChunk FileChunk;
89506
89507/*
89508** The rollback journal is composed of a linked list of these structures.
89509**
89510** The zChunk array is always at least 8 bytes in size - usually much more.
89511** Its actual size is stored in the MemJournal.nChunkSize variable.
89512*/
89513struct FileChunk {
89514  FileChunk *pNext;               /* Next chunk in the journal */
89515  u8 zChunk[8];                   /* Content of this chunk */
89516};
89517
89518/*
89519** By default, allocate this many bytes of memory for each FileChunk object.
89520*/
89521#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
89522
89523/*
89524** For chunk size nChunkSize, return the number of bytes that should
89525** be allocated for each FileChunk structure.
89526*/
89527#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
89528
89529/*
89530** An instance of this object serves as a cursor into the rollback journal.
89531** The cursor can be either for reading or writing.
89532*/
89533struct FilePoint {
89534  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
89535  FileChunk *pChunk;              /* Specific chunk into which cursor points */
89536};
89537
89538/*
89539** This structure is a subclass of sqlite3_file. Each open memory-journal
89540** is an instance of this class.
89541*/
89542struct MemJournal {
89543  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
89544  int nChunkSize;                 /* In-memory chunk-size */
89545
89546  int nSpill;                     /* Bytes of data before flushing */
89547  int nSize;                      /* Bytes of data currently in memory */
89548  FileChunk *pFirst;              /* Head of in-memory chunk-list */
89549  FilePoint endpoint;             /* Pointer to the end of the file */
89550  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
89551
89552  int flags;                      /* xOpen flags */
89553  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
89554  const char *zJournal;           /* Name of the journal file */
89555};
89556
89557/*
89558** Read data from the in-memory journal file.  This is the implementation
89559** of the sqlite3_vfs.xRead method.
89560*/
89561static int memjrnlRead(
89562  sqlite3_file *pJfd,    /* The journal file from which to read */
89563  void *zBuf,            /* Put the results here */
89564  int iAmt,              /* Number of bytes to read */
89565  sqlite_int64 iOfst     /* Begin reading at this offset */
89566){
89567  MemJournal *p = (MemJournal *)pJfd;
89568  u8 *zOut = zBuf;
89569  int nRead = iAmt;
89570  int iChunkOffset;
89571  FileChunk *pChunk;
89572
89573#ifdef SQLITE_ENABLE_ATOMIC_WRITE
89574  if( (iAmt+iOfst)>p->endpoint.iOffset ){
89575    return SQLITE_IOERR_SHORT_READ;
89576  }
89577#endif
89578
89579  assert( (iAmt+iOfst)<=p->endpoint.iOffset );
89580  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
89581  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
89582    sqlite3_int64 iOff = 0;
89583    for(pChunk=p->pFirst;
89584        ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
89585        pChunk=pChunk->pNext
89586    ){
89587      iOff += p->nChunkSize;
89588    }
89589  }else{
89590    pChunk = p->readpoint.pChunk;
89591    assert( pChunk!=0 );
89592  }
89593
89594  iChunkOffset = (int)(iOfst%p->nChunkSize);
89595  do {
89596    int iSpace = p->nChunkSize - iChunkOffset;
89597    int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
89598    memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
89599    zOut += nCopy;
89600    nRead -= iSpace;
89601    iChunkOffset = 0;
89602  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
89603  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
89604  p->readpoint.pChunk = pChunk;
89605
89606  return SQLITE_OK;
89607}
89608
89609/*
89610** Free the list of FileChunk structures headed at MemJournal.pFirst.
89611*/
89612static void memjrnlFreeChunks(MemJournal *p){
89613  FileChunk *pIter;
89614  FileChunk *pNext;
89615  for(pIter=p->pFirst; pIter; pIter=pNext){
89616    pNext = pIter->pNext;
89617    sqlite3_free(pIter);
89618  }
89619  p->pFirst = 0;
89620}
89621
89622/*
89623** Flush the contents of memory to a real file on disk.
89624*/
89625static int memjrnlCreateFile(MemJournal *p){
89626  int rc;
89627  sqlite3_file *pReal = (sqlite3_file*)p;
89628  MemJournal copy = *p;
89629
89630  memset(p, 0, sizeof(MemJournal));
89631  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
89632  if( rc==SQLITE_OK ){
89633    int nChunk = copy.nChunkSize;
89634    i64 iOff = 0;
89635    FileChunk *pIter;
89636    for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
89637      if( iOff + nChunk > copy.endpoint.iOffset ){
89638        nChunk = copy.endpoint.iOffset - iOff;
89639      }
89640      rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
89641      if( rc ) break;
89642      iOff += nChunk;
89643    }
89644    if( rc==SQLITE_OK ){
89645      /* No error has occurred. Free the in-memory buffers. */
89646      memjrnlFreeChunks(&copy);
89647    }
89648  }
89649  if( rc!=SQLITE_OK ){
89650    /* If an error occurred while creating or writing to the file, restore
89651    ** the original before returning. This way, SQLite uses the in-memory
89652    ** journal data to roll back changes made to the internal page-cache
89653    ** before this function was called.  */
89654    sqlite3OsClose(pReal);
89655    *p = copy;
89656  }
89657  return rc;
89658}
89659
89660
89661/*
89662** Write data to the file.
89663*/
89664static int memjrnlWrite(
89665  sqlite3_file *pJfd,    /* The journal file into which to write */
89666  const void *zBuf,      /* Take data to be written from here */
89667  int iAmt,              /* Number of bytes to write */
89668  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
89669){
89670  MemJournal *p = (MemJournal *)pJfd;
89671  int nWrite = iAmt;
89672  u8 *zWrite = (u8 *)zBuf;
89673
89674  /* If the file should be created now, create it and write the new data
89675  ** into the file on disk. */
89676  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
89677    int rc = memjrnlCreateFile(p);
89678    if( rc==SQLITE_OK ){
89679      rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
89680    }
89681    return rc;
89682  }
89683
89684  /* If the contents of this write should be stored in memory */
89685  else{
89686    /* An in-memory journal file should only ever be appended to. Random
89687    ** access writes are not required. The only exception to this is when
89688    ** the in-memory journal is being used by a connection using the
89689    ** atomic-write optimization. In this case the first 28 bytes of the
89690    ** journal file may be written as part of committing the transaction. */
89691    assert( iOfst==p->endpoint.iOffset || iOfst==0 );
89692#ifdef SQLITE_ENABLE_ATOMIC_WRITE
89693    if( iOfst==0 && p->pFirst ){
89694      assert( p->nChunkSize>iAmt );
89695      memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
89696    }else
89697#else
89698    assert( iOfst>0 || p->pFirst==0 );
89699#endif
89700    {
89701      while( nWrite>0 ){
89702        FileChunk *pChunk = p->endpoint.pChunk;
89703        int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
89704        int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
89705
89706        if( iChunkOffset==0 ){
89707          /* New chunk is required to extend the file. */
89708          FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
89709          if( !pNew ){
89710            return SQLITE_IOERR_NOMEM_BKPT;
89711          }
89712          pNew->pNext = 0;
89713          if( pChunk ){
89714            assert( p->pFirst );
89715            pChunk->pNext = pNew;
89716          }else{
89717            assert( !p->pFirst );
89718            p->pFirst = pNew;
89719          }
89720          p->endpoint.pChunk = pNew;
89721        }
89722
89723        memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
89724        zWrite += iSpace;
89725        nWrite -= iSpace;
89726        p->endpoint.iOffset += iSpace;
89727      }
89728      p->nSize = iAmt + iOfst;
89729    }
89730  }
89731
89732  return SQLITE_OK;
89733}
89734
89735/*
89736** Truncate the file.
89737**
89738** If the journal file is already on disk, truncate it there. Or, if it
89739** is still in main memory but is being truncated to zero bytes in size,
89740** ignore
89741*/
89742static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
89743  MemJournal *p = (MemJournal *)pJfd;
89744  if( ALWAYS(size==0) ){
89745    memjrnlFreeChunks(p);
89746    p->nSize = 0;
89747    p->endpoint.pChunk = 0;
89748    p->endpoint.iOffset = 0;
89749    p->readpoint.pChunk = 0;
89750    p->readpoint.iOffset = 0;
89751  }
89752  return SQLITE_OK;
89753}
89754
89755/*
89756** Close the file.
89757*/
89758static int memjrnlClose(sqlite3_file *pJfd){
89759  MemJournal *p = (MemJournal *)pJfd;
89760  memjrnlFreeChunks(p);
89761  return SQLITE_OK;
89762}
89763
89764/*
89765** Sync the file.
89766**
89767** If the real file has been created, call its xSync method. Otherwise,
89768** syncing an in-memory journal is a no-op.
89769*/
89770static int memjrnlSync(sqlite3_file *pJfd, int flags){
89771  UNUSED_PARAMETER2(pJfd, flags);
89772  return SQLITE_OK;
89773}
89774
89775/*
89776** Query the size of the file in bytes.
89777*/
89778static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
89779  MemJournal *p = (MemJournal *)pJfd;
89780  *pSize = (sqlite_int64) p->endpoint.iOffset;
89781  return SQLITE_OK;
89782}
89783
89784/*
89785** Table of methods for MemJournal sqlite3_file object.
89786*/
89787static const struct sqlite3_io_methods MemJournalMethods = {
89788  1,                /* iVersion */
89789  memjrnlClose,     /* xClose */
89790  memjrnlRead,      /* xRead */
89791  memjrnlWrite,     /* xWrite */
89792  memjrnlTruncate,  /* xTruncate */
89793  memjrnlSync,      /* xSync */
89794  memjrnlFileSize,  /* xFileSize */
89795  0,                /* xLock */
89796  0,                /* xUnlock */
89797  0,                /* xCheckReservedLock */
89798  0,                /* xFileControl */
89799  0,                /* xSectorSize */
89800  0,                /* xDeviceCharacteristics */
89801  0,                /* xShmMap */
89802  0,                /* xShmLock */
89803  0,                /* xShmBarrier */
89804  0,                /* xShmUnmap */
89805  0,                /* xFetch */
89806  0                 /* xUnfetch */
89807};
89808
89809/*
89810** Open a journal file.
89811**
89812** The behaviour of the journal file depends on the value of parameter
89813** nSpill. If nSpill is 0, then the journal file is always create and
89814** accessed using the underlying VFS. If nSpill is less than zero, then
89815** all content is always stored in main-memory. Finally, if nSpill is a
89816** positive value, then the journal file is initially created in-memory
89817** but may be flushed to disk later on. In this case the journal file is
89818** flushed to disk either when it grows larger than nSpill bytes in size,
89819** or when sqlite3JournalCreate() is called.
89820*/
89821SQLITE_PRIVATE int sqlite3JournalOpen(
89822  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
89823  const char *zName,         /* Name of the journal file */
89824  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
89825  int flags,                 /* Opening flags */
89826  int nSpill                 /* Bytes buffered before opening the file */
89827){
89828  MemJournal *p = (MemJournal*)pJfd;
89829
89830  /* Zero the file-handle object. If nSpill was passed zero, initialize
89831  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
89832  ** case none of the code in this module is executed as a result of calls
89833  ** made on the journal file-handle.  */
89834  memset(p, 0, sizeof(MemJournal));
89835  if( nSpill==0 ){
89836    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
89837  }
89838
89839  if( nSpill>0 ){
89840    p->nChunkSize = nSpill;
89841  }else{
89842    p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
89843    assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
89844  }
89845
89846  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
89847  p->nSpill = nSpill;
89848  p->flags = flags;
89849  p->zJournal = zName;
89850  p->pVfs = pVfs;
89851  return SQLITE_OK;
89852}
89853
89854/*
89855** Open an in-memory journal file.
89856*/
89857SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
89858  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
89859}
89860
89861#ifdef SQLITE_ENABLE_ATOMIC_WRITE
89862/*
89863** If the argument p points to a MemJournal structure that is not an
89864** in-memory-only journal file (i.e. is one that was opened with a +ve
89865** nSpill parameter), and the underlying file has not yet been created,
89866** create it now.
89867*/
89868SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
89869  int rc = SQLITE_OK;
89870  if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
89871    rc = memjrnlCreateFile((MemJournal*)p);
89872  }
89873  return rc;
89874}
89875#endif
89876
89877/*
89878** The file-handle passed as the only argument is open on a journal file.
89879** Return true if this "journal file" is currently stored in heap memory,
89880** or false otherwise.
89881*/
89882SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
89883  return p->pMethods==&MemJournalMethods;
89884}
89885
89886/*
89887** Return the number of bytes required to store a JournalFile that uses vfs
89888** pVfs to create the underlying on-disk files.
89889*/
89890SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
89891  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
89892}
89893
89894/************** End of memjournal.c ******************************************/
89895/************** Begin file walker.c ******************************************/
89896/*
89897** 2008 August 16
89898**
89899** The author disclaims copyright to this source code.  In place of
89900** a legal notice, here is a blessing:
89901**
89902**    May you do good and not evil.
89903**    May you find forgiveness for yourself and forgive others.
89904**    May you share freely, never taking more than you give.
89905**
89906*************************************************************************
89907** This file contains routines used for walking the parser tree for
89908** an SQL statement.
89909*/
89910/* #include "sqliteInt.h" */
89911/* #include <stdlib.h> */
89912/* #include <string.h> */
89913
89914
89915/*
89916** Walk an expression tree.  Invoke the callback once for each node
89917** of the expression, while descending.  (In other words, the callback
89918** is invoked before visiting children.)
89919**
89920** The return value from the callback should be one of the WRC_*
89921** constants to specify how to proceed with the walk.
89922**
89923**    WRC_Continue      Continue descending down the tree.
89924**
89925**    WRC_Prune         Do not descend into child nodes, but allow
89926**                      the walk to continue with sibling nodes.
89927**
89928**    WRC_Abort         Do no more callbacks.  Unwind the stack and
89929**                      return from the top-level walk call.
89930**
89931** The return value from this routine is WRC_Abort to abandon the tree walk
89932** and WRC_Continue to continue.
89933*/
89934static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
89935  int rc;
89936  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
89937  testcase( ExprHasProperty(pExpr, EP_Reduced) );
89938  rc = pWalker->xExprCallback(pWalker, pExpr);
89939  if( rc ) return rc & WRC_Abort;
89940  if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
89941    if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
89942    assert( pExpr->x.pList==0 || pExpr->pRight==0 );
89943    if( pExpr->pRight ){
89944      if( walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
89945    }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89946      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
89947    }else if( pExpr->x.pList ){
89948      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
89949    }
89950  }
89951  return WRC_Continue;
89952}
89953SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
89954  return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
89955}
89956
89957/*
89958** Call sqlite3WalkExpr() for every expression in list p or until
89959** an abort request is seen.
89960*/
89961SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
89962  int i;
89963  struct ExprList_item *pItem;
89964  if( p ){
89965    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
89966      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
89967    }
89968  }
89969  return WRC_Continue;
89970}
89971
89972/*
89973** Walk all expressions associated with SELECT statement p.  Do
89974** not invoke the SELECT callback on p, but do (of course) invoke
89975** any expr callbacks and SELECT callbacks that come from subqueries.
89976** Return WRC_Abort or WRC_Continue.
89977*/
89978SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
89979  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
89980  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
89981  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
89982  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
89983  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
89984  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
89985  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
89986  return WRC_Continue;
89987}
89988
89989/*
89990** Walk the parse trees associated with all subqueries in the
89991** FROM clause of SELECT statement p.  Do not invoke the select
89992** callback on p, but do invoke it on each FROM clause subquery
89993** and on any subqueries further down in the tree.  Return
89994** WRC_Abort or WRC_Continue;
89995*/
89996SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
89997  SrcList *pSrc;
89998  int i;
89999  struct SrcList_item *pItem;
90000
90001  pSrc = p->pSrc;
90002  if( ALWAYS(pSrc) ){
90003    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
90004      if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
90005        return WRC_Abort;
90006      }
90007      if( pItem->fg.isTabFunc
90008       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
90009      ){
90010        return WRC_Abort;
90011      }
90012    }
90013  }
90014  return WRC_Continue;
90015}
90016
90017/*
90018** Call sqlite3WalkExpr() for every expression in Select statement p.
90019** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
90020** on the compound select chain, p->pPrior.
90021**
90022** If it is not NULL, the xSelectCallback() callback is invoked before
90023** the walk of the expressions and FROM clause. The xSelectCallback2()
90024** method is invoked following the walk of the expressions and FROM clause,
90025** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
90026** and if the expressions and FROM clause both return WRC_Continue;
90027**
90028** Return WRC_Continue under normal conditions.  Return WRC_Abort if
90029** there is an abort request.
90030**
90031** If the Walker does not have an xSelectCallback() then this routine
90032** is a no-op returning WRC_Continue.
90033*/
90034SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
90035  int rc;
90036  if( p==0 ) return WRC_Continue;
90037  if( pWalker->xSelectCallback==0 ) return WRC_Continue;
90038  do{
90039    rc = pWalker->xSelectCallback(pWalker, p);
90040    if( rc ) return rc & WRC_Abort;
90041    if( sqlite3WalkSelectExpr(pWalker, p)
90042     || sqlite3WalkSelectFrom(pWalker, p)
90043    ){
90044      return WRC_Abort;
90045    }
90046    if( pWalker->xSelectCallback2 ){
90047      pWalker->xSelectCallback2(pWalker, p);
90048    }
90049    p = p->pPrior;
90050  }while( p!=0 );
90051  return WRC_Continue;
90052}
90053
90054/************** End of walker.c **********************************************/
90055/************** Begin file resolve.c *****************************************/
90056/*
90057** 2008 August 18
90058**
90059** The author disclaims copyright to this source code.  In place of
90060** a legal notice, here is a blessing:
90061**
90062**    May you do good and not evil.
90063**    May you find forgiveness for yourself and forgive others.
90064**    May you share freely, never taking more than you give.
90065**
90066*************************************************************************
90067**
90068** This file contains routines used for walking the parser tree and
90069** resolve all identifiers by associating them with a particular
90070** table and column.
90071*/
90072/* #include "sqliteInt.h" */
90073
90074/*
90075** Walk the expression tree pExpr and increase the aggregate function
90076** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
90077** This needs to occur when copying a TK_AGG_FUNCTION node from an
90078** outer query into an inner subquery.
90079**
90080** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
90081** is a helper function - a callback for the tree walker.
90082*/
90083static int incrAggDepth(Walker *pWalker, Expr *pExpr){
90084  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
90085  return WRC_Continue;
90086}
90087static void incrAggFunctionDepth(Expr *pExpr, int N){
90088  if( N>0 ){
90089    Walker w;
90090    memset(&w, 0, sizeof(w));
90091    w.xExprCallback = incrAggDepth;
90092    w.u.n = N;
90093    sqlite3WalkExpr(&w, pExpr);
90094  }
90095}
90096
90097/*
90098** Turn the pExpr expression into an alias for the iCol-th column of the
90099** result set in pEList.
90100**
90101** If the reference is followed by a COLLATE operator, then make sure
90102** the COLLATE operator is preserved.  For example:
90103**
90104**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
90105**
90106** Should be transformed into:
90107**
90108**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
90109**
90110** The nSubquery parameter specifies how many levels of subquery the
90111** alias is removed from the original expression.  The usual value is
90112** zero but it might be more if the alias is contained within a subquery
90113** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
90114** structures must be increased by the nSubquery amount.
90115*/
90116static void resolveAlias(
90117  Parse *pParse,         /* Parsing context */
90118  ExprList *pEList,      /* A result set */
90119  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
90120  Expr *pExpr,           /* Transform this into an alias to the result set */
90121  const char *zType,     /* "GROUP" or "ORDER" or "" */
90122  int nSubquery          /* Number of subqueries that the label is moving */
90123){
90124  Expr *pOrig;           /* The iCol-th column of the result set */
90125  Expr *pDup;            /* Copy of pOrig */
90126  sqlite3 *db;           /* The database connection */
90127
90128  assert( iCol>=0 && iCol<pEList->nExpr );
90129  pOrig = pEList->a[iCol].pExpr;
90130  assert( pOrig!=0 );
90131  db = pParse->db;
90132  pDup = sqlite3ExprDup(db, pOrig, 0);
90133  if( pDup==0 ) return;
90134  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
90135  if( pExpr->op==TK_COLLATE ){
90136    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
90137  }
90138  ExprSetProperty(pDup, EP_Alias);
90139
90140  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
90141  ** prevents ExprDelete() from deleting the Expr structure itself,
90142  ** allowing it to be repopulated by the memcpy() on the following line.
90143  ** The pExpr->u.zToken might point into memory that will be freed by the
90144  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
90145  ** make a copy of the token before doing the sqlite3DbFree().
90146  */
90147  ExprSetProperty(pExpr, EP_Static);
90148  sqlite3ExprDelete(db, pExpr);
90149  memcpy(pExpr, pDup, sizeof(*pExpr));
90150  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
90151    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
90152    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
90153    pExpr->flags |= EP_MemToken;
90154  }
90155  sqlite3DbFree(db, pDup);
90156}
90157
90158
90159/*
90160** Return TRUE if the name zCol occurs anywhere in the USING clause.
90161**
90162** Return FALSE if the USING clause is NULL or if it does not contain
90163** zCol.
90164*/
90165static int nameInUsingClause(IdList *pUsing, const char *zCol){
90166  if( pUsing ){
90167    int k;
90168    for(k=0; k<pUsing->nId; k++){
90169      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
90170    }
90171  }
90172  return 0;
90173}
90174
90175/*
90176** Subqueries stores the original database, table and column names for their
90177** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
90178** Check to see if the zSpan given to this routine matches the zDb, zTab,
90179** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
90180** match anything.
90181*/
90182SQLITE_PRIVATE int sqlite3MatchSpanName(
90183  const char *zSpan,
90184  const char *zCol,
90185  const char *zTab,
90186  const char *zDb
90187){
90188  int n;
90189  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
90190  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
90191    return 0;
90192  }
90193  zSpan += n+1;
90194  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
90195  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
90196    return 0;
90197  }
90198  zSpan += n+1;
90199  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
90200    return 0;
90201  }
90202  return 1;
90203}
90204
90205/*
90206** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
90207** that name in the set of source tables in pSrcList and make the pExpr
90208** expression node refer back to that source column.  The following changes
90209** are made to pExpr:
90210**
90211**    pExpr->iDb           Set the index in db->aDb[] of the database X
90212**                         (even if X is implied).
90213**    pExpr->iTable        Set to the cursor number for the table obtained
90214**                         from pSrcList.
90215**    pExpr->pTab          Points to the Table structure of X.Y (even if
90216**                         X and/or Y are implied.)
90217**    pExpr->iColumn       Set to the column number within the table.
90218**    pExpr->op            Set to TK_COLUMN.
90219**    pExpr->pLeft         Any expression this points to is deleted
90220**    pExpr->pRight        Any expression this points to is deleted.
90221**
90222** The zDb variable is the name of the database (the "X").  This value may be
90223** NULL meaning that name is of the form Y.Z or Z.  Any available database
90224** can be used.  The zTable variable is the name of the table (the "Y").  This
90225** value can be NULL if zDb is also NULL.  If zTable is NULL it
90226** means that the form of the name is Z and that columns from any table
90227** can be used.
90228**
90229** If the name cannot be resolved unambiguously, leave an error message
90230** in pParse and return WRC_Abort.  Return WRC_Prune on success.
90231*/
90232static int lookupName(
90233  Parse *pParse,       /* The parsing context */
90234  const char *zDb,     /* Name of the database containing table, or NULL */
90235  const char *zTab,    /* Name of table containing column, or NULL */
90236  const char *zCol,    /* Name of the column. */
90237  NameContext *pNC,    /* The name context used to resolve the name */
90238  Expr *pExpr          /* Make this EXPR node point to the selected column */
90239){
90240  int i, j;                         /* Loop counters */
90241  int cnt = 0;                      /* Number of matching column names */
90242  int cntTab = 0;                   /* Number of matching table names */
90243  int nSubquery = 0;                /* How many levels of subquery */
90244  sqlite3 *db = pParse->db;         /* The database connection */
90245  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
90246  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
90247  NameContext *pTopNC = pNC;        /* First namecontext in the list */
90248  Schema *pSchema = 0;              /* Schema of the expression */
90249  int isTrigger = 0;                /* True if resolved to a trigger column */
90250  Table *pTab = 0;                  /* Table hold the row */
90251  Column *pCol;                     /* A column of pTab */
90252
90253  assert( pNC );     /* the name context cannot be NULL. */
90254  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
90255  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
90256
90257  /* Initialize the node to no-match */
90258  pExpr->iTable = -1;
90259  pExpr->pTab = 0;
90260  ExprSetVVAProperty(pExpr, EP_NoReduce);
90261
90262  /* Translate the schema name in zDb into a pointer to the corresponding
90263  ** schema.  If not found, pSchema will remain NULL and nothing will match
90264  ** resulting in an appropriate error message toward the end of this routine
90265  */
90266  if( zDb ){
90267    testcase( pNC->ncFlags & NC_PartIdx );
90268    testcase( pNC->ncFlags & NC_IsCheck );
90269    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
90270      /* Silently ignore database qualifiers inside CHECK constraints and
90271      ** partial indices.  Do not raise errors because that might break
90272      ** legacy and because it does not hurt anything to just ignore the
90273      ** database name. */
90274      zDb = 0;
90275    }else{
90276      for(i=0; i<db->nDb; i++){
90277        assert( db->aDb[i].zDbSName );
90278        if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
90279          pSchema = db->aDb[i].pSchema;
90280          break;
90281        }
90282      }
90283    }
90284  }
90285
90286  /* Start at the inner-most context and move outward until a match is found */
90287  assert( pNC && cnt==0 );
90288  do{
90289    ExprList *pEList;
90290    SrcList *pSrcList = pNC->pSrcList;
90291
90292    if( pSrcList ){
90293      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
90294        pTab = pItem->pTab;
90295        assert( pTab!=0 && pTab->zName!=0 );
90296        assert( pTab->nCol>0 );
90297        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
90298          int hit = 0;
90299          pEList = pItem->pSelect->pEList;
90300          for(j=0; j<pEList->nExpr; j++){
90301            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
90302              cnt++;
90303              cntTab = 2;
90304              pMatch = pItem;
90305              pExpr->iColumn = j;
90306              hit = 1;
90307            }
90308          }
90309          if( hit || zTab==0 ) continue;
90310        }
90311        if( zDb && pTab->pSchema!=pSchema ){
90312          continue;
90313        }
90314        if( zTab ){
90315          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
90316          assert( zTabName!=0 );
90317          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
90318            continue;
90319          }
90320        }
90321        if( 0==(cntTab++) ){
90322          pMatch = pItem;
90323        }
90324        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
90325          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
90326            /* If there has been exactly one prior match and this match
90327            ** is for the right-hand table of a NATURAL JOIN or is in a
90328            ** USING clause, then skip this match.
90329            */
90330            if( cnt==1 ){
90331              if( pItem->fg.jointype & JT_NATURAL ) continue;
90332              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
90333            }
90334            cnt++;
90335            pMatch = pItem;
90336            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
90337            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
90338            break;
90339          }
90340        }
90341      }
90342      if( pMatch ){
90343        pExpr->iTable = pMatch->iCursor;
90344        pExpr->pTab = pMatch->pTab;
90345        /* RIGHT JOIN not (yet) supported */
90346        assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
90347        if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
90348          ExprSetProperty(pExpr, EP_CanBeNull);
90349        }
90350        pSchema = pExpr->pTab->pSchema;
90351      }
90352    } /* if( pSrcList ) */
90353
90354#ifndef SQLITE_OMIT_TRIGGER
90355    /* If we have not already resolved the name, then maybe
90356    ** it is a new.* or old.* trigger argument reference
90357    */
90358    if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
90359      int op = pParse->eTriggerOp;
90360      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
90361      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
90362        pExpr->iTable = 1;
90363        pTab = pParse->pTriggerTab;
90364      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
90365        pExpr->iTable = 0;
90366        pTab = pParse->pTriggerTab;
90367      }else{
90368        pTab = 0;
90369      }
90370
90371      if( pTab ){
90372        int iCol;
90373        pSchema = pTab->pSchema;
90374        cntTab++;
90375        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
90376          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
90377            if( iCol==pTab->iPKey ){
90378              iCol = -1;
90379            }
90380            break;
90381          }
90382        }
90383        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
90384          /* IMP: R-51414-32910 */
90385          iCol = -1;
90386        }
90387        if( iCol<pTab->nCol ){
90388          cnt++;
90389          if( iCol<0 ){
90390            pExpr->affinity = SQLITE_AFF_INTEGER;
90391          }else if( pExpr->iTable==0 ){
90392            testcase( iCol==31 );
90393            testcase( iCol==32 );
90394            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
90395          }else{
90396            testcase( iCol==31 );
90397            testcase( iCol==32 );
90398            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
90399          }
90400          pExpr->iColumn = (i16)iCol;
90401          pExpr->pTab = pTab;
90402          isTrigger = 1;
90403        }
90404      }
90405    }
90406#endif /* !defined(SQLITE_OMIT_TRIGGER) */
90407
90408    /*
90409    ** Perhaps the name is a reference to the ROWID
90410    */
90411    if( cnt==0
90412     && cntTab==1
90413     && pMatch
90414     && (pNC->ncFlags & NC_IdxExpr)==0
90415     && sqlite3IsRowid(zCol)
90416     && VisibleRowid(pMatch->pTab)
90417    ){
90418      cnt = 1;
90419      pExpr->iColumn = -1;
90420      pExpr->affinity = SQLITE_AFF_INTEGER;
90421    }
90422
90423    /*
90424    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
90425    ** might refer to an result-set alias.  This happens, for example, when
90426    ** we are resolving names in the WHERE clause of the following command:
90427    **
90428    **     SELECT a+b AS x FROM table WHERE x<10;
90429    **
90430    ** In cases like this, replace pExpr with a copy of the expression that
90431    ** forms the result set entry ("a+b" in the example) and return immediately.
90432    ** Note that the expression in the result set should have already been
90433    ** resolved by the time the WHERE clause is resolved.
90434    **
90435    ** The ability to use an output result-set column in the WHERE, GROUP BY,
90436    ** or HAVING clauses, or as part of a larger expression in the ORDER BY
90437    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
90438    ** is supported for backwards compatibility only. Hence, we issue a warning
90439    ** on sqlite3_log() whenever the capability is used.
90440    */
90441    if( (pEList = pNC->pEList)!=0
90442     && zTab==0
90443     && cnt==0
90444    ){
90445      for(j=0; j<pEList->nExpr; j++){
90446        char *zAs = pEList->a[j].zName;
90447        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
90448          Expr *pOrig;
90449          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
90450          assert( pExpr->x.pList==0 );
90451          assert( pExpr->x.pSelect==0 );
90452          pOrig = pEList->a[j].pExpr;
90453          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
90454            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
90455            return WRC_Abort;
90456          }
90457          if( sqlite3ExprVectorSize(pOrig)!=1 ){
90458            sqlite3ErrorMsg(pParse, "row value misused");
90459            return WRC_Abort;
90460          }
90461          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
90462          cnt = 1;
90463          pMatch = 0;
90464          assert( zTab==0 && zDb==0 );
90465          goto lookupname_end;
90466        }
90467      }
90468    }
90469
90470    /* Advance to the next name context.  The loop will exit when either
90471    ** we have a match (cnt>0) or when we run out of name contexts.
90472    */
90473    if( cnt ) break;
90474    pNC = pNC->pNext;
90475    nSubquery++;
90476  }while( pNC );
90477
90478
90479  /*
90480  ** If X and Y are NULL (in other words if only the column name Z is
90481  ** supplied) and the value of Z is enclosed in double-quotes, then
90482  ** Z is a string literal if it doesn't match any column names.  In that
90483  ** case, we need to return right away and not make any changes to
90484  ** pExpr.
90485  **
90486  ** Because no reference was made to outer contexts, the pNC->nRef
90487  ** fields are not changed in any context.
90488  */
90489  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
90490    pExpr->op = TK_STRING;
90491    pExpr->pTab = 0;
90492    return WRC_Prune;
90493  }
90494
90495  /*
90496  ** cnt==0 means there was not match.  cnt>1 means there were two or
90497  ** more matches.  Either way, we have an error.
90498  */
90499  if( cnt!=1 ){
90500    const char *zErr;
90501    zErr = cnt==0 ? "no such column" : "ambiguous column name";
90502    if( zDb ){
90503      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
90504    }else if( zTab ){
90505      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
90506    }else{
90507      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
90508    }
90509    pParse->checkSchema = 1;
90510    pTopNC->nErr++;
90511  }
90512
90513  /* If a column from a table in pSrcList is referenced, then record
90514  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
90515  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
90516  ** column number is greater than the number of bits in the bitmask
90517  ** then set the high-order bit of the bitmask.
90518  */
90519  if( pExpr->iColumn>=0 && pMatch!=0 ){
90520    int n = pExpr->iColumn;
90521    testcase( n==BMS-1 );
90522    if( n>=BMS ){
90523      n = BMS-1;
90524    }
90525    assert( pMatch->iCursor==pExpr->iTable );
90526    pMatch->colUsed |= ((Bitmask)1)<<n;
90527  }
90528
90529  /* Clean up and return
90530  */
90531  sqlite3ExprDelete(db, pExpr->pLeft);
90532  pExpr->pLeft = 0;
90533  sqlite3ExprDelete(db, pExpr->pRight);
90534  pExpr->pRight = 0;
90535  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
90536  ExprSetProperty(pExpr, EP_Leaf);
90537lookupname_end:
90538  if( cnt==1 ){
90539    assert( pNC!=0 );
90540    if( !ExprHasProperty(pExpr, EP_Alias) ){
90541      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
90542    }
90543    /* Increment the nRef value on all name contexts from TopNC up to
90544    ** the point where the name matched. */
90545    for(;;){
90546      assert( pTopNC!=0 );
90547      pTopNC->nRef++;
90548      if( pTopNC==pNC ) break;
90549      pTopNC = pTopNC->pNext;
90550    }
90551    return WRC_Prune;
90552  } else {
90553    return WRC_Abort;
90554  }
90555}
90556
90557/*
90558** Allocate and return a pointer to an expression to load the column iCol
90559** from datasource iSrc in SrcList pSrc.
90560*/
90561SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
90562  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
90563  if( p ){
90564    struct SrcList_item *pItem = &pSrc->a[iSrc];
90565    p->pTab = pItem->pTab;
90566    p->iTable = pItem->iCursor;
90567    if( p->pTab->iPKey==iCol ){
90568      p->iColumn = -1;
90569    }else{
90570      p->iColumn = (ynVar)iCol;
90571      testcase( iCol==BMS );
90572      testcase( iCol==BMS-1 );
90573      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
90574    }
90575  }
90576  return p;
90577}
90578
90579/*
90580** Report an error that an expression is not valid for some set of
90581** pNC->ncFlags values determined by validMask.
90582*/
90583static void notValid(
90584  Parse *pParse,       /* Leave error message here */
90585  NameContext *pNC,    /* The name context */
90586  const char *zMsg,    /* Type of error */
90587  int validMask        /* Set of contexts for which prohibited */
90588){
90589  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
90590  if( (pNC->ncFlags & validMask)!=0 ){
90591    const char *zIn = "partial index WHERE clauses";
90592    if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
90593#ifndef SQLITE_OMIT_CHECK
90594    else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
90595#endif
90596    sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
90597  }
90598}
90599
90600/*
90601** Expression p should encode a floating point value between 1.0 and 0.0.
90602** Return 1024 times this value.  Or return -1 if p is not a floating point
90603** value between 1.0 and 0.0.
90604*/
90605static int exprProbability(Expr *p){
90606  double r = -1.0;
90607  if( p->op!=TK_FLOAT ) return -1;
90608  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
90609  assert( r>=0.0 );
90610  if( r>1.0 ) return -1;
90611  return (int)(r*134217728.0);
90612}
90613
90614/*
90615** This routine is callback for sqlite3WalkExpr().
90616**
90617** Resolve symbolic names into TK_COLUMN operators for the current
90618** node in the expression tree.  Return 0 to continue the search down
90619** the tree or 2 to abort the tree walk.
90620**
90621** This routine also does error checking and name resolution for
90622** function names.  The operator for aggregate functions is changed
90623** to TK_AGG_FUNCTION.
90624*/
90625static int resolveExprStep(Walker *pWalker, Expr *pExpr){
90626  NameContext *pNC;
90627  Parse *pParse;
90628
90629  pNC = pWalker->u.pNC;
90630  assert( pNC!=0 );
90631  pParse = pNC->pParse;
90632  assert( pParse==pWalker->pParse );
90633
90634#ifndef NDEBUG
90635  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
90636    SrcList *pSrcList = pNC->pSrcList;
90637    int i;
90638    for(i=0; i<pNC->pSrcList->nSrc; i++){
90639      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
90640    }
90641  }
90642#endif
90643  switch( pExpr->op ){
90644
90645#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
90646    /* The special operator TK_ROW means use the rowid for the first
90647    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
90648    ** clause processing on UPDATE and DELETE statements.
90649    */
90650    case TK_ROW: {
90651      SrcList *pSrcList = pNC->pSrcList;
90652      struct SrcList_item *pItem;
90653      assert( pSrcList && pSrcList->nSrc==1 );
90654      pItem = pSrcList->a;
90655      pExpr->op = TK_COLUMN;
90656      pExpr->pTab = pItem->pTab;
90657      pExpr->iTable = pItem->iCursor;
90658      pExpr->iColumn = -1;
90659      pExpr->affinity = SQLITE_AFF_INTEGER;
90660      break;
90661    }
90662#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
90663          && !defined(SQLITE_OMIT_SUBQUERY) */
90664
90665    /* A column name:                    ID
90666    ** Or table name and column name:    ID.ID
90667    ** Or a database, table and column:  ID.ID.ID
90668    **
90669    ** The TK_ID and TK_OUT cases are combined so that there will only
90670    ** be one call to lookupName().  Then the compiler will in-line
90671    ** lookupName() for a size reduction and performance increase.
90672    */
90673    case TK_ID:
90674    case TK_DOT: {
90675      const char *zColumn;
90676      const char *zTable;
90677      const char *zDb;
90678      Expr *pRight;
90679
90680      if( pExpr->op==TK_ID ){
90681        zDb = 0;
90682        zTable = 0;
90683        zColumn = pExpr->u.zToken;
90684      }else{
90685        notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
90686        pRight = pExpr->pRight;
90687        if( pRight->op==TK_ID ){
90688          zDb = 0;
90689          zTable = pExpr->pLeft->u.zToken;
90690          zColumn = pRight->u.zToken;
90691        }else{
90692          assert( pRight->op==TK_DOT );
90693          zDb = pExpr->pLeft->u.zToken;
90694          zTable = pRight->pLeft->u.zToken;
90695          zColumn = pRight->pRight->u.zToken;
90696        }
90697      }
90698      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
90699    }
90700
90701    /* Resolve function names
90702    */
90703    case TK_FUNCTION: {
90704      ExprList *pList = pExpr->x.pList;    /* The argument list */
90705      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
90706      int no_such_func = 0;       /* True if no such function exists */
90707      int wrong_num_args = 0;     /* True if wrong number of arguments */
90708      int is_agg = 0;             /* True if is an aggregate function */
90709      int nId;                    /* Number of characters in function name */
90710      const char *zId;            /* The function name. */
90711      FuncDef *pDef;              /* Information about the function */
90712      u8 enc = ENC(pParse->db);   /* The database encoding */
90713
90714      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
90715      zId = pExpr->u.zToken;
90716      nId = sqlite3Strlen30(zId);
90717      pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
90718      if( pDef==0 ){
90719        pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
90720        if( pDef==0 ){
90721          no_such_func = 1;
90722        }else{
90723          wrong_num_args = 1;
90724        }
90725      }else{
90726        is_agg = pDef->xFinalize!=0;
90727        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
90728          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
90729          if( n==2 ){
90730            pExpr->iTable = exprProbability(pList->a[1].pExpr);
90731            if( pExpr->iTable<0 ){
90732              sqlite3ErrorMsg(pParse,
90733                "second argument to likelihood() must be a "
90734                "constant between 0.0 and 1.0");
90735              pNC->nErr++;
90736            }
90737          }else{
90738            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
90739            ** equivalent to likelihood(X, 0.0625).
90740            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
90741            ** short-hand for likelihood(X,0.0625).
90742            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
90743            ** for likelihood(X,0.9375).
90744            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
90745            ** to likelihood(X,0.9375). */
90746            /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
90747            pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
90748          }
90749        }
90750#ifndef SQLITE_OMIT_AUTHORIZATION
90751        {
90752          int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
90753          if( auth!=SQLITE_OK ){
90754            if( auth==SQLITE_DENY ){
90755              sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
90756                                      pDef->zName);
90757              pNC->nErr++;
90758            }
90759            pExpr->op = TK_NULL;
90760            return WRC_Prune;
90761          }
90762        }
90763#endif
90764        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
90765          /* For the purposes of the EP_ConstFunc flag, date and time
90766          ** functions and other functions that change slowly are considered
90767          ** constant because they are constant for the duration of one query */
90768          ExprSetProperty(pExpr,EP_ConstFunc);
90769        }
90770        if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
90771          /* Date/time functions that use 'now', and other functions like
90772          ** sqlite_version() that might change over time cannot be used
90773          ** in an index. */
90774          notValid(pParse, pNC, "non-deterministic functions",
90775                   NC_IdxExpr|NC_PartIdx);
90776        }
90777      }
90778      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
90779        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
90780        pNC->nErr++;
90781        is_agg = 0;
90782      }else if( no_such_func && pParse->db->init.busy==0
90783#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
90784                && pParse->explain==0
90785#endif
90786      ){
90787        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
90788        pNC->nErr++;
90789      }else if( wrong_num_args ){
90790        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
90791             nId, zId);
90792        pNC->nErr++;
90793      }
90794      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
90795      sqlite3WalkExprList(pWalker, pList);
90796      if( is_agg ){
90797        NameContext *pNC2 = pNC;
90798        pExpr->op = TK_AGG_FUNCTION;
90799        pExpr->op2 = 0;
90800        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
90801          pExpr->op2++;
90802          pNC2 = pNC2->pNext;
90803        }
90804        assert( pDef!=0 );
90805        if( pNC2 ){
90806          assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
90807          testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
90808          pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
90809
90810        }
90811        pNC->ncFlags |= NC_AllowAgg;
90812      }
90813      /* FIX ME:  Compute pExpr->affinity based on the expected return
90814      ** type of the function
90815      */
90816      return WRC_Prune;
90817    }
90818#ifndef SQLITE_OMIT_SUBQUERY
90819    case TK_SELECT:
90820    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
90821#endif
90822    case TK_IN: {
90823      testcase( pExpr->op==TK_IN );
90824      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90825        int nRef = pNC->nRef;
90826        notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
90827        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
90828        assert( pNC->nRef>=nRef );
90829        if( nRef!=pNC->nRef ){
90830          ExprSetProperty(pExpr, EP_VarSelect);
90831          pNC->ncFlags |= NC_VarSelect;
90832        }
90833      }
90834      break;
90835    }
90836    case TK_VARIABLE: {
90837      notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
90838      break;
90839    }
90840    case TK_BETWEEN:
90841    case TK_EQ:
90842    case TK_NE:
90843    case TK_LT:
90844    case TK_LE:
90845    case TK_GT:
90846    case TK_GE:
90847    case TK_IS:
90848    case TK_ISNOT: {
90849      int nLeft, nRight;
90850      if( pParse->db->mallocFailed ) break;
90851      assert( pExpr->pLeft!=0 );
90852      nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
90853      if( pExpr->op==TK_BETWEEN ){
90854        nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
90855        if( nRight==nLeft ){
90856          nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
90857        }
90858      }else{
90859        assert( pExpr->pRight!=0 );
90860        nRight = sqlite3ExprVectorSize(pExpr->pRight);
90861      }
90862      if( nLeft!=nRight ){
90863        testcase( pExpr->op==TK_EQ );
90864        testcase( pExpr->op==TK_NE );
90865        testcase( pExpr->op==TK_LT );
90866        testcase( pExpr->op==TK_LE );
90867        testcase( pExpr->op==TK_GT );
90868        testcase( pExpr->op==TK_GE );
90869        testcase( pExpr->op==TK_IS );
90870        testcase( pExpr->op==TK_ISNOT );
90871        testcase( pExpr->op==TK_BETWEEN );
90872        sqlite3ErrorMsg(pParse, "row value misused");
90873      }
90874      break;
90875    }
90876  }
90877  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
90878}
90879
90880/*
90881** pEList is a list of expressions which are really the result set of the
90882** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
90883** This routine checks to see if pE is a simple identifier which corresponds
90884** to the AS-name of one of the terms of the expression list.  If it is,
90885** this routine return an integer between 1 and N where N is the number of
90886** elements in pEList, corresponding to the matching entry.  If there is
90887** no match, or if pE is not a simple identifier, then this routine
90888** return 0.
90889**
90890** pEList has been resolved.  pE has not.
90891*/
90892static int resolveAsName(
90893  Parse *pParse,     /* Parsing context for error messages */
90894  ExprList *pEList,  /* List of expressions to scan */
90895  Expr *pE           /* Expression we are trying to match */
90896){
90897  int i;             /* Loop counter */
90898
90899  UNUSED_PARAMETER(pParse);
90900
90901  if( pE->op==TK_ID ){
90902    char *zCol = pE->u.zToken;
90903    for(i=0; i<pEList->nExpr; i++){
90904      char *zAs = pEList->a[i].zName;
90905      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
90906        return i+1;
90907      }
90908    }
90909  }
90910  return 0;
90911}
90912
90913/*
90914** pE is a pointer to an expression which is a single term in the
90915** ORDER BY of a compound SELECT.  The expression has not been
90916** name resolved.
90917**
90918** At the point this routine is called, we already know that the
90919** ORDER BY term is not an integer index into the result set.  That
90920** case is handled by the calling routine.
90921**
90922** Attempt to match pE against result set columns in the left-most
90923** SELECT statement.  Return the index i of the matching column,
90924** as an indication to the caller that it should sort by the i-th column.
90925** The left-most column is 1.  In other words, the value returned is the
90926** same integer value that would be used in the SQL statement to indicate
90927** the column.
90928**
90929** If there is no match, return 0.  Return -1 if an error occurs.
90930*/
90931static int resolveOrderByTermToExprList(
90932  Parse *pParse,     /* Parsing context for error messages */
90933  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
90934  Expr *pE           /* The specific ORDER BY term */
90935){
90936  int i;             /* Loop counter */
90937  ExprList *pEList;  /* The columns of the result set */
90938  NameContext nc;    /* Name context for resolving pE */
90939  sqlite3 *db;       /* Database connection */
90940  int rc;            /* Return code from subprocedures */
90941  u8 savedSuppErr;   /* Saved value of db->suppressErr */
90942
90943  assert( sqlite3ExprIsInteger(pE, &i)==0 );
90944  pEList = pSelect->pEList;
90945
90946  /* Resolve all names in the ORDER BY term expression
90947  */
90948  memset(&nc, 0, sizeof(nc));
90949  nc.pParse = pParse;
90950  nc.pSrcList = pSelect->pSrc;
90951  nc.pEList = pEList;
90952  nc.ncFlags = NC_AllowAgg;
90953  nc.nErr = 0;
90954  db = pParse->db;
90955  savedSuppErr = db->suppressErr;
90956  db->suppressErr = 1;
90957  rc = sqlite3ResolveExprNames(&nc, pE);
90958  db->suppressErr = savedSuppErr;
90959  if( rc ) return 0;
90960
90961  /* Try to match the ORDER BY expression against an expression
90962  ** in the result set.  Return an 1-based index of the matching
90963  ** result-set entry.
90964  */
90965  for(i=0; i<pEList->nExpr; i++){
90966    if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
90967      return i+1;
90968    }
90969  }
90970
90971  /* If no match, return 0. */
90972  return 0;
90973}
90974
90975/*
90976** Generate an ORDER BY or GROUP BY term out-of-range error.
90977*/
90978static void resolveOutOfRangeError(
90979  Parse *pParse,         /* The error context into which to write the error */
90980  const char *zType,     /* "ORDER" or "GROUP" */
90981  int i,                 /* The index (1-based) of the term out of range */
90982  int mx                 /* Largest permissible value of i */
90983){
90984  sqlite3ErrorMsg(pParse,
90985    "%r %s BY term out of range - should be "
90986    "between 1 and %d", i, zType, mx);
90987}
90988
90989/*
90990** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
90991** each term of the ORDER BY clause is a constant integer between 1
90992** and N where N is the number of columns in the compound SELECT.
90993**
90994** ORDER BY terms that are already an integer between 1 and N are
90995** unmodified.  ORDER BY terms that are integers outside the range of
90996** 1 through N generate an error.  ORDER BY terms that are expressions
90997** are matched against result set expressions of compound SELECT
90998** beginning with the left-most SELECT and working toward the right.
90999** At the first match, the ORDER BY expression is transformed into
91000** the integer column number.
91001**
91002** Return the number of errors seen.
91003*/
91004static int resolveCompoundOrderBy(
91005  Parse *pParse,        /* Parsing context.  Leave error messages here */
91006  Select *pSelect       /* The SELECT statement containing the ORDER BY */
91007){
91008  int i;
91009  ExprList *pOrderBy;
91010  ExprList *pEList;
91011  sqlite3 *db;
91012  int moreToDo = 1;
91013
91014  pOrderBy = pSelect->pOrderBy;
91015  if( pOrderBy==0 ) return 0;
91016  db = pParse->db;
91017#if SQLITE_MAX_COLUMN
91018  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
91019    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
91020    return 1;
91021  }
91022#endif
91023  for(i=0; i<pOrderBy->nExpr; i++){
91024    pOrderBy->a[i].done = 0;
91025  }
91026  pSelect->pNext = 0;
91027  while( pSelect->pPrior ){
91028    pSelect->pPrior->pNext = pSelect;
91029    pSelect = pSelect->pPrior;
91030  }
91031  while( pSelect && moreToDo ){
91032    struct ExprList_item *pItem;
91033    moreToDo = 0;
91034    pEList = pSelect->pEList;
91035    assert( pEList!=0 );
91036    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
91037      int iCol = -1;
91038      Expr *pE, *pDup;
91039      if( pItem->done ) continue;
91040      pE = sqlite3ExprSkipCollate(pItem->pExpr);
91041      if( sqlite3ExprIsInteger(pE, &iCol) ){
91042        if( iCol<=0 || iCol>pEList->nExpr ){
91043          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
91044          return 1;
91045        }
91046      }else{
91047        iCol = resolveAsName(pParse, pEList, pE);
91048        if( iCol==0 ){
91049          pDup = sqlite3ExprDup(db, pE, 0);
91050          if( !db->mallocFailed ){
91051            assert(pDup);
91052            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
91053          }
91054          sqlite3ExprDelete(db, pDup);
91055        }
91056      }
91057      if( iCol>0 ){
91058        /* Convert the ORDER BY term into an integer column number iCol,
91059        ** taking care to preserve the COLLATE clause if it exists */
91060        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
91061        if( pNew==0 ) return 1;
91062        pNew->flags |= EP_IntValue;
91063        pNew->u.iValue = iCol;
91064        if( pItem->pExpr==pE ){
91065          pItem->pExpr = pNew;
91066        }else{
91067          Expr *pParent = pItem->pExpr;
91068          assert( pParent->op==TK_COLLATE );
91069          while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
91070          assert( pParent->pLeft==pE );
91071          pParent->pLeft = pNew;
91072        }
91073        sqlite3ExprDelete(db, pE);
91074        pItem->u.x.iOrderByCol = (u16)iCol;
91075        pItem->done = 1;
91076      }else{
91077        moreToDo = 1;
91078      }
91079    }
91080    pSelect = pSelect->pNext;
91081  }
91082  for(i=0; i<pOrderBy->nExpr; i++){
91083    if( pOrderBy->a[i].done==0 ){
91084      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
91085            "column in the result set", i+1);
91086      return 1;
91087    }
91088  }
91089  return 0;
91090}
91091
91092/*
91093** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
91094** the SELECT statement pSelect.  If any term is reference to a
91095** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
91096** field) then convert that term into a copy of the corresponding result set
91097** column.
91098**
91099** If any errors are detected, add an error message to pParse and
91100** return non-zero.  Return zero if no errors are seen.
91101*/
91102SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
91103  Parse *pParse,        /* Parsing context.  Leave error messages here */
91104  Select *pSelect,      /* The SELECT statement containing the clause */
91105  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
91106  const char *zType     /* "ORDER" or "GROUP" */
91107){
91108  int i;
91109  sqlite3 *db = pParse->db;
91110  ExprList *pEList;
91111  struct ExprList_item *pItem;
91112
91113  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
91114#if SQLITE_MAX_COLUMN
91115  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
91116    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
91117    return 1;
91118  }
91119#endif
91120  pEList = pSelect->pEList;
91121  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
91122  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
91123    if( pItem->u.x.iOrderByCol ){
91124      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
91125        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
91126        return 1;
91127      }
91128      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
91129                   zType,0);
91130    }
91131  }
91132  return 0;
91133}
91134
91135/*
91136** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
91137** The Name context of the SELECT statement is pNC.  zType is either
91138** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
91139**
91140** This routine resolves each term of the clause into an expression.
91141** If the order-by term is an integer I between 1 and N (where N is the
91142** number of columns in the result set of the SELECT) then the expression
91143** in the resolution is a copy of the I-th result-set expression.  If
91144** the order-by term is an identifier that corresponds to the AS-name of
91145** a result-set expression, then the term resolves to a copy of the
91146** result-set expression.  Otherwise, the expression is resolved in
91147** the usual way - using sqlite3ResolveExprNames().
91148**
91149** This routine returns the number of errors.  If errors occur, then
91150** an appropriate error message might be left in pParse.  (OOM errors
91151** excepted.)
91152*/
91153static int resolveOrderGroupBy(
91154  NameContext *pNC,     /* The name context of the SELECT statement */
91155  Select *pSelect,      /* The SELECT statement holding pOrderBy */
91156  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
91157  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
91158){
91159  int i, j;                      /* Loop counters */
91160  int iCol;                      /* Column number */
91161  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
91162  Parse *pParse;                 /* Parsing context */
91163  int nResult;                   /* Number of terms in the result set */
91164
91165  if( pOrderBy==0 ) return 0;
91166  nResult = pSelect->pEList->nExpr;
91167  pParse = pNC->pParse;
91168  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
91169    Expr *pE = pItem->pExpr;
91170    Expr *pE2 = sqlite3ExprSkipCollate(pE);
91171    if( zType[0]!='G' ){
91172      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
91173      if( iCol>0 ){
91174        /* If an AS-name match is found, mark this ORDER BY column as being
91175        ** a copy of the iCol-th result-set column.  The subsequent call to
91176        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
91177        ** copy of the iCol-th result-set expression. */
91178        pItem->u.x.iOrderByCol = (u16)iCol;
91179        continue;
91180      }
91181    }
91182    if( sqlite3ExprIsInteger(pE2, &iCol) ){
91183      /* The ORDER BY term is an integer constant.  Again, set the column
91184      ** number so that sqlite3ResolveOrderGroupBy() will convert the
91185      ** order-by term to a copy of the result-set expression */
91186      if( iCol<1 || iCol>0xffff ){
91187        resolveOutOfRangeError(pParse, zType, i+1, nResult);
91188        return 1;
91189      }
91190      pItem->u.x.iOrderByCol = (u16)iCol;
91191      continue;
91192    }
91193
91194    /* Otherwise, treat the ORDER BY term as an ordinary expression */
91195    pItem->u.x.iOrderByCol = 0;
91196    if( sqlite3ResolveExprNames(pNC, pE) ){
91197      return 1;
91198    }
91199    for(j=0; j<pSelect->pEList->nExpr; j++){
91200      if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
91201        pItem->u.x.iOrderByCol = j+1;
91202      }
91203    }
91204  }
91205  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
91206}
91207
91208/*
91209** Resolve names in the SELECT statement p and all of its descendants.
91210*/
91211static int resolveSelectStep(Walker *pWalker, Select *p){
91212  NameContext *pOuterNC;  /* Context that contains this SELECT */
91213  NameContext sNC;        /* Name context of this SELECT */
91214  int isCompound;         /* True if p is a compound select */
91215  int nCompound;          /* Number of compound terms processed so far */
91216  Parse *pParse;          /* Parsing context */
91217  int i;                  /* Loop counter */
91218  ExprList *pGroupBy;     /* The GROUP BY clause */
91219  Select *pLeftmost;      /* Left-most of SELECT of a compound */
91220  sqlite3 *db;            /* Database connection */
91221
91222
91223  assert( p!=0 );
91224  if( p->selFlags & SF_Resolved ){
91225    return WRC_Prune;
91226  }
91227  pOuterNC = pWalker->u.pNC;
91228  pParse = pWalker->pParse;
91229  db = pParse->db;
91230
91231  /* Normally sqlite3SelectExpand() will be called first and will have
91232  ** already expanded this SELECT.  However, if this is a subquery within
91233  ** an expression, sqlite3ResolveExprNames() will be called without a
91234  ** prior call to sqlite3SelectExpand().  When that happens, let
91235  ** sqlite3SelectPrep() do all of the processing for this SELECT.
91236  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
91237  ** this routine in the correct order.
91238  */
91239  if( (p->selFlags & SF_Expanded)==0 ){
91240    sqlite3SelectPrep(pParse, p, pOuterNC);
91241    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
91242  }
91243
91244  isCompound = p->pPrior!=0;
91245  nCompound = 0;
91246  pLeftmost = p;
91247  while( p ){
91248    assert( (p->selFlags & SF_Expanded)!=0 );
91249    assert( (p->selFlags & SF_Resolved)==0 );
91250    p->selFlags |= SF_Resolved;
91251
91252    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
91253    ** are not allowed to refer to any names, so pass an empty NameContext.
91254    */
91255    memset(&sNC, 0, sizeof(sNC));
91256    sNC.pParse = pParse;
91257    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
91258        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
91259      return WRC_Abort;
91260    }
91261
91262    /* If the SF_Converted flags is set, then this Select object was
91263    ** was created by the convertCompoundSelectToSubquery() function.
91264    ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
91265    ** as if it were part of the sub-query, not the parent. This block
91266    ** moves the pOrderBy down to the sub-query. It will be moved back
91267    ** after the names have been resolved.  */
91268    if( p->selFlags & SF_Converted ){
91269      Select *pSub = p->pSrc->a[0].pSelect;
91270      assert( p->pSrc->nSrc==1 && p->pOrderBy );
91271      assert( pSub->pPrior && pSub->pOrderBy==0 );
91272      pSub->pOrderBy = p->pOrderBy;
91273      p->pOrderBy = 0;
91274    }
91275
91276    /* Recursively resolve names in all subqueries
91277    */
91278    for(i=0; i<p->pSrc->nSrc; i++){
91279      struct SrcList_item *pItem = &p->pSrc->a[i];
91280      if( pItem->pSelect ){
91281        NameContext *pNC;         /* Used to iterate name contexts */
91282        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
91283        const char *zSavedContext = pParse->zAuthContext;
91284
91285        /* Count the total number of references to pOuterNC and all of its
91286        ** parent contexts. After resolving references to expressions in
91287        ** pItem->pSelect, check if this value has changed. If so, then
91288        ** SELECT statement pItem->pSelect must be correlated. Set the
91289        ** pItem->fg.isCorrelated flag if this is the case. */
91290        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
91291
91292        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
91293        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
91294        pParse->zAuthContext = zSavedContext;
91295        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
91296
91297        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
91298        assert( pItem->fg.isCorrelated==0 && nRef<=0 );
91299        pItem->fg.isCorrelated = (nRef!=0);
91300      }
91301    }
91302
91303    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
91304    ** resolve the result-set expression list.
91305    */
91306    sNC.ncFlags = NC_AllowAgg;
91307    sNC.pSrcList = p->pSrc;
91308    sNC.pNext = pOuterNC;
91309
91310    /* Resolve names in the result set. */
91311    if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
91312
91313    /* If there are no aggregate functions in the result-set, and no GROUP BY
91314    ** expression, do not allow aggregates in any of the other expressions.
91315    */
91316    assert( (p->selFlags & SF_Aggregate)==0 );
91317    pGroupBy = p->pGroupBy;
91318    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
91319      assert( NC_MinMaxAgg==SF_MinMaxAgg );
91320      p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
91321    }else{
91322      sNC.ncFlags &= ~NC_AllowAgg;
91323    }
91324
91325    /* If a HAVING clause is present, then there must be a GROUP BY clause.
91326    */
91327    if( p->pHaving && !pGroupBy ){
91328      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
91329      return WRC_Abort;
91330    }
91331
91332    /* Add the output column list to the name-context before parsing the
91333    ** other expressions in the SELECT statement. This is so that
91334    ** expressions in the WHERE clause (etc.) can refer to expressions by
91335    ** aliases in the result set.
91336    **
91337    ** Minor point: If this is the case, then the expression will be
91338    ** re-evaluated for each reference to it.
91339    */
91340    sNC.pEList = p->pEList;
91341    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
91342    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
91343
91344    /* Resolve names in table-valued-function arguments */
91345    for(i=0; i<p->pSrc->nSrc; i++){
91346      struct SrcList_item *pItem = &p->pSrc->a[i];
91347      if( pItem->fg.isTabFunc
91348       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
91349      ){
91350        return WRC_Abort;
91351      }
91352    }
91353
91354    /* The ORDER BY and GROUP BY clauses may not refer to terms in
91355    ** outer queries
91356    */
91357    sNC.pNext = 0;
91358    sNC.ncFlags |= NC_AllowAgg;
91359
91360    /* If this is a converted compound query, move the ORDER BY clause from
91361    ** the sub-query back to the parent query. At this point each term
91362    ** within the ORDER BY clause has been transformed to an integer value.
91363    ** These integers will be replaced by copies of the corresponding result
91364    ** set expressions by the call to resolveOrderGroupBy() below.  */
91365    if( p->selFlags & SF_Converted ){
91366      Select *pSub = p->pSrc->a[0].pSelect;
91367      p->pOrderBy = pSub->pOrderBy;
91368      pSub->pOrderBy = 0;
91369    }
91370
91371    /* Process the ORDER BY clause for singleton SELECT statements.
91372    ** The ORDER BY clause for compounds SELECT statements is handled
91373    ** below, after all of the result-sets for all of the elements of
91374    ** the compound have been resolved.
91375    **
91376    ** If there is an ORDER BY clause on a term of a compound-select other
91377    ** than the right-most term, then that is a syntax error.  But the error
91378    ** is not detected until much later, and so we need to go ahead and
91379    ** resolve those symbols on the incorrect ORDER BY for consistency.
91380    */
91381    if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
91382     && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
91383    ){
91384      return WRC_Abort;
91385    }
91386    if( db->mallocFailed ){
91387      return WRC_Abort;
91388    }
91389
91390    /* Resolve the GROUP BY clause.  At the same time, make sure
91391    ** the GROUP BY clause does not contain aggregate functions.
91392    */
91393    if( pGroupBy ){
91394      struct ExprList_item *pItem;
91395
91396      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
91397        return WRC_Abort;
91398      }
91399      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
91400        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
91401          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
91402              "the GROUP BY clause");
91403          return WRC_Abort;
91404        }
91405      }
91406    }
91407
91408    /* If this is part of a compound SELECT, check that it has the right
91409    ** number of expressions in the select list. */
91410    if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
91411      sqlite3SelectWrongNumTermsError(pParse, p->pNext);
91412      return WRC_Abort;
91413    }
91414
91415    /* Advance to the next term of the compound
91416    */
91417    p = p->pPrior;
91418    nCompound++;
91419  }
91420
91421  /* Resolve the ORDER BY on a compound SELECT after all terms of
91422  ** the compound have been resolved.
91423  */
91424  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
91425    return WRC_Abort;
91426  }
91427
91428  return WRC_Prune;
91429}
91430
91431/*
91432** This routine walks an expression tree and resolves references to
91433** table columns and result-set columns.  At the same time, do error
91434** checking on function usage and set a flag if any aggregate functions
91435** are seen.
91436**
91437** To resolve table columns references we look for nodes (or subtrees) of the
91438** form X.Y.Z or Y.Z or just Z where
91439**
91440**      X:   The name of a database.  Ex:  "main" or "temp" or
91441**           the symbolic name assigned to an ATTACH-ed database.
91442**
91443**      Y:   The name of a table in a FROM clause.  Or in a trigger
91444**           one of the special names "old" or "new".
91445**
91446**      Z:   The name of a column in table Y.
91447**
91448** The node at the root of the subtree is modified as follows:
91449**
91450**    Expr.op        Changed to TK_COLUMN
91451**    Expr.pTab      Points to the Table object for X.Y
91452**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
91453**    Expr.iTable    The VDBE cursor number for X.Y
91454**
91455**
91456** To resolve result-set references, look for expression nodes of the
91457** form Z (with no X and Y prefix) where the Z matches the right-hand
91458** size of an AS clause in the result-set of a SELECT.  The Z expression
91459** is replaced by a copy of the left-hand side of the result-set expression.
91460** Table-name and function resolution occurs on the substituted expression
91461** tree.  For example, in:
91462**
91463**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
91464**
91465** The "x" term of the order by is replaced by "a+b" to render:
91466**
91467**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
91468**
91469** Function calls are checked to make sure that the function is
91470** defined and that the correct number of arguments are specified.
91471** If the function is an aggregate function, then the NC_HasAgg flag is
91472** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
91473** If an expression contains aggregate functions then the EP_Agg
91474** property on the expression is set.
91475**
91476** An error message is left in pParse if anything is amiss.  The number
91477** if errors is returned.
91478*/
91479SQLITE_PRIVATE int sqlite3ResolveExprNames(
91480  NameContext *pNC,       /* Namespace to resolve expressions in. */
91481  Expr *pExpr             /* The expression to be analyzed. */
91482){
91483  u16 savedHasAgg;
91484  Walker w;
91485
91486  if( pExpr==0 ) return SQLITE_OK;
91487  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
91488  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
91489  w.pParse = pNC->pParse;
91490  w.xExprCallback = resolveExprStep;
91491  w.xSelectCallback = resolveSelectStep;
91492  w.xSelectCallback2 = 0;
91493  w.u.pNC = pNC;
91494#if SQLITE_MAX_EXPR_DEPTH>0
91495  w.pParse->nHeight += pExpr->nHeight;
91496  if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
91497    return SQLITE_ERROR;
91498  }
91499#endif
91500  sqlite3WalkExpr(&w, pExpr);
91501#if SQLITE_MAX_EXPR_DEPTH>0
91502  w.pParse->nHeight -= pExpr->nHeight;
91503#endif
91504  if( pNC->ncFlags & NC_HasAgg ){
91505    ExprSetProperty(pExpr, EP_Agg);
91506  }
91507  pNC->ncFlags |= savedHasAgg;
91508  return pNC->nErr>0 || w.pParse->nErr>0;
91509}
91510
91511/*
91512** Resolve all names for all expression in an expression list.  This is
91513** just like sqlite3ResolveExprNames() except that it works for an expression
91514** list rather than a single expression.
91515*/
91516SQLITE_PRIVATE int sqlite3ResolveExprListNames(
91517  NameContext *pNC,       /* Namespace to resolve expressions in. */
91518  ExprList *pList         /* The expression list to be analyzed. */
91519){
91520  int i;
91521  if( pList ){
91522    for(i=0; i<pList->nExpr; i++){
91523      if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
91524    }
91525  }
91526  return WRC_Continue;
91527}
91528
91529/*
91530** Resolve all names in all expressions of a SELECT and in all
91531** decendents of the SELECT, including compounds off of p->pPrior,
91532** subqueries in expressions, and subqueries used as FROM clause
91533** terms.
91534**
91535** See sqlite3ResolveExprNames() for a description of the kinds of
91536** transformations that occur.
91537**
91538** All SELECT statements should have been expanded using
91539** sqlite3SelectExpand() prior to invoking this routine.
91540*/
91541SQLITE_PRIVATE void sqlite3ResolveSelectNames(
91542  Parse *pParse,         /* The parser context */
91543  Select *p,             /* The SELECT statement being coded. */
91544  NameContext *pOuterNC  /* Name context for parent SELECT statement */
91545){
91546  Walker w;
91547
91548  assert( p!=0 );
91549  w.xExprCallback = resolveExprStep;
91550  w.xSelectCallback = resolveSelectStep;
91551  w.xSelectCallback2 = 0;
91552  w.pParse = pParse;
91553  w.u.pNC = pOuterNC;
91554  sqlite3WalkSelect(&w, p);
91555}
91556
91557/*
91558** Resolve names in expressions that can only reference a single table:
91559**
91560**    *   CHECK constraints
91561**    *   WHERE clauses on partial indices
91562**
91563** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
91564** is set to -1 and the Expr.iColumn value is set to the column number.
91565**
91566** Any errors cause an error message to be set in pParse.
91567*/
91568SQLITE_PRIVATE void sqlite3ResolveSelfReference(
91569  Parse *pParse,      /* Parsing context */
91570  Table *pTab,        /* The table being referenced */
91571  int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
91572  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
91573  ExprList *pList     /* Expression list to resolve.  May be NUL. */
91574){
91575  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
91576  NameContext sNC;                /* Name context for pParse->pNewTable */
91577
91578  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
91579  memset(&sNC, 0, sizeof(sNC));
91580  memset(&sSrc, 0, sizeof(sSrc));
91581  sSrc.nSrc = 1;
91582  sSrc.a[0].zName = pTab->zName;
91583  sSrc.a[0].pTab = pTab;
91584  sSrc.a[0].iCursor = -1;
91585  sNC.pParse = pParse;
91586  sNC.pSrcList = &sSrc;
91587  sNC.ncFlags = type;
91588  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
91589  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
91590}
91591
91592/************** End of resolve.c *********************************************/
91593/************** Begin file expr.c ********************************************/
91594/*
91595** 2001 September 15
91596**
91597** The author disclaims copyright to this source code.  In place of
91598** a legal notice, here is a blessing:
91599**
91600**    May you do good and not evil.
91601**    May you find forgiveness for yourself and forgive others.
91602**    May you share freely, never taking more than you give.
91603**
91604*************************************************************************
91605** This file contains routines used for analyzing expressions and
91606** for generating VDBE code that evaluates expressions in SQLite.
91607*/
91608/* #include "sqliteInt.h" */
91609
91610/* Forward declarations */
91611static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
91612static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
91613
91614/*
91615** Return the affinity character for a single column of a table.
91616*/
91617SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
91618  assert( iCol<pTab->nCol );
91619  return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
91620}
91621
91622/*
91623** Return the 'affinity' of the expression pExpr if any.
91624**
91625** If pExpr is a column, a reference to a column via an 'AS' alias,
91626** or a sub-select with a column as the return value, then the
91627** affinity of that column is returned. Otherwise, 0x00 is returned,
91628** indicating no affinity for the expression.
91629**
91630** i.e. the WHERE clause expressions in the following statements all
91631** have an affinity:
91632**
91633** CREATE TABLE t1(a);
91634** SELECT * FROM t1 WHERE a;
91635** SELECT a AS b FROM t1 WHERE b;
91636** SELECT * FROM t1 WHERE (select a from t1);
91637*/
91638SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
91639  int op;
91640  pExpr = sqlite3ExprSkipCollate(pExpr);
91641  if( pExpr->flags & EP_Generic ) return 0;
91642  op = pExpr->op;
91643  if( op==TK_SELECT ){
91644    assert( pExpr->flags&EP_xIsSelect );
91645    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
91646  }
91647  if( op==TK_REGISTER ) op = pExpr->op2;
91648#ifndef SQLITE_OMIT_CAST
91649  if( op==TK_CAST ){
91650    assert( !ExprHasProperty(pExpr, EP_IntValue) );
91651    return sqlite3AffinityType(pExpr->u.zToken, 0);
91652  }
91653#endif
91654  if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
91655    return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
91656  }
91657  if( op==TK_SELECT_COLUMN ){
91658    assert( pExpr->pLeft->flags&EP_xIsSelect );
91659    return sqlite3ExprAffinity(
91660        pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
91661    );
91662  }
91663  return pExpr->affinity;
91664}
91665
91666/*
91667** Set the collating sequence for expression pExpr to be the collating
91668** sequence named by pToken.   Return a pointer to a new Expr node that
91669** implements the COLLATE operator.
91670**
91671** If a memory allocation error occurs, that fact is recorded in pParse->db
91672** and the pExpr parameter is returned unchanged.
91673*/
91674SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
91675  Parse *pParse,           /* Parsing context */
91676  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
91677  const Token *pCollName,  /* Name of collating sequence */
91678  int dequote              /* True to dequote pCollName */
91679){
91680  if( pCollName->n>0 ){
91681    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
91682    if( pNew ){
91683      pNew->pLeft = pExpr;
91684      pNew->flags |= EP_Collate|EP_Skip;
91685      pExpr = pNew;
91686    }
91687  }
91688  return pExpr;
91689}
91690SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
91691  Token s;
91692  assert( zC!=0 );
91693  sqlite3TokenInit(&s, (char*)zC);
91694  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
91695}
91696
91697/*
91698** Skip over any TK_COLLATE operators and any unlikely()
91699** or likelihood() function at the root of an expression.
91700*/
91701SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
91702  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
91703    if( ExprHasProperty(pExpr, EP_Unlikely) ){
91704      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
91705      assert( pExpr->x.pList->nExpr>0 );
91706      assert( pExpr->op==TK_FUNCTION );
91707      pExpr = pExpr->x.pList->a[0].pExpr;
91708    }else{
91709      assert( pExpr->op==TK_COLLATE );
91710      pExpr = pExpr->pLeft;
91711    }
91712  }
91713  return pExpr;
91714}
91715
91716/*
91717** Return the collation sequence for the expression pExpr. If
91718** there is no defined collating sequence, return NULL.
91719**
91720** The collating sequence might be determined by a COLLATE operator
91721** or by the presence of a column with a defined collating sequence.
91722** COLLATE operators take first precedence.  Left operands take
91723** precedence over right operands.
91724*/
91725SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
91726  sqlite3 *db = pParse->db;
91727  CollSeq *pColl = 0;
91728  Expr *p = pExpr;
91729  while( p ){
91730    int op = p->op;
91731    if( p->flags & EP_Generic ) break;
91732    if( op==TK_CAST || op==TK_UPLUS ){
91733      p = p->pLeft;
91734      continue;
91735    }
91736    if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
91737      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
91738      break;
91739    }
91740    if( (op==TK_AGG_COLUMN || op==TK_COLUMN
91741          || op==TK_REGISTER || op==TK_TRIGGER)
91742     && p->pTab!=0
91743    ){
91744      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
91745      ** a TK_COLUMN but was previously evaluated and cached in a register */
91746      int j = p->iColumn;
91747      if( j>=0 ){
91748        const char *zColl = p->pTab->aCol[j].zColl;
91749        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
91750      }
91751      break;
91752    }
91753    if( p->flags & EP_Collate ){
91754      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
91755        p = p->pLeft;
91756      }else{
91757        Expr *pNext  = p->pRight;
91758        /* The Expr.x union is never used at the same time as Expr.pRight */
91759        assert( p->x.pList==0 || p->pRight==0 );
91760        /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
91761        ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
91762        ** least one EP_Collate. Thus the following two ALWAYS. */
91763        if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
91764          int i;
91765          for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
91766            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
91767              pNext = p->x.pList->a[i].pExpr;
91768              break;
91769            }
91770          }
91771        }
91772        p = pNext;
91773      }
91774    }else{
91775      break;
91776    }
91777  }
91778  if( sqlite3CheckCollSeq(pParse, pColl) ){
91779    pColl = 0;
91780  }
91781  return pColl;
91782}
91783
91784/*
91785** pExpr is an operand of a comparison operator.  aff2 is the
91786** type affinity of the other operand.  This routine returns the
91787** type affinity that should be used for the comparison operator.
91788*/
91789SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
91790  char aff1 = sqlite3ExprAffinity(pExpr);
91791  if( aff1 && aff2 ){
91792    /* Both sides of the comparison are columns. If one has numeric
91793    ** affinity, use that. Otherwise use no affinity.
91794    */
91795    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
91796      return SQLITE_AFF_NUMERIC;
91797    }else{
91798      return SQLITE_AFF_BLOB;
91799    }
91800  }else if( !aff1 && !aff2 ){
91801    /* Neither side of the comparison is a column.  Compare the
91802    ** results directly.
91803    */
91804    return SQLITE_AFF_BLOB;
91805  }else{
91806    /* One side is a column, the other is not. Use the columns affinity. */
91807    assert( aff1==0 || aff2==0 );
91808    return (aff1 + aff2);
91809  }
91810}
91811
91812/*
91813** pExpr is a comparison operator.  Return the type affinity that should
91814** be applied to both operands prior to doing the comparison.
91815*/
91816static char comparisonAffinity(Expr *pExpr){
91817  char aff;
91818  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
91819          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
91820          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
91821  assert( pExpr->pLeft );
91822  aff = sqlite3ExprAffinity(pExpr->pLeft);
91823  if( pExpr->pRight ){
91824    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
91825  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
91826    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
91827  }else if( aff==0 ){
91828    aff = SQLITE_AFF_BLOB;
91829  }
91830  return aff;
91831}
91832
91833/*
91834** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
91835** idx_affinity is the affinity of an indexed column. Return true
91836** if the index with affinity idx_affinity may be used to implement
91837** the comparison in pExpr.
91838*/
91839SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
91840  char aff = comparisonAffinity(pExpr);
91841  switch( aff ){
91842    case SQLITE_AFF_BLOB:
91843      return 1;
91844    case SQLITE_AFF_TEXT:
91845      return idx_affinity==SQLITE_AFF_TEXT;
91846    default:
91847      return sqlite3IsNumericAffinity(idx_affinity);
91848  }
91849}
91850
91851/*
91852** Return the P5 value that should be used for a binary comparison
91853** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
91854*/
91855static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
91856  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
91857  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
91858  return aff;
91859}
91860
91861/*
91862** Return a pointer to the collation sequence that should be used by
91863** a binary comparison operator comparing pLeft and pRight.
91864**
91865** If the left hand expression has a collating sequence type, then it is
91866** used. Otherwise the collation sequence for the right hand expression
91867** is used, or the default (BINARY) if neither expression has a collating
91868** type.
91869**
91870** Argument pRight (but not pLeft) may be a null pointer. In this case,
91871** it is not considered.
91872*/
91873SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
91874  Parse *pParse,
91875  Expr *pLeft,
91876  Expr *pRight
91877){
91878  CollSeq *pColl;
91879  assert( pLeft );
91880  if( pLeft->flags & EP_Collate ){
91881    pColl = sqlite3ExprCollSeq(pParse, pLeft);
91882  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
91883    pColl = sqlite3ExprCollSeq(pParse, pRight);
91884  }else{
91885    pColl = sqlite3ExprCollSeq(pParse, pLeft);
91886    if( !pColl ){
91887      pColl = sqlite3ExprCollSeq(pParse, pRight);
91888    }
91889  }
91890  return pColl;
91891}
91892
91893/*
91894** Generate code for a comparison operator.
91895*/
91896static int codeCompare(
91897  Parse *pParse,    /* The parsing (and code generating) context */
91898  Expr *pLeft,      /* The left operand */
91899  Expr *pRight,     /* The right operand */
91900  int opcode,       /* The comparison opcode */
91901  int in1, int in2, /* Register holding operands */
91902  int dest,         /* Jump here if true.  */
91903  int jumpIfNull    /* If true, jump if either operand is NULL */
91904){
91905  int p5;
91906  int addr;
91907  CollSeq *p4;
91908
91909  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
91910  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
91911  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
91912                           (void*)p4, P4_COLLSEQ);
91913  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
91914  return addr;
91915}
91916
91917/*
91918** Return true if expression pExpr is a vector, or false otherwise.
91919**
91920** A vector is defined as any expression that results in two or more
91921** columns of result.  Every TK_VECTOR node is an vector because the
91922** parser will not generate a TK_VECTOR with fewer than two entries.
91923** But a TK_SELECT might be either a vector or a scalar. It is only
91924** considered a vector if it has two or more result columns.
91925*/
91926SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
91927  return sqlite3ExprVectorSize(pExpr)>1;
91928}
91929
91930/*
91931** If the expression passed as the only argument is of type TK_VECTOR
91932** return the number of expressions in the vector. Or, if the expression
91933** is a sub-select, return the number of columns in the sub-select. For
91934** any other type of expression, return 1.
91935*/
91936SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
91937  u8 op = pExpr->op;
91938  if( op==TK_REGISTER ) op = pExpr->op2;
91939  if( op==TK_VECTOR ){
91940    return pExpr->x.pList->nExpr;
91941  }else if( op==TK_SELECT ){
91942    return pExpr->x.pSelect->pEList->nExpr;
91943  }else{
91944    return 1;
91945  }
91946}
91947
91948/*
91949** Return a pointer to a subexpression of pVector that is the i-th
91950** column of the vector (numbered starting with 0).  The caller must
91951** ensure that i is within range.
91952**
91953** If pVector is really a scalar (and "scalar" here includes subqueries
91954** that return a single column!) then return pVector unmodified.
91955**
91956** pVector retains ownership of the returned subexpression.
91957**
91958** If the vector is a (SELECT ...) then the expression returned is
91959** just the expression for the i-th term of the result set, and may
91960** not be ready for evaluation because the table cursor has not yet
91961** been positioned.
91962*/
91963SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
91964  assert( i<sqlite3ExprVectorSize(pVector) );
91965  if( sqlite3ExprIsVector(pVector) ){
91966    assert( pVector->op2==0 || pVector->op==TK_REGISTER );
91967    if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
91968      return pVector->x.pSelect->pEList->a[i].pExpr;
91969    }else{
91970      return pVector->x.pList->a[i].pExpr;
91971    }
91972  }
91973  return pVector;
91974}
91975
91976/*
91977** Compute and return a new Expr object which when passed to
91978** sqlite3ExprCode() will generate all necessary code to compute
91979** the iField-th column of the vector expression pVector.
91980**
91981** It is ok for pVector to be a scalar (as long as iField==0).
91982** In that case, this routine works like sqlite3ExprDup().
91983**
91984** The caller owns the returned Expr object and is responsible for
91985** ensuring that the returned value eventually gets freed.
91986**
91987** The caller retains ownership of pVector.  If pVector is a TK_SELECT,
91988** then the returned object will reference pVector and so pVector must remain
91989** valid for the life of the returned object.  If pVector is a TK_VECTOR
91990** or a scalar expression, then it can be deleted as soon as this routine
91991** returns.
91992**
91993** A trick to cause a TK_SELECT pVector to be deleted together with
91994** the returned Expr object is to attach the pVector to the pRight field
91995** of the returned TK_SELECT_COLUMN Expr object.
91996*/
91997SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
91998  Parse *pParse,       /* Parsing context */
91999  Expr *pVector,       /* The vector.  List of expressions or a sub-SELECT */
92000  int iField           /* Which column of the vector to return */
92001){
92002  Expr *pRet;
92003  if( pVector->op==TK_SELECT ){
92004    assert( pVector->flags & EP_xIsSelect );
92005    /* The TK_SELECT_COLUMN Expr node:
92006    **
92007    ** pLeft:           pVector containing TK_SELECT.  Not deleted.
92008    ** pRight:          not used.  But recursively deleted.
92009    ** iColumn:         Index of a column in pVector
92010    ** iTable:          0 or the number of columns on the LHS of an assignment
92011    ** pLeft->iTable:   First in an array of register holding result, or 0
92012    **                  if the result is not yet computed.
92013    **
92014    ** sqlite3ExprDelete() specifically skips the recursive delete of
92015    ** pLeft on TK_SELECT_COLUMN nodes.  But pRight is followed, so pVector
92016    ** can be attached to pRight to cause this node to take ownership of
92017    ** pVector.  Typically there will be multiple TK_SELECT_COLUMN nodes
92018    ** with the same pLeft pointer to the pVector, but only one of them
92019    ** will own the pVector.
92020    */
92021    pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
92022    if( pRet ){
92023      pRet->iColumn = iField;
92024      pRet->pLeft = pVector;
92025    }
92026    assert( pRet==0 || pRet->iTable==0 );
92027  }else{
92028    if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
92029    pRet = sqlite3ExprDup(pParse->db, pVector, 0);
92030  }
92031  return pRet;
92032}
92033
92034/*
92035** If expression pExpr is of type TK_SELECT, generate code to evaluate
92036** it. Return the register in which the result is stored (or, if the
92037** sub-select returns more than one column, the first in an array
92038** of registers in which the result is stored).
92039**
92040** If pExpr is not a TK_SELECT expression, return 0.
92041*/
92042static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
92043  int reg = 0;
92044#ifndef SQLITE_OMIT_SUBQUERY
92045  if( pExpr->op==TK_SELECT ){
92046    reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
92047  }
92048#endif
92049  return reg;
92050}
92051
92052/*
92053** Argument pVector points to a vector expression - either a TK_VECTOR
92054** or TK_SELECT that returns more than one column. This function returns
92055** the register number of a register that contains the value of
92056** element iField of the vector.
92057**
92058** If pVector is a TK_SELECT expression, then code for it must have
92059** already been generated using the exprCodeSubselect() routine. In this
92060** case parameter regSelect should be the first in an array of registers
92061** containing the results of the sub-select.
92062**
92063** If pVector is of type TK_VECTOR, then code for the requested field
92064** is generated. In this case (*pRegFree) may be set to the number of
92065** a temporary register to be freed by the caller before returning.
92066**
92067** Before returning, output parameter (*ppExpr) is set to point to the
92068** Expr object corresponding to element iElem of the vector.
92069*/
92070static int exprVectorRegister(
92071  Parse *pParse,                  /* Parse context */
92072  Expr *pVector,                  /* Vector to extract element from */
92073  int iField,                     /* Field to extract from pVector */
92074  int regSelect,                  /* First in array of registers */
92075  Expr **ppExpr,                  /* OUT: Expression element */
92076  int *pRegFree                   /* OUT: Temp register to free */
92077){
92078  u8 op = pVector->op;
92079  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
92080  if( op==TK_REGISTER ){
92081    *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
92082    return pVector->iTable+iField;
92083  }
92084  if( op==TK_SELECT ){
92085    *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
92086     return regSelect+iField;
92087  }
92088  *ppExpr = pVector->x.pList->a[iField].pExpr;
92089  return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
92090}
92091
92092/*
92093** Expression pExpr is a comparison between two vector values. Compute
92094** the result of the comparison (1, 0, or NULL) and write that
92095** result into register dest.
92096**
92097** The caller must satisfy the following preconditions:
92098**
92099**    if pExpr->op==TK_IS:      op==TK_EQ and p5==SQLITE_NULLEQ
92100**    if pExpr->op==TK_ISNOT:   op==TK_NE and p5==SQLITE_NULLEQ
92101**    otherwise:                op==pExpr->op and p5==0
92102*/
92103static void codeVectorCompare(
92104  Parse *pParse,        /* Code generator context */
92105  Expr *pExpr,          /* The comparison operation */
92106  int dest,             /* Write results into this register */
92107  u8 op,                /* Comparison operator */
92108  u8 p5                 /* SQLITE_NULLEQ or zero */
92109){
92110  Vdbe *v = pParse->pVdbe;
92111  Expr *pLeft = pExpr->pLeft;
92112  Expr *pRight = pExpr->pRight;
92113  int nLeft = sqlite3ExprVectorSize(pLeft);
92114  int i;
92115  int regLeft = 0;
92116  int regRight = 0;
92117  u8 opx = op;
92118  int addrDone = sqlite3VdbeMakeLabel(v);
92119
92120  if( nLeft!=sqlite3ExprVectorSize(pRight) ){
92121    sqlite3ErrorMsg(pParse, "row value misused");
92122    return;
92123  }
92124  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
92125       || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
92126       || pExpr->op==TK_LT || pExpr->op==TK_GT
92127       || pExpr->op==TK_LE || pExpr->op==TK_GE
92128  );
92129  assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
92130            || (pExpr->op==TK_ISNOT && op==TK_NE) );
92131  assert( p5==0 || pExpr->op!=op );
92132  assert( p5==SQLITE_NULLEQ || pExpr->op==op );
92133
92134  p5 |= SQLITE_STOREP2;
92135  if( opx==TK_LE ) opx = TK_LT;
92136  if( opx==TK_GE ) opx = TK_GT;
92137
92138  regLeft = exprCodeSubselect(pParse, pLeft);
92139  regRight = exprCodeSubselect(pParse, pRight);
92140
92141  for(i=0; 1 /*Loop exits by "break"*/; i++){
92142    int regFree1 = 0, regFree2 = 0;
92143    Expr *pL, *pR;
92144    int r1, r2;
92145    assert( i>=0 && i<nLeft );
92146    if( i>0 ) sqlite3ExprCachePush(pParse);
92147    r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
92148    r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
92149    codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
92150    testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
92151    testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
92152    testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
92153    testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
92154    testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
92155    testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
92156    sqlite3ReleaseTempReg(pParse, regFree1);
92157    sqlite3ReleaseTempReg(pParse, regFree2);
92158    if( i>0 ) sqlite3ExprCachePop(pParse);
92159    if( i==nLeft-1 ){
92160      break;
92161    }
92162    if( opx==TK_EQ ){
92163      sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
92164      p5 |= SQLITE_KEEPNULL;
92165    }else if( opx==TK_NE ){
92166      sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
92167      p5 |= SQLITE_KEEPNULL;
92168    }else{
92169      assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
92170      sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
92171      VdbeCoverageIf(v, op==TK_LT);
92172      VdbeCoverageIf(v, op==TK_GT);
92173      VdbeCoverageIf(v, op==TK_LE);
92174      VdbeCoverageIf(v, op==TK_GE);
92175      if( i==nLeft-2 ) opx = op;
92176    }
92177  }
92178  sqlite3VdbeResolveLabel(v, addrDone);
92179}
92180
92181#if SQLITE_MAX_EXPR_DEPTH>0
92182/*
92183** Check that argument nHeight is less than or equal to the maximum
92184** expression depth allowed. If it is not, leave an error message in
92185** pParse.
92186*/
92187SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
92188  int rc = SQLITE_OK;
92189  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
92190  if( nHeight>mxHeight ){
92191    sqlite3ErrorMsg(pParse,
92192       "Expression tree is too large (maximum depth %d)", mxHeight
92193    );
92194    rc = SQLITE_ERROR;
92195  }
92196  return rc;
92197}
92198
92199/* The following three functions, heightOfExpr(), heightOfExprList()
92200** and heightOfSelect(), are used to determine the maximum height
92201** of any expression tree referenced by the structure passed as the
92202** first argument.
92203**
92204** If this maximum height is greater than the current value pointed
92205** to by pnHeight, the second parameter, then set *pnHeight to that
92206** value.
92207*/
92208static void heightOfExpr(Expr *p, int *pnHeight){
92209  if( p ){
92210    if( p->nHeight>*pnHeight ){
92211      *pnHeight = p->nHeight;
92212    }
92213  }
92214}
92215static void heightOfExprList(ExprList *p, int *pnHeight){
92216  if( p ){
92217    int i;
92218    for(i=0; i<p->nExpr; i++){
92219      heightOfExpr(p->a[i].pExpr, pnHeight);
92220    }
92221  }
92222}
92223static void heightOfSelect(Select *p, int *pnHeight){
92224  if( p ){
92225    heightOfExpr(p->pWhere, pnHeight);
92226    heightOfExpr(p->pHaving, pnHeight);
92227    heightOfExpr(p->pLimit, pnHeight);
92228    heightOfExpr(p->pOffset, pnHeight);
92229    heightOfExprList(p->pEList, pnHeight);
92230    heightOfExprList(p->pGroupBy, pnHeight);
92231    heightOfExprList(p->pOrderBy, pnHeight);
92232    heightOfSelect(p->pPrior, pnHeight);
92233  }
92234}
92235
92236/*
92237** Set the Expr.nHeight variable in the structure passed as an
92238** argument. An expression with no children, Expr.pList or
92239** Expr.pSelect member has a height of 1. Any other expression
92240** has a height equal to the maximum height of any other
92241** referenced Expr plus one.
92242**
92243** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
92244** if appropriate.
92245*/
92246static void exprSetHeight(Expr *p){
92247  int nHeight = 0;
92248  heightOfExpr(p->pLeft, &nHeight);
92249  heightOfExpr(p->pRight, &nHeight);
92250  if( ExprHasProperty(p, EP_xIsSelect) ){
92251    heightOfSelect(p->x.pSelect, &nHeight);
92252  }else if( p->x.pList ){
92253    heightOfExprList(p->x.pList, &nHeight);
92254    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
92255  }
92256  p->nHeight = nHeight + 1;
92257}
92258
92259/*
92260** Set the Expr.nHeight variable using the exprSetHeight() function. If
92261** the height is greater than the maximum allowed expression depth,
92262** leave an error in pParse.
92263**
92264** Also propagate all EP_Propagate flags from the Expr.x.pList into
92265** Expr.flags.
92266*/
92267SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
92268  if( pParse->nErr ) return;
92269  exprSetHeight(p);
92270  sqlite3ExprCheckHeight(pParse, p->nHeight);
92271}
92272
92273/*
92274** Return the maximum height of any expression tree referenced
92275** by the select statement passed as an argument.
92276*/
92277SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
92278  int nHeight = 0;
92279  heightOfSelect(p, &nHeight);
92280  return nHeight;
92281}
92282#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
92283/*
92284** Propagate all EP_Propagate flags from the Expr.x.pList into
92285** Expr.flags.
92286*/
92287SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
92288  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
92289    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
92290  }
92291}
92292#define exprSetHeight(y)
92293#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
92294
92295/*
92296** This routine is the core allocator for Expr nodes.
92297**
92298** Construct a new expression node and return a pointer to it.  Memory
92299** for this node and for the pToken argument is a single allocation
92300** obtained from sqlite3DbMalloc().  The calling function
92301** is responsible for making sure the node eventually gets freed.
92302**
92303** If dequote is true, then the token (if it exists) is dequoted.
92304** If dequote is false, no dequoting is performed.  The deQuote
92305** parameter is ignored if pToken is NULL or if the token does not
92306** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
92307** then the EP_DblQuoted flag is set on the expression node.
92308**
92309** Special case:  If op==TK_INTEGER and pToken points to a string that
92310** can be translated into a 32-bit integer, then the token is not
92311** stored in u.zToken.  Instead, the integer values is written
92312** into u.iValue and the EP_IntValue flag is set.  No extra storage
92313** is allocated to hold the integer text and the dequote flag is ignored.
92314*/
92315SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
92316  sqlite3 *db,            /* Handle for sqlite3DbMallocRawNN() */
92317  int op,                 /* Expression opcode */
92318  const Token *pToken,    /* Token argument.  Might be NULL */
92319  int dequote             /* True to dequote */
92320){
92321  Expr *pNew;
92322  int nExtra = 0;
92323  int iValue = 0;
92324
92325  assert( db!=0 );
92326  if( pToken ){
92327    if( op!=TK_INTEGER || pToken->z==0
92328          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
92329      nExtra = pToken->n+1;
92330      assert( iValue>=0 );
92331    }
92332  }
92333  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
92334  if( pNew ){
92335    memset(pNew, 0, sizeof(Expr));
92336    pNew->op = (u8)op;
92337    pNew->iAgg = -1;
92338    if( pToken ){
92339      if( nExtra==0 ){
92340        pNew->flags |= EP_IntValue|EP_Leaf;
92341        pNew->u.iValue = iValue;
92342      }else{
92343        pNew->u.zToken = (char*)&pNew[1];
92344        assert( pToken->z!=0 || pToken->n==0 );
92345        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
92346        pNew->u.zToken[pToken->n] = 0;
92347        if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
92348          if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
92349          sqlite3Dequote(pNew->u.zToken);
92350        }
92351      }
92352    }
92353#if SQLITE_MAX_EXPR_DEPTH>0
92354    pNew->nHeight = 1;
92355#endif
92356  }
92357  return pNew;
92358}
92359
92360/*
92361** Allocate a new expression node from a zero-terminated token that has
92362** already been dequoted.
92363*/
92364SQLITE_PRIVATE Expr *sqlite3Expr(
92365  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
92366  int op,                 /* Expression opcode */
92367  const char *zToken      /* Token argument.  Might be NULL */
92368){
92369  Token x;
92370  x.z = zToken;
92371  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
92372  return sqlite3ExprAlloc(db, op, &x, 0);
92373}
92374
92375/*
92376** Attach subtrees pLeft and pRight to the Expr node pRoot.
92377**
92378** If pRoot==NULL that means that a memory allocation error has occurred.
92379** In that case, delete the subtrees pLeft and pRight.
92380*/
92381SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
92382  sqlite3 *db,
92383  Expr *pRoot,
92384  Expr *pLeft,
92385  Expr *pRight
92386){
92387  if( pRoot==0 ){
92388    assert( db->mallocFailed );
92389    sqlite3ExprDelete(db, pLeft);
92390    sqlite3ExprDelete(db, pRight);
92391  }else{
92392    if( pRight ){
92393      pRoot->pRight = pRight;
92394      pRoot->flags |= EP_Propagate & pRight->flags;
92395    }
92396    if( pLeft ){
92397      pRoot->pLeft = pLeft;
92398      pRoot->flags |= EP_Propagate & pLeft->flags;
92399    }
92400    exprSetHeight(pRoot);
92401  }
92402}
92403
92404/*
92405** Allocate an Expr node which joins as many as two subtrees.
92406**
92407** One or both of the subtrees can be NULL.  Return a pointer to the new
92408** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
92409** free the subtrees and return NULL.
92410*/
92411SQLITE_PRIVATE Expr *sqlite3PExpr(
92412  Parse *pParse,          /* Parsing context */
92413  int op,                 /* Expression opcode */
92414  Expr *pLeft,            /* Left operand */
92415  Expr *pRight            /* Right operand */
92416){
92417  Expr *p;
92418  if( op==TK_AND && pParse->nErr==0 ){
92419    /* Take advantage of short-circuit false optimization for AND */
92420    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
92421  }else{
92422    p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
92423    if( p ){
92424      memset(p, 0, sizeof(Expr));
92425      p->op = op & TKFLG_MASK;
92426      p->iAgg = -1;
92427    }
92428    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
92429  }
92430  if( p ) {
92431    sqlite3ExprCheckHeight(pParse, p->nHeight);
92432  }
92433  return p;
92434}
92435
92436/*
92437** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
92438** do a memory allocation failure) then delete the pSelect object.
92439*/
92440SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
92441  if( pExpr ){
92442    pExpr->x.pSelect = pSelect;
92443    ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
92444    sqlite3ExprSetHeightAndFlags(pParse, pExpr);
92445  }else{
92446    assert( pParse->db->mallocFailed );
92447    sqlite3SelectDelete(pParse->db, pSelect);
92448  }
92449}
92450
92451
92452/*
92453** If the expression is always either TRUE or FALSE (respectively),
92454** then return 1.  If one cannot determine the truth value of the
92455** expression at compile-time return 0.
92456**
92457** This is an optimization.  If is OK to return 0 here even if
92458** the expression really is always false or false (a false negative).
92459** But it is a bug to return 1 if the expression might have different
92460** boolean values in different circumstances (a false positive.)
92461**
92462** Note that if the expression is part of conditional for a
92463** LEFT JOIN, then we cannot determine at compile-time whether or not
92464** is it true or false, so always return 0.
92465*/
92466static int exprAlwaysTrue(Expr *p){
92467  int v = 0;
92468  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
92469  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
92470  return v!=0;
92471}
92472static int exprAlwaysFalse(Expr *p){
92473  int v = 0;
92474  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
92475  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
92476  return v==0;
92477}
92478
92479/*
92480** Join two expressions using an AND operator.  If either expression is
92481** NULL, then just return the other expression.
92482**
92483** If one side or the other of the AND is known to be false, then instead
92484** of returning an AND expression, just return a constant expression with
92485** a value of false.
92486*/
92487SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
92488  if( pLeft==0 ){
92489    return pRight;
92490  }else if( pRight==0 ){
92491    return pLeft;
92492  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
92493    sqlite3ExprDelete(db, pLeft);
92494    sqlite3ExprDelete(db, pRight);
92495    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
92496  }else{
92497    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
92498    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
92499    return pNew;
92500  }
92501}
92502
92503/*
92504** Construct a new expression node for a function with multiple
92505** arguments.
92506*/
92507SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
92508  Expr *pNew;
92509  sqlite3 *db = pParse->db;
92510  assert( pToken );
92511  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
92512  if( pNew==0 ){
92513    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
92514    return 0;
92515  }
92516  pNew->x.pList = pList;
92517  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
92518  sqlite3ExprSetHeightAndFlags(pParse, pNew);
92519  return pNew;
92520}
92521
92522/*
92523** Assign a variable number to an expression that encodes a wildcard
92524** in the original SQL statement.
92525**
92526** Wildcards consisting of a single "?" are assigned the next sequential
92527** variable number.
92528**
92529** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
92530** sure "nnn" is not too big to avoid a denial of service attack when
92531** the SQL statement comes from an external source.
92532**
92533** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
92534** as the previous instance of the same wildcard.  Or if this is the first
92535** instance of the wildcard, the next sequential variable number is
92536** assigned.
92537*/
92538SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
92539  sqlite3 *db = pParse->db;
92540  const char *z;
92541  ynVar x;
92542
92543  if( pExpr==0 ) return;
92544  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
92545  z = pExpr->u.zToken;
92546  assert( z!=0 );
92547  assert( z[0]!=0 );
92548  assert( n==(u32)sqlite3Strlen30(z) );
92549  if( z[1]==0 ){
92550    /* Wildcard of the form "?".  Assign the next variable number */
92551    assert( z[0]=='?' );
92552    x = (ynVar)(++pParse->nVar);
92553  }else{
92554    int doAdd = 0;
92555    if( z[0]=='?' ){
92556      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
92557      ** use it as the variable number */
92558      i64 i;
92559      int bOk;
92560      if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
92561        i = z[1]-'0';  /* The common case of ?N for a single digit N */
92562        bOk = 1;
92563      }else{
92564        bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
92565      }
92566      testcase( i==0 );
92567      testcase( i==1 );
92568      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
92569      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
92570      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
92571        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
92572            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
92573        return;
92574      }
92575      x = (ynVar)i;
92576      if( x>pParse->nVar ){
92577        pParse->nVar = (int)x;
92578        doAdd = 1;
92579      }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
92580        doAdd = 1;
92581      }
92582    }else{
92583      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
92584      ** number as the prior appearance of the same name, or if the name
92585      ** has never appeared before, reuse the same variable number
92586      */
92587      x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
92588      if( x==0 ){
92589        x = (ynVar)(++pParse->nVar);
92590        doAdd = 1;
92591      }
92592    }
92593    if( doAdd ){
92594      pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
92595    }
92596  }
92597  pExpr->iColumn = x;
92598  if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
92599    sqlite3ErrorMsg(pParse, "too many SQL variables");
92600  }
92601}
92602
92603/*
92604** Recursively delete an expression tree.
92605*/
92606static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
92607  assert( p!=0 );
92608  /* Sanity check: Assert that the IntValue is non-negative if it exists */
92609  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
92610#ifdef SQLITE_DEBUG
92611  if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
92612    assert( p->pLeft==0 );
92613    assert( p->pRight==0 );
92614    assert( p->x.pSelect==0 );
92615  }
92616#endif
92617  if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
92618    /* The Expr.x union is never used at the same time as Expr.pRight */
92619    assert( p->x.pList==0 || p->pRight==0 );
92620    if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
92621    if( p->pRight ){
92622      sqlite3ExprDeleteNN(db, p->pRight);
92623    }else if( ExprHasProperty(p, EP_xIsSelect) ){
92624      sqlite3SelectDelete(db, p->x.pSelect);
92625    }else{
92626      sqlite3ExprListDelete(db, p->x.pList);
92627    }
92628  }
92629  if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
92630  if( !ExprHasProperty(p, EP_Static) ){
92631    sqlite3DbFreeNN(db, p);
92632  }
92633}
92634SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
92635  if( p ) sqlite3ExprDeleteNN(db, p);
92636}
92637
92638/*
92639** Return the number of bytes allocated for the expression structure
92640** passed as the first argument. This is always one of EXPR_FULLSIZE,
92641** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
92642*/
92643static int exprStructSize(Expr *p){
92644  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
92645  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
92646  return EXPR_FULLSIZE;
92647}
92648
92649/*
92650** The dupedExpr*Size() routines each return the number of bytes required
92651** to store a copy of an expression or expression tree.  They differ in
92652** how much of the tree is measured.
92653**
92654**     dupedExprStructSize()     Size of only the Expr structure
92655**     dupedExprNodeSize()       Size of Expr + space for token
92656**     dupedExprSize()           Expr + token + subtree components
92657**
92658***************************************************************************
92659**
92660** The dupedExprStructSize() function returns two values OR-ed together:
92661** (1) the space required for a copy of the Expr structure only and
92662** (2) the EP_xxx flags that indicate what the structure size should be.
92663** The return values is always one of:
92664**
92665**      EXPR_FULLSIZE
92666**      EXPR_REDUCEDSIZE   | EP_Reduced
92667**      EXPR_TOKENONLYSIZE | EP_TokenOnly
92668**
92669** The size of the structure can be found by masking the return value
92670** of this routine with 0xfff.  The flags can be found by masking the
92671** return value with EP_Reduced|EP_TokenOnly.
92672**
92673** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
92674** (unreduced) Expr objects as they or originally constructed by the parser.
92675** During expression analysis, extra information is computed and moved into
92676** later parts of teh Expr object and that extra information might get chopped
92677** off if the expression is reduced.  Note also that it does not work to
92678** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
92679** to reduce a pristine expression tree from the parser.  The implementation
92680** of dupedExprStructSize() contain multiple assert() statements that attempt
92681** to enforce this constraint.
92682*/
92683static int dupedExprStructSize(Expr *p, int flags){
92684  int nSize;
92685  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
92686  assert( EXPR_FULLSIZE<=0xfff );
92687  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
92688  if( 0==flags || p->op==TK_SELECT_COLUMN ){
92689    nSize = EXPR_FULLSIZE;
92690  }else{
92691    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
92692    assert( !ExprHasProperty(p, EP_FromJoin) );
92693    assert( !ExprHasProperty(p, EP_MemToken) );
92694    assert( !ExprHasProperty(p, EP_NoReduce) );
92695    if( p->pLeft || p->x.pList ){
92696      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
92697    }else{
92698      assert( p->pRight==0 );
92699      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
92700    }
92701  }
92702  return nSize;
92703}
92704
92705/*
92706** This function returns the space in bytes required to store the copy
92707** of the Expr structure and a copy of the Expr.u.zToken string (if that
92708** string is defined.)
92709*/
92710static int dupedExprNodeSize(Expr *p, int flags){
92711  int nByte = dupedExprStructSize(p, flags) & 0xfff;
92712  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
92713    nByte += sqlite3Strlen30(p->u.zToken)+1;
92714  }
92715  return ROUND8(nByte);
92716}
92717
92718/*
92719** Return the number of bytes required to create a duplicate of the
92720** expression passed as the first argument. The second argument is a
92721** mask containing EXPRDUP_XXX flags.
92722**
92723** The value returned includes space to create a copy of the Expr struct
92724** itself and the buffer referred to by Expr.u.zToken, if any.
92725**
92726** If the EXPRDUP_REDUCE flag is set, then the return value includes
92727** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
92728** and Expr.pRight variables (but not for any structures pointed to or
92729** descended from the Expr.x.pList or Expr.x.pSelect variables).
92730*/
92731static int dupedExprSize(Expr *p, int flags){
92732  int nByte = 0;
92733  if( p ){
92734    nByte = dupedExprNodeSize(p, flags);
92735    if( flags&EXPRDUP_REDUCE ){
92736      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
92737    }
92738  }
92739  return nByte;
92740}
92741
92742/*
92743** This function is similar to sqlite3ExprDup(), except that if pzBuffer
92744** is not NULL then *pzBuffer is assumed to point to a buffer large enough
92745** to store the copy of expression p, the copies of p->u.zToken
92746** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
92747** if any. Before returning, *pzBuffer is set to the first byte past the
92748** portion of the buffer copied into by this function.
92749*/
92750static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
92751  Expr *pNew;           /* Value to return */
92752  u8 *zAlloc;           /* Memory space from which to build Expr object */
92753  u32 staticFlag;       /* EP_Static if space not obtained from malloc */
92754
92755  assert( db!=0 );
92756  assert( p );
92757  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
92758  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
92759
92760  /* Figure out where to write the new Expr structure. */
92761  if( pzBuffer ){
92762    zAlloc = *pzBuffer;
92763    staticFlag = EP_Static;
92764  }else{
92765    zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
92766    staticFlag = 0;
92767  }
92768  pNew = (Expr *)zAlloc;
92769
92770  if( pNew ){
92771    /* Set nNewSize to the size allocated for the structure pointed to
92772    ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
92773    ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
92774    ** by the copy of the p->u.zToken string (if any).
92775    */
92776    const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
92777    const int nNewSize = nStructSize & 0xfff;
92778    int nToken;
92779    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
92780      nToken = sqlite3Strlen30(p->u.zToken) + 1;
92781    }else{
92782      nToken = 0;
92783    }
92784    if( dupFlags ){
92785      assert( ExprHasProperty(p, EP_Reduced)==0 );
92786      memcpy(zAlloc, p, nNewSize);
92787    }else{
92788      u32 nSize = (u32)exprStructSize(p);
92789      memcpy(zAlloc, p, nSize);
92790      if( nSize<EXPR_FULLSIZE ){
92791        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
92792      }
92793    }
92794
92795    /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
92796    pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
92797    pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
92798    pNew->flags |= staticFlag;
92799
92800    /* Copy the p->u.zToken string, if any. */
92801    if( nToken ){
92802      char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
92803      memcpy(zToken, p->u.zToken, nToken);
92804    }
92805
92806    if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
92807      /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
92808      if( ExprHasProperty(p, EP_xIsSelect) ){
92809        pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
92810      }else{
92811        pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
92812      }
92813    }
92814
92815    /* Fill in pNew->pLeft and pNew->pRight. */
92816    if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
92817      zAlloc += dupedExprNodeSize(p, dupFlags);
92818      if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
92819        pNew->pLeft = p->pLeft ?
92820                      exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
92821        pNew->pRight = p->pRight ?
92822                       exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
92823      }
92824      if( pzBuffer ){
92825        *pzBuffer = zAlloc;
92826      }
92827    }else{
92828      if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
92829        if( pNew->op==TK_SELECT_COLUMN ){
92830          pNew->pLeft = p->pLeft;
92831          assert( p->iColumn==0 || p->pRight==0 );
92832          assert( p->pRight==0  || p->pRight==p->pLeft );
92833        }else{
92834          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
92835        }
92836        pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
92837      }
92838    }
92839  }
92840  return pNew;
92841}
92842
92843/*
92844** Create and return a deep copy of the object passed as the second
92845** argument. If an OOM condition is encountered, NULL is returned
92846** and the db->mallocFailed flag set.
92847*/
92848#ifndef SQLITE_OMIT_CTE
92849static With *withDup(sqlite3 *db, With *p){
92850  With *pRet = 0;
92851  if( p ){
92852    int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
92853    pRet = sqlite3DbMallocZero(db, nByte);
92854    if( pRet ){
92855      int i;
92856      pRet->nCte = p->nCte;
92857      for(i=0; i<p->nCte; i++){
92858        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
92859        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
92860        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
92861      }
92862    }
92863  }
92864  return pRet;
92865}
92866#else
92867# define withDup(x,y) 0
92868#endif
92869
92870/*
92871** The following group of routines make deep copies of expressions,
92872** expression lists, ID lists, and select statements.  The copies can
92873** be deleted (by being passed to their respective ...Delete() routines)
92874** without effecting the originals.
92875**
92876** The expression list, ID, and source lists return by sqlite3ExprListDup(),
92877** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
92878** by subsequent calls to sqlite*ListAppend() routines.
92879**
92880** Any tables that the SrcList might point to are not duplicated.
92881**
92882** The flags parameter contains a combination of the EXPRDUP_XXX flags.
92883** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
92884** truncated version of the usual Expr structure that will be stored as
92885** part of the in-memory representation of the database schema.
92886*/
92887SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
92888  assert( flags==0 || flags==EXPRDUP_REDUCE );
92889  return p ? exprDup(db, p, flags, 0) : 0;
92890}
92891SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
92892  ExprList *pNew;
92893  struct ExprList_item *pItem, *pOldItem;
92894  int i;
92895  Expr *pPriorSelectCol = 0;
92896  assert( db!=0 );
92897  if( p==0 ) return 0;
92898  pNew = sqlite3DbMallocRawNN(db,
92899             sizeof(*pNew)+sizeof(pNew->a[0])*(p->nExpr-1) );
92900  if( pNew==0 ) return 0;
92901  pNew->nAlloc = pNew->nExpr = p->nExpr;
92902  pItem = pNew->a;
92903  pOldItem = p->a;
92904  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
92905    Expr *pOldExpr = pOldItem->pExpr;
92906    Expr *pNewExpr;
92907    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
92908    if( pOldExpr
92909     && pOldExpr->op==TK_SELECT_COLUMN
92910     && (pNewExpr = pItem->pExpr)!=0
92911    ){
92912      assert( pNewExpr->iColumn==0 || i>0 );
92913      if( pNewExpr->iColumn==0 ){
92914        assert( pOldExpr->pLeft==pOldExpr->pRight );
92915        pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
92916      }else{
92917        assert( i>0 );
92918        assert( pItem[-1].pExpr!=0 );
92919        assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
92920        assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
92921        pNewExpr->pLeft = pPriorSelectCol;
92922      }
92923    }
92924    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
92925    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
92926    pItem->sortOrder = pOldItem->sortOrder;
92927    pItem->done = 0;
92928    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
92929    pItem->u = pOldItem->u;
92930  }
92931  return pNew;
92932}
92933
92934/*
92935** If cursors, triggers, views and subqueries are all omitted from
92936** the build, then none of the following routines, except for
92937** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
92938** called with a NULL argument.
92939*/
92940#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
92941 || !defined(SQLITE_OMIT_SUBQUERY)
92942SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
92943  SrcList *pNew;
92944  int i;
92945  int nByte;
92946  assert( db!=0 );
92947  if( p==0 ) return 0;
92948  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
92949  pNew = sqlite3DbMallocRawNN(db, nByte );
92950  if( pNew==0 ) return 0;
92951  pNew->nSrc = pNew->nAlloc = p->nSrc;
92952  for(i=0; i<p->nSrc; i++){
92953    struct SrcList_item *pNewItem = &pNew->a[i];
92954    struct SrcList_item *pOldItem = &p->a[i];
92955    Table *pTab;
92956    pNewItem->pSchema = pOldItem->pSchema;
92957    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
92958    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
92959    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
92960    pNewItem->fg = pOldItem->fg;
92961    pNewItem->iCursor = pOldItem->iCursor;
92962    pNewItem->addrFillSub = pOldItem->addrFillSub;
92963    pNewItem->regReturn = pOldItem->regReturn;
92964    if( pNewItem->fg.isIndexedBy ){
92965      pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
92966    }
92967    pNewItem->pIBIndex = pOldItem->pIBIndex;
92968    if( pNewItem->fg.isTabFunc ){
92969      pNewItem->u1.pFuncArg =
92970          sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
92971    }
92972    pTab = pNewItem->pTab = pOldItem->pTab;
92973    if( pTab ){
92974      pTab->nTabRef++;
92975    }
92976    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
92977    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
92978    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
92979    pNewItem->colUsed = pOldItem->colUsed;
92980  }
92981  return pNew;
92982}
92983SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
92984  IdList *pNew;
92985  int i;
92986  assert( db!=0 );
92987  if( p==0 ) return 0;
92988  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
92989  if( pNew==0 ) return 0;
92990  pNew->nId = p->nId;
92991  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
92992  if( pNew->a==0 ){
92993    sqlite3DbFreeNN(db, pNew);
92994    return 0;
92995  }
92996  /* Note that because the size of the allocation for p->a[] is not
92997  ** necessarily a power of two, sqlite3IdListAppend() may not be called
92998  ** on the duplicate created by this function. */
92999  for(i=0; i<p->nId; i++){
93000    struct IdList_item *pNewItem = &pNew->a[i];
93001    struct IdList_item *pOldItem = &p->a[i];
93002    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
93003    pNewItem->idx = pOldItem->idx;
93004  }
93005  return pNew;
93006}
93007SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
93008  Select *pRet = 0;
93009  Select *pNext = 0;
93010  Select **pp = &pRet;
93011  Select *p;
93012
93013  assert( db!=0 );
93014  for(p=pDup; p; p=p->pPrior){
93015    Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
93016    if( pNew==0 ) break;
93017    pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
93018    pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
93019    pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
93020    pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
93021    pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
93022    pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
93023    pNew->op = p->op;
93024    pNew->pNext = pNext;
93025    pNew->pPrior = 0;
93026    pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
93027    pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
93028    pNew->iLimit = 0;
93029    pNew->iOffset = 0;
93030    pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
93031    pNew->addrOpenEphm[0] = -1;
93032    pNew->addrOpenEphm[1] = -1;
93033    pNew->nSelectRow = p->nSelectRow;
93034    pNew->pWith = withDup(db, p->pWith);
93035    sqlite3SelectSetName(pNew, p->zSelName);
93036    *pp = pNew;
93037    pp = &pNew->pPrior;
93038    pNext = pNew;
93039  }
93040
93041  return pRet;
93042}
93043#else
93044SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
93045  assert( p==0 );
93046  return 0;
93047}
93048#endif
93049
93050
93051/*
93052** Add a new element to the end of an expression list.  If pList is
93053** initially NULL, then create a new expression list.
93054**
93055** If a memory allocation error occurs, the entire list is freed and
93056** NULL is returned.  If non-NULL is returned, then it is guaranteed
93057** that the new entry was successfully appended.
93058*/
93059SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
93060  Parse *pParse,          /* Parsing context */
93061  ExprList *pList,        /* List to which to append. Might be NULL */
93062  Expr *pExpr             /* Expression to be appended. Might be NULL */
93063){
93064  struct ExprList_item *pItem;
93065  sqlite3 *db = pParse->db;
93066  assert( db!=0 );
93067  if( pList==0 ){
93068    pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
93069    if( pList==0 ){
93070      goto no_mem;
93071    }
93072    pList->nExpr = 0;
93073    pList->nAlloc = 1;
93074  }else if( pList->nExpr==pList->nAlloc ){
93075    ExprList *pNew;
93076    pNew = sqlite3DbRealloc(db, pList,
93077             sizeof(*pList)+(2*pList->nAlloc - 1)*sizeof(pList->a[0]));
93078    if( pNew==0 ){
93079      goto no_mem;
93080    }
93081    pList = pNew;
93082    pList->nAlloc *= 2;
93083  }
93084  pItem = &pList->a[pList->nExpr++];
93085  assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
93086  assert( offsetof(struct ExprList_item,pExpr)==0 );
93087  memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
93088  pItem->pExpr = pExpr;
93089  return pList;
93090
93091no_mem:
93092  /* Avoid leaking memory if malloc has failed. */
93093  sqlite3ExprDelete(db, pExpr);
93094  sqlite3ExprListDelete(db, pList);
93095  return 0;
93096}
93097
93098/*
93099** pColumns and pExpr form a vector assignment which is part of the SET
93100** clause of an UPDATE statement.  Like this:
93101**
93102**        (a,b,c) = (expr1,expr2,expr3)
93103** Or:    (a,b,c) = (SELECT x,y,z FROM ....)
93104**
93105** For each term of the vector assignment, append new entries to the
93106** expression list pList.  In the case of a subquery on the RHS, append
93107** TK_SELECT_COLUMN expressions.
93108*/
93109SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
93110  Parse *pParse,         /* Parsing context */
93111  ExprList *pList,       /* List to which to append. Might be NULL */
93112  IdList *pColumns,      /* List of names of LHS of the assignment */
93113  Expr *pExpr            /* Vector expression to be appended. Might be NULL */
93114){
93115  sqlite3 *db = pParse->db;
93116  int n;
93117  int i;
93118  int iFirst = pList ? pList->nExpr : 0;
93119  /* pColumns can only be NULL due to an OOM but an OOM will cause an
93120  ** exit prior to this routine being invoked */
93121  if( NEVER(pColumns==0) ) goto vector_append_error;
93122  if( pExpr==0 ) goto vector_append_error;
93123
93124  /* If the RHS is a vector, then we can immediately check to see that
93125  ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
93126  ** wildcards ("*") in the result set of the SELECT must be expanded before
93127  ** we can do the size check, so defer the size check until code generation.
93128  */
93129  if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
93130    sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
93131                    pColumns->nId, n);
93132    goto vector_append_error;
93133  }
93134
93135  for(i=0; i<pColumns->nId; i++){
93136    Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
93137    pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
93138    if( pList ){
93139      assert( pList->nExpr==iFirst+i+1 );
93140      pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
93141      pColumns->a[i].zName = 0;
93142    }
93143  }
93144
93145  if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
93146    Expr *pFirst = pList->a[iFirst].pExpr;
93147    assert( pFirst!=0 );
93148    assert( pFirst->op==TK_SELECT_COLUMN );
93149
93150    /* Store the SELECT statement in pRight so it will be deleted when
93151    ** sqlite3ExprListDelete() is called */
93152    pFirst->pRight = pExpr;
93153    pExpr = 0;
93154
93155    /* Remember the size of the LHS in iTable so that we can check that
93156    ** the RHS and LHS sizes match during code generation. */
93157    pFirst->iTable = pColumns->nId;
93158  }
93159
93160vector_append_error:
93161  sqlite3ExprDelete(db, pExpr);
93162  sqlite3IdListDelete(db, pColumns);
93163  return pList;
93164}
93165
93166/*
93167** Set the sort order for the last element on the given ExprList.
93168*/
93169SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
93170  if( p==0 ) return;
93171  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
93172  assert( p->nExpr>0 );
93173  if( iSortOrder<0 ){
93174    assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
93175    return;
93176  }
93177  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
93178}
93179
93180/*
93181** Set the ExprList.a[].zName element of the most recently added item
93182** on the expression list.
93183**
93184** pList might be NULL following an OOM error.  But pName should never be
93185** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
93186** is set.
93187*/
93188SQLITE_PRIVATE void sqlite3ExprListSetName(
93189  Parse *pParse,          /* Parsing context */
93190  ExprList *pList,        /* List to which to add the span. */
93191  Token *pName,           /* Name to be added */
93192  int dequote             /* True to cause the name to be dequoted */
93193){
93194  assert( pList!=0 || pParse->db->mallocFailed!=0 );
93195  if( pList ){
93196    struct ExprList_item *pItem;
93197    assert( pList->nExpr>0 );
93198    pItem = &pList->a[pList->nExpr-1];
93199    assert( pItem->zName==0 );
93200    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
93201    if( dequote ) sqlite3Dequote(pItem->zName);
93202  }
93203}
93204
93205/*
93206** Set the ExprList.a[].zSpan element of the most recently added item
93207** on the expression list.
93208**
93209** pList might be NULL following an OOM error.  But pSpan should never be
93210** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
93211** is set.
93212*/
93213SQLITE_PRIVATE void sqlite3ExprListSetSpan(
93214  Parse *pParse,          /* Parsing context */
93215  ExprList *pList,        /* List to which to add the span. */
93216  ExprSpan *pSpan         /* The span to be added */
93217){
93218  sqlite3 *db = pParse->db;
93219  assert( pList!=0 || db->mallocFailed!=0 );
93220  if( pList ){
93221    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
93222    assert( pList->nExpr>0 );
93223    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
93224    sqlite3DbFree(db, pItem->zSpan);
93225    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
93226                                    (int)(pSpan->zEnd - pSpan->zStart));
93227  }
93228}
93229
93230/*
93231** If the expression list pEList contains more than iLimit elements,
93232** leave an error message in pParse.
93233*/
93234SQLITE_PRIVATE void sqlite3ExprListCheckLength(
93235  Parse *pParse,
93236  ExprList *pEList,
93237  const char *zObject
93238){
93239  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
93240  testcase( pEList && pEList->nExpr==mx );
93241  testcase( pEList && pEList->nExpr==mx+1 );
93242  if( pEList && pEList->nExpr>mx ){
93243    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
93244  }
93245}
93246
93247/*
93248** Delete an entire expression list.
93249*/
93250static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
93251  int i = pList->nExpr;
93252  struct ExprList_item *pItem =  pList->a;
93253  assert( pList->nExpr>0 );
93254  do{
93255    sqlite3ExprDelete(db, pItem->pExpr);
93256    sqlite3DbFree(db, pItem->zName);
93257    sqlite3DbFree(db, pItem->zSpan);
93258    pItem++;
93259  }while( --i>0 );
93260  sqlite3DbFreeNN(db, pList);
93261}
93262SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
93263  if( pList ) exprListDeleteNN(db, pList);
93264}
93265
93266/*
93267** Return the bitwise-OR of all Expr.flags fields in the given
93268** ExprList.
93269*/
93270SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
93271  int i;
93272  u32 m = 0;
93273  if( pList ){
93274    for(i=0; i<pList->nExpr; i++){
93275       Expr *pExpr = pList->a[i].pExpr;
93276       assert( pExpr!=0 );
93277       m |= pExpr->flags;
93278    }
93279  }
93280  return m;
93281}
93282
93283/*
93284** These routines are Walker callbacks used to check expressions to
93285** see if they are "constant" for some definition of constant.  The
93286** Walker.eCode value determines the type of "constant" we are looking
93287** for.
93288**
93289** These callback routines are used to implement the following:
93290**
93291**     sqlite3ExprIsConstant()                  pWalker->eCode==1
93292**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
93293**     sqlite3ExprIsTableConstant()             pWalker->eCode==3
93294**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
93295**
93296** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
93297** is found to not be a constant.
93298**
93299** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
93300** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
93301** an existing schema and 4 when processing a new statement.  A bound
93302** parameter raises an error for new statements, but is silently converted
93303** to NULL for existing schemas.  This allows sqlite_master tables that
93304** contain a bound parameter because they were generated by older versions
93305** of SQLite to be parsed by newer versions of SQLite without raising a
93306** malformed schema error.
93307*/
93308static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
93309
93310  /* If pWalker->eCode is 2 then any term of the expression that comes from
93311  ** the ON or USING clauses of a left join disqualifies the expression
93312  ** from being considered constant. */
93313  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
93314    pWalker->eCode = 0;
93315    return WRC_Abort;
93316  }
93317
93318  switch( pExpr->op ){
93319    /* Consider functions to be constant if all their arguments are constant
93320    ** and either pWalker->eCode==4 or 5 or the function has the
93321    ** SQLITE_FUNC_CONST flag. */
93322    case TK_FUNCTION:
93323      if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
93324        return WRC_Continue;
93325      }else{
93326        pWalker->eCode = 0;
93327        return WRC_Abort;
93328      }
93329    case TK_ID:
93330    case TK_COLUMN:
93331    case TK_AGG_FUNCTION:
93332    case TK_AGG_COLUMN:
93333      testcase( pExpr->op==TK_ID );
93334      testcase( pExpr->op==TK_COLUMN );
93335      testcase( pExpr->op==TK_AGG_FUNCTION );
93336      testcase( pExpr->op==TK_AGG_COLUMN );
93337      if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
93338        return WRC_Continue;
93339      }
93340      /* Fall through */
93341    case TK_IF_NULL_ROW:
93342      testcase( pExpr->op==TK_IF_NULL_ROW );
93343      pWalker->eCode = 0;
93344      return WRC_Abort;
93345    case TK_VARIABLE:
93346      if( pWalker->eCode==5 ){
93347        /* Silently convert bound parameters that appear inside of CREATE
93348        ** statements into a NULL when parsing the CREATE statement text out
93349        ** of the sqlite_master table */
93350        pExpr->op = TK_NULL;
93351      }else if( pWalker->eCode==4 ){
93352        /* A bound parameter in a CREATE statement that originates from
93353        ** sqlite3_prepare() causes an error */
93354        pWalker->eCode = 0;
93355        return WRC_Abort;
93356      }
93357      /* Fall through */
93358    default:
93359      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
93360      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
93361      return WRC_Continue;
93362  }
93363}
93364static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
93365  UNUSED_PARAMETER(NotUsed);
93366  pWalker->eCode = 0;
93367  return WRC_Abort;
93368}
93369static int exprIsConst(Expr *p, int initFlag, int iCur){
93370  Walker w;
93371  w.eCode = initFlag;
93372  w.xExprCallback = exprNodeIsConstant;
93373  w.xSelectCallback = selectNodeIsConstant;
93374#ifdef SQLITE_DEBUG
93375  w.xSelectCallback2 = sqlite3SelectWalkAssert2;
93376#endif
93377  w.u.iCur = iCur;
93378  sqlite3WalkExpr(&w, p);
93379  return w.eCode;
93380}
93381
93382/*
93383** Walk an expression tree.  Return non-zero if the expression is constant
93384** and 0 if it involves variables or function calls.
93385**
93386** For the purposes of this function, a double-quoted string (ex: "abc")
93387** is considered a variable but a single-quoted string (ex: 'abc') is
93388** a constant.
93389*/
93390SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
93391  return exprIsConst(p, 1, 0);
93392}
93393
93394/*
93395** Walk an expression tree.  Return non-zero if the expression is constant
93396** that does no originate from the ON or USING clauses of a join.
93397** Return 0 if it involves variables or function calls or terms from
93398** an ON or USING clause.
93399*/
93400SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
93401  return exprIsConst(p, 2, 0);
93402}
93403
93404/*
93405** Walk an expression tree.  Return non-zero if the expression is constant
93406** for any single row of the table with cursor iCur.  In other words, the
93407** expression must not refer to any non-deterministic function nor any
93408** table other than iCur.
93409*/
93410SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
93411  return exprIsConst(p, 3, iCur);
93412}
93413
93414
93415/*
93416** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
93417*/
93418static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
93419  ExprList *pGroupBy = pWalker->u.pGroupBy;
93420  int i;
93421
93422  /* Check if pExpr is identical to any GROUP BY term. If so, consider
93423  ** it constant.  */
93424  for(i=0; i<pGroupBy->nExpr; i++){
93425    Expr *p = pGroupBy->a[i].pExpr;
93426    if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
93427      CollSeq *pColl = sqlite3ExprCollSeq(pWalker->pParse, p);
93428      if( pColl==0 || sqlite3_stricmp("BINARY", pColl->zName)==0 ){
93429        return WRC_Prune;
93430      }
93431    }
93432  }
93433
93434  /* Check if pExpr is a sub-select. If so, consider it variable. */
93435  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
93436    pWalker->eCode = 0;
93437    return WRC_Abort;
93438  }
93439
93440  return exprNodeIsConstant(pWalker, pExpr);
93441}
93442
93443/*
93444** Walk the expression tree passed as the first argument. Return non-zero
93445** if the expression consists entirely of constants or copies of terms
93446** in pGroupBy that sort with the BINARY collation sequence.
93447**
93448** This routine is used to determine if a term of the HAVING clause can
93449** be promoted into the WHERE clause.  In order for such a promotion to work,
93450** the value of the HAVING clause term must be the same for all members of
93451** a "group".  The requirement that the GROUP BY term must be BINARY
93452** assumes that no other collating sequence will have a finer-grained
93453** grouping than binary.  In other words (A=B COLLATE binary) implies
93454** A=B in every other collating sequence.  The requirement that the
93455** GROUP BY be BINARY is stricter than necessary.  It would also work
93456** to promote HAVING clauses that use the same alternative collating
93457** sequence as the GROUP BY term, but that is much harder to check,
93458** alternative collating sequences are uncommon, and this is only an
93459** optimization, so we take the easy way out and simply require the
93460** GROUP BY to use the BINARY collating sequence.
93461*/
93462SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
93463  Walker w;
93464  w.eCode = 1;
93465  w.xExprCallback = exprNodeIsConstantOrGroupBy;
93466  w.xSelectCallback = 0;
93467  w.u.pGroupBy = pGroupBy;
93468  w.pParse = pParse;
93469  sqlite3WalkExpr(&w, p);
93470  return w.eCode;
93471}
93472
93473/*
93474** Walk an expression tree.  Return non-zero if the expression is constant
93475** or a function call with constant arguments.  Return and 0 if there
93476** are any variables.
93477**
93478** For the purposes of this function, a double-quoted string (ex: "abc")
93479** is considered a variable but a single-quoted string (ex: 'abc') is
93480** a constant.
93481*/
93482SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
93483  assert( isInit==0 || isInit==1 );
93484  return exprIsConst(p, 4+isInit, 0);
93485}
93486
93487#ifdef SQLITE_ENABLE_CURSOR_HINTS
93488/*
93489** Walk an expression tree.  Return 1 if the expression contains a
93490** subquery of some kind.  Return 0 if there are no subqueries.
93491*/
93492SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
93493  Walker w;
93494  w.eCode = 1;
93495  w.xExprCallback = sqlite3ExprWalkNoop;
93496  w.xSelectCallback = selectNodeIsConstant;
93497#ifdef SQLITE_DEBUG
93498  w.xSelectCallback2 = sqlite3SelectWalkAssert2;
93499#endif
93500  sqlite3WalkExpr(&w, p);
93501  return w.eCode==0;
93502}
93503#endif
93504
93505/*
93506** If the expression p codes a constant integer that is small enough
93507** to fit in a 32-bit integer, return 1 and put the value of the integer
93508** in *pValue.  If the expression is not an integer or if it is too big
93509** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
93510*/
93511SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
93512  int rc = 0;
93513  if( p==0 ) return 0;  /* Can only happen following on OOM */
93514
93515  /* If an expression is an integer literal that fits in a signed 32-bit
93516  ** integer, then the EP_IntValue flag will have already been set */
93517  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
93518           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
93519
93520  if( p->flags & EP_IntValue ){
93521    *pValue = p->u.iValue;
93522    return 1;
93523  }
93524  switch( p->op ){
93525    case TK_UPLUS: {
93526      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
93527      break;
93528    }
93529    case TK_UMINUS: {
93530      int v;
93531      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
93532        assert( v!=(-2147483647-1) );
93533        *pValue = -v;
93534        rc = 1;
93535      }
93536      break;
93537    }
93538    default: break;
93539  }
93540  return rc;
93541}
93542
93543/*
93544** Return FALSE if there is no chance that the expression can be NULL.
93545**
93546** If the expression might be NULL or if the expression is too complex
93547** to tell return TRUE.
93548**
93549** This routine is used as an optimization, to skip OP_IsNull opcodes
93550** when we know that a value cannot be NULL.  Hence, a false positive
93551** (returning TRUE when in fact the expression can never be NULL) might
93552** be a small performance hit but is otherwise harmless.  On the other
93553** hand, a false negative (returning FALSE when the result could be NULL)
93554** will likely result in an incorrect answer.  So when in doubt, return
93555** TRUE.
93556*/
93557SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
93558  u8 op;
93559  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
93560  op = p->op;
93561  if( op==TK_REGISTER ) op = p->op2;
93562  switch( op ){
93563    case TK_INTEGER:
93564    case TK_STRING:
93565    case TK_FLOAT:
93566    case TK_BLOB:
93567      return 0;
93568    case TK_COLUMN:
93569      assert( p->pTab!=0 );
93570      return ExprHasProperty(p, EP_CanBeNull) ||
93571             (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
93572    default:
93573      return 1;
93574  }
93575}
93576
93577/*
93578** Return TRUE if the given expression is a constant which would be
93579** unchanged by OP_Affinity with the affinity given in the second
93580** argument.
93581**
93582** This routine is used to determine if the OP_Affinity operation
93583** can be omitted.  When in doubt return FALSE.  A false negative
93584** is harmless.  A false positive, however, can result in the wrong
93585** answer.
93586*/
93587SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
93588  u8 op;
93589  if( aff==SQLITE_AFF_BLOB ) return 1;
93590  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
93591  op = p->op;
93592  if( op==TK_REGISTER ) op = p->op2;
93593  switch( op ){
93594    case TK_INTEGER: {
93595      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
93596    }
93597    case TK_FLOAT: {
93598      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
93599    }
93600    case TK_STRING: {
93601      return aff==SQLITE_AFF_TEXT;
93602    }
93603    case TK_BLOB: {
93604      return 1;
93605    }
93606    case TK_COLUMN: {
93607      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
93608      return p->iColumn<0
93609          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
93610    }
93611    default: {
93612      return 0;
93613    }
93614  }
93615}
93616
93617/*
93618** Return TRUE if the given string is a row-id column name.
93619*/
93620SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
93621  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
93622  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
93623  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
93624  return 0;
93625}
93626
93627/*
93628** pX is the RHS of an IN operator.  If pX is a SELECT statement
93629** that can be simplified to a direct table access, then return
93630** a pointer to the SELECT statement.  If pX is not a SELECT statement,
93631** or if the SELECT statement needs to be manifested into a transient
93632** table, then return NULL.
93633*/
93634#ifndef SQLITE_OMIT_SUBQUERY
93635static Select *isCandidateForInOpt(Expr *pX){
93636  Select *p;
93637  SrcList *pSrc;
93638  ExprList *pEList;
93639  Table *pTab;
93640  int i;
93641  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
93642  if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
93643  p = pX->x.pSelect;
93644  if( p->pPrior ) return 0;              /* Not a compound SELECT */
93645  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
93646    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
93647    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
93648    return 0; /* No DISTINCT keyword and no aggregate functions */
93649  }
93650  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
93651  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
93652  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
93653  if( p->pWhere ) return 0;              /* Has no WHERE clause */
93654  pSrc = p->pSrc;
93655  assert( pSrc!=0 );
93656  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
93657  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
93658  pTab = pSrc->a[0].pTab;
93659  assert( pTab!=0 );
93660  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
93661  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
93662  pEList = p->pEList;
93663  assert( pEList!=0 );
93664  /* All SELECT results must be columns. */
93665  for(i=0; i<pEList->nExpr; i++){
93666    Expr *pRes = pEList->a[i].pExpr;
93667    if( pRes->op!=TK_COLUMN ) return 0;
93668    assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
93669  }
93670  return p;
93671}
93672#endif /* SQLITE_OMIT_SUBQUERY */
93673
93674#ifndef SQLITE_OMIT_SUBQUERY
93675/*
93676** Generate code that checks the left-most column of index table iCur to see if
93677** it contains any NULL entries.  Cause the register at regHasNull to be set
93678** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
93679** to be set to NULL if iCur contains one or more NULL values.
93680*/
93681static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
93682  int addr1;
93683  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
93684  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
93685  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
93686  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
93687  VdbeComment((v, "first_entry_in(%d)", iCur));
93688  sqlite3VdbeJumpHere(v, addr1);
93689}
93690#endif
93691
93692
93693#ifndef SQLITE_OMIT_SUBQUERY
93694/*
93695** The argument is an IN operator with a list (not a subquery) on the
93696** right-hand side.  Return TRUE if that list is constant.
93697*/
93698static int sqlite3InRhsIsConstant(Expr *pIn){
93699  Expr *pLHS;
93700  int res;
93701  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
93702  pLHS = pIn->pLeft;
93703  pIn->pLeft = 0;
93704  res = sqlite3ExprIsConstant(pIn);
93705  pIn->pLeft = pLHS;
93706  return res;
93707}
93708#endif
93709
93710/*
93711** This function is used by the implementation of the IN (...) operator.
93712** The pX parameter is the expression on the RHS of the IN operator, which
93713** might be either a list of expressions or a subquery.
93714**
93715** The job of this routine is to find or create a b-tree object that can
93716** be used either to test for membership in the RHS set or to iterate through
93717** all members of the RHS set, skipping duplicates.
93718**
93719** A cursor is opened on the b-tree object that is the RHS of the IN operator
93720** and pX->iTable is set to the index of that cursor.
93721**
93722** The returned value of this function indicates the b-tree type, as follows:
93723**
93724**   IN_INDEX_ROWID      - The cursor was opened on a database table.
93725**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
93726**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
93727**   IN_INDEX_EPH        - The cursor was opened on a specially created and
93728**                         populated epheremal table.
93729**   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
93730**                         implemented as a sequence of comparisons.
93731**
93732** An existing b-tree might be used if the RHS expression pX is a simple
93733** subquery such as:
93734**
93735**     SELECT <column1>, <column2>... FROM <table>
93736**
93737** If the RHS of the IN operator is a list or a more complex subquery, then
93738** an ephemeral table might need to be generated from the RHS and then
93739** pX->iTable made to point to the ephemeral table instead of an
93740** existing table.
93741**
93742** The inFlags parameter must contain exactly one of the bits
93743** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
93744** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
93745** fast membership test.  When the IN_INDEX_LOOP bit is set, the
93746** IN index will be used to loop over all values of the RHS of the
93747** IN operator.
93748**
93749** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
93750** through the set members) then the b-tree must not contain duplicates.
93751** An epheremal table must be used unless the selected columns are guaranteed
93752** to be unique - either because it is an INTEGER PRIMARY KEY or due to
93753** a UNIQUE constraint or index.
93754**
93755** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
93756** for fast set membership tests) then an epheremal table must
93757** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
93758** index can be found with the specified <columns> as its left-most.
93759**
93760** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
93761** if the RHS of the IN operator is a list (not a subquery) then this
93762** routine might decide that creating an ephemeral b-tree for membership
93763** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
93764** calling routine should implement the IN operator using a sequence
93765** of Eq or Ne comparison operations.
93766**
93767** When the b-tree is being used for membership tests, the calling function
93768** might need to know whether or not the RHS side of the IN operator
93769** contains a NULL.  If prRhsHasNull is not a NULL pointer and
93770** if there is any chance that the (...) might contain a NULL value at
93771** runtime, then a register is allocated and the register number written
93772** to *prRhsHasNull. If there is no chance that the (...) contains a
93773** NULL value, then *prRhsHasNull is left unchanged.
93774**
93775** If a register is allocated and its location stored in *prRhsHasNull, then
93776** the value in that register will be NULL if the b-tree contains one or more
93777** NULL values, and it will be some non-NULL value if the b-tree contains no
93778** NULL values.
93779**
93780** If the aiMap parameter is not NULL, it must point to an array containing
93781** one element for each column returned by the SELECT statement on the RHS
93782** of the IN(...) operator. The i'th entry of the array is populated with the
93783** offset of the index column that matches the i'th column returned by the
93784** SELECT. For example, if the expression and selected index are:
93785**
93786**   (?,?,?) IN (SELECT a, b, c FROM t1)
93787**   CREATE INDEX i1 ON t1(b, c, a);
93788**
93789** then aiMap[] is populated with {2, 0, 1}.
93790*/
93791#ifndef SQLITE_OMIT_SUBQUERY
93792SQLITE_PRIVATE int sqlite3FindInIndex(
93793  Parse *pParse,             /* Parsing context */
93794  Expr *pX,                  /* The right-hand side (RHS) of the IN operator */
93795  u32 inFlags,               /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
93796  int *prRhsHasNull,         /* Register holding NULL status.  See notes */
93797  int *aiMap                 /* Mapping from Index fields to RHS fields */
93798){
93799  Select *p;                            /* SELECT to the right of IN operator */
93800  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
93801  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
93802  int mustBeUnique;                     /* True if RHS must be unique */
93803  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
93804
93805  assert( pX->op==TK_IN );
93806  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
93807
93808  /* If the RHS of this IN(...) operator is a SELECT, and if it matters
93809  ** whether or not the SELECT result contains NULL values, check whether
93810  ** or not NULL is actually possible (it may not be, for example, due
93811  ** to NOT NULL constraints in the schema). If no NULL values are possible,
93812  ** set prRhsHasNull to 0 before continuing.  */
93813  if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
93814    int i;
93815    ExprList *pEList = pX->x.pSelect->pEList;
93816    for(i=0; i<pEList->nExpr; i++){
93817      if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
93818    }
93819    if( i==pEList->nExpr ){
93820      prRhsHasNull = 0;
93821    }
93822  }
93823
93824  /* Check to see if an existing table or index can be used to
93825  ** satisfy the query.  This is preferable to generating a new
93826  ** ephemeral table.  */
93827  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
93828    sqlite3 *db = pParse->db;              /* Database connection */
93829    Table *pTab;                           /* Table <table>. */
93830    i16 iDb;                               /* Database idx for pTab */
93831    ExprList *pEList = p->pEList;
93832    int nExpr = pEList->nExpr;
93833
93834    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
93835    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
93836    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
93837    pTab = p->pSrc->a[0].pTab;
93838
93839    /* Code an OP_Transaction and OP_TableLock for <table>. */
93840    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93841    sqlite3CodeVerifySchema(pParse, iDb);
93842    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
93843
93844    assert(v);  /* sqlite3GetVdbe() has always been previously called */
93845    if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
93846      /* The "x IN (SELECT rowid FROM table)" case */
93847      int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
93848      VdbeCoverage(v);
93849
93850      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
93851      eType = IN_INDEX_ROWID;
93852
93853      sqlite3VdbeJumpHere(v, iAddr);
93854    }else{
93855      Index *pIdx;                         /* Iterator variable */
93856      int affinity_ok = 1;
93857      int i;
93858
93859      /* Check that the affinity that will be used to perform each
93860      ** comparison is the same as the affinity of each column in table
93861      ** on the RHS of the IN operator.  If it not, it is not possible to
93862      ** use any index of the RHS table.  */
93863      for(i=0; i<nExpr && affinity_ok; i++){
93864        Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
93865        int iCol = pEList->a[i].pExpr->iColumn;
93866        char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
93867        char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
93868        testcase( cmpaff==SQLITE_AFF_BLOB );
93869        testcase( cmpaff==SQLITE_AFF_TEXT );
93870        switch( cmpaff ){
93871          case SQLITE_AFF_BLOB:
93872            break;
93873          case SQLITE_AFF_TEXT:
93874            /* sqlite3CompareAffinity() only returns TEXT if one side or the
93875            ** other has no affinity and the other side is TEXT.  Hence,
93876            ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
93877            ** and for the term on the LHS of the IN to have no affinity. */
93878            assert( idxaff==SQLITE_AFF_TEXT );
93879            break;
93880          default:
93881            affinity_ok = sqlite3IsNumericAffinity(idxaff);
93882        }
93883      }
93884
93885      if( affinity_ok ){
93886        /* Search for an existing index that will work for this IN operator */
93887        for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
93888          Bitmask colUsed;      /* Columns of the index used */
93889          Bitmask mCol;         /* Mask for the current column */
93890          if( pIdx->nColumn<nExpr ) continue;
93891          /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
93892          ** BITMASK(nExpr) without overflowing */
93893          testcase( pIdx->nColumn==BMS-2 );
93894          testcase( pIdx->nColumn==BMS-1 );
93895          if( pIdx->nColumn>=BMS-1 ) continue;
93896          if( mustBeUnique ){
93897            if( pIdx->nKeyCol>nExpr
93898             ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
93899            ){
93900              continue;  /* This index is not unique over the IN RHS columns */
93901            }
93902          }
93903
93904          colUsed = 0;   /* Columns of index used so far */
93905          for(i=0; i<nExpr; i++){
93906            Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
93907            Expr *pRhs = pEList->a[i].pExpr;
93908            CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
93909            int j;
93910
93911            assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
93912            for(j=0; j<nExpr; j++){
93913              if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
93914              assert( pIdx->azColl[j] );
93915              if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
93916                continue;
93917              }
93918              break;
93919            }
93920            if( j==nExpr ) break;
93921            mCol = MASKBIT(j);
93922            if( mCol & colUsed ) break; /* Each column used only once */
93923            colUsed |= mCol;
93924            if( aiMap ) aiMap[i] = j;
93925          }
93926
93927          assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
93928          if( colUsed==(MASKBIT(nExpr)-1) ){
93929            /* If we reach this point, that means the index pIdx is usable */
93930            int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
93931#ifndef SQLITE_OMIT_EXPLAIN
93932            sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
93933              sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
93934              P4_DYNAMIC);
93935#endif
93936            sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
93937            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
93938            VdbeComment((v, "%s", pIdx->zName));
93939            assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
93940            eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
93941
93942            if( prRhsHasNull ){
93943#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
93944              i64 mask = (1<<nExpr)-1;
93945              sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
93946                  iTab, 0, 0, (u8*)&mask, P4_INT64);
93947#endif
93948              *prRhsHasNull = ++pParse->nMem;
93949              if( nExpr==1 ){
93950                sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
93951              }
93952            }
93953            sqlite3VdbeJumpHere(v, iAddr);
93954          }
93955        } /* End loop over indexes */
93956      } /* End if( affinity_ok ) */
93957    } /* End if not an rowid index */
93958  } /* End attempt to optimize using an index */
93959
93960  /* If no preexisting index is available for the IN clause
93961  ** and IN_INDEX_NOOP is an allowed reply
93962  ** and the RHS of the IN operator is a list, not a subquery
93963  ** and the RHS is not constant or has two or fewer terms,
93964  ** then it is not worth creating an ephemeral table to evaluate
93965  ** the IN operator so return IN_INDEX_NOOP.
93966  */
93967  if( eType==0
93968   && (inFlags & IN_INDEX_NOOP_OK)
93969   && !ExprHasProperty(pX, EP_xIsSelect)
93970   && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
93971  ){
93972    eType = IN_INDEX_NOOP;
93973  }
93974
93975  if( eType==0 ){
93976    /* Could not find an existing table or index to use as the RHS b-tree.
93977    ** We will have to generate an ephemeral table to do the job.
93978    */
93979    u32 savedNQueryLoop = pParse->nQueryLoop;
93980    int rMayHaveNull = 0;
93981    eType = IN_INDEX_EPH;
93982    if( inFlags & IN_INDEX_LOOP ){
93983      pParse->nQueryLoop = 0;
93984      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
93985        eType = IN_INDEX_ROWID;
93986      }
93987    }else if( prRhsHasNull ){
93988      *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
93989    }
93990    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
93991    pParse->nQueryLoop = savedNQueryLoop;
93992  }else{
93993    pX->iTable = iTab;
93994  }
93995
93996  if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
93997    int i, n;
93998    n = sqlite3ExprVectorSize(pX->pLeft);
93999    for(i=0; i<n; i++) aiMap[i] = i;
94000  }
94001  return eType;
94002}
94003#endif
94004
94005#ifndef SQLITE_OMIT_SUBQUERY
94006/*
94007** Argument pExpr is an (?, ?...) IN(...) expression. This
94008** function allocates and returns a nul-terminated string containing
94009** the affinities to be used for each column of the comparison.
94010**
94011** It is the responsibility of the caller to ensure that the returned
94012** string is eventually freed using sqlite3DbFree().
94013*/
94014static char *exprINAffinity(Parse *pParse, Expr *pExpr){
94015  Expr *pLeft = pExpr->pLeft;
94016  int nVal = sqlite3ExprVectorSize(pLeft);
94017  Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
94018  char *zRet;
94019
94020  assert( pExpr->op==TK_IN );
94021  zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
94022  if( zRet ){
94023    int i;
94024    for(i=0; i<nVal; i++){
94025      Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
94026      char a = sqlite3ExprAffinity(pA);
94027      if( pSelect ){
94028        zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
94029      }else{
94030        zRet[i] = a;
94031      }
94032    }
94033    zRet[nVal] = '\0';
94034  }
94035  return zRet;
94036}
94037#endif
94038
94039#ifndef SQLITE_OMIT_SUBQUERY
94040/*
94041** Load the Parse object passed as the first argument with an error
94042** message of the form:
94043**
94044**   "sub-select returns N columns - expected M"
94045*/
94046SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
94047  const char *zFmt = "sub-select returns %d columns - expected %d";
94048  sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
94049}
94050#endif
94051
94052/*
94053** Expression pExpr is a vector that has been used in a context where
94054** it is not permitted. If pExpr is a sub-select vector, this routine
94055** loads the Parse object with a message of the form:
94056**
94057**   "sub-select returns N columns - expected 1"
94058**
94059** Or, if it is a regular scalar vector:
94060**
94061**   "row value misused"
94062*/
94063SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
94064#ifndef SQLITE_OMIT_SUBQUERY
94065  if( pExpr->flags & EP_xIsSelect ){
94066    sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
94067  }else
94068#endif
94069  {
94070    sqlite3ErrorMsg(pParse, "row value misused");
94071  }
94072}
94073
94074/*
94075** Generate code for scalar subqueries used as a subquery expression, EXISTS,
94076** or IN operators.  Examples:
94077**
94078**     (SELECT a FROM b)          -- subquery
94079**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
94080**     x IN (4,5,11)              -- IN operator with list on right-hand side
94081**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
94082**
94083** The pExpr parameter describes the expression that contains the IN
94084** operator or subquery.
94085**
94086** If parameter isRowid is non-zero, then expression pExpr is guaranteed
94087** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
94088** to some integer key column of a table B-Tree. In this case, use an
94089** intkey B-Tree to store the set of IN(...) values instead of the usual
94090** (slower) variable length keys B-Tree.
94091**
94092** If rMayHaveNull is non-zero, that means that the operation is an IN
94093** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
94094** All this routine does is initialize the register given by rMayHaveNull
94095** to NULL.  Calling routines will take care of changing this register
94096** value to non-NULL if the RHS is NULL-free.
94097**
94098** For a SELECT or EXISTS operator, return the register that holds the
94099** result.  For a multi-column SELECT, the result is stored in a contiguous
94100** array of registers and the return value is the register of the left-most
94101** result column.  Return 0 for IN operators or if an error occurs.
94102*/
94103#ifndef SQLITE_OMIT_SUBQUERY
94104SQLITE_PRIVATE int sqlite3CodeSubselect(
94105  Parse *pParse,          /* Parsing context */
94106  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
94107  int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
94108  int isRowid             /* If true, LHS of IN operator is a rowid */
94109){
94110  int jmpIfDynamic = -1;                      /* One-time test address */
94111  int rReg = 0;                           /* Register storing resulting */
94112  Vdbe *v = sqlite3GetVdbe(pParse);
94113  if( NEVER(v==0) ) return 0;
94114  sqlite3ExprCachePush(pParse);
94115
94116  /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
94117  ** is encountered if any of the following is true:
94118  **
94119  **    *  The right-hand side is a correlated subquery
94120  **    *  The right-hand side is an expression list containing variables
94121  **    *  We are inside a trigger
94122  **
94123  ** If all of the above are false, then we can run this code just once
94124  ** save the results, and reuse the same result on subsequent invocations.
94125  */
94126  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
94127    jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
94128  }
94129
94130#ifndef SQLITE_OMIT_EXPLAIN
94131  if( pParse->explain==2 ){
94132    char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
94133        jmpIfDynamic>=0?"":"CORRELATED ",
94134        pExpr->op==TK_IN?"LIST":"SCALAR",
94135        pParse->iNextSelectId
94136    );
94137    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
94138  }
94139#endif
94140
94141  switch( pExpr->op ){
94142    case TK_IN: {
94143      int addr;                   /* Address of OP_OpenEphemeral instruction */
94144      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
94145      KeyInfo *pKeyInfo = 0;      /* Key information */
94146      int nVal;                   /* Size of vector pLeft */
94147
94148      nVal = sqlite3ExprVectorSize(pLeft);
94149      assert( !isRowid || nVal==1 );
94150
94151      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
94152      ** expression it is handled the same way.  An ephemeral table is
94153      ** filled with index keys representing the results from the
94154      ** SELECT or the <exprlist>.
94155      **
94156      ** If the 'x' expression is a column value, or the SELECT...
94157      ** statement returns a column value, then the affinity of that
94158      ** column is used to build the index keys. If both 'x' and the
94159      ** SELECT... statement are columns, then numeric affinity is used
94160      ** if either column has NUMERIC or INTEGER affinity. If neither
94161      ** 'x' nor the SELECT... statement are columns, then numeric affinity
94162      ** is used.
94163      */
94164      pExpr->iTable = pParse->nTab++;
94165      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
94166          pExpr->iTable, (isRowid?0:nVal));
94167      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
94168
94169      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
94170        /* Case 1:     expr IN (SELECT ...)
94171        **
94172        ** Generate code to write the results of the select into the temporary
94173        ** table allocated and opened above.
94174        */
94175        Select *pSelect = pExpr->x.pSelect;
94176        ExprList *pEList = pSelect->pEList;
94177
94178        assert( !isRowid );
94179        /* If the LHS and RHS of the IN operator do not match, that
94180        ** error will have been caught long before we reach this point. */
94181        if( ALWAYS(pEList->nExpr==nVal) ){
94182          SelectDest dest;
94183          int i;
94184          sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
94185          dest.zAffSdst = exprINAffinity(pParse, pExpr);
94186          pSelect->iLimit = 0;
94187          testcase( pSelect->selFlags & SF_Distinct );
94188          testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
94189          if( sqlite3Select(pParse, pSelect, &dest) ){
94190            sqlite3DbFree(pParse->db, dest.zAffSdst);
94191            sqlite3KeyInfoUnref(pKeyInfo);
94192            return 0;
94193          }
94194          sqlite3DbFree(pParse->db, dest.zAffSdst);
94195          assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
94196          assert( pEList!=0 );
94197          assert( pEList->nExpr>0 );
94198          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
94199          for(i=0; i<nVal; i++){
94200            Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
94201            pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
94202                pParse, p, pEList->a[i].pExpr
94203            );
94204          }
94205        }
94206      }else if( ALWAYS(pExpr->x.pList!=0) ){
94207        /* Case 2:     expr IN (exprlist)
94208        **
94209        ** For each expression, build an index key from the evaluation and
94210        ** store it in the temporary table. If <expr> is a column, then use
94211        ** that columns affinity when building index keys. If <expr> is not
94212        ** a column, use numeric affinity.
94213        */
94214        char affinity;            /* Affinity of the LHS of the IN */
94215        int i;
94216        ExprList *pList = pExpr->x.pList;
94217        struct ExprList_item *pItem;
94218        int r1, r2, r3;
94219
94220        affinity = sqlite3ExprAffinity(pLeft);
94221        if( !affinity ){
94222          affinity = SQLITE_AFF_BLOB;
94223        }
94224        if( pKeyInfo ){
94225          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
94226          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
94227        }
94228
94229        /* Loop through each expression in <exprlist>. */
94230        r1 = sqlite3GetTempReg(pParse);
94231        r2 = sqlite3GetTempReg(pParse);
94232        if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
94233        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
94234          Expr *pE2 = pItem->pExpr;
94235          int iValToIns;
94236
94237          /* If the expression is not constant then we will need to
94238          ** disable the test that was generated above that makes sure
94239          ** this code only executes once.  Because for a non-constant
94240          ** expression we need to rerun this code each time.
94241          */
94242          if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
94243            sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
94244            jmpIfDynamic = -1;
94245          }
94246
94247          /* Evaluate the expression and insert it into the temp table */
94248          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
94249            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
94250          }else{
94251            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
94252            if( isRowid ){
94253              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
94254                                sqlite3VdbeCurrentAddr(v)+2);
94255              VdbeCoverage(v);
94256              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
94257            }else{
94258              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
94259              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
94260              sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
94261            }
94262          }
94263        }
94264        sqlite3ReleaseTempReg(pParse, r1);
94265        sqlite3ReleaseTempReg(pParse, r2);
94266      }
94267      if( pKeyInfo ){
94268        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
94269      }
94270      break;
94271    }
94272
94273    case TK_EXISTS:
94274    case TK_SELECT:
94275    default: {
94276      /* Case 3:    (SELECT ... FROM ...)
94277      **     or:    EXISTS(SELECT ... FROM ...)
94278      **
94279      ** For a SELECT, generate code to put the values for all columns of
94280      ** the first row into an array of registers and return the index of
94281      ** the first register.
94282      **
94283      ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
94284      ** into a register and return that register number.
94285      **
94286      ** In both cases, the query is augmented with "LIMIT 1".  Any
94287      ** preexisting limit is discarded in place of the new LIMIT 1.
94288      */
94289      Select *pSel;                         /* SELECT statement to encode */
94290      SelectDest dest;                      /* How to deal with SELECT result */
94291      int nReg;                             /* Registers to allocate */
94292
94293      testcase( pExpr->op==TK_EXISTS );
94294      testcase( pExpr->op==TK_SELECT );
94295      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
94296      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
94297
94298      pSel = pExpr->x.pSelect;
94299      nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
94300      sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
94301      pParse->nMem += nReg;
94302      if( pExpr->op==TK_SELECT ){
94303        dest.eDest = SRT_Mem;
94304        dest.iSdst = dest.iSDParm;
94305        dest.nSdst = nReg;
94306        sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
94307        VdbeComment((v, "Init subquery result"));
94308      }else{
94309        dest.eDest = SRT_Exists;
94310        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
94311        VdbeComment((v, "Init EXISTS result"));
94312      }
94313      sqlite3ExprDelete(pParse->db, pSel->pLimit);
94314      pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
94315                                  &sqlite3IntTokens[1], 0);
94316      pSel->iLimit = 0;
94317      pSel->selFlags &= ~SF_MultiValue;
94318      if( sqlite3Select(pParse, pSel, &dest) ){
94319        return 0;
94320      }
94321      rReg = dest.iSDParm;
94322      ExprSetVVAProperty(pExpr, EP_NoReduce);
94323      break;
94324    }
94325  }
94326
94327  if( rHasNullFlag ){
94328    sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
94329  }
94330
94331  if( jmpIfDynamic>=0 ){
94332    sqlite3VdbeJumpHere(v, jmpIfDynamic);
94333  }
94334  sqlite3ExprCachePop(pParse);
94335
94336  return rReg;
94337}
94338#endif /* SQLITE_OMIT_SUBQUERY */
94339
94340#ifndef SQLITE_OMIT_SUBQUERY
94341/*
94342** Expr pIn is an IN(...) expression. This function checks that the
94343** sub-select on the RHS of the IN() operator has the same number of
94344** columns as the vector on the LHS. Or, if the RHS of the IN() is not
94345** a sub-query, that the LHS is a vector of size 1.
94346*/
94347SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
94348  int nVector = sqlite3ExprVectorSize(pIn->pLeft);
94349  if( (pIn->flags & EP_xIsSelect) ){
94350    if( nVector!=pIn->x.pSelect->pEList->nExpr ){
94351      sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
94352      return 1;
94353    }
94354  }else if( nVector!=1 ){
94355    sqlite3VectorErrorMsg(pParse, pIn->pLeft);
94356    return 1;
94357  }
94358  return 0;
94359}
94360#endif
94361
94362#ifndef SQLITE_OMIT_SUBQUERY
94363/*
94364** Generate code for an IN expression.
94365**
94366**      x IN (SELECT ...)
94367**      x IN (value, value, ...)
94368**
94369** The left-hand side (LHS) is a scalar or vector expression.  The
94370** right-hand side (RHS) is an array of zero or more scalar values, or a
94371** subquery.  If the RHS is a subquery, the number of result columns must
94372** match the number of columns in the vector on the LHS.  If the RHS is
94373** a list of values, the LHS must be a scalar.
94374**
94375** The IN operator is true if the LHS value is contained within the RHS.
94376** The result is false if the LHS is definitely not in the RHS.  The
94377** result is NULL if the presence of the LHS in the RHS cannot be
94378** determined due to NULLs.
94379**
94380** This routine generates code that jumps to destIfFalse if the LHS is not
94381** contained within the RHS.  If due to NULLs we cannot determine if the LHS
94382** is contained in the RHS then jump to destIfNull.  If the LHS is contained
94383** within the RHS then fall through.
94384**
94385** See the separate in-operator.md documentation file in the canonical
94386** SQLite source tree for additional information.
94387*/
94388static void sqlite3ExprCodeIN(
94389  Parse *pParse,        /* Parsing and code generating context */
94390  Expr *pExpr,          /* The IN expression */
94391  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
94392  int destIfNull        /* Jump here if the results are unknown due to NULLs */
94393){
94394  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
94395  int eType;            /* Type of the RHS */
94396  int rLhs;             /* Register(s) holding the LHS values */
94397  int rLhsOrig;         /* LHS values prior to reordering by aiMap[] */
94398  Vdbe *v;              /* Statement under construction */
94399  int *aiMap = 0;       /* Map from vector field to index column */
94400  char *zAff = 0;       /* Affinity string for comparisons */
94401  int nVector;          /* Size of vectors for this IN operator */
94402  int iDummy;           /* Dummy parameter to exprCodeVector() */
94403  Expr *pLeft;          /* The LHS of the IN operator */
94404  int i;                /* loop counter */
94405  int destStep2;        /* Where to jump when NULLs seen in step 2 */
94406  int destStep6 = 0;    /* Start of code for Step 6 */
94407  int addrTruthOp;      /* Address of opcode that determines the IN is true */
94408  int destNotNull;      /* Jump here if a comparison is not true in step 6 */
94409  int addrTop;          /* Top of the step-6 loop */
94410
94411  pLeft = pExpr->pLeft;
94412  if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
94413  zAff = exprINAffinity(pParse, pExpr);
94414  nVector = sqlite3ExprVectorSize(pExpr->pLeft);
94415  aiMap = (int*)sqlite3DbMallocZero(
94416      pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
94417  );
94418  if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
94419
94420  /* Attempt to compute the RHS. After this step, if anything other than
94421  ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
94422  ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
94423  ** the RHS has not yet been coded.  */
94424  v = pParse->pVdbe;
94425  assert( v!=0 );       /* OOM detected prior to this routine */
94426  VdbeNoopComment((v, "begin IN expr"));
94427  eType = sqlite3FindInIndex(pParse, pExpr,
94428                             IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
94429                             destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
94430
94431  assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
94432       || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
94433  );
94434#ifdef SQLITE_DEBUG
94435  /* Confirm that aiMap[] contains nVector integer values between 0 and
94436  ** nVector-1. */
94437  for(i=0; i<nVector; i++){
94438    int j, cnt;
94439    for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
94440    assert( cnt==1 );
94441  }
94442#endif
94443
94444  /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
94445  ** vector, then it is stored in an array of nVector registers starting
94446  ** at r1.
94447  **
94448  ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
94449  ** so that the fields are in the same order as an existing index.   The
94450  ** aiMap[] array contains a mapping from the original LHS field order to
94451  ** the field order that matches the RHS index.
94452  */
94453  sqlite3ExprCachePush(pParse);
94454  rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
94455  for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
94456  if( i==nVector ){
94457    /* LHS fields are not reordered */
94458    rLhs = rLhsOrig;
94459  }else{
94460    /* Need to reorder the LHS fields according to aiMap */
94461    rLhs = sqlite3GetTempRange(pParse, nVector);
94462    for(i=0; i<nVector; i++){
94463      sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
94464    }
94465  }
94466
94467  /* If sqlite3FindInIndex() did not find or create an index that is
94468  ** suitable for evaluating the IN operator, then evaluate using a
94469  ** sequence of comparisons.
94470  **
94471  ** This is step (1) in the in-operator.md optimized algorithm.
94472  */
94473  if( eType==IN_INDEX_NOOP ){
94474    ExprList *pList = pExpr->x.pList;
94475    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
94476    int labelOk = sqlite3VdbeMakeLabel(v);
94477    int r2, regToFree;
94478    int regCkNull = 0;
94479    int ii;
94480    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
94481    if( destIfNull!=destIfFalse ){
94482      regCkNull = sqlite3GetTempReg(pParse);
94483      sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
94484    }
94485    for(ii=0; ii<pList->nExpr; ii++){
94486      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
94487      if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
94488        sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
94489      }
94490      if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
94491        sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
94492                          (void*)pColl, P4_COLLSEQ);
94493        VdbeCoverageIf(v, ii<pList->nExpr-1);
94494        VdbeCoverageIf(v, ii==pList->nExpr-1);
94495        sqlite3VdbeChangeP5(v, zAff[0]);
94496      }else{
94497        assert( destIfNull==destIfFalse );
94498        sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
94499                          (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
94500        sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
94501      }
94502      sqlite3ReleaseTempReg(pParse, regToFree);
94503    }
94504    if( regCkNull ){
94505      sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
94506      sqlite3VdbeGoto(v, destIfFalse);
94507    }
94508    sqlite3VdbeResolveLabel(v, labelOk);
94509    sqlite3ReleaseTempReg(pParse, regCkNull);
94510    goto sqlite3ExprCodeIN_finished;
94511  }
94512
94513  /* Step 2: Check to see if the LHS contains any NULL columns.  If the
94514  ** LHS does contain NULLs then the result must be either FALSE or NULL.
94515  ** We will then skip the binary search of the RHS.
94516  */
94517  if( destIfNull==destIfFalse ){
94518    destStep2 = destIfFalse;
94519  }else{
94520    destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
94521  }
94522  for(i=0; i<nVector; i++){
94523    Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
94524    if( sqlite3ExprCanBeNull(p) ){
94525      sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
94526      VdbeCoverage(v);
94527    }
94528  }
94529
94530  /* Step 3.  The LHS is now known to be non-NULL.  Do the binary search
94531  ** of the RHS using the LHS as a probe.  If found, the result is
94532  ** true.
94533  */
94534  if( eType==IN_INDEX_ROWID ){
94535    /* In this case, the RHS is the ROWID of table b-tree and so we also
94536    ** know that the RHS is non-NULL.  Hence, we combine steps 3 and 4
94537    ** into a single opcode. */
94538    sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
94539    VdbeCoverage(v);
94540    addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto);  /* Return True */
94541  }else{
94542    sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
94543    if( destIfFalse==destIfNull ){
94544      /* Combine Step 3 and Step 5 into a single opcode */
94545      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
94546                           rLhs, nVector); VdbeCoverage(v);
94547      goto sqlite3ExprCodeIN_finished;
94548    }
94549    /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
94550    addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
94551                                      rLhs, nVector); VdbeCoverage(v);
94552  }
94553
94554  /* Step 4.  If the RHS is known to be non-NULL and we did not find
94555  ** an match on the search above, then the result must be FALSE.
94556  */
94557  if( rRhsHasNull && nVector==1 ){
94558    sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
94559    VdbeCoverage(v);
94560  }
94561
94562  /* Step 5.  If we do not care about the difference between NULL and
94563  ** FALSE, then just return false.
94564  */
94565  if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
94566
94567  /* Step 6: Loop through rows of the RHS.  Compare each row to the LHS.
94568  ** If any comparison is NULL, then the result is NULL.  If all
94569  ** comparisons are FALSE then the final result is FALSE.
94570  **
94571  ** For a scalar LHS, it is sufficient to check just the first row
94572  ** of the RHS.
94573  */
94574  if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
94575  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
94576  VdbeCoverage(v);
94577  if( nVector>1 ){
94578    destNotNull = sqlite3VdbeMakeLabel(v);
94579  }else{
94580    /* For nVector==1, combine steps 6 and 7 by immediately returning
94581    ** FALSE if the first comparison is not NULL */
94582    destNotNull = destIfFalse;
94583  }
94584  for(i=0; i<nVector; i++){
94585    Expr *p;
94586    CollSeq *pColl;
94587    int r3 = sqlite3GetTempReg(pParse);
94588    p = sqlite3VectorFieldSubexpr(pLeft, i);
94589    pColl = sqlite3ExprCollSeq(pParse, p);
94590    sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
94591    sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
94592                      (void*)pColl, P4_COLLSEQ);
94593    VdbeCoverage(v);
94594    sqlite3ReleaseTempReg(pParse, r3);
94595  }
94596  sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
94597  if( nVector>1 ){
94598    sqlite3VdbeResolveLabel(v, destNotNull);
94599    sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
94600    VdbeCoverage(v);
94601
94602    /* Step 7:  If we reach this point, we know that the result must
94603    ** be false. */
94604    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
94605  }
94606
94607  /* Jumps here in order to return true. */
94608  sqlite3VdbeJumpHere(v, addrTruthOp);
94609
94610sqlite3ExprCodeIN_finished:
94611  if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
94612  sqlite3ExprCachePop(pParse);
94613  VdbeComment((v, "end IN expr"));
94614sqlite3ExprCodeIN_oom_error:
94615  sqlite3DbFree(pParse->db, aiMap);
94616  sqlite3DbFree(pParse->db, zAff);
94617}
94618#endif /* SQLITE_OMIT_SUBQUERY */
94619
94620#ifndef SQLITE_OMIT_FLOATING_POINT
94621/*
94622** Generate an instruction that will put the floating point
94623** value described by z[0..n-1] into register iMem.
94624**
94625** The z[] string will probably not be zero-terminated.  But the
94626** z[n] character is guaranteed to be something that does not look
94627** like the continuation of the number.
94628*/
94629static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
94630  if( ALWAYS(z!=0) ){
94631    double value;
94632    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
94633    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
94634    if( negateFlag ) value = -value;
94635    sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
94636  }
94637}
94638#endif
94639
94640
94641/*
94642** Generate an instruction that will put the integer describe by
94643** text z[0..n-1] into register iMem.
94644**
94645** Expr.u.zToken is always UTF8 and zero-terminated.
94646*/
94647static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
94648  Vdbe *v = pParse->pVdbe;
94649  if( pExpr->flags & EP_IntValue ){
94650    int i = pExpr->u.iValue;
94651    assert( i>=0 );
94652    if( negFlag ) i = -i;
94653    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
94654  }else{
94655    int c;
94656    i64 value;
94657    const char *z = pExpr->u.zToken;
94658    assert( z!=0 );
94659    c = sqlite3DecOrHexToI64(z, &value);
94660    if( c==1 || (c==2 && !negFlag) || (negFlag && value==SMALLEST_INT64)){
94661#ifdef SQLITE_OMIT_FLOATING_POINT
94662      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
94663#else
94664#ifndef SQLITE_OMIT_HEX_INTEGER
94665      if( sqlite3_strnicmp(z,"0x",2)==0 ){
94666        sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
94667      }else
94668#endif
94669      {
94670        codeReal(v, z, negFlag, iMem);
94671      }
94672#endif
94673    }else{
94674      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
94675      sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
94676    }
94677  }
94678}
94679
94680/*
94681** Erase column-cache entry number i
94682*/
94683static void cacheEntryClear(Parse *pParse, int i){
94684  if( pParse->aColCache[i].tempReg ){
94685    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
94686      pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
94687    }
94688  }
94689  pParse->nColCache--;
94690  if( i<pParse->nColCache ){
94691    pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
94692  }
94693}
94694
94695
94696/*
94697** Record in the column cache that a particular column from a
94698** particular table is stored in a particular register.
94699*/
94700SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
94701  int i;
94702  int minLru;
94703  int idxLru;
94704  struct yColCache *p;
94705
94706  /* Unless an error has occurred, register numbers are always positive. */
94707  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
94708  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
94709
94710  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
94711  ** for testing only - to verify that SQLite always gets the same answer
94712  ** with and without the column cache.
94713  */
94714  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
94715
94716  /* First replace any existing entry.
94717  **
94718  ** Actually, the way the column cache is currently used, we are guaranteed
94719  ** that the object will never already be in cache.  Verify this guarantee.
94720  */
94721#ifndef NDEBUG
94722  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
94723    assert( p->iTable!=iTab || p->iColumn!=iCol );
94724  }
94725#endif
94726
94727  /* If the cache is already full, delete the least recently used entry */
94728  if( pParse->nColCache>=SQLITE_N_COLCACHE ){
94729    minLru = 0x7fffffff;
94730    idxLru = -1;
94731    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
94732      if( p->lru<minLru ){
94733        idxLru = i;
94734        minLru = p->lru;
94735      }
94736    }
94737    p = &pParse->aColCache[idxLru];
94738  }else{
94739    p = &pParse->aColCache[pParse->nColCache++];
94740  }
94741
94742  /* Add the new entry to the end of the cache */
94743  p->iLevel = pParse->iCacheLevel;
94744  p->iTable = iTab;
94745  p->iColumn = iCol;
94746  p->iReg = iReg;
94747  p->tempReg = 0;
94748  p->lru = pParse->iCacheCnt++;
94749}
94750
94751/*
94752** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
94753** Purge the range of registers from the column cache.
94754*/
94755SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
94756  int i = 0;
94757  while( i<pParse->nColCache ){
94758    struct yColCache *p = &pParse->aColCache[i];
94759    if( p->iReg >= iReg && p->iReg < iReg+nReg ){
94760      cacheEntryClear(pParse, i);
94761    }else{
94762      i++;
94763    }
94764  }
94765}
94766
94767/*
94768** Remember the current column cache context.  Any new entries added
94769** added to the column cache after this call are removed when the
94770** corresponding pop occurs.
94771*/
94772SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
94773  pParse->iCacheLevel++;
94774#ifdef SQLITE_DEBUG
94775  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
94776    printf("PUSH to %d\n", pParse->iCacheLevel);
94777  }
94778#endif
94779}
94780
94781/*
94782** Remove from the column cache any entries that were added since the
94783** the previous sqlite3ExprCachePush operation.  In other words, restore
94784** the cache to the state it was in prior the most recent Push.
94785*/
94786SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
94787  int i = 0;
94788  assert( pParse->iCacheLevel>=1 );
94789  pParse->iCacheLevel--;
94790#ifdef SQLITE_DEBUG
94791  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
94792    printf("POP  to %d\n", pParse->iCacheLevel);
94793  }
94794#endif
94795  while( i<pParse->nColCache ){
94796    if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
94797      cacheEntryClear(pParse, i);
94798    }else{
94799      i++;
94800    }
94801  }
94802}
94803
94804/*
94805** When a cached column is reused, make sure that its register is
94806** no longer available as a temp register.  ticket #3879:  that same
94807** register might be in the cache in multiple places, so be sure to
94808** get them all.
94809*/
94810static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
94811  int i;
94812  struct yColCache *p;
94813  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
94814    if( p->iReg==iReg ){
94815      p->tempReg = 0;
94816    }
94817  }
94818}
94819
94820/* Generate code that will load into register regOut a value that is
94821** appropriate for the iIdxCol-th column of index pIdx.
94822*/
94823SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
94824  Parse *pParse,  /* The parsing context */
94825  Index *pIdx,    /* The index whose column is to be loaded */
94826  int iTabCur,    /* Cursor pointing to a table row */
94827  int iIdxCol,    /* The column of the index to be loaded */
94828  int regOut      /* Store the index column value in this register */
94829){
94830  i16 iTabCol = pIdx->aiColumn[iIdxCol];
94831  if( iTabCol==XN_EXPR ){
94832    assert( pIdx->aColExpr );
94833    assert( pIdx->aColExpr->nExpr>iIdxCol );
94834    pParse->iSelfTab = iTabCur + 1;
94835    sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
94836    pParse->iSelfTab = 0;
94837  }else{
94838    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
94839                                    iTabCol, regOut);
94840  }
94841}
94842
94843/*
94844** Generate code to extract the value of the iCol-th column of a table.
94845*/
94846SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
94847  Vdbe *v,        /* The VDBE under construction */
94848  Table *pTab,    /* The table containing the value */
94849  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
94850  int iCol,       /* Index of the column to extract */
94851  int regOut      /* Extract the value into this register */
94852){
94853  if( pTab==0 ){
94854    sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
94855    return;
94856  }
94857  if( iCol<0 || iCol==pTab->iPKey ){
94858    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
94859  }else{
94860    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
94861    int x = iCol;
94862    if( !HasRowid(pTab) && !IsVirtual(pTab) ){
94863      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
94864    }
94865    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
94866  }
94867  if( iCol>=0 ){
94868    sqlite3ColumnDefault(v, pTab, iCol, regOut);
94869  }
94870}
94871
94872/*
94873** Generate code that will extract the iColumn-th column from
94874** table pTab and store the column value in a register.
94875**
94876** An effort is made to store the column value in register iReg.  This
94877** is not garanteeed for GetColumn() - the result can be stored in
94878** any register.  But the result is guaranteed to land in register iReg
94879** for GetColumnToReg().
94880**
94881** There must be an open cursor to pTab in iTable when this routine
94882** is called.  If iColumn<0 then code is generated that extracts the rowid.
94883*/
94884SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
94885  Parse *pParse,   /* Parsing and code generating context */
94886  Table *pTab,     /* Description of the table we are reading from */
94887  int iColumn,     /* Index of the table column */
94888  int iTable,      /* The cursor pointing to the table */
94889  int iReg,        /* Store results here */
94890  u8 p5            /* P5 value for OP_Column + FLAGS */
94891){
94892  Vdbe *v = pParse->pVdbe;
94893  int i;
94894  struct yColCache *p;
94895
94896  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
94897    if( p->iTable==iTable && p->iColumn==iColumn ){
94898      p->lru = pParse->iCacheCnt++;
94899      sqlite3ExprCachePinRegister(pParse, p->iReg);
94900      return p->iReg;
94901    }
94902  }
94903  assert( v!=0 );
94904  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
94905  if( p5 ){
94906    sqlite3VdbeChangeP5(v, p5);
94907  }else{
94908    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
94909  }
94910  return iReg;
94911}
94912SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
94913  Parse *pParse,   /* Parsing and code generating context */
94914  Table *pTab,     /* Description of the table we are reading from */
94915  int iColumn,     /* Index of the table column */
94916  int iTable,      /* The cursor pointing to the table */
94917  int iReg         /* Store results here */
94918){
94919  int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
94920  if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
94921}
94922
94923
94924/*
94925** Clear all column cache entries.
94926*/
94927SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
94928  int i;
94929
94930#ifdef SQLITE_DEBUG
94931  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
94932    printf("CLEAR\n");
94933  }
94934#endif
94935  for(i=0; i<pParse->nColCache; i++){
94936    if( pParse->aColCache[i].tempReg
94937     && pParse->nTempReg<ArraySize(pParse->aTempReg)
94938    ){
94939       pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
94940    }
94941  }
94942  pParse->nColCache = 0;
94943}
94944
94945/*
94946** Record the fact that an affinity change has occurred on iCount
94947** registers starting with iStart.
94948*/
94949SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
94950  sqlite3ExprCacheRemove(pParse, iStart, iCount);
94951}
94952
94953/*
94954** Generate code to move content from registers iFrom...iFrom+nReg-1
94955** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
94956*/
94957SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
94958  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
94959  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
94960  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
94961}
94962
94963#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
94964/*
94965** Return true if any register in the range iFrom..iTo (inclusive)
94966** is used as part of the column cache.
94967**
94968** This routine is used within assert() and testcase() macros only
94969** and does not appear in a normal build.
94970*/
94971static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
94972  int i;
94973  struct yColCache *p;
94974  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
94975    int r = p->iReg;
94976    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
94977  }
94978  return 0;
94979}
94980#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
94981
94982
94983/*
94984** Convert a scalar expression node to a TK_REGISTER referencing
94985** register iReg.  The caller must ensure that iReg already contains
94986** the correct value for the expression.
94987*/
94988static void exprToRegister(Expr *p, int iReg){
94989  p->op2 = p->op;
94990  p->op = TK_REGISTER;
94991  p->iTable = iReg;
94992  ExprClearProperty(p, EP_Skip);
94993}
94994
94995/*
94996** Evaluate an expression (either a vector or a scalar expression) and store
94997** the result in continguous temporary registers.  Return the index of
94998** the first register used to store the result.
94999**
95000** If the returned result register is a temporary scalar, then also write
95001** that register number into *piFreeable.  If the returned result register
95002** is not a temporary or if the expression is a vector set *piFreeable
95003** to 0.
95004*/
95005static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
95006  int iResult;
95007  int nResult = sqlite3ExprVectorSize(p);
95008  if( nResult==1 ){
95009    iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
95010  }else{
95011    *piFreeable = 0;
95012    if( p->op==TK_SELECT ){
95013#if SQLITE_OMIT_SUBQUERY
95014      iResult = 0;
95015#else
95016      iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
95017#endif
95018    }else{
95019      int i;
95020      iResult = pParse->nMem+1;
95021      pParse->nMem += nResult;
95022      for(i=0; i<nResult; i++){
95023        sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
95024      }
95025    }
95026  }
95027  return iResult;
95028}
95029
95030
95031/*
95032** Generate code into the current Vdbe to evaluate the given
95033** expression.  Attempt to store the results in register "target".
95034** Return the register where results are stored.
95035**
95036** With this routine, there is no guarantee that results will
95037** be stored in target.  The result might be stored in some other
95038** register if it is convenient to do so.  The calling function
95039** must check the return code and move the results to the desired
95040** register.
95041*/
95042SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
95043  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
95044  int op;                   /* The opcode being coded */
95045  int inReg = target;       /* Results stored in register inReg */
95046  int regFree1 = 0;         /* If non-zero free this temporary register */
95047  int regFree2 = 0;         /* If non-zero free this temporary register */
95048  int r1, r2;               /* Various register numbers */
95049  Expr tempX;               /* Temporary expression node */
95050  int p5 = 0;
95051
95052  assert( target>0 && target<=pParse->nMem );
95053  if( v==0 ){
95054    assert( pParse->db->mallocFailed );
95055    return 0;
95056  }
95057
95058  if( pExpr==0 ){
95059    op = TK_NULL;
95060  }else{
95061    op = pExpr->op;
95062  }
95063  switch( op ){
95064    case TK_AGG_COLUMN: {
95065      AggInfo *pAggInfo = pExpr->pAggInfo;
95066      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
95067      if( !pAggInfo->directMode ){
95068        assert( pCol->iMem>0 );
95069        return pCol->iMem;
95070      }else if( pAggInfo->useSortingIdx ){
95071        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
95072                              pCol->iSorterColumn, target);
95073        return target;
95074      }
95075      /* Otherwise, fall thru into the TK_COLUMN case */
95076    }
95077    case TK_COLUMN: {
95078      int iTab = pExpr->iTable;
95079      if( iTab<0 ){
95080        if( pParse->iSelfTab<0 ){
95081          /* Generating CHECK constraints or inserting into partial index */
95082          return pExpr->iColumn - pParse->iSelfTab;
95083        }else{
95084          /* Coding an expression that is part of an index where column names
95085          ** in the index refer to the table to which the index belongs */
95086          iTab = pParse->iSelfTab - 1;
95087        }
95088      }
95089      return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
95090                               pExpr->iColumn, iTab, target,
95091                               pExpr->op2);
95092    }
95093    case TK_INTEGER: {
95094      codeInteger(pParse, pExpr, 0, target);
95095      return target;
95096    }
95097#ifndef SQLITE_OMIT_FLOATING_POINT
95098    case TK_FLOAT: {
95099      assert( !ExprHasProperty(pExpr, EP_IntValue) );
95100      codeReal(v, pExpr->u.zToken, 0, target);
95101      return target;
95102    }
95103#endif
95104    case TK_STRING: {
95105      assert( !ExprHasProperty(pExpr, EP_IntValue) );
95106      sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
95107      return target;
95108    }
95109    case TK_NULL: {
95110      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
95111      return target;
95112    }
95113#ifndef SQLITE_OMIT_BLOB_LITERAL
95114    case TK_BLOB: {
95115      int n;
95116      const char *z;
95117      char *zBlob;
95118      assert( !ExprHasProperty(pExpr, EP_IntValue) );
95119      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
95120      assert( pExpr->u.zToken[1]=='\'' );
95121      z = &pExpr->u.zToken[2];
95122      n = sqlite3Strlen30(z) - 1;
95123      assert( z[n]=='\'' );
95124      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
95125      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
95126      return target;
95127    }
95128#endif
95129    case TK_VARIABLE: {
95130      assert( !ExprHasProperty(pExpr, EP_IntValue) );
95131      assert( pExpr->u.zToken!=0 );
95132      assert( pExpr->u.zToken[0]!=0 );
95133      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
95134      if( pExpr->u.zToken[1]!=0 ){
95135        const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
95136        assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
95137        pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
95138        sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
95139      }
95140      return target;
95141    }
95142    case TK_REGISTER: {
95143      return pExpr->iTable;
95144    }
95145#ifndef SQLITE_OMIT_CAST
95146    case TK_CAST: {
95147      /* Expressions of the form:   CAST(pLeft AS token) */
95148      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
95149      if( inReg!=target ){
95150        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
95151        inReg = target;
95152      }
95153      sqlite3VdbeAddOp2(v, OP_Cast, target,
95154                        sqlite3AffinityType(pExpr->u.zToken, 0));
95155      testcase( usedAsColumnCache(pParse, inReg, inReg) );
95156      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
95157      return inReg;
95158    }
95159#endif /* SQLITE_OMIT_CAST */
95160    case TK_IS:
95161    case TK_ISNOT:
95162      op = (op==TK_IS) ? TK_EQ : TK_NE;
95163      p5 = SQLITE_NULLEQ;
95164      /* fall-through */
95165    case TK_LT:
95166    case TK_LE:
95167    case TK_GT:
95168    case TK_GE:
95169    case TK_NE:
95170    case TK_EQ: {
95171      Expr *pLeft = pExpr->pLeft;
95172      if( sqlite3ExprIsVector(pLeft) ){
95173        codeVectorCompare(pParse, pExpr, target, op, p5);
95174      }else{
95175        r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
95176        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
95177        codeCompare(pParse, pLeft, pExpr->pRight, op,
95178            r1, r2, inReg, SQLITE_STOREP2 | p5);
95179        assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
95180        assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
95181        assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
95182        assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
95183        assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
95184        assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
95185        testcase( regFree1==0 );
95186        testcase( regFree2==0 );
95187      }
95188      break;
95189    }
95190    case TK_AND:
95191    case TK_OR:
95192    case TK_PLUS:
95193    case TK_STAR:
95194    case TK_MINUS:
95195    case TK_REM:
95196    case TK_BITAND:
95197    case TK_BITOR:
95198    case TK_SLASH:
95199    case TK_LSHIFT:
95200    case TK_RSHIFT:
95201    case TK_CONCAT: {
95202      assert( TK_AND==OP_And );            testcase( op==TK_AND );
95203      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
95204      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
95205      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
95206      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
95207      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
95208      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
95209      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
95210      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
95211      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
95212      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
95213      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95214      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
95215      sqlite3VdbeAddOp3(v, op, r2, r1, target);
95216      testcase( regFree1==0 );
95217      testcase( regFree2==0 );
95218      break;
95219    }
95220    case TK_UMINUS: {
95221      Expr *pLeft = pExpr->pLeft;
95222      assert( pLeft );
95223      if( pLeft->op==TK_INTEGER ){
95224        codeInteger(pParse, pLeft, 1, target);
95225        return target;
95226#ifndef SQLITE_OMIT_FLOATING_POINT
95227      }else if( pLeft->op==TK_FLOAT ){
95228        assert( !ExprHasProperty(pExpr, EP_IntValue) );
95229        codeReal(v, pLeft->u.zToken, 1, target);
95230        return target;
95231#endif
95232      }else{
95233        tempX.op = TK_INTEGER;
95234        tempX.flags = EP_IntValue|EP_TokenOnly;
95235        tempX.u.iValue = 0;
95236        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
95237        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
95238        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
95239        testcase( regFree2==0 );
95240      }
95241      break;
95242    }
95243    case TK_BITNOT:
95244    case TK_NOT: {
95245      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
95246      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
95247      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95248      testcase( regFree1==0 );
95249      sqlite3VdbeAddOp2(v, op, r1, inReg);
95250      break;
95251    }
95252    case TK_ISNULL:
95253    case TK_NOTNULL: {
95254      int addr;
95255      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
95256      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
95257      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
95258      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
95259      testcase( regFree1==0 );
95260      addr = sqlite3VdbeAddOp1(v, op, r1);
95261      VdbeCoverageIf(v, op==TK_ISNULL);
95262      VdbeCoverageIf(v, op==TK_NOTNULL);
95263      sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
95264      sqlite3VdbeJumpHere(v, addr);
95265      break;
95266    }
95267    case TK_AGG_FUNCTION: {
95268      AggInfo *pInfo = pExpr->pAggInfo;
95269      if( pInfo==0 ){
95270        assert( !ExprHasProperty(pExpr, EP_IntValue) );
95271        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
95272      }else{
95273        return pInfo->aFunc[pExpr->iAgg].iMem;
95274      }
95275      break;
95276    }
95277    case TK_FUNCTION: {
95278      ExprList *pFarg;       /* List of function arguments */
95279      int nFarg;             /* Number of function arguments */
95280      FuncDef *pDef;         /* The function definition object */
95281      const char *zId;       /* The function name */
95282      u32 constMask = 0;     /* Mask of function arguments that are constant */
95283      int i;                 /* Loop counter */
95284      sqlite3 *db = pParse->db;  /* The database connection */
95285      u8 enc = ENC(db);      /* The text encoding used by this database */
95286      CollSeq *pColl = 0;    /* A collating sequence */
95287
95288      if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
95289        /* SQL functions can be expensive. So try to move constant functions
95290        ** out of the inner loop, even if that means an extra OP_Copy. */
95291        return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
95292      }
95293      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
95294      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
95295        pFarg = 0;
95296      }else{
95297        pFarg = pExpr->x.pList;
95298      }
95299      nFarg = pFarg ? pFarg->nExpr : 0;
95300      assert( !ExprHasProperty(pExpr, EP_IntValue) );
95301      zId = pExpr->u.zToken;
95302      pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
95303#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
95304      if( pDef==0 && pParse->explain ){
95305        pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
95306      }
95307#endif
95308      if( pDef==0 || pDef->xFinalize!=0 ){
95309        sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
95310        break;
95311      }
95312
95313      /* Attempt a direct implementation of the built-in COALESCE() and
95314      ** IFNULL() functions.  This avoids unnecessary evaluation of
95315      ** arguments past the first non-NULL argument.
95316      */
95317      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
95318        int endCoalesce = sqlite3VdbeMakeLabel(v);
95319        assert( nFarg>=2 );
95320        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
95321        for(i=1; i<nFarg; i++){
95322          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
95323          VdbeCoverage(v);
95324          sqlite3ExprCacheRemove(pParse, target, 1);
95325          sqlite3ExprCachePush(pParse);
95326          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
95327          sqlite3ExprCachePop(pParse);
95328        }
95329        sqlite3VdbeResolveLabel(v, endCoalesce);
95330        break;
95331      }
95332
95333      /* The UNLIKELY() function is a no-op.  The result is the value
95334      ** of the first argument.
95335      */
95336      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
95337        assert( nFarg>=1 );
95338        return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
95339      }
95340
95341#ifdef SQLITE_DEBUG
95342      /* The AFFINITY() function evaluates to a string that describes
95343      ** the type affinity of the argument.  This is used for testing of
95344      ** the SQLite type logic.
95345      */
95346      if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
95347        const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
95348        char aff;
95349        assert( nFarg==1 );
95350        aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
95351        sqlite3VdbeLoadString(v, target,
95352                              aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
95353        return target;
95354      }
95355#endif
95356
95357      for(i=0; i<nFarg; i++){
95358        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
95359          testcase( i==31 );
95360          constMask |= MASKBIT32(i);
95361        }
95362        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
95363          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
95364        }
95365      }
95366      if( pFarg ){
95367        if( constMask ){
95368          r1 = pParse->nMem+1;
95369          pParse->nMem += nFarg;
95370        }else{
95371          r1 = sqlite3GetTempRange(pParse, nFarg);
95372        }
95373
95374        /* For length() and typeof() functions with a column argument,
95375        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
95376        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
95377        ** loading.
95378        */
95379        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
95380          u8 exprOp;
95381          assert( nFarg==1 );
95382          assert( pFarg->a[0].pExpr!=0 );
95383          exprOp = pFarg->a[0].pExpr->op;
95384          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
95385            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
95386            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
95387            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
95388            pFarg->a[0].pExpr->op2 =
95389                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
95390          }
95391        }
95392
95393        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
95394        sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
95395                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
95396        sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
95397      }else{
95398        r1 = 0;
95399      }
95400#ifndef SQLITE_OMIT_VIRTUALTABLE
95401      /* Possibly overload the function if the first argument is
95402      ** a virtual table column.
95403      **
95404      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
95405      ** second argument, not the first, as the argument to test to
95406      ** see if it is a column in a virtual table.  This is done because
95407      ** the left operand of infix functions (the operand we want to
95408      ** control overloading) ends up as the second argument to the
95409      ** function.  The expression "A glob B" is equivalent to
95410      ** "glob(B,A).  We want to use the A in "A glob B" to test
95411      ** for function overloading.  But we use the B term in "glob(B,A)".
95412      */
95413      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
95414        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
95415      }else if( nFarg>0 ){
95416        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
95417      }
95418#endif
95419      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
95420        if( !pColl ) pColl = db->pDfltColl;
95421        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
95422      }
95423      sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
95424                        constMask, r1, target, (char*)pDef, P4_FUNCDEF);
95425      sqlite3VdbeChangeP5(v, (u8)nFarg);
95426      if( nFarg && constMask==0 ){
95427        sqlite3ReleaseTempRange(pParse, r1, nFarg);
95428      }
95429      return target;
95430    }
95431#ifndef SQLITE_OMIT_SUBQUERY
95432    case TK_EXISTS:
95433    case TK_SELECT: {
95434      int nCol;
95435      testcase( op==TK_EXISTS );
95436      testcase( op==TK_SELECT );
95437      if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
95438        sqlite3SubselectError(pParse, nCol, 1);
95439      }else{
95440        return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
95441      }
95442      break;
95443    }
95444    case TK_SELECT_COLUMN: {
95445      int n;
95446      if( pExpr->pLeft->iTable==0 ){
95447        pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
95448      }
95449      assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
95450      if( pExpr->iTable
95451       && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
95452      ){
95453        sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
95454                                pExpr->iTable, n);
95455      }
95456      return pExpr->pLeft->iTable + pExpr->iColumn;
95457    }
95458    case TK_IN: {
95459      int destIfFalse = sqlite3VdbeMakeLabel(v);
95460      int destIfNull = sqlite3VdbeMakeLabel(v);
95461      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
95462      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
95463      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
95464      sqlite3VdbeResolveLabel(v, destIfFalse);
95465      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
95466      sqlite3VdbeResolveLabel(v, destIfNull);
95467      return target;
95468    }
95469#endif /* SQLITE_OMIT_SUBQUERY */
95470
95471
95472    /*
95473    **    x BETWEEN y AND z
95474    **
95475    ** This is equivalent to
95476    **
95477    **    x>=y AND x<=z
95478    **
95479    ** X is stored in pExpr->pLeft.
95480    ** Y is stored in pExpr->pList->a[0].pExpr.
95481    ** Z is stored in pExpr->pList->a[1].pExpr.
95482    */
95483    case TK_BETWEEN: {
95484      exprCodeBetween(pParse, pExpr, target, 0, 0);
95485      return target;
95486    }
95487    case TK_SPAN:
95488    case TK_COLLATE:
95489    case TK_UPLUS: {
95490      return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
95491    }
95492
95493    case TK_TRIGGER: {
95494      /* If the opcode is TK_TRIGGER, then the expression is a reference
95495      ** to a column in the new.* or old.* pseudo-tables available to
95496      ** trigger programs. In this case Expr.iTable is set to 1 for the
95497      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
95498      ** is set to the column of the pseudo-table to read, or to -1 to
95499      ** read the rowid field.
95500      **
95501      ** The expression is implemented using an OP_Param opcode. The p1
95502      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
95503      ** to reference another column of the old.* pseudo-table, where
95504      ** i is the index of the column. For a new.rowid reference, p1 is
95505      ** set to (n+1), where n is the number of columns in each pseudo-table.
95506      ** For a reference to any other column in the new.* pseudo-table, p1
95507      ** is set to (n+2+i), where n and i are as defined previously. For
95508      ** example, if the table on which triggers are being fired is
95509      ** declared as:
95510      **
95511      **   CREATE TABLE t1(a, b);
95512      **
95513      ** Then p1 is interpreted as follows:
95514      **
95515      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
95516      **   p1==1   ->    old.a         p1==4   ->    new.a
95517      **   p1==2   ->    old.b         p1==5   ->    new.b
95518      */
95519      Table *pTab = pExpr->pTab;
95520      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
95521
95522      assert( pExpr->iTable==0 || pExpr->iTable==1 );
95523      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
95524      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
95525      assert( p1>=0 && p1<(pTab->nCol*2+2) );
95526
95527      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
95528      VdbeComment((v, "%s.%s -> $%d",
95529        (pExpr->iTable ? "new" : "old"),
95530        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
95531        target
95532      ));
95533
95534#ifndef SQLITE_OMIT_FLOATING_POINT
95535      /* If the column has REAL affinity, it may currently be stored as an
95536      ** integer. Use OP_RealAffinity to make sure it is really real.
95537      **
95538      ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
95539      ** floating point when extracting it from the record.  */
95540      if( pExpr->iColumn>=0
95541       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
95542      ){
95543        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
95544      }
95545#endif
95546      break;
95547    }
95548
95549    case TK_VECTOR: {
95550      sqlite3ErrorMsg(pParse, "row value misused");
95551      break;
95552    }
95553
95554    case TK_IF_NULL_ROW: {
95555      int addrINR;
95556      addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
95557      sqlite3ExprCachePush(pParse);
95558      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
95559      sqlite3ExprCachePop(pParse);
95560      sqlite3VdbeJumpHere(v, addrINR);
95561      sqlite3VdbeChangeP3(v, addrINR, inReg);
95562      break;
95563    }
95564
95565    /*
95566    ** Form A:
95567    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
95568    **
95569    ** Form B:
95570    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
95571    **
95572    ** Form A is can be transformed into the equivalent form B as follows:
95573    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
95574    **        WHEN x=eN THEN rN ELSE y END
95575    **
95576    ** X (if it exists) is in pExpr->pLeft.
95577    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
95578    ** odd.  The Y is also optional.  If the number of elements in x.pList
95579    ** is even, then Y is omitted and the "otherwise" result is NULL.
95580    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
95581    **
95582    ** The result of the expression is the Ri for the first matching Ei,
95583    ** or if there is no matching Ei, the ELSE term Y, or if there is
95584    ** no ELSE term, NULL.
95585    */
95586    default: assert( op==TK_CASE ); {
95587      int endLabel;                     /* GOTO label for end of CASE stmt */
95588      int nextCase;                     /* GOTO label for next WHEN clause */
95589      int nExpr;                        /* 2x number of WHEN terms */
95590      int i;                            /* Loop counter */
95591      ExprList *pEList;                 /* List of WHEN terms */
95592      struct ExprList_item *aListelem;  /* Array of WHEN terms */
95593      Expr opCompare;                   /* The X==Ei expression */
95594      Expr *pX;                         /* The X expression */
95595      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
95596      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
95597
95598      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
95599      assert(pExpr->x.pList->nExpr > 0);
95600      pEList = pExpr->x.pList;
95601      aListelem = pEList->a;
95602      nExpr = pEList->nExpr;
95603      endLabel = sqlite3VdbeMakeLabel(v);
95604      if( (pX = pExpr->pLeft)!=0 ){
95605        tempX = *pX;
95606        testcase( pX->op==TK_COLUMN );
95607        exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
95608        testcase( regFree1==0 );
95609        memset(&opCompare, 0, sizeof(opCompare));
95610        opCompare.op = TK_EQ;
95611        opCompare.pLeft = &tempX;
95612        pTest = &opCompare;
95613        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
95614        ** The value in regFree1 might get SCopy-ed into the file result.
95615        ** So make sure that the regFree1 register is not reused for other
95616        ** purposes and possibly overwritten.  */
95617        regFree1 = 0;
95618      }
95619      for(i=0; i<nExpr-1; i=i+2){
95620        sqlite3ExprCachePush(pParse);
95621        if( pX ){
95622          assert( pTest!=0 );
95623          opCompare.pRight = aListelem[i].pExpr;
95624        }else{
95625          pTest = aListelem[i].pExpr;
95626        }
95627        nextCase = sqlite3VdbeMakeLabel(v);
95628        testcase( pTest->op==TK_COLUMN );
95629        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
95630        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
95631        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
95632        sqlite3VdbeGoto(v, endLabel);
95633        sqlite3ExprCachePop(pParse);
95634        sqlite3VdbeResolveLabel(v, nextCase);
95635      }
95636      if( (nExpr&1)!=0 ){
95637        sqlite3ExprCachePush(pParse);
95638        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
95639        sqlite3ExprCachePop(pParse);
95640      }else{
95641        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
95642      }
95643      assert( pParse->db->mallocFailed || pParse->nErr>0
95644           || pParse->iCacheLevel==iCacheLevel );
95645      sqlite3VdbeResolveLabel(v, endLabel);
95646      break;
95647    }
95648#ifndef SQLITE_OMIT_TRIGGER
95649    case TK_RAISE: {
95650      assert( pExpr->affinity==OE_Rollback
95651           || pExpr->affinity==OE_Abort
95652           || pExpr->affinity==OE_Fail
95653           || pExpr->affinity==OE_Ignore
95654      );
95655      if( !pParse->pTriggerTab ){
95656        sqlite3ErrorMsg(pParse,
95657                       "RAISE() may only be used within a trigger-program");
95658        return 0;
95659      }
95660      if( pExpr->affinity==OE_Abort ){
95661        sqlite3MayAbort(pParse);
95662      }
95663      assert( !ExprHasProperty(pExpr, EP_IntValue) );
95664      if( pExpr->affinity==OE_Ignore ){
95665        sqlite3VdbeAddOp4(
95666            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
95667        VdbeCoverage(v);
95668      }else{
95669        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
95670                              pExpr->affinity, pExpr->u.zToken, 0, 0);
95671      }
95672
95673      break;
95674    }
95675#endif
95676  }
95677  sqlite3ReleaseTempReg(pParse, regFree1);
95678  sqlite3ReleaseTempReg(pParse, regFree2);
95679  return inReg;
95680}
95681
95682/*
95683** Factor out the code of the given expression to initialization time.
95684**
95685** If regDest>=0 then the result is always stored in that register and the
95686** result is not reusable.  If regDest<0 then this routine is free to
95687** store the value whereever it wants.  The register where the expression
95688** is stored is returned.  When regDest<0, two identical expressions will
95689** code to the same register.
95690*/
95691SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
95692  Parse *pParse,    /* Parsing context */
95693  Expr *pExpr,      /* The expression to code when the VDBE initializes */
95694  int regDest       /* Store the value in this register */
95695){
95696  ExprList *p;
95697  assert( ConstFactorOk(pParse) );
95698  p = pParse->pConstExpr;
95699  if( regDest<0 && p ){
95700    struct ExprList_item *pItem;
95701    int i;
95702    for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
95703      if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
95704        return pItem->u.iConstExprReg;
95705      }
95706    }
95707  }
95708  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
95709  p = sqlite3ExprListAppend(pParse, p, pExpr);
95710  if( p ){
95711     struct ExprList_item *pItem = &p->a[p->nExpr-1];
95712     pItem->reusable = regDest<0;
95713     if( regDest<0 ) regDest = ++pParse->nMem;
95714     pItem->u.iConstExprReg = regDest;
95715  }
95716  pParse->pConstExpr = p;
95717  return regDest;
95718}
95719
95720/*
95721** Generate code to evaluate an expression and store the results
95722** into a register.  Return the register number where the results
95723** are stored.
95724**
95725** If the register is a temporary register that can be deallocated,
95726** then write its number into *pReg.  If the result register is not
95727** a temporary, then set *pReg to zero.
95728**
95729** If pExpr is a constant, then this routine might generate this
95730** code to fill the register in the initialization section of the
95731** VDBE program, in order to factor it out of the evaluation loop.
95732*/
95733SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
95734  int r2;
95735  pExpr = sqlite3ExprSkipCollate(pExpr);
95736  if( ConstFactorOk(pParse)
95737   && pExpr->op!=TK_REGISTER
95738   && sqlite3ExprIsConstantNotJoin(pExpr)
95739  ){
95740    *pReg  = 0;
95741    r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
95742  }else{
95743    int r1 = sqlite3GetTempReg(pParse);
95744    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
95745    if( r2==r1 ){
95746      *pReg = r1;
95747    }else{
95748      sqlite3ReleaseTempReg(pParse, r1);
95749      *pReg = 0;
95750    }
95751  }
95752  return r2;
95753}
95754
95755/*
95756** Generate code that will evaluate expression pExpr and store the
95757** results in register target.  The results are guaranteed to appear
95758** in register target.
95759*/
95760SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
95761  int inReg;
95762
95763  assert( target>0 && target<=pParse->nMem );
95764  if( pExpr && pExpr->op==TK_REGISTER ){
95765    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
95766  }else{
95767    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
95768    assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
95769    if( inReg!=target && pParse->pVdbe ){
95770      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
95771    }
95772  }
95773}
95774
95775/*
95776** Make a transient copy of expression pExpr and then code it using
95777** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
95778** except that the input expression is guaranteed to be unchanged.
95779*/
95780SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
95781  sqlite3 *db = pParse->db;
95782  pExpr = sqlite3ExprDup(db, pExpr, 0);
95783  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
95784  sqlite3ExprDelete(db, pExpr);
95785}
95786
95787/*
95788** Generate code that will evaluate expression pExpr and store the
95789** results in register target.  The results are guaranteed to appear
95790** in register target.  If the expression is constant, then this routine
95791** might choose to code the expression at initialization time.
95792*/
95793SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
95794  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
95795    sqlite3ExprCodeAtInit(pParse, pExpr, target);
95796  }else{
95797    sqlite3ExprCode(pParse, pExpr, target);
95798  }
95799}
95800
95801/*
95802** Generate code that evaluates the given expression and puts the result
95803** in register target.
95804**
95805** Also make a copy of the expression results into another "cache" register
95806** and modify the expression so that the next time it is evaluated,
95807** the result is a copy of the cache register.
95808**
95809** This routine is used for expressions that are used multiple
95810** times.  They are evaluated once and the results of the expression
95811** are reused.
95812*/
95813SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
95814  Vdbe *v = pParse->pVdbe;
95815  int iMem;
95816
95817  assert( target>0 );
95818  assert( pExpr->op!=TK_REGISTER );
95819  sqlite3ExprCode(pParse, pExpr, target);
95820  iMem = ++pParse->nMem;
95821  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
95822  exprToRegister(pExpr, iMem);
95823}
95824
95825/*
95826** Generate code that pushes the value of every element of the given
95827** expression list into a sequence of registers beginning at target.
95828**
95829** Return the number of elements evaluated.
95830**
95831** The SQLITE_ECEL_DUP flag prevents the arguments from being
95832** filled using OP_SCopy.  OP_Copy must be used instead.
95833**
95834** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
95835** factored out into initialization code.
95836**
95837** The SQLITE_ECEL_REF flag means that expressions in the list with
95838** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
95839** in registers at srcReg, and so the value can be copied from there.
95840*/
95841SQLITE_PRIVATE int sqlite3ExprCodeExprList(
95842  Parse *pParse,     /* Parsing context */
95843  ExprList *pList,   /* The expression list to be coded */
95844  int target,        /* Where to write results */
95845  int srcReg,        /* Source registers if SQLITE_ECEL_REF */
95846  u8 flags           /* SQLITE_ECEL_* flags */
95847){
95848  struct ExprList_item *pItem;
95849  int i, j, n;
95850  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
95851  Vdbe *v = pParse->pVdbe;
95852  assert( pList!=0 );
95853  assert( target>0 );
95854  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
95855  n = pList->nExpr;
95856  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
95857  for(pItem=pList->a, i=0; i<n; i++, pItem++){
95858    Expr *pExpr = pItem->pExpr;
95859    if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
95860      if( flags & SQLITE_ECEL_OMITREF ){
95861        i--;
95862        n--;
95863      }else{
95864        sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
95865      }
95866    }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
95867      sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
95868    }else{
95869      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
95870      if( inReg!=target+i ){
95871        VdbeOp *pOp;
95872        if( copyOp==OP_Copy
95873         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
95874         && pOp->p1+pOp->p3+1==inReg
95875         && pOp->p2+pOp->p3+1==target+i
95876        ){
95877          pOp->p3++;
95878        }else{
95879          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
95880        }
95881      }
95882    }
95883  }
95884  return n;
95885}
95886
95887/*
95888** Generate code for a BETWEEN operator.
95889**
95890**    x BETWEEN y AND z
95891**
95892** The above is equivalent to
95893**
95894**    x>=y AND x<=z
95895**
95896** Code it as such, taking care to do the common subexpression
95897** elimination of x.
95898**
95899** The xJumpIf parameter determines details:
95900**
95901**    NULL:                   Store the boolean result in reg[dest]
95902**    sqlite3ExprIfTrue:      Jump to dest if true
95903**    sqlite3ExprIfFalse:     Jump to dest if false
95904**
95905** The jumpIfNull parameter is ignored if xJumpIf is NULL.
95906*/
95907static void exprCodeBetween(
95908  Parse *pParse,    /* Parsing and code generating context */
95909  Expr *pExpr,      /* The BETWEEN expression */
95910  int dest,         /* Jump destination or storage location */
95911  void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
95912  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
95913){
95914 Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
95915  Expr compLeft;    /* The  x>=y  term */
95916  Expr compRight;   /* The  x<=z  term */
95917  Expr exprX;       /* The  x  subexpression */
95918  int regFree1 = 0; /* Temporary use register */
95919
95920
95921  memset(&compLeft, 0, sizeof(Expr));
95922  memset(&compRight, 0, sizeof(Expr));
95923  memset(&exprAnd, 0, sizeof(Expr));
95924
95925  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
95926  exprX = *pExpr->pLeft;
95927  exprAnd.op = TK_AND;
95928  exprAnd.pLeft = &compLeft;
95929  exprAnd.pRight = &compRight;
95930  compLeft.op = TK_GE;
95931  compLeft.pLeft = &exprX;
95932  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
95933  compRight.op = TK_LE;
95934  compRight.pLeft = &exprX;
95935  compRight.pRight = pExpr->x.pList->a[1].pExpr;
95936  exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
95937  if( xJump ){
95938    xJump(pParse, &exprAnd, dest, jumpIfNull);
95939  }else{
95940    /* Mark the expression is being from the ON or USING clause of a join
95941    ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
95942    ** it into the Parse.pConstExpr list.  We should use a new bit for this,
95943    ** for clarity, but we are out of bits in the Expr.flags field so we
95944    ** have to reuse the EP_FromJoin bit.  Bummer. */
95945    exprX.flags |= EP_FromJoin;
95946    sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
95947  }
95948  sqlite3ReleaseTempReg(pParse, regFree1);
95949
95950  /* Ensure adequate test coverage */
95951  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1==0 );
95952  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull==0 && regFree1!=0 );
95953  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1==0 );
95954  testcase( xJump==sqlite3ExprIfTrue  && jumpIfNull!=0 && regFree1!=0 );
95955  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
95956  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
95957  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
95958  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
95959  testcase( xJump==0 );
95960}
95961
95962/*
95963** Generate code for a boolean expression such that a jump is made
95964** to the label "dest" if the expression is true but execution
95965** continues straight thru if the expression is false.
95966**
95967** If the expression evaluates to NULL (neither true nor false), then
95968** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
95969**
95970** This code depends on the fact that certain token values (ex: TK_EQ)
95971** are the same as opcode values (ex: OP_Eq) that implement the corresponding
95972** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
95973** the make process cause these values to align.  Assert()s in the code
95974** below verify that the numbers are aligned correctly.
95975*/
95976SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
95977  Vdbe *v = pParse->pVdbe;
95978  int op = 0;
95979  int regFree1 = 0;
95980  int regFree2 = 0;
95981  int r1, r2;
95982
95983  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
95984  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
95985  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
95986  op = pExpr->op;
95987  switch( op ){
95988    case TK_AND: {
95989      int d2 = sqlite3VdbeMakeLabel(v);
95990      testcase( jumpIfNull==0 );
95991      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
95992      sqlite3ExprCachePush(pParse);
95993      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
95994      sqlite3VdbeResolveLabel(v, d2);
95995      sqlite3ExprCachePop(pParse);
95996      break;
95997    }
95998    case TK_OR: {
95999      testcase( jumpIfNull==0 );
96000      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
96001      sqlite3ExprCachePush(pParse);
96002      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
96003      sqlite3ExprCachePop(pParse);
96004      break;
96005    }
96006    case TK_NOT: {
96007      testcase( jumpIfNull==0 );
96008      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
96009      break;
96010    }
96011    case TK_IS:
96012    case TK_ISNOT:
96013      testcase( op==TK_IS );
96014      testcase( op==TK_ISNOT );
96015      op = (op==TK_IS) ? TK_EQ : TK_NE;
96016      jumpIfNull = SQLITE_NULLEQ;
96017      /* Fall thru */
96018    case TK_LT:
96019    case TK_LE:
96020    case TK_GT:
96021    case TK_GE:
96022    case TK_NE:
96023    case TK_EQ: {
96024      if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
96025      testcase( jumpIfNull==0 );
96026      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
96027      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
96028      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
96029                  r1, r2, dest, jumpIfNull);
96030      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
96031      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
96032      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
96033      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
96034      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
96035      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
96036      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
96037      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
96038      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
96039      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
96040      testcase( regFree1==0 );
96041      testcase( regFree2==0 );
96042      break;
96043    }
96044    case TK_ISNULL:
96045    case TK_NOTNULL: {
96046      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
96047      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
96048      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
96049      sqlite3VdbeAddOp2(v, op, r1, dest);
96050      VdbeCoverageIf(v, op==TK_ISNULL);
96051      VdbeCoverageIf(v, op==TK_NOTNULL);
96052      testcase( regFree1==0 );
96053      break;
96054    }
96055    case TK_BETWEEN: {
96056      testcase( jumpIfNull==0 );
96057      exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
96058      break;
96059    }
96060#ifndef SQLITE_OMIT_SUBQUERY
96061    case TK_IN: {
96062      int destIfFalse = sqlite3VdbeMakeLabel(v);
96063      int destIfNull = jumpIfNull ? dest : destIfFalse;
96064      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
96065      sqlite3VdbeGoto(v, dest);
96066      sqlite3VdbeResolveLabel(v, destIfFalse);
96067      break;
96068    }
96069#endif
96070    default: {
96071    default_expr:
96072      if( exprAlwaysTrue(pExpr) ){
96073        sqlite3VdbeGoto(v, dest);
96074      }else if( exprAlwaysFalse(pExpr) ){
96075        /* No-op */
96076      }else{
96077        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
96078        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
96079        VdbeCoverage(v);
96080        testcase( regFree1==0 );
96081        testcase( jumpIfNull==0 );
96082      }
96083      break;
96084    }
96085  }
96086  sqlite3ReleaseTempReg(pParse, regFree1);
96087  sqlite3ReleaseTempReg(pParse, regFree2);
96088}
96089
96090/*
96091** Generate code for a boolean expression such that a jump is made
96092** to the label "dest" if the expression is false but execution
96093** continues straight thru if the expression is true.
96094**
96095** If the expression evaluates to NULL (neither true nor false) then
96096** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
96097** is 0.
96098*/
96099SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
96100  Vdbe *v = pParse->pVdbe;
96101  int op = 0;
96102  int regFree1 = 0;
96103  int regFree2 = 0;
96104  int r1, r2;
96105
96106  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
96107  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
96108  if( pExpr==0 )    return;
96109
96110  /* The value of pExpr->op and op are related as follows:
96111  **
96112  **       pExpr->op            op
96113  **       ---------          ----------
96114  **       TK_ISNULL          OP_NotNull
96115  **       TK_NOTNULL         OP_IsNull
96116  **       TK_NE              OP_Eq
96117  **       TK_EQ              OP_Ne
96118  **       TK_GT              OP_Le
96119  **       TK_LE              OP_Gt
96120  **       TK_GE              OP_Lt
96121  **       TK_LT              OP_Ge
96122  **
96123  ** For other values of pExpr->op, op is undefined and unused.
96124  ** The value of TK_ and OP_ constants are arranged such that we
96125  ** can compute the mapping above using the following expression.
96126  ** Assert()s verify that the computation is correct.
96127  */
96128  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
96129
96130  /* Verify correct alignment of TK_ and OP_ constants
96131  */
96132  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
96133  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
96134  assert( pExpr->op!=TK_NE || op==OP_Eq );
96135  assert( pExpr->op!=TK_EQ || op==OP_Ne );
96136  assert( pExpr->op!=TK_LT || op==OP_Ge );
96137  assert( pExpr->op!=TK_LE || op==OP_Gt );
96138  assert( pExpr->op!=TK_GT || op==OP_Le );
96139  assert( pExpr->op!=TK_GE || op==OP_Lt );
96140
96141  switch( pExpr->op ){
96142    case TK_AND: {
96143      testcase( jumpIfNull==0 );
96144      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
96145      sqlite3ExprCachePush(pParse);
96146      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
96147      sqlite3ExprCachePop(pParse);
96148      break;
96149    }
96150    case TK_OR: {
96151      int d2 = sqlite3VdbeMakeLabel(v);
96152      testcase( jumpIfNull==0 );
96153      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
96154      sqlite3ExprCachePush(pParse);
96155      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
96156      sqlite3VdbeResolveLabel(v, d2);
96157      sqlite3ExprCachePop(pParse);
96158      break;
96159    }
96160    case TK_NOT: {
96161      testcase( jumpIfNull==0 );
96162      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
96163      break;
96164    }
96165    case TK_IS:
96166    case TK_ISNOT:
96167      testcase( pExpr->op==TK_IS );
96168      testcase( pExpr->op==TK_ISNOT );
96169      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
96170      jumpIfNull = SQLITE_NULLEQ;
96171      /* Fall thru */
96172    case TK_LT:
96173    case TK_LE:
96174    case TK_GT:
96175    case TK_GE:
96176    case TK_NE:
96177    case TK_EQ: {
96178      if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
96179      testcase( jumpIfNull==0 );
96180      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
96181      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
96182      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
96183                  r1, r2, dest, jumpIfNull);
96184      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
96185      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
96186      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
96187      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
96188      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
96189      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
96190      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
96191      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
96192      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
96193      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
96194      testcase( regFree1==0 );
96195      testcase( regFree2==0 );
96196      break;
96197    }
96198    case TK_ISNULL:
96199    case TK_NOTNULL: {
96200      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
96201      sqlite3VdbeAddOp2(v, op, r1, dest);
96202      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
96203      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
96204      testcase( regFree1==0 );
96205      break;
96206    }
96207    case TK_BETWEEN: {
96208      testcase( jumpIfNull==0 );
96209      exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
96210      break;
96211    }
96212#ifndef SQLITE_OMIT_SUBQUERY
96213    case TK_IN: {
96214      if( jumpIfNull ){
96215        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
96216      }else{
96217        int destIfNull = sqlite3VdbeMakeLabel(v);
96218        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
96219        sqlite3VdbeResolveLabel(v, destIfNull);
96220      }
96221      break;
96222    }
96223#endif
96224    default: {
96225    default_expr:
96226      if( exprAlwaysFalse(pExpr) ){
96227        sqlite3VdbeGoto(v, dest);
96228      }else if( exprAlwaysTrue(pExpr) ){
96229        /* no-op */
96230      }else{
96231        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
96232        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
96233        VdbeCoverage(v);
96234        testcase( regFree1==0 );
96235        testcase( jumpIfNull==0 );
96236      }
96237      break;
96238    }
96239  }
96240  sqlite3ReleaseTempReg(pParse, regFree1);
96241  sqlite3ReleaseTempReg(pParse, regFree2);
96242}
96243
96244/*
96245** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
96246** code generation, and that copy is deleted after code generation. This
96247** ensures that the original pExpr is unchanged.
96248*/
96249SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
96250  sqlite3 *db = pParse->db;
96251  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
96252  if( db->mallocFailed==0 ){
96253    sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
96254  }
96255  sqlite3ExprDelete(db, pCopy);
96256}
96257
96258/*
96259** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
96260** type of expression.
96261**
96262** If pExpr is a simple SQL value - an integer, real, string, blob
96263** or NULL value - then the VDBE currently being prepared is configured
96264** to re-prepare each time a new value is bound to variable pVar.
96265**
96266** Additionally, if pExpr is a simple SQL value and the value is the
96267** same as that currently bound to variable pVar, non-zero is returned.
96268** Otherwise, if the values are not the same or if pExpr is not a simple
96269** SQL value, zero is returned.
96270*/
96271static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
96272  int res = 0;
96273  int iVar;
96274  sqlite3_value *pL, *pR = 0;
96275
96276  sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
96277  if( pR ){
96278    iVar = pVar->iColumn;
96279    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
96280    pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
96281    if( pL ){
96282      if( sqlite3_value_type(pL)==SQLITE_TEXT ){
96283        sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
96284      }
96285      res =  0==sqlite3MemCompare(pL, pR, 0);
96286    }
96287    sqlite3ValueFree(pR);
96288    sqlite3ValueFree(pL);
96289  }
96290
96291  return res;
96292}
96293
96294/*
96295** Do a deep comparison of two expression trees.  Return 0 if the two
96296** expressions are completely identical.  Return 1 if they differ only
96297** by a COLLATE operator at the top level.  Return 2 if there are differences
96298** other than the top-level COLLATE operator.
96299**
96300** If any subelement of pB has Expr.iTable==(-1) then it is allowed
96301** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
96302**
96303** The pA side might be using TK_REGISTER.  If that is the case and pB is
96304** not using TK_REGISTER but is otherwise equivalent, then still return 0.
96305**
96306** Sometimes this routine will return 2 even if the two expressions
96307** really are equivalent.  If we cannot prove that the expressions are
96308** identical, we return 2 just to be safe.  So if this routine
96309** returns 2, then you do not really know for certain if the two
96310** expressions are the same.  But if you get a 0 or 1 return, then you
96311** can be sure the expressions are the same.  In the places where
96312** this routine is used, it does not hurt to get an extra 2 - that
96313** just might result in some slightly slower code.  But returning
96314** an incorrect 0 or 1 could lead to a malfunction.
96315**
96316** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
96317** pParse->pReprepare can be matched against literals in pB.  The
96318** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
96319** If pParse is NULL (the normal case) then any TK_VARIABLE term in
96320** Argument pParse should normally be NULL. If it is not NULL and pA or
96321** pB causes a return value of 2.
96322*/
96323SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
96324  u32 combinedFlags;
96325  if( pA==0 || pB==0 ){
96326    return pB==pA ? 0 : 2;
96327  }
96328  if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
96329    return 0;
96330  }
96331  combinedFlags = pA->flags | pB->flags;
96332  if( combinedFlags & EP_IntValue ){
96333    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
96334      return 0;
96335    }
96336    return 2;
96337  }
96338  if( pA->op!=pB->op ){
96339    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
96340      return 1;
96341    }
96342    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
96343      return 1;
96344    }
96345    return 2;
96346  }
96347  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
96348    if( pA->op==TK_FUNCTION ){
96349      if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
96350    }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
96351      return pA->op==TK_COLLATE ? 1 : 2;
96352    }
96353  }
96354  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
96355  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
96356    if( combinedFlags & EP_xIsSelect ) return 2;
96357    if( sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
96358    if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
96359    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
96360    if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
96361      if( pA->iColumn!=pB->iColumn ) return 2;
96362      if( pA->iTable!=pB->iTable
96363       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
96364    }
96365  }
96366  return 0;
96367}
96368
96369/*
96370** Compare two ExprList objects.  Return 0 if they are identical and
96371** non-zero if they differ in any way.
96372**
96373** If any subelement of pB has Expr.iTable==(-1) then it is allowed
96374** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
96375**
96376** This routine might return non-zero for equivalent ExprLists.  The
96377** only consequence will be disabled optimizations.  But this routine
96378** must never return 0 if the two ExprList objects are different, or
96379** a malfunction will result.
96380**
96381** Two NULL pointers are considered to be the same.  But a NULL pointer
96382** always differs from a non-NULL pointer.
96383*/
96384SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
96385  int i;
96386  if( pA==0 && pB==0 ) return 0;
96387  if( pA==0 || pB==0 ) return 1;
96388  if( pA->nExpr!=pB->nExpr ) return 1;
96389  for(i=0; i<pA->nExpr; i++){
96390    Expr *pExprA = pA->a[i].pExpr;
96391    Expr *pExprB = pB->a[i].pExpr;
96392    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
96393    if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
96394  }
96395  return 0;
96396}
96397
96398/*
96399** Like sqlite3ExprCompare() except COLLATE operators at the top-level
96400** are ignored.
96401*/
96402SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
96403  return sqlite3ExprCompare(0,
96404             sqlite3ExprSkipCollate(pA),
96405             sqlite3ExprSkipCollate(pB),
96406             iTab);
96407}
96408
96409/*
96410** Return true if we can prove the pE2 will always be true if pE1 is
96411** true.  Return false if we cannot complete the proof or if pE2 might
96412** be false.  Examples:
96413**
96414**     pE1: x==5       pE2: x==5             Result: true
96415**     pE1: x>0        pE2: x==5             Result: false
96416**     pE1: x=21       pE2: x=21 OR y=43     Result: true
96417**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
96418**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
96419**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
96420**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
96421**
96422** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
96423** Expr.iTable<0 then assume a table number given by iTab.
96424**
96425** If pParse is not NULL, then the values of bound variables in pE1 are
96426** compared against literal values in pE2 and pParse->pVdbe->expmask is
96427** modified to record which bound variables are referenced.  If pParse
96428** is NULL, then false will be returned if pE1 contains any bound variables.
96429**
96430** When in doubt, return false.  Returning true might give a performance
96431** improvement.  Returning false might cause a performance reduction, but
96432** it will always give the correct answer and is hence always safe.
96433*/
96434SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
96435  if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
96436    return 1;
96437  }
96438  if( pE2->op==TK_OR
96439   && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
96440             || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
96441  ){
96442    return 1;
96443  }
96444  if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
96445    Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
96446    testcase( pX!=pE1->pLeft );
96447    if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
96448  }
96449  return 0;
96450}
96451
96452/*
96453** An instance of the following structure is used by the tree walker
96454** to determine if an expression can be evaluated by reference to the
96455** index only, without having to do a search for the corresponding
96456** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
96457** is the cursor for the table.
96458*/
96459struct IdxCover {
96460  Index *pIdx;     /* The index to be tested for coverage */
96461  int iCur;        /* Cursor number for the table corresponding to the index */
96462};
96463
96464/*
96465** Check to see if there are references to columns in table
96466** pWalker->u.pIdxCover->iCur can be satisfied using the index
96467** pWalker->u.pIdxCover->pIdx.
96468*/
96469static int exprIdxCover(Walker *pWalker, Expr *pExpr){
96470  if( pExpr->op==TK_COLUMN
96471   && pExpr->iTable==pWalker->u.pIdxCover->iCur
96472   && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
96473  ){
96474    pWalker->eCode = 1;
96475    return WRC_Abort;
96476  }
96477  return WRC_Continue;
96478}
96479
96480/*
96481** Determine if an index pIdx on table with cursor iCur contains will
96482** the expression pExpr.  Return true if the index does cover the
96483** expression and false if the pExpr expression references table columns
96484** that are not found in the index pIdx.
96485**
96486** An index covering an expression means that the expression can be
96487** evaluated using only the index and without having to lookup the
96488** corresponding table entry.
96489*/
96490SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
96491  Expr *pExpr,        /* The index to be tested */
96492  int iCur,           /* The cursor number for the corresponding table */
96493  Index *pIdx         /* The index that might be used for coverage */
96494){
96495  Walker w;
96496  struct IdxCover xcov;
96497  memset(&w, 0, sizeof(w));
96498  xcov.iCur = iCur;
96499  xcov.pIdx = pIdx;
96500  w.xExprCallback = exprIdxCover;
96501  w.u.pIdxCover = &xcov;
96502  sqlite3WalkExpr(&w, pExpr);
96503  return !w.eCode;
96504}
96505
96506
96507/*
96508** An instance of the following structure is used by the tree walker
96509** to count references to table columns in the arguments of an
96510** aggregate function, in order to implement the
96511** sqlite3FunctionThisSrc() routine.
96512*/
96513struct SrcCount {
96514  SrcList *pSrc;   /* One particular FROM clause in a nested query */
96515  int nThis;       /* Number of references to columns in pSrcList */
96516  int nOther;      /* Number of references to columns in other FROM clauses */
96517};
96518
96519/*
96520** Count the number of references to columns.
96521*/
96522static int exprSrcCount(Walker *pWalker, Expr *pExpr){
96523  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
96524  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
96525  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
96526  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
96527  ** NEVER() will need to be removed. */
96528  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
96529    int i;
96530    struct SrcCount *p = pWalker->u.pSrcCount;
96531    SrcList *pSrc = p->pSrc;
96532    int nSrc = pSrc ? pSrc->nSrc : 0;
96533    for(i=0; i<nSrc; i++){
96534      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
96535    }
96536    if( i<nSrc ){
96537      p->nThis++;
96538    }else{
96539      p->nOther++;
96540    }
96541  }
96542  return WRC_Continue;
96543}
96544
96545/*
96546** Determine if any of the arguments to the pExpr Function reference
96547** pSrcList.  Return true if they do.  Also return true if the function
96548** has no arguments or has only constant arguments.  Return false if pExpr
96549** references columns but not columns of tables found in pSrcList.
96550*/
96551SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
96552  Walker w;
96553  struct SrcCount cnt;
96554  assert( pExpr->op==TK_AGG_FUNCTION );
96555  w.xExprCallback = exprSrcCount;
96556  w.xSelectCallback = 0;
96557  w.u.pSrcCount = &cnt;
96558  cnt.pSrc = pSrcList;
96559  cnt.nThis = 0;
96560  cnt.nOther = 0;
96561  sqlite3WalkExprList(&w, pExpr->x.pList);
96562  return cnt.nThis>0 || cnt.nOther==0;
96563}
96564
96565/*
96566** Add a new element to the pAggInfo->aCol[] array.  Return the index of
96567** the new element.  Return a negative number if malloc fails.
96568*/
96569static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
96570  int i;
96571  pInfo->aCol = sqlite3ArrayAllocate(
96572       db,
96573       pInfo->aCol,
96574       sizeof(pInfo->aCol[0]),
96575       &pInfo->nColumn,
96576       &i
96577  );
96578  return i;
96579}
96580
96581/*
96582** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
96583** the new element.  Return a negative number if malloc fails.
96584*/
96585static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
96586  int i;
96587  pInfo->aFunc = sqlite3ArrayAllocate(
96588       db,
96589       pInfo->aFunc,
96590       sizeof(pInfo->aFunc[0]),
96591       &pInfo->nFunc,
96592       &i
96593  );
96594  return i;
96595}
96596
96597/*
96598** This is the xExprCallback for a tree walker.  It is used to
96599** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
96600** for additional information.
96601*/
96602static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
96603  int i;
96604  NameContext *pNC = pWalker->u.pNC;
96605  Parse *pParse = pNC->pParse;
96606  SrcList *pSrcList = pNC->pSrcList;
96607  AggInfo *pAggInfo = pNC->pAggInfo;
96608
96609  switch( pExpr->op ){
96610    case TK_AGG_COLUMN:
96611    case TK_COLUMN: {
96612      testcase( pExpr->op==TK_AGG_COLUMN );
96613      testcase( pExpr->op==TK_COLUMN );
96614      /* Check to see if the column is in one of the tables in the FROM
96615      ** clause of the aggregate query */
96616      if( ALWAYS(pSrcList!=0) ){
96617        struct SrcList_item *pItem = pSrcList->a;
96618        for(i=0; i<pSrcList->nSrc; i++, pItem++){
96619          struct AggInfo_col *pCol;
96620          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
96621          if( pExpr->iTable==pItem->iCursor ){
96622            /* If we reach this point, it means that pExpr refers to a table
96623            ** that is in the FROM clause of the aggregate query.
96624            **
96625            ** Make an entry for the column in pAggInfo->aCol[] if there
96626            ** is not an entry there already.
96627            */
96628            int k;
96629            pCol = pAggInfo->aCol;
96630            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
96631              if( pCol->iTable==pExpr->iTable &&
96632                  pCol->iColumn==pExpr->iColumn ){
96633                break;
96634              }
96635            }
96636            if( (k>=pAggInfo->nColumn)
96637             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
96638            ){
96639              pCol = &pAggInfo->aCol[k];
96640              pCol->pTab = pExpr->pTab;
96641              pCol->iTable = pExpr->iTable;
96642              pCol->iColumn = pExpr->iColumn;
96643              pCol->iMem = ++pParse->nMem;
96644              pCol->iSorterColumn = -1;
96645              pCol->pExpr = pExpr;
96646              if( pAggInfo->pGroupBy ){
96647                int j, n;
96648                ExprList *pGB = pAggInfo->pGroupBy;
96649                struct ExprList_item *pTerm = pGB->a;
96650                n = pGB->nExpr;
96651                for(j=0; j<n; j++, pTerm++){
96652                  Expr *pE = pTerm->pExpr;
96653                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
96654                      pE->iColumn==pExpr->iColumn ){
96655                    pCol->iSorterColumn = j;
96656                    break;
96657                  }
96658                }
96659              }
96660              if( pCol->iSorterColumn<0 ){
96661                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
96662              }
96663            }
96664            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
96665            ** because it was there before or because we just created it).
96666            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
96667            ** pAggInfo->aCol[] entry.
96668            */
96669            ExprSetVVAProperty(pExpr, EP_NoReduce);
96670            pExpr->pAggInfo = pAggInfo;
96671            pExpr->op = TK_AGG_COLUMN;
96672            pExpr->iAgg = (i16)k;
96673            break;
96674          } /* endif pExpr->iTable==pItem->iCursor */
96675        } /* end loop over pSrcList */
96676      }
96677      return WRC_Prune;
96678    }
96679    case TK_AGG_FUNCTION: {
96680      if( (pNC->ncFlags & NC_InAggFunc)==0
96681       && pWalker->walkerDepth==pExpr->op2
96682      ){
96683        /* Check to see if pExpr is a duplicate of another aggregate
96684        ** function that is already in the pAggInfo structure
96685        */
96686        struct AggInfo_func *pItem = pAggInfo->aFunc;
96687        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
96688          if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
96689            break;
96690          }
96691        }
96692        if( i>=pAggInfo->nFunc ){
96693          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
96694          */
96695          u8 enc = ENC(pParse->db);
96696          i = addAggInfoFunc(pParse->db, pAggInfo);
96697          if( i>=0 ){
96698            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
96699            pItem = &pAggInfo->aFunc[i];
96700            pItem->pExpr = pExpr;
96701            pItem->iMem = ++pParse->nMem;
96702            assert( !ExprHasProperty(pExpr, EP_IntValue) );
96703            pItem->pFunc = sqlite3FindFunction(pParse->db,
96704                   pExpr->u.zToken,
96705                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
96706            if( pExpr->flags & EP_Distinct ){
96707              pItem->iDistinct = pParse->nTab++;
96708            }else{
96709              pItem->iDistinct = -1;
96710            }
96711          }
96712        }
96713        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
96714        */
96715        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
96716        ExprSetVVAProperty(pExpr, EP_NoReduce);
96717        pExpr->iAgg = (i16)i;
96718        pExpr->pAggInfo = pAggInfo;
96719        return WRC_Prune;
96720      }else{
96721        return WRC_Continue;
96722      }
96723    }
96724  }
96725  return WRC_Continue;
96726}
96727static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
96728  UNUSED_PARAMETER(pSelect);
96729  pWalker->walkerDepth++;
96730  return WRC_Continue;
96731}
96732static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
96733  UNUSED_PARAMETER(pSelect);
96734  pWalker->walkerDepth--;
96735}
96736
96737/*
96738** Analyze the pExpr expression looking for aggregate functions and
96739** for variables that need to be added to AggInfo object that pNC->pAggInfo
96740** points to.  Additional entries are made on the AggInfo object as
96741** necessary.
96742**
96743** This routine should only be called after the expression has been
96744** analyzed by sqlite3ResolveExprNames().
96745*/
96746SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
96747  Walker w;
96748  w.xExprCallback = analyzeAggregate;
96749  w.xSelectCallback = analyzeAggregatesInSelect;
96750  w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
96751  w.walkerDepth = 0;
96752  w.u.pNC = pNC;
96753  assert( pNC->pSrcList!=0 );
96754  sqlite3WalkExpr(&w, pExpr);
96755}
96756
96757/*
96758** Call sqlite3ExprAnalyzeAggregates() for every expression in an
96759** expression list.  Return the number of errors.
96760**
96761** If an error is found, the analysis is cut short.
96762*/
96763SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
96764  struct ExprList_item *pItem;
96765  int i;
96766  if( pList ){
96767    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
96768      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
96769    }
96770  }
96771}
96772
96773/*
96774** Allocate a single new register for use to hold some intermediate result.
96775*/
96776SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
96777  if( pParse->nTempReg==0 ){
96778    return ++pParse->nMem;
96779  }
96780  return pParse->aTempReg[--pParse->nTempReg];
96781}
96782
96783/*
96784** Deallocate a register, making available for reuse for some other
96785** purpose.
96786**
96787** If a register is currently being used by the column cache, then
96788** the deallocation is deferred until the column cache line that uses
96789** the register becomes stale.
96790*/
96791SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
96792  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
96793    int i;
96794    struct yColCache *p;
96795    for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
96796      if( p->iReg==iReg ){
96797        p->tempReg = 1;
96798        return;
96799      }
96800    }
96801    pParse->aTempReg[pParse->nTempReg++] = iReg;
96802  }
96803}
96804
96805/*
96806** Allocate or deallocate a block of nReg consecutive registers.
96807*/
96808SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
96809  int i, n;
96810  if( nReg==1 ) return sqlite3GetTempReg(pParse);
96811  i = pParse->iRangeReg;
96812  n = pParse->nRangeReg;
96813  if( nReg<=n ){
96814    assert( !usedAsColumnCache(pParse, i, i+n-1) );
96815    pParse->iRangeReg += nReg;
96816    pParse->nRangeReg -= nReg;
96817  }else{
96818    i = pParse->nMem+1;
96819    pParse->nMem += nReg;
96820  }
96821  return i;
96822}
96823SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
96824  if( nReg==1 ){
96825    sqlite3ReleaseTempReg(pParse, iReg);
96826    return;
96827  }
96828  sqlite3ExprCacheRemove(pParse, iReg, nReg);
96829  if( nReg>pParse->nRangeReg ){
96830    pParse->nRangeReg = nReg;
96831    pParse->iRangeReg = iReg;
96832  }
96833}
96834
96835/*
96836** Mark all temporary registers as being unavailable for reuse.
96837*/
96838SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
96839  pParse->nTempReg = 0;
96840  pParse->nRangeReg = 0;
96841}
96842
96843/*
96844** Validate that no temporary register falls within the range of
96845** iFirst..iLast, inclusive.  This routine is only call from within assert()
96846** statements.
96847*/
96848#ifdef SQLITE_DEBUG
96849SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
96850  int i;
96851  if( pParse->nRangeReg>0
96852   && pParse->iRangeReg+pParse->nRangeReg > iFirst
96853   && pParse->iRangeReg <= iLast
96854  ){
96855     return 0;
96856  }
96857  for(i=0; i<pParse->nTempReg; i++){
96858    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
96859      return 0;
96860    }
96861  }
96862  return 1;
96863}
96864#endif /* SQLITE_DEBUG */
96865
96866/************** End of expr.c ************************************************/
96867/************** Begin file alter.c *******************************************/
96868/*
96869** 2005 February 15
96870**
96871** The author disclaims copyright to this source code.  In place of
96872** a legal notice, here is a blessing:
96873**
96874**    May you do good and not evil.
96875**    May you find forgiveness for yourself and forgive others.
96876**    May you share freely, never taking more than you give.
96877**
96878*************************************************************************
96879** This file contains C code routines that used to generate VDBE code
96880** that implements the ALTER TABLE command.
96881*/
96882/* #include "sqliteInt.h" */
96883
96884/*
96885** The code in this file only exists if we are not omitting the
96886** ALTER TABLE logic from the build.
96887*/
96888#ifndef SQLITE_OMIT_ALTERTABLE
96889
96890
96891/*
96892** This function is used by SQL generated to implement the
96893** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
96894** CREATE INDEX command. The second is a table name. The table name in
96895** the CREATE TABLE or CREATE INDEX statement is replaced with the third
96896** argument and the result returned. Examples:
96897**
96898** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
96899**     -> 'CREATE TABLE def(a, b, c)'
96900**
96901** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
96902**     -> 'CREATE INDEX i ON def(a, b, c)'
96903*/
96904static void renameTableFunc(
96905  sqlite3_context *context,
96906  int NotUsed,
96907  sqlite3_value **argv
96908){
96909  unsigned char const *zSql = sqlite3_value_text(argv[0]);
96910  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
96911
96912  int token;
96913  Token tname;
96914  unsigned char const *zCsr = zSql;
96915  int len = 0;
96916  char *zRet;
96917
96918  sqlite3 *db = sqlite3_context_db_handle(context);
96919
96920  UNUSED_PARAMETER(NotUsed);
96921
96922  /* The principle used to locate the table name in the CREATE TABLE
96923  ** statement is that the table name is the first non-space token that
96924  ** is immediately followed by a TK_LP or TK_USING token.
96925  */
96926  if( zSql ){
96927    do {
96928      if( !*zCsr ){
96929        /* Ran out of input before finding an opening bracket. Return NULL. */
96930        return;
96931      }
96932
96933      /* Store the token that zCsr points to in tname. */
96934      tname.z = (char*)zCsr;
96935      tname.n = len;
96936
96937      /* Advance zCsr to the next token. Store that token type in 'token',
96938      ** and its length in 'len' (to be used next iteration of this loop).
96939      */
96940      do {
96941        zCsr += len;
96942        len = sqlite3GetToken(zCsr, &token);
96943      } while( token==TK_SPACE );
96944      assert( len>0 );
96945    } while( token!=TK_LP && token!=TK_USING );
96946
96947    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
96948       zSql, zTableName, tname.z+tname.n);
96949    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
96950  }
96951}
96952
96953/*
96954** This C function implements an SQL user function that is used by SQL code
96955** generated by the ALTER TABLE ... RENAME command to modify the definition
96956** of any foreign key constraints that use the table being renamed as the
96957** parent table. It is passed three arguments:
96958**
96959**   1) The complete text of the CREATE TABLE statement being modified,
96960**   2) The old name of the table being renamed, and
96961**   3) The new name of the table being renamed.
96962**
96963** It returns the new CREATE TABLE statement. For example:
96964**
96965**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
96966**       -> 'CREATE TABLE t1(a REFERENCES t3)'
96967*/
96968#ifndef SQLITE_OMIT_FOREIGN_KEY
96969static void renameParentFunc(
96970  sqlite3_context *context,
96971  int NotUsed,
96972  sqlite3_value **argv
96973){
96974  sqlite3 *db = sqlite3_context_db_handle(context);
96975  char *zOutput = 0;
96976  char *zResult;
96977  unsigned char const *zInput = sqlite3_value_text(argv[0]);
96978  unsigned char const *zOld = sqlite3_value_text(argv[1]);
96979  unsigned char const *zNew = sqlite3_value_text(argv[2]);
96980
96981  unsigned const char *z;         /* Pointer to token */
96982  int n;                          /* Length of token z */
96983  int token;                      /* Type of token */
96984
96985  UNUSED_PARAMETER(NotUsed);
96986  if( zInput==0 || zOld==0 ) return;
96987  for(z=zInput; *z; z=z+n){
96988    n = sqlite3GetToken(z, &token);
96989    if( token==TK_REFERENCES ){
96990      char *zParent;
96991      do {
96992        z += n;
96993        n = sqlite3GetToken(z, &token);
96994      }while( token==TK_SPACE );
96995
96996      if( token==TK_ILLEGAL ) break;
96997      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
96998      if( zParent==0 ) break;
96999      sqlite3Dequote(zParent);
97000      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
97001        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
97002            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
97003        );
97004        sqlite3DbFree(db, zOutput);
97005        zOutput = zOut;
97006        zInput = &z[n];
97007      }
97008      sqlite3DbFree(db, zParent);
97009    }
97010  }
97011
97012  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
97013  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
97014  sqlite3DbFree(db, zOutput);
97015}
97016#endif
97017
97018#ifndef SQLITE_OMIT_TRIGGER
97019/* This function is used by SQL generated to implement the
97020** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
97021** statement. The second is a table name. The table name in the CREATE
97022** TRIGGER statement is replaced with the third argument and the result
97023** returned. This is analagous to renameTableFunc() above, except for CREATE
97024** TRIGGER, not CREATE INDEX and CREATE TABLE.
97025*/
97026static void renameTriggerFunc(
97027  sqlite3_context *context,
97028  int NotUsed,
97029  sqlite3_value **argv
97030){
97031  unsigned char const *zSql = sqlite3_value_text(argv[0]);
97032  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
97033
97034  int token;
97035  Token tname;
97036  int dist = 3;
97037  unsigned char const *zCsr = zSql;
97038  int len = 0;
97039  char *zRet;
97040  sqlite3 *db = sqlite3_context_db_handle(context);
97041
97042  UNUSED_PARAMETER(NotUsed);
97043
97044  /* The principle used to locate the table name in the CREATE TRIGGER
97045  ** statement is that the table name is the first token that is immediately
97046  ** preceded by either TK_ON or TK_DOT and immediately followed by one
97047  ** of TK_WHEN, TK_BEGIN or TK_FOR.
97048  */
97049  if( zSql ){
97050    do {
97051
97052      if( !*zCsr ){
97053        /* Ran out of input before finding the table name. Return NULL. */
97054        return;
97055      }
97056
97057      /* Store the token that zCsr points to in tname. */
97058      tname.z = (char*)zCsr;
97059      tname.n = len;
97060
97061      /* Advance zCsr to the next token. Store that token type in 'token',
97062      ** and its length in 'len' (to be used next iteration of this loop).
97063      */
97064      do {
97065        zCsr += len;
97066        len = sqlite3GetToken(zCsr, &token);
97067      }while( token==TK_SPACE );
97068      assert( len>0 );
97069
97070      /* Variable 'dist' stores the number of tokens read since the most
97071      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
97072      ** token is read and 'dist' equals 2, the condition stated above
97073      ** to be met.
97074      **
97075      ** Note that ON cannot be a database, table or column name, so
97076      ** there is no need to worry about syntax like
97077      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
97078      */
97079      dist++;
97080      if( token==TK_DOT || token==TK_ON ){
97081        dist = 0;
97082      }
97083    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
97084
97085    /* Variable tname now contains the token that is the old table-name
97086    ** in the CREATE TRIGGER statement.
97087    */
97088    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
97089       zSql, zTableName, tname.z+tname.n);
97090    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
97091  }
97092}
97093#endif   /* !SQLITE_OMIT_TRIGGER */
97094
97095/*
97096** Register built-in functions used to help implement ALTER TABLE
97097*/
97098SQLITE_PRIVATE void sqlite3AlterFunctions(void){
97099  static FuncDef aAlterTableFuncs[] = {
97100    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
97101#ifndef SQLITE_OMIT_TRIGGER
97102    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
97103#endif
97104#ifndef SQLITE_OMIT_FOREIGN_KEY
97105    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
97106#endif
97107  };
97108  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
97109}
97110
97111/*
97112** This function is used to create the text of expressions of the form:
97113**
97114**   name=<constant1> OR name=<constant2> OR ...
97115**
97116** If argument zWhere is NULL, then a pointer string containing the text
97117** "name=<constant>" is returned, where <constant> is the quoted version
97118** of the string passed as argument zConstant. The returned buffer is
97119** allocated using sqlite3DbMalloc(). It is the responsibility of the
97120** caller to ensure that it is eventually freed.
97121**
97122** If argument zWhere is not NULL, then the string returned is
97123** "<where> OR name=<constant>", where <where> is the contents of zWhere.
97124** In this case zWhere is passed to sqlite3DbFree() before returning.
97125**
97126*/
97127static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
97128  char *zNew;
97129  if( !zWhere ){
97130    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
97131  }else{
97132    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
97133    sqlite3DbFree(db, zWhere);
97134  }
97135  return zNew;
97136}
97137
97138#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97139/*
97140** Generate the text of a WHERE expression which can be used to select all
97141** tables that have foreign key constraints that refer to table pTab (i.e.
97142** constraints for which pTab is the parent table) from the sqlite_master
97143** table.
97144*/
97145static char *whereForeignKeys(Parse *pParse, Table *pTab){
97146  FKey *p;
97147  char *zWhere = 0;
97148  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97149    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
97150  }
97151  return zWhere;
97152}
97153#endif
97154
97155/*
97156** Generate the text of a WHERE expression which can be used to select all
97157** temporary triggers on table pTab from the sqlite_temp_master table. If
97158** table pTab has no temporary triggers, or is itself stored in the
97159** temporary database, NULL is returned.
97160*/
97161static char *whereTempTriggers(Parse *pParse, Table *pTab){
97162  Trigger *pTrig;
97163  char *zWhere = 0;
97164  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
97165
97166  /* If the table is not located in the temp-db (in which case NULL is
97167  ** returned, loop through the tables list of triggers. For each trigger
97168  ** that is not part of the temp-db schema, add a clause to the WHERE
97169  ** expression being built up in zWhere.
97170  */
97171  if( pTab->pSchema!=pTempSchema ){
97172    sqlite3 *db = pParse->db;
97173    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
97174      if( pTrig->pSchema==pTempSchema ){
97175        zWhere = whereOrName(db, zWhere, pTrig->zName);
97176      }
97177    }
97178  }
97179  if( zWhere ){
97180    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
97181    sqlite3DbFree(pParse->db, zWhere);
97182    zWhere = zNew;
97183  }
97184  return zWhere;
97185}
97186
97187/*
97188** Generate code to drop and reload the internal representation of table
97189** pTab from the database, including triggers and temporary triggers.
97190** Argument zName is the name of the table in the database schema at
97191** the time the generated code is executed. This can be different from
97192** pTab->zName if this function is being called to code part of an
97193** "ALTER TABLE RENAME TO" statement.
97194*/
97195static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
97196  Vdbe *v;
97197  char *zWhere;
97198  int iDb;                   /* Index of database containing pTab */
97199#ifndef SQLITE_OMIT_TRIGGER
97200  Trigger *pTrig;
97201#endif
97202
97203  v = sqlite3GetVdbe(pParse);
97204  if( NEVER(v==0) ) return;
97205  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
97206  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
97207  assert( iDb>=0 );
97208
97209#ifndef SQLITE_OMIT_TRIGGER
97210  /* Drop any table triggers from the internal schema. */
97211  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
97212    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
97213    assert( iTrigDb==iDb || iTrigDb==1 );
97214    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
97215  }
97216#endif
97217
97218  /* Drop the table and index from the internal schema.  */
97219  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
97220
97221  /* Reload the table, index and permanent trigger schemas. */
97222  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
97223  if( !zWhere ) return;
97224  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
97225
97226#ifndef SQLITE_OMIT_TRIGGER
97227  /* Now, if the table is not stored in the temp database, reload any temp
97228  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
97229  */
97230  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
97231    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
97232  }
97233#endif
97234}
97235
97236/*
97237** Parameter zName is the name of a table that is about to be altered
97238** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
97239** If the table is a system table, this function leaves an error message
97240** in pParse->zErr (system tables may not be altered) and returns non-zero.
97241**
97242** Or, if zName is not a system table, zero is returned.
97243*/
97244static int isSystemTable(Parse *pParse, const char *zName){
97245  if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
97246    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
97247    return 1;
97248  }
97249  return 0;
97250}
97251
97252/*
97253** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
97254** command.
97255*/
97256SQLITE_PRIVATE void sqlite3AlterRenameTable(
97257  Parse *pParse,            /* Parser context. */
97258  SrcList *pSrc,            /* The table to rename. */
97259  Token *pName              /* The new table name. */
97260){
97261  int iDb;                  /* Database that contains the table */
97262  char *zDb;                /* Name of database iDb */
97263  Table *pTab;              /* Table being renamed */
97264  char *zName = 0;          /* NULL-terminated version of pName */
97265  sqlite3 *db = pParse->db; /* Database connection */
97266  int nTabName;             /* Number of UTF-8 characters in zTabName */
97267  const char *zTabName;     /* Original name of the table */
97268  Vdbe *v;
97269#ifndef SQLITE_OMIT_TRIGGER
97270  char *zWhere = 0;         /* Where clause to locate temp triggers */
97271#endif
97272  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
97273  int savedDbFlags;         /* Saved value of db->flags */
97274
97275  savedDbFlags = db->flags;
97276  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
97277  assert( pSrc->nSrc==1 );
97278  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
97279
97280  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
97281  if( !pTab ) goto exit_rename_table;
97282  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
97283  zDb = db->aDb[iDb].zDbSName;
97284  db->flags |= SQLITE_PreferBuiltin;
97285
97286  /* Get a NULL terminated version of the new table name. */
97287  zName = sqlite3NameFromToken(db, pName);
97288  if( !zName ) goto exit_rename_table;
97289
97290  /* Check that a table or index named 'zName' does not already exist
97291  ** in database iDb. If so, this is an error.
97292  */
97293  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
97294    sqlite3ErrorMsg(pParse,
97295        "there is already another table or index with this name: %s", zName);
97296    goto exit_rename_table;
97297  }
97298
97299  /* Make sure it is not a system table being altered, or a reserved name
97300  ** that the table is being renamed to.
97301  */
97302  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
97303    goto exit_rename_table;
97304  }
97305  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
97306    exit_rename_table;
97307  }
97308
97309#ifndef SQLITE_OMIT_VIEW
97310  if( pTab->pSelect ){
97311    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
97312    goto exit_rename_table;
97313  }
97314#endif
97315
97316#ifndef SQLITE_OMIT_AUTHORIZATION
97317  /* Invoke the authorization callback. */
97318  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
97319    goto exit_rename_table;
97320  }
97321#endif
97322
97323#ifndef SQLITE_OMIT_VIRTUALTABLE
97324  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
97325    goto exit_rename_table;
97326  }
97327  if( IsVirtual(pTab) ){
97328    pVTab = sqlite3GetVTable(db, pTab);
97329    if( pVTab->pVtab->pModule->xRename==0 ){
97330      pVTab = 0;
97331    }
97332  }
97333#endif
97334
97335  /* Begin a transaction for database iDb.
97336  ** Then modify the schema cookie (since the ALTER TABLE modifies the
97337  ** schema). Open a statement transaction if the table is a virtual
97338  ** table.
97339  */
97340  v = sqlite3GetVdbe(pParse);
97341  if( v==0 ){
97342    goto exit_rename_table;
97343  }
97344  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
97345  sqlite3ChangeCookie(pParse, iDb);
97346
97347  /* If this is a virtual table, invoke the xRename() function if
97348  ** one is defined. The xRename() callback will modify the names
97349  ** of any resources used by the v-table implementation (including other
97350  ** SQLite tables) that are identified by the name of the virtual table.
97351  */
97352#ifndef SQLITE_OMIT_VIRTUALTABLE
97353  if( pVTab ){
97354    int i = ++pParse->nMem;
97355    sqlite3VdbeLoadString(v, i, zName);
97356    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
97357    sqlite3MayAbort(pParse);
97358  }
97359#endif
97360
97361  /* figure out how many UTF-8 characters are in zName */
97362  zTabName = pTab->zName;
97363  nTabName = sqlite3Utf8CharLen(zTabName, -1);
97364
97365#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97366  if( db->flags&SQLITE_ForeignKeys ){
97367    /* If foreign-key support is enabled, rewrite the CREATE TABLE
97368    ** statements corresponding to all child tables of foreign key constraints
97369    ** for which the renamed table is the parent table.  */
97370    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
97371      sqlite3NestedParse(pParse,
97372          "UPDATE \"%w\".%s SET "
97373              "sql = sqlite_rename_parent(sql, %Q, %Q) "
97374              "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
97375      sqlite3DbFree(db, zWhere);
97376    }
97377  }
97378#endif
97379
97380  /* Modify the sqlite_master table to use the new table name. */
97381  sqlite3NestedParse(pParse,
97382      "UPDATE %Q.%s SET "
97383#ifdef SQLITE_OMIT_TRIGGER
97384          "sql = sqlite_rename_table(sql, %Q), "
97385#else
97386          "sql = CASE "
97387            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
97388            "ELSE sqlite_rename_table(sql, %Q) END, "
97389#endif
97390          "tbl_name = %Q, "
97391          "name = CASE "
97392            "WHEN type='table' THEN %Q "
97393            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
97394             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
97395            "ELSE name END "
97396      "WHERE tbl_name=%Q COLLATE nocase AND "
97397          "(type='table' OR type='index' OR type='trigger');",
97398      zDb, MASTER_NAME, zName, zName, zName,
97399#ifndef SQLITE_OMIT_TRIGGER
97400      zName,
97401#endif
97402      zName, nTabName, zTabName
97403  );
97404
97405#ifndef SQLITE_OMIT_AUTOINCREMENT
97406  /* If the sqlite_sequence table exists in this database, then update
97407  ** it with the new table name.
97408  */
97409  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
97410    sqlite3NestedParse(pParse,
97411        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
97412        zDb, zName, pTab->zName);
97413  }
97414#endif
97415
97416#ifndef SQLITE_OMIT_TRIGGER
97417  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
97418  ** table. Don't do this if the table being ALTERed is itself located in
97419  ** the temp database.
97420  */
97421  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
97422    sqlite3NestedParse(pParse,
97423        "UPDATE sqlite_temp_master SET "
97424            "sql = sqlite_rename_trigger(sql, %Q), "
97425            "tbl_name = %Q "
97426            "WHERE %s;", zName, zName, zWhere);
97427    sqlite3DbFree(db, zWhere);
97428  }
97429#endif
97430
97431#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97432  if( db->flags&SQLITE_ForeignKeys ){
97433    FKey *p;
97434    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
97435      Table *pFrom = p->pFrom;
97436      if( pFrom!=pTab ){
97437        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
97438      }
97439    }
97440  }
97441#endif
97442
97443  /* Drop and reload the internal table schema. */
97444  reloadTableSchema(pParse, pTab, zName);
97445
97446exit_rename_table:
97447  sqlite3SrcListDelete(db, pSrc);
97448  sqlite3DbFree(db, zName);
97449  db->flags = savedDbFlags;
97450}
97451
97452/*
97453** This function is called after an "ALTER TABLE ... ADD" statement
97454** has been parsed. Argument pColDef contains the text of the new
97455** column definition.
97456**
97457** The Table structure pParse->pNewTable was extended to include
97458** the new column during parsing.
97459*/
97460SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
97461  Table *pNew;              /* Copy of pParse->pNewTable */
97462  Table *pTab;              /* Table being altered */
97463  int iDb;                  /* Database number */
97464  const char *zDb;          /* Database name */
97465  const char *zTab;         /* Table name */
97466  char *zCol;               /* Null-terminated column definition */
97467  Column *pCol;             /* The new column */
97468  Expr *pDflt;              /* Default value for the new column */
97469  sqlite3 *db;              /* The database connection; */
97470  Vdbe *v = pParse->pVdbe;  /* The prepared statement under construction */
97471  int r1;                   /* Temporary registers */
97472
97473  db = pParse->db;
97474  if( pParse->nErr || db->mallocFailed ) return;
97475  assert( v!=0 );
97476  pNew = pParse->pNewTable;
97477  assert( pNew );
97478
97479  assert( sqlite3BtreeHoldsAllMutexes(db) );
97480  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
97481  zDb = db->aDb[iDb].zDbSName;
97482  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
97483  pCol = &pNew->aCol[pNew->nCol-1];
97484  pDflt = pCol->pDflt;
97485  pTab = sqlite3FindTable(db, zTab, zDb);
97486  assert( pTab );
97487
97488#ifndef SQLITE_OMIT_AUTHORIZATION
97489  /* Invoke the authorization callback. */
97490  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
97491    return;
97492  }
97493#endif
97494
97495  /* If the default value for the new column was specified with a
97496  ** literal NULL, then set pDflt to 0. This simplifies checking
97497  ** for an SQL NULL default below.
97498  */
97499  assert( pDflt==0 || pDflt->op==TK_SPAN );
97500  if( pDflt && pDflt->pLeft->op==TK_NULL ){
97501    pDflt = 0;
97502  }
97503
97504  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
97505  ** If there is a NOT NULL constraint, then the default value for the
97506  ** column must not be NULL.
97507  */
97508  if( pCol->colFlags & COLFLAG_PRIMKEY ){
97509    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
97510    return;
97511  }
97512  if( pNew->pIndex ){
97513    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
97514    return;
97515  }
97516  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
97517    sqlite3ErrorMsg(pParse,
97518        "Cannot add a REFERENCES column with non-NULL default value");
97519    return;
97520  }
97521  if( pCol->notNull && !pDflt ){
97522    sqlite3ErrorMsg(pParse,
97523        "Cannot add a NOT NULL column with default value NULL");
97524    return;
97525  }
97526
97527  /* Ensure the default expression is something that sqlite3ValueFromExpr()
97528  ** can handle (i.e. not CURRENT_TIME etc.)
97529  */
97530  if( pDflt ){
97531    sqlite3_value *pVal = 0;
97532    int rc;
97533    rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
97534    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
97535    if( rc!=SQLITE_OK ){
97536      assert( db->mallocFailed == 1 );
97537      return;
97538    }
97539    if( !pVal ){
97540      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
97541      return;
97542    }
97543    sqlite3ValueFree(pVal);
97544  }
97545
97546  /* Modify the CREATE TABLE statement. */
97547  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
97548  if( zCol ){
97549    char *zEnd = &zCol[pColDef->n-1];
97550    int savedDbFlags = db->flags;
97551    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
97552      *zEnd-- = '\0';
97553    }
97554    db->flags |= SQLITE_PreferBuiltin;
97555    sqlite3NestedParse(pParse,
97556        "UPDATE \"%w\".%s SET "
97557          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
97558        "WHERE type = 'table' AND name = %Q",
97559      zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
97560      zTab
97561    );
97562    sqlite3DbFree(db, zCol);
97563    db->flags = savedDbFlags;
97564  }
97565
97566  /* Make sure the schema version is at least 3.  But do not upgrade
97567  ** from less than 3 to 4, as that will corrupt any preexisting DESC
97568  ** index.
97569  */
97570  r1 = sqlite3GetTempReg(pParse);
97571  sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
97572  sqlite3VdbeUsesBtree(v, iDb);
97573  sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
97574  sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
97575  VdbeCoverage(v);
97576  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
97577  sqlite3ReleaseTempReg(pParse, r1);
97578
97579  /* Reload the schema of the modified table. */
97580  reloadTableSchema(pParse, pTab, pTab->zName);
97581}
97582
97583/*
97584** This function is called by the parser after the table-name in
97585** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
97586** pSrc is the full-name of the table being altered.
97587**
97588** This routine makes a (partial) copy of the Table structure
97589** for the table being altered and sets Parse.pNewTable to point
97590** to it. Routines called by the parser as the column definition
97591** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
97592** the copy. The copy of the Table structure is deleted by tokenize.c
97593** after parsing is finished.
97594**
97595** Routine sqlite3AlterFinishAddColumn() will be called to complete
97596** coding the "ALTER TABLE ... ADD" statement.
97597*/
97598SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
97599  Table *pNew;
97600  Table *pTab;
97601  Vdbe *v;
97602  int iDb;
97603  int i;
97604  int nAlloc;
97605  sqlite3 *db = pParse->db;
97606
97607  /* Look up the table being altered. */
97608  assert( pParse->pNewTable==0 );
97609  assert( sqlite3BtreeHoldsAllMutexes(db) );
97610  if( db->mallocFailed ) goto exit_begin_add_column;
97611  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
97612  if( !pTab ) goto exit_begin_add_column;
97613
97614#ifndef SQLITE_OMIT_VIRTUALTABLE
97615  if( IsVirtual(pTab) ){
97616    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
97617    goto exit_begin_add_column;
97618  }
97619#endif
97620
97621  /* Make sure this is not an attempt to ALTER a view. */
97622  if( pTab->pSelect ){
97623    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
97624    goto exit_begin_add_column;
97625  }
97626  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
97627    goto exit_begin_add_column;
97628  }
97629
97630  assert( pTab->addColOffset>0 );
97631  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97632
97633  /* Put a copy of the Table struct in Parse.pNewTable for the
97634  ** sqlite3AddColumn() function and friends to modify.  But modify
97635  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
97636  ** prefix, we insure that the name will not collide with an existing
97637  ** table because user table are not allowed to have the "sqlite_"
97638  ** prefix on their name.
97639  */
97640  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
97641  if( !pNew ) goto exit_begin_add_column;
97642  pParse->pNewTable = pNew;
97643  pNew->nTabRef = 1;
97644  pNew->nCol = pTab->nCol;
97645  assert( pNew->nCol>0 );
97646  nAlloc = (((pNew->nCol-1)/8)*8)+8;
97647  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
97648  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
97649  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
97650  if( !pNew->aCol || !pNew->zName ){
97651    assert( db->mallocFailed );
97652    goto exit_begin_add_column;
97653  }
97654  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
97655  for(i=0; i<pNew->nCol; i++){
97656    Column *pCol = &pNew->aCol[i];
97657    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
97658    pCol->zColl = 0;
97659    pCol->pDflt = 0;
97660  }
97661  pNew->pSchema = db->aDb[iDb].pSchema;
97662  pNew->addColOffset = pTab->addColOffset;
97663  pNew->nTabRef = 1;
97664
97665  /* Begin a transaction and increment the schema cookie.  */
97666  sqlite3BeginWriteOperation(pParse, 0, iDb);
97667  v = sqlite3GetVdbe(pParse);
97668  if( !v ) goto exit_begin_add_column;
97669  sqlite3ChangeCookie(pParse, iDb);
97670
97671exit_begin_add_column:
97672  sqlite3SrcListDelete(db, pSrc);
97673  return;
97674}
97675#endif  /* SQLITE_ALTER_TABLE */
97676
97677/************** End of alter.c ***********************************************/
97678/************** Begin file analyze.c *****************************************/
97679/*
97680** 2005-07-08
97681**
97682** The author disclaims copyright to this source code.  In place of
97683** a legal notice, here is a blessing:
97684**
97685**    May you do good and not evil.
97686**    May you find forgiveness for yourself and forgive others.
97687**    May you share freely, never taking more than you give.
97688**
97689*************************************************************************
97690** This file contains code associated with the ANALYZE command.
97691**
97692** The ANALYZE command gather statistics about the content of tables
97693** and indices.  These statistics are made available to the query planner
97694** to help it make better decisions about how to perform queries.
97695**
97696** The following system tables are or have been supported:
97697**
97698**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
97699**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
97700**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
97701**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
97702**
97703** Additional tables might be added in future releases of SQLite.
97704** The sqlite_stat2 table is not created or used unless the SQLite version
97705** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
97706** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
97707** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
97708** created and used by SQLite versions 3.7.9 and later and with
97709** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
97710** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
97711** version of sqlite_stat3 and is only available when compiled with
97712** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
97713** not possible to enable both STAT3 and STAT4 at the same time.  If they
97714** are both enabled, then STAT4 takes precedence.
97715**
97716** For most applications, sqlite_stat1 provides all the statistics required
97717** for the query planner to make good choices.
97718**
97719** Format of sqlite_stat1:
97720**
97721** There is normally one row per index, with the index identified by the
97722** name in the idx column.  The tbl column is the name of the table to
97723** which the index belongs.  In each such row, the stat column will be
97724** a string consisting of a list of integers.  The first integer in this
97725** list is the number of rows in the index.  (This is the same as the
97726** number of rows in the table, except for partial indices.)  The second
97727** integer is the average number of rows in the index that have the same
97728** value in the first column of the index.  The third integer is the average
97729** number of rows in the index that have the same value for the first two
97730** columns.  The N-th integer (for N>1) is the average number of rows in
97731** the index which have the same value for the first N-1 columns.  For
97732** a K-column index, there will be K+1 integers in the stat column.  If
97733** the index is unique, then the last integer will be 1.
97734**
97735** The list of integers in the stat column can optionally be followed
97736** by the keyword "unordered".  The "unordered" keyword, if it is present,
97737** must be separated from the last integer by a single space.  If the
97738** "unordered" keyword is present, then the query planner assumes that
97739** the index is unordered and will not use the index for a range query.
97740**
97741** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
97742** column contains a single integer which is the (estimated) number of
97743** rows in the table identified by sqlite_stat1.tbl.
97744**
97745** Format of sqlite_stat2:
97746**
97747** The sqlite_stat2 is only created and is only used if SQLite is compiled
97748** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
97749** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
97750** about the distribution of keys within an index.  The index is identified by
97751** the "idx" column and the "tbl" column is the name of the table to which
97752** the index belongs.  There are usually 10 rows in the sqlite_stat2
97753** table for each index.
97754**
97755** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
97756** inclusive are samples of the left-most key value in the index taken at
97757** evenly spaced points along the index.  Let the number of samples be S
97758** (10 in the standard build) and let C be the number of rows in the index.
97759** Then the sampled rows are given by:
97760**
97761**     rownumber = (i*C*2 + C)/(S*2)
97762**
97763** For i between 0 and S-1.  Conceptually, the index space is divided into
97764** S uniform buckets and the samples are the middle row from each bucket.
97765**
97766** The format for sqlite_stat2 is recorded here for legacy reference.  This
97767** version of SQLite does not support sqlite_stat2.  It neither reads nor
97768** writes the sqlite_stat2 table.  This version of SQLite only supports
97769** sqlite_stat3.
97770**
97771** Format for sqlite_stat3:
97772**
97773** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
97774** sqlite_stat4 format will be described first.  Further information
97775** about sqlite_stat3 follows the sqlite_stat4 description.
97776**
97777** Format for sqlite_stat4:
97778**
97779** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
97780** to aid the query planner in choosing good indices based on the values
97781** that indexed columns are compared against in the WHERE clauses of
97782** queries.
97783**
97784** The sqlite_stat4 table contains multiple entries for each index.
97785** The idx column names the index and the tbl column is the table of the
97786** index.  If the idx and tbl columns are the same, then the sample is
97787** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
97788** binary encoding of a key from the index.  The nEq column is a
97789** list of integers.  The first integer is the approximate number
97790** of entries in the index whose left-most column exactly matches
97791** the left-most column of the sample.  The second integer in nEq
97792** is the approximate number of entries in the index where the
97793** first two columns match the first two columns of the sample.
97794** And so forth.  nLt is another list of integers that show the approximate
97795** number of entries that are strictly less than the sample.  The first
97796** integer in nLt contains the number of entries in the index where the
97797** left-most column is less than the left-most column of the sample.
97798** The K-th integer in the nLt entry is the number of index entries
97799** where the first K columns are less than the first K columns of the
97800** sample.  The nDLt column is like nLt except that it contains the
97801** number of distinct entries in the index that are less than the
97802** sample.
97803**
97804** There can be an arbitrary number of sqlite_stat4 entries per index.
97805** The ANALYZE command will typically generate sqlite_stat4 tables
97806** that contain between 10 and 40 samples which are distributed across
97807** the key space, though not uniformly, and which include samples with
97808** large nEq values.
97809**
97810** Format for sqlite_stat3 redux:
97811**
97812** The sqlite_stat3 table is like sqlite_stat4 except that it only
97813** looks at the left-most column of the index.  The sqlite_stat3.sample
97814** column contains the actual value of the left-most column instead
97815** of a blob encoding of the complete index key as is found in
97816** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
97817** all contain just a single integer which is the same as the first
97818** integer in the equivalent columns in sqlite_stat4.
97819*/
97820#ifndef SQLITE_OMIT_ANALYZE
97821/* #include "sqliteInt.h" */
97822
97823#if defined(SQLITE_ENABLE_STAT4)
97824# define IsStat4     1
97825# define IsStat3     0
97826#elif defined(SQLITE_ENABLE_STAT3)
97827# define IsStat4     0
97828# define IsStat3     1
97829#else
97830# define IsStat4     0
97831# define IsStat3     0
97832# undef SQLITE_STAT4_SAMPLES
97833# define SQLITE_STAT4_SAMPLES 1
97834#endif
97835#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
97836
97837/*
97838** This routine generates code that opens the sqlite_statN tables.
97839** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
97840** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
97841** appropriate compile-time options are provided.
97842**
97843** If the sqlite_statN tables do not previously exist, it is created.
97844**
97845** Argument zWhere may be a pointer to a buffer containing a table name,
97846** or it may be a NULL pointer. If it is not NULL, then all entries in
97847** the sqlite_statN tables associated with the named table are deleted.
97848** If zWhere==0, then code is generated to delete all stat table entries.
97849*/
97850static void openStatTable(
97851  Parse *pParse,          /* Parsing context */
97852  int iDb,                /* The database we are looking in */
97853  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
97854  const char *zWhere,     /* Delete entries for this table or index */
97855  const char *zWhereType  /* Either "tbl" or "idx" */
97856){
97857  static const struct {
97858    const char *zName;
97859    const char *zCols;
97860  } aTable[] = {
97861    { "sqlite_stat1", "tbl,idx,stat" },
97862#if defined(SQLITE_ENABLE_STAT4)
97863    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
97864    { "sqlite_stat3", 0 },
97865#elif defined(SQLITE_ENABLE_STAT3)
97866    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
97867    { "sqlite_stat4", 0 },
97868#else
97869    { "sqlite_stat3", 0 },
97870    { "sqlite_stat4", 0 },
97871#endif
97872  };
97873  int i;
97874  sqlite3 *db = pParse->db;
97875  Db *pDb;
97876  Vdbe *v = sqlite3GetVdbe(pParse);
97877  int aRoot[ArraySize(aTable)];
97878  u8 aCreateTbl[ArraySize(aTable)];
97879
97880  if( v==0 ) return;
97881  assert( sqlite3BtreeHoldsAllMutexes(db) );
97882  assert( sqlite3VdbeDb(v)==db );
97883  pDb = &db->aDb[iDb];
97884
97885  /* Create new statistic tables if they do not exist, or clear them
97886  ** if they do already exist.
97887  */
97888  for(i=0; i<ArraySize(aTable); i++){
97889    const char *zTab = aTable[i].zName;
97890    Table *pStat;
97891    if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
97892      if( aTable[i].zCols ){
97893        /* The sqlite_statN table does not exist. Create it. Note that a
97894        ** side-effect of the CREATE TABLE statement is to leave the rootpage
97895        ** of the new table in register pParse->regRoot. This is important
97896        ** because the OpenWrite opcode below will be needing it. */
97897        sqlite3NestedParse(pParse,
97898            "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
97899        );
97900        aRoot[i] = pParse->regRoot;
97901        aCreateTbl[i] = OPFLAG_P2ISREG;
97902      }
97903    }else{
97904      /* The table already exists. If zWhere is not NULL, delete all entries
97905      ** associated with the table zWhere. If zWhere is NULL, delete the
97906      ** entire contents of the table. */
97907      aRoot[i] = pStat->tnum;
97908      aCreateTbl[i] = 0;
97909      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
97910      if( zWhere ){
97911        sqlite3NestedParse(pParse,
97912           "DELETE FROM %Q.%s WHERE %s=%Q",
97913           pDb->zDbSName, zTab, zWhereType, zWhere
97914        );
97915      }else{
97916        /* The sqlite_stat[134] table already exists.  Delete all rows. */
97917        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
97918      }
97919    }
97920  }
97921
97922  /* Open the sqlite_stat[134] tables for writing. */
97923  for(i=0; aTable[i].zCols; i++){
97924    assert( i<ArraySize(aTable) );
97925    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
97926    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
97927    VdbeComment((v, aTable[i].zName));
97928  }
97929}
97930
97931/*
97932** Recommended number of samples for sqlite_stat4
97933*/
97934#ifndef SQLITE_STAT4_SAMPLES
97935# define SQLITE_STAT4_SAMPLES 24
97936#endif
97937
97938/*
97939** Three SQL functions - stat_init(), stat_push(), and stat_get() -
97940** share an instance of the following structure to hold their state
97941** information.
97942*/
97943typedef struct Stat4Accum Stat4Accum;
97944typedef struct Stat4Sample Stat4Sample;
97945struct Stat4Sample {
97946  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
97947  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
97948#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97949  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
97950  union {
97951    i64 iRowid;                     /* Rowid in main table of the key */
97952    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
97953  } u;
97954  u32 nRowid;                     /* Sizeof aRowid[] */
97955  u8 isPSample;                   /* True if a periodic sample */
97956  int iCol;                       /* If !isPSample, the reason for inclusion */
97957  u32 iHash;                      /* Tiebreaker hash */
97958#endif
97959};
97960struct Stat4Accum {
97961  tRowcnt nRow;             /* Number of rows in the entire table */
97962  tRowcnt nPSample;         /* How often to do a periodic sample */
97963  int nCol;                 /* Number of columns in index + pk/rowid */
97964  int nKeyCol;              /* Number of index columns w/o the pk/rowid */
97965  int mxSample;             /* Maximum number of samples to accumulate */
97966  Stat4Sample current;      /* Current row as a Stat4Sample */
97967  u32 iPrn;                 /* Pseudo-random number used for sampling */
97968  Stat4Sample *aBest;       /* Array of nCol best samples */
97969  int iMin;                 /* Index in a[] of entry with minimum score */
97970  int nSample;              /* Current number of samples */
97971  int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */
97972  int iGet;                 /* Index of current sample accessed by stat_get() */
97973  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
97974  sqlite3 *db;              /* Database connection, for malloc() */
97975};
97976
97977/* Reclaim memory used by a Stat4Sample
97978*/
97979#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97980static void sampleClear(sqlite3 *db, Stat4Sample *p){
97981  assert( db!=0 );
97982  if( p->nRowid ){
97983    sqlite3DbFree(db, p->u.aRowid);
97984    p->nRowid = 0;
97985  }
97986}
97987#endif
97988
97989/* Initialize the BLOB value of a ROWID
97990*/
97991#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97992static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
97993  assert( db!=0 );
97994  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
97995  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
97996  if( p->u.aRowid ){
97997    p->nRowid = n;
97998    memcpy(p->u.aRowid, pData, n);
97999  }else{
98000    p->nRowid = 0;
98001  }
98002}
98003#endif
98004
98005/* Initialize the INTEGER value of a ROWID.
98006*/
98007#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98008static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
98009  assert( db!=0 );
98010  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
98011  p->nRowid = 0;
98012  p->u.iRowid = iRowid;
98013}
98014#endif
98015
98016
98017/*
98018** Copy the contents of object (*pFrom) into (*pTo).
98019*/
98020#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98021static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
98022  pTo->isPSample = pFrom->isPSample;
98023  pTo->iCol = pFrom->iCol;
98024  pTo->iHash = pFrom->iHash;
98025  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
98026  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
98027  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
98028  if( pFrom->nRowid ){
98029    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
98030  }else{
98031    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
98032  }
98033}
98034#endif
98035
98036/*
98037** Reclaim all memory of a Stat4Accum structure.
98038*/
98039static void stat4Destructor(void *pOld){
98040  Stat4Accum *p = (Stat4Accum*)pOld;
98041#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98042  int i;
98043  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
98044  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
98045  sampleClear(p->db, &p->current);
98046#endif
98047  sqlite3DbFree(p->db, p);
98048}
98049
98050/*
98051** Implementation of the stat_init(N,K,C) SQL function. The three parameters
98052** are:
98053**     N:    The number of columns in the index including the rowid/pk (note 1)
98054**     K:    The number of columns in the index excluding the rowid/pk.
98055**     C:    The number of rows in the index (note 2)
98056**
98057** Note 1:  In the special case of the covering index that implements a
98058** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
98059** total number of columns in the table.
98060**
98061** Note 2:  C is only used for STAT3 and STAT4.
98062**
98063** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
98064** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
98065** PRIMARY KEY of the table.  The covering index that implements the
98066** original WITHOUT ROWID table as N==K as a special case.
98067**
98068** This routine allocates the Stat4Accum object in heap memory. The return
98069** value is a pointer to the Stat4Accum object.  The datatype of the
98070** return value is BLOB, but it is really just a pointer to the Stat4Accum
98071** object.
98072*/
98073static void statInit(
98074  sqlite3_context *context,
98075  int argc,
98076  sqlite3_value **argv
98077){
98078  Stat4Accum *p;
98079  int nCol;                       /* Number of columns in index being sampled */
98080  int nKeyCol;                    /* Number of key columns */
98081  int nColUp;                     /* nCol rounded up for alignment */
98082  int n;                          /* Bytes of space to allocate */
98083  sqlite3 *db;                    /* Database connection */
98084#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98085  int mxSample = SQLITE_STAT4_SAMPLES;
98086#endif
98087
98088  /* Decode the three function arguments */
98089  UNUSED_PARAMETER(argc);
98090  nCol = sqlite3_value_int(argv[0]);
98091  assert( nCol>0 );
98092  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
98093  nKeyCol = sqlite3_value_int(argv[1]);
98094  assert( nKeyCol<=nCol );
98095  assert( nKeyCol>0 );
98096
98097  /* Allocate the space required for the Stat4Accum object */
98098  n = sizeof(*p)
98099    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
98100    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
98101#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98102    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
98103    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
98104    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
98105#endif
98106  ;
98107  db = sqlite3_context_db_handle(context);
98108  p = sqlite3DbMallocZero(db, n);
98109  if( p==0 ){
98110    sqlite3_result_error_nomem(context);
98111    return;
98112  }
98113
98114  p->db = db;
98115  p->nRow = 0;
98116  p->nCol = nCol;
98117  p->nKeyCol = nKeyCol;
98118  p->current.anDLt = (tRowcnt*)&p[1];
98119  p->current.anEq = &p->current.anDLt[nColUp];
98120
98121#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98122  {
98123    u8 *pSpace;                     /* Allocated space not yet assigned */
98124    int i;                          /* Used to iterate through p->aSample[] */
98125
98126    p->iGet = -1;
98127    p->mxSample = mxSample;
98128    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
98129    p->current.anLt = &p->current.anEq[nColUp];
98130    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
98131
98132    /* Set up the Stat4Accum.a[] and aBest[] arrays */
98133    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
98134    p->aBest = &p->a[mxSample];
98135    pSpace = (u8*)(&p->a[mxSample+nCol]);
98136    for(i=0; i<(mxSample+nCol); i++){
98137      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
98138      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
98139      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
98140    }
98141    assert( (pSpace - (u8*)p)==n );
98142
98143    for(i=0; i<nCol; i++){
98144      p->aBest[i].iCol = i;
98145    }
98146  }
98147#endif
98148
98149  /* Return a pointer to the allocated object to the caller.  Note that
98150  ** only the pointer (the 2nd parameter) matters.  The size of the object
98151  ** (given by the 3rd parameter) is never used and can be any positive
98152  ** value. */
98153  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
98154}
98155static const FuncDef statInitFuncdef = {
98156  2+IsStat34,      /* nArg */
98157  SQLITE_UTF8,     /* funcFlags */
98158  0,               /* pUserData */
98159  0,               /* pNext */
98160  statInit,        /* xSFunc */
98161  0,               /* xFinalize */
98162  "stat_init",     /* zName */
98163  {0}
98164};
98165
98166#ifdef SQLITE_ENABLE_STAT4
98167/*
98168** pNew and pOld are both candidate non-periodic samples selected for
98169** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
98170** considering only any trailing columns and the sample hash value, this
98171** function returns true if sample pNew is to be preferred over pOld.
98172** In other words, if we assume that the cardinalities of the selected
98173** column for pNew and pOld are equal, is pNew to be preferred over pOld.
98174**
98175** This function assumes that for each argument sample, the contents of
98176** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
98177*/
98178static int sampleIsBetterPost(
98179  Stat4Accum *pAccum,
98180  Stat4Sample *pNew,
98181  Stat4Sample *pOld
98182){
98183  int nCol = pAccum->nCol;
98184  int i;
98185  assert( pNew->iCol==pOld->iCol );
98186  for(i=pNew->iCol+1; i<nCol; i++){
98187    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
98188    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
98189  }
98190  if( pNew->iHash>pOld->iHash ) return 1;
98191  return 0;
98192}
98193#endif
98194
98195#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98196/*
98197** Return true if pNew is to be preferred over pOld.
98198**
98199** This function assumes that for each argument sample, the contents of
98200** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
98201*/
98202static int sampleIsBetter(
98203  Stat4Accum *pAccum,
98204  Stat4Sample *pNew,
98205  Stat4Sample *pOld
98206){
98207  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
98208  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
98209
98210  assert( pOld->isPSample==0 && pNew->isPSample==0 );
98211  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
98212
98213  if( (nEqNew>nEqOld) ) return 1;
98214#ifdef SQLITE_ENABLE_STAT4
98215  if( nEqNew==nEqOld ){
98216    if( pNew->iCol<pOld->iCol ) return 1;
98217    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
98218  }
98219  return 0;
98220#else
98221  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
98222#endif
98223}
98224
98225/*
98226** Copy the contents of sample *pNew into the p->a[] array. If necessary,
98227** remove the least desirable sample from p->a[] to make room.
98228*/
98229static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
98230  Stat4Sample *pSample = 0;
98231  int i;
98232
98233  assert( IsStat4 || nEqZero==0 );
98234
98235#ifdef SQLITE_ENABLE_STAT4
98236  /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
98237  ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
98238  ** other words, if nMaxEqZero is n, then it is guaranteed that there
98239  ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
98240  if( nEqZero>p->nMaxEqZero ){
98241    p->nMaxEqZero = nEqZero;
98242  }
98243  if( pNew->isPSample==0 ){
98244    Stat4Sample *pUpgrade = 0;
98245    assert( pNew->anEq[pNew->iCol]>0 );
98246
98247    /* This sample is being added because the prefix that ends in column
98248    ** iCol occurs many times in the table. However, if we have already
98249    ** added a sample that shares this prefix, there is no need to add
98250    ** this one. Instead, upgrade the priority of the highest priority
98251    ** existing sample that shares this prefix.  */
98252    for(i=p->nSample-1; i>=0; i--){
98253      Stat4Sample *pOld = &p->a[i];
98254      if( pOld->anEq[pNew->iCol]==0 ){
98255        if( pOld->isPSample ) return;
98256        assert( pOld->iCol>pNew->iCol );
98257        assert( sampleIsBetter(p, pNew, pOld) );
98258        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
98259          pUpgrade = pOld;
98260        }
98261      }
98262    }
98263    if( pUpgrade ){
98264      pUpgrade->iCol = pNew->iCol;
98265      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
98266      goto find_new_min;
98267    }
98268  }
98269#endif
98270
98271  /* If necessary, remove sample iMin to make room for the new sample. */
98272  if( p->nSample>=p->mxSample ){
98273    Stat4Sample *pMin = &p->a[p->iMin];
98274    tRowcnt *anEq = pMin->anEq;
98275    tRowcnt *anLt = pMin->anLt;
98276    tRowcnt *anDLt = pMin->anDLt;
98277    sampleClear(p->db, pMin);
98278    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
98279    pSample = &p->a[p->nSample-1];
98280    pSample->nRowid = 0;
98281    pSample->anEq = anEq;
98282    pSample->anDLt = anDLt;
98283    pSample->anLt = anLt;
98284    p->nSample = p->mxSample-1;
98285  }
98286
98287  /* The "rows less-than" for the rowid column must be greater than that
98288  ** for the last sample in the p->a[] array. Otherwise, the samples would
98289  ** be out of order. */
98290#ifdef SQLITE_ENABLE_STAT4
98291  assert( p->nSample==0
98292       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
98293#endif
98294
98295  /* Insert the new sample */
98296  pSample = &p->a[p->nSample];
98297  sampleCopy(p, pSample, pNew);
98298  p->nSample++;
98299
98300  /* Zero the first nEqZero entries in the anEq[] array. */
98301  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
98302
98303#ifdef SQLITE_ENABLE_STAT4
98304 find_new_min:
98305#endif
98306  if( p->nSample>=p->mxSample ){
98307    int iMin = -1;
98308    for(i=0; i<p->mxSample; i++){
98309      if( p->a[i].isPSample ) continue;
98310      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
98311        iMin = i;
98312      }
98313    }
98314    assert( iMin>=0 );
98315    p->iMin = iMin;
98316  }
98317}
98318#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
98319
98320/*
98321** Field iChng of the index being scanned has changed. So at this point
98322** p->current contains a sample that reflects the previous row of the
98323** index. The value of anEq[iChng] and subsequent anEq[] elements are
98324** correct at this point.
98325*/
98326static void samplePushPrevious(Stat4Accum *p, int iChng){
98327#ifdef SQLITE_ENABLE_STAT4
98328  int i;
98329
98330  /* Check if any samples from the aBest[] array should be pushed
98331  ** into IndexSample.a[] at this point.  */
98332  for(i=(p->nCol-2); i>=iChng; i--){
98333    Stat4Sample *pBest = &p->aBest[i];
98334    pBest->anEq[i] = p->current.anEq[i];
98335    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
98336      sampleInsert(p, pBest, i);
98337    }
98338  }
98339
98340  /* Check that no sample contains an anEq[] entry with an index of
98341  ** p->nMaxEqZero or greater set to zero. */
98342  for(i=p->nSample-1; i>=0; i--){
98343    int j;
98344    for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
98345  }
98346
98347  /* Update the anEq[] fields of any samples already collected. */
98348  if( iChng<p->nMaxEqZero ){
98349    for(i=p->nSample-1; i>=0; i--){
98350      int j;
98351      for(j=iChng; j<p->nCol; j++){
98352        if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
98353      }
98354    }
98355    p->nMaxEqZero = iChng;
98356  }
98357#endif
98358
98359#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
98360  if( iChng==0 ){
98361    tRowcnt nLt = p->current.anLt[0];
98362    tRowcnt nEq = p->current.anEq[0];
98363
98364    /* Check if this is to be a periodic sample. If so, add it. */
98365    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
98366      p->current.isPSample = 1;
98367      sampleInsert(p, &p->current, 0);
98368      p->current.isPSample = 0;
98369    }else
98370
98371    /* Or if it is a non-periodic sample. Add it in this case too. */
98372    if( p->nSample<p->mxSample
98373     || sampleIsBetter(p, &p->current, &p->a[p->iMin])
98374    ){
98375      sampleInsert(p, &p->current, 0);
98376    }
98377  }
98378#endif
98379
98380#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
98381  UNUSED_PARAMETER( p );
98382  UNUSED_PARAMETER( iChng );
98383#endif
98384}
98385
98386/*
98387** Implementation of the stat_push SQL function:  stat_push(P,C,R)
98388** Arguments:
98389**
98390**    P     Pointer to the Stat4Accum object created by stat_init()
98391**    C     Index of left-most column to differ from previous row
98392**    R     Rowid for the current row.  Might be a key record for
98393**          WITHOUT ROWID tables.
98394**
98395** This SQL function always returns NULL.  It's purpose it to accumulate
98396** statistical data and/or samples in the Stat4Accum object about the
98397** index being analyzed.  The stat_get() SQL function will later be used to
98398** extract relevant information for constructing the sqlite_statN tables.
98399**
98400** The R parameter is only used for STAT3 and STAT4
98401*/
98402static void statPush(
98403  sqlite3_context *context,
98404  int argc,
98405  sqlite3_value **argv
98406){
98407  int i;
98408
98409  /* The three function arguments */
98410  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
98411  int iChng = sqlite3_value_int(argv[1]);
98412
98413  UNUSED_PARAMETER( argc );
98414  UNUSED_PARAMETER( context );
98415  assert( p->nCol>0 );
98416  assert( iChng<p->nCol );
98417
98418  if( p->nRow==0 ){
98419    /* This is the first call to this function. Do initialization. */
98420    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
98421  }else{
98422    /* Second and subsequent calls get processed here */
98423    samplePushPrevious(p, iChng);
98424
98425    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
98426    ** to the current row of the index. */
98427    for(i=0; i<iChng; i++){
98428      p->current.anEq[i]++;
98429    }
98430    for(i=iChng; i<p->nCol; i++){
98431      p->current.anDLt[i]++;
98432#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98433      p->current.anLt[i] += p->current.anEq[i];
98434#endif
98435      p->current.anEq[i] = 1;
98436    }
98437  }
98438  p->nRow++;
98439#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98440  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
98441    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
98442  }else{
98443    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
98444                                       sqlite3_value_blob(argv[2]));
98445  }
98446  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
98447#endif
98448
98449#ifdef SQLITE_ENABLE_STAT4
98450  {
98451    tRowcnt nLt = p->current.anLt[p->nCol-1];
98452
98453    /* Check if this is to be a periodic sample. If so, add it. */
98454    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
98455      p->current.isPSample = 1;
98456      p->current.iCol = 0;
98457      sampleInsert(p, &p->current, p->nCol-1);
98458      p->current.isPSample = 0;
98459    }
98460
98461    /* Update the aBest[] array. */
98462    for(i=0; i<(p->nCol-1); i++){
98463      p->current.iCol = i;
98464      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
98465        sampleCopy(p, &p->aBest[i], &p->current);
98466      }
98467    }
98468  }
98469#endif
98470}
98471static const FuncDef statPushFuncdef = {
98472  2+IsStat34,      /* nArg */
98473  SQLITE_UTF8,     /* funcFlags */
98474  0,               /* pUserData */
98475  0,               /* pNext */
98476  statPush,        /* xSFunc */
98477  0,               /* xFinalize */
98478  "stat_push",     /* zName */
98479  {0}
98480};
98481
98482#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
98483#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
98484#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
98485#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
98486#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
98487
98488/*
98489** Implementation of the stat_get(P,J) SQL function.  This routine is
98490** used to query statistical information that has been gathered into
98491** the Stat4Accum object by prior calls to stat_push().  The P parameter
98492** has type BLOB but it is really just a pointer to the Stat4Accum object.
98493** The content to returned is determined by the parameter J
98494** which is one of the STAT_GET_xxxx values defined above.
98495**
98496** The stat_get(P,J) function is not available to generic SQL.  It is
98497** inserted as part of a manually constructed bytecode program.  (See
98498** the callStatGet() routine below.)  It is guaranteed that the P
98499** parameter will always be a poiner to a Stat4Accum object, never a
98500** NULL.
98501**
98502** If neither STAT3 nor STAT4 are enabled, then J is always
98503** STAT_GET_STAT1 and is hence omitted and this routine becomes
98504** a one-parameter function, stat_get(P), that always returns the
98505** stat1 table entry information.
98506*/
98507static void statGet(
98508  sqlite3_context *context,
98509  int argc,
98510  sqlite3_value **argv
98511){
98512  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
98513#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98514  /* STAT3 and STAT4 have a parameter on this routine. */
98515  int eCall = sqlite3_value_int(argv[1]);
98516  assert( argc==2 );
98517  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
98518       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
98519       || eCall==STAT_GET_NDLT
98520  );
98521  if( eCall==STAT_GET_STAT1 )
98522#else
98523  assert( argc==1 );
98524#endif
98525  {
98526    /* Return the value to store in the "stat" column of the sqlite_stat1
98527    ** table for this index.
98528    **
98529    ** The value is a string composed of a list of integers describing
98530    ** the index. The first integer in the list is the total number of
98531    ** entries in the index. There is one additional integer in the list
98532    ** for each indexed column. This additional integer is an estimate of
98533    ** the number of rows matched by a stabbing query on the index using
98534    ** a key with the corresponding number of fields. In other words,
98535    ** if the index is on columns (a,b) and the sqlite_stat1 value is
98536    ** "100 10 2", then SQLite estimates that:
98537    **
98538    **   * the index contains 100 rows,
98539    **   * "WHERE a=?" matches 10 rows, and
98540    **   * "WHERE a=? AND b=?" matches 2 rows.
98541    **
98542    ** If D is the count of distinct values and K is the total number of
98543    ** rows, then each estimate is computed as:
98544    **
98545    **        I = (K+D-1)/D
98546    */
98547    char *z;
98548    int i;
98549
98550    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
98551    if( zRet==0 ){
98552      sqlite3_result_error_nomem(context);
98553      return;
98554    }
98555
98556    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
98557    z = zRet + sqlite3Strlen30(zRet);
98558    for(i=0; i<p->nKeyCol; i++){
98559      u64 nDistinct = p->current.anDLt[i] + 1;
98560      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
98561      sqlite3_snprintf(24, z, " %llu", iVal);
98562      z += sqlite3Strlen30(z);
98563      assert( p->current.anEq[i] );
98564    }
98565    assert( z[0]=='\0' && z>zRet );
98566
98567    sqlite3_result_text(context, zRet, -1, sqlite3_free);
98568  }
98569#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98570  else if( eCall==STAT_GET_ROWID ){
98571    if( p->iGet<0 ){
98572      samplePushPrevious(p, 0);
98573      p->iGet = 0;
98574    }
98575    if( p->iGet<p->nSample ){
98576      Stat4Sample *pS = p->a + p->iGet;
98577      if( pS->nRowid==0 ){
98578        sqlite3_result_int64(context, pS->u.iRowid);
98579      }else{
98580        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
98581                            SQLITE_TRANSIENT);
98582      }
98583    }
98584  }else{
98585    tRowcnt *aCnt = 0;
98586
98587    assert( p->iGet<p->nSample );
98588    switch( eCall ){
98589      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
98590      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
98591      default: {
98592        aCnt = p->a[p->iGet].anDLt;
98593        p->iGet++;
98594        break;
98595      }
98596    }
98597
98598    if( IsStat3 ){
98599      sqlite3_result_int64(context, (i64)aCnt[0]);
98600    }else{
98601      char *zRet = sqlite3MallocZero(p->nCol * 25);
98602      if( zRet==0 ){
98603        sqlite3_result_error_nomem(context);
98604      }else{
98605        int i;
98606        char *z = zRet;
98607        for(i=0; i<p->nCol; i++){
98608          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
98609          z += sqlite3Strlen30(z);
98610        }
98611        assert( z[0]=='\0' && z>zRet );
98612        z[-1] = '\0';
98613        sqlite3_result_text(context, zRet, -1, sqlite3_free);
98614      }
98615    }
98616  }
98617#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
98618#ifndef SQLITE_DEBUG
98619  UNUSED_PARAMETER( argc );
98620#endif
98621}
98622static const FuncDef statGetFuncdef = {
98623  1+IsStat34,      /* nArg */
98624  SQLITE_UTF8,     /* funcFlags */
98625  0,               /* pUserData */
98626  0,               /* pNext */
98627  statGet,         /* xSFunc */
98628  0,               /* xFinalize */
98629  "stat_get",      /* zName */
98630  {0}
98631};
98632
98633static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
98634  assert( regOut!=regStat4 && regOut!=regStat4+1 );
98635#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98636  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
98637#elif SQLITE_DEBUG
98638  assert( iParam==STAT_GET_STAT1 );
98639#else
98640  UNUSED_PARAMETER( iParam );
98641#endif
98642  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
98643                    (char*)&statGetFuncdef, P4_FUNCDEF);
98644  sqlite3VdbeChangeP5(v, 1 + IsStat34);
98645}
98646
98647/*
98648** Generate code to do an analysis of all indices associated with
98649** a single table.
98650*/
98651static void analyzeOneTable(
98652  Parse *pParse,   /* Parser context */
98653  Table *pTab,     /* Table whose indices are to be analyzed */
98654  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
98655  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
98656  int iMem,        /* Available memory locations begin here */
98657  int iTab         /* Next available cursor */
98658){
98659  sqlite3 *db = pParse->db;    /* Database handle */
98660  Index *pIdx;                 /* An index to being analyzed */
98661  int iIdxCur;                 /* Cursor open on index being analyzed */
98662  int iTabCur;                 /* Table cursor */
98663  Vdbe *v;                     /* The virtual machine being built up */
98664  int i;                       /* Loop counter */
98665  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
98666  int iDb;                     /* Index of database containing pTab */
98667  u8 needTableCnt = 1;         /* True to count the table */
98668  int regNewRowid = iMem++;    /* Rowid for the inserted record */
98669  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
98670  int regChng = iMem++;        /* Index of changed index field */
98671#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98672  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
98673#endif
98674  int regTemp = iMem++;        /* Temporary use register */
98675  int regTabname = iMem++;     /* Register containing table name */
98676  int regIdxname = iMem++;     /* Register containing index name */
98677  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
98678  int regPrev = iMem;          /* MUST BE LAST (see below) */
98679
98680  pParse->nMem = MAX(pParse->nMem, iMem);
98681  v = sqlite3GetVdbe(pParse);
98682  if( v==0 || NEVER(pTab==0) ){
98683    return;
98684  }
98685  if( pTab->tnum==0 ){
98686    /* Do not gather statistics on views or virtual tables */
98687    return;
98688  }
98689  if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
98690    /* Do not gather statistics on system tables */
98691    return;
98692  }
98693  assert( sqlite3BtreeHoldsAllMutexes(db) );
98694  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98695  assert( iDb>=0 );
98696  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98697#ifndef SQLITE_OMIT_AUTHORIZATION
98698  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
98699      db->aDb[iDb].zDbSName ) ){
98700    return;
98701  }
98702#endif
98703
98704  /* Establish a read-lock on the table at the shared-cache level.
98705  ** Open a read-only cursor on the table. Also allocate a cursor number
98706  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
98707  ** this time though.  */
98708  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98709  iTabCur = iTab++;
98710  iIdxCur = iTab++;
98711  pParse->nTab = MAX(pParse->nTab, iTab);
98712  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
98713  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
98714
98715  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98716    int nCol;                     /* Number of columns in pIdx. "N" */
98717    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
98718    int addrNextRow;              /* Address of "next_row:" */
98719    const char *zIdxName;         /* Name of the index */
98720    int nColTest;                 /* Number of columns to test for changes */
98721
98722    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
98723    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
98724    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
98725      nCol = pIdx->nKeyCol;
98726      zIdxName = pTab->zName;
98727      nColTest = nCol - 1;
98728    }else{
98729      nCol = pIdx->nColumn;
98730      zIdxName = pIdx->zName;
98731      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
98732    }
98733
98734    /* Populate the register containing the index name. */
98735    sqlite3VdbeLoadString(v, regIdxname, zIdxName);
98736    VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
98737
98738    /*
98739    ** Pseudo-code for loop that calls stat_push():
98740    **
98741    **   Rewind csr
98742    **   if eof(csr) goto end_of_scan;
98743    **   regChng = 0
98744    **   goto chng_addr_0;
98745    **
98746    **  next_row:
98747    **   regChng = 0
98748    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
98749    **   regChng = 1
98750    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
98751    **   ...
98752    **   regChng = N
98753    **   goto chng_addr_N
98754    **
98755    **  chng_addr_0:
98756    **   regPrev(0) = idx(0)
98757    **  chng_addr_1:
98758    **   regPrev(1) = idx(1)
98759    **  ...
98760    **
98761    **  endDistinctTest:
98762    **   regRowid = idx(rowid)
98763    **   stat_push(P, regChng, regRowid)
98764    **   Next csr
98765    **   if !eof(csr) goto next_row;
98766    **
98767    **  end_of_scan:
98768    */
98769
98770    /* Make sure there are enough memory cells allocated to accommodate
98771    ** the regPrev array and a trailing rowid (the rowid slot is required
98772    ** when building a record to insert into the sample column of
98773    ** the sqlite_stat4 table.  */
98774    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
98775
98776    /* Open a read-only cursor on the index being analyzed. */
98777    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
98778    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
98779    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
98780    VdbeComment((v, "%s", pIdx->zName));
98781
98782    /* Invoke the stat_init() function. The arguments are:
98783    **
98784    **    (1) the number of columns in the index including the rowid
98785    **        (or for a WITHOUT ROWID table, the number of PK columns),
98786    **    (2) the number of columns in the key without the rowid/pk
98787    **    (3) the number of rows in the index,
98788    **
98789    **
98790    ** The third argument is only used for STAT3 and STAT4
98791    */
98792#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98793    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
98794#endif
98795    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
98796    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
98797    sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
98798                     (char*)&statInitFuncdef, P4_FUNCDEF);
98799    sqlite3VdbeChangeP5(v, 2+IsStat34);
98800
98801    /* Implementation of the following:
98802    **
98803    **   Rewind csr
98804    **   if eof(csr) goto end_of_scan;
98805    **   regChng = 0
98806    **   goto next_push_0;
98807    **
98808    */
98809    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
98810    VdbeCoverage(v);
98811    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
98812    addrNextRow = sqlite3VdbeCurrentAddr(v);
98813
98814    if( nColTest>0 ){
98815      int endDistinctTest = sqlite3VdbeMakeLabel(v);
98816      int *aGotoChng;               /* Array of jump instruction addresses */
98817      aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
98818      if( aGotoChng==0 ) continue;
98819
98820      /*
98821      **  next_row:
98822      **   regChng = 0
98823      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
98824      **   regChng = 1
98825      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
98826      **   ...
98827      **   regChng = N
98828      **   goto endDistinctTest
98829      */
98830      sqlite3VdbeAddOp0(v, OP_Goto);
98831      addrNextRow = sqlite3VdbeCurrentAddr(v);
98832      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
98833        /* For a single-column UNIQUE index, once we have found a non-NULL
98834        ** row, we know that all the rest will be distinct, so skip
98835        ** subsequent distinctness tests. */
98836        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
98837        VdbeCoverage(v);
98838      }
98839      for(i=0; i<nColTest; i++){
98840        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
98841        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
98842        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
98843        aGotoChng[i] =
98844        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
98845        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
98846        VdbeCoverage(v);
98847      }
98848      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
98849      sqlite3VdbeGoto(v, endDistinctTest);
98850
98851
98852      /*
98853      **  chng_addr_0:
98854      **   regPrev(0) = idx(0)
98855      **  chng_addr_1:
98856      **   regPrev(1) = idx(1)
98857      **  ...
98858      */
98859      sqlite3VdbeJumpHere(v, addrNextRow-1);
98860      for(i=0; i<nColTest; i++){
98861        sqlite3VdbeJumpHere(v, aGotoChng[i]);
98862        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
98863      }
98864      sqlite3VdbeResolveLabel(v, endDistinctTest);
98865      sqlite3DbFree(db, aGotoChng);
98866    }
98867
98868    /*
98869    **  chng_addr_N:
98870    **   regRowid = idx(rowid)            // STAT34 only
98871    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
98872    **   Next csr
98873    **   if !eof(csr) goto next_row;
98874    */
98875#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98876    assert( regRowid==(regStat4+2) );
98877    if( HasRowid(pTab) ){
98878      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
98879    }else{
98880      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
98881      int j, k, regKey;
98882      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
98883      for(j=0; j<pPk->nKeyCol; j++){
98884        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
98885        assert( k>=0 && k<pIdx->nColumn );
98886        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
98887        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
98888      }
98889      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
98890      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
98891    }
98892#endif
98893    assert( regChng==(regStat4+1) );
98894    sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
98895                     (char*)&statPushFuncdef, P4_FUNCDEF);
98896    sqlite3VdbeChangeP5(v, 2+IsStat34);
98897    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
98898
98899    /* Add the entry to the stat1 table. */
98900    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
98901    assert( "BBB"[0]==SQLITE_AFF_TEXT );
98902    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
98903    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
98904    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
98905    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98906
98907    /* Add the entries to the stat3 or stat4 table. */
98908#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98909    {
98910      int regEq = regStat1;
98911      int regLt = regStat1+1;
98912      int regDLt = regStat1+2;
98913      int regSample = regStat1+3;
98914      int regCol = regStat1+4;
98915      int regSampleRowid = regCol + nCol;
98916      int addrNext;
98917      int addrIsNull;
98918      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
98919
98920      pParse->nMem = MAX(pParse->nMem, regCol+nCol);
98921
98922      addrNext = sqlite3VdbeCurrentAddr(v);
98923      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
98924      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
98925      VdbeCoverage(v);
98926      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
98927      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
98928      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
98929      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
98930      /* We know that the regSampleRowid row exists because it was read by
98931      ** the previous loop.  Thus the not-found jump of seekOp will never
98932      ** be taken */
98933      VdbeCoverageNeverTaken(v);
98934#ifdef SQLITE_ENABLE_STAT3
98935      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
98936#else
98937      for(i=0; i<nCol; i++){
98938        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
98939      }
98940      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
98941#endif
98942      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
98943      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
98944      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
98945      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
98946      sqlite3VdbeJumpHere(v, addrIsNull);
98947    }
98948#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
98949
98950    /* End of analysis */
98951    sqlite3VdbeJumpHere(v, addrRewind);
98952  }
98953
98954
98955  /* Create a single sqlite_stat1 entry containing NULL as the index
98956  ** name and the row count as the content.
98957  */
98958  if( pOnlyIdx==0 && needTableCnt ){
98959    VdbeComment((v, "%s", pTab->zName));
98960    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
98961    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
98962    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
98963    assert( "BBB"[0]==SQLITE_AFF_TEXT );
98964    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
98965    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
98966    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
98967    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98968    sqlite3VdbeJumpHere(v, jZeroRows);
98969  }
98970}
98971
98972
98973/*
98974** Generate code that will cause the most recent index analysis to
98975** be loaded into internal hash tables where is can be used.
98976*/
98977static void loadAnalysis(Parse *pParse, int iDb){
98978  Vdbe *v = sqlite3GetVdbe(pParse);
98979  if( v ){
98980    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
98981  }
98982}
98983
98984/*
98985** Generate code that will do an analysis of an entire database
98986*/
98987static void analyzeDatabase(Parse *pParse, int iDb){
98988  sqlite3 *db = pParse->db;
98989  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
98990  HashElem *k;
98991  int iStatCur;
98992  int iMem;
98993  int iTab;
98994
98995  sqlite3BeginWriteOperation(pParse, 0, iDb);
98996  iStatCur = pParse->nTab;
98997  pParse->nTab += 3;
98998  openStatTable(pParse, iDb, iStatCur, 0, 0);
98999  iMem = pParse->nMem+1;
99000  iTab = pParse->nTab;
99001  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99002  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
99003    Table *pTab = (Table*)sqliteHashData(k);
99004    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
99005  }
99006  loadAnalysis(pParse, iDb);
99007}
99008
99009/*
99010** Generate code that will do an analysis of a single table in
99011** a database.  If pOnlyIdx is not NULL then it is a single index
99012** in pTab that should be analyzed.
99013*/
99014static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
99015  int iDb;
99016  int iStatCur;
99017
99018  assert( pTab!=0 );
99019  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
99020  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99021  sqlite3BeginWriteOperation(pParse, 0, iDb);
99022  iStatCur = pParse->nTab;
99023  pParse->nTab += 3;
99024  if( pOnlyIdx ){
99025    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
99026  }else{
99027    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
99028  }
99029  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
99030  loadAnalysis(pParse, iDb);
99031}
99032
99033/*
99034** Generate code for the ANALYZE command.  The parser calls this routine
99035** when it recognizes an ANALYZE command.
99036**
99037**        ANALYZE                            -- 1
99038**        ANALYZE  <database>                -- 2
99039**        ANALYZE  ?<database>.?<tablename>  -- 3
99040**
99041** Form 1 causes all indices in all attached databases to be analyzed.
99042** Form 2 analyzes all indices the single database named.
99043** Form 3 analyzes all indices associated with the named table.
99044*/
99045SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
99046  sqlite3 *db = pParse->db;
99047  int iDb;
99048  int i;
99049  char *z, *zDb;
99050  Table *pTab;
99051  Index *pIdx;
99052  Token *pTableName;
99053  Vdbe *v;
99054
99055  /* Read the database schema. If an error occurs, leave an error message
99056  ** and code in pParse and return NULL. */
99057  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
99058  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99059    return;
99060  }
99061
99062  assert( pName2!=0 || pName1==0 );
99063  if( pName1==0 ){
99064    /* Form 1:  Analyze everything */
99065    for(i=0; i<db->nDb; i++){
99066      if( i==1 ) continue;  /* Do not analyze the TEMP database */
99067      analyzeDatabase(pParse, i);
99068    }
99069  }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
99070    /* Analyze the schema named as the argument */
99071    analyzeDatabase(pParse, iDb);
99072  }else{
99073    /* Form 3: Analyze the table or index named as an argument */
99074    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
99075    if( iDb>=0 ){
99076      zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
99077      z = sqlite3NameFromToken(db, pTableName);
99078      if( z ){
99079        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
99080          analyzeTable(pParse, pIdx->pTable, pIdx);
99081        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
99082          analyzeTable(pParse, pTab, 0);
99083        }
99084        sqlite3DbFree(db, z);
99085      }
99086    }
99087  }
99088  if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
99089    sqlite3VdbeAddOp0(v, OP_Expire);
99090  }
99091}
99092
99093/*
99094** Used to pass information from the analyzer reader through to the
99095** callback routine.
99096*/
99097typedef struct analysisInfo analysisInfo;
99098struct analysisInfo {
99099  sqlite3 *db;
99100  const char *zDatabase;
99101};
99102
99103/*
99104** The first argument points to a nul-terminated string containing a
99105** list of space separated integers. Read the first nOut of these into
99106** the array aOut[].
99107*/
99108static void decodeIntArray(
99109  char *zIntArray,       /* String containing int array to decode */
99110  int nOut,              /* Number of slots in aOut[] */
99111  tRowcnt *aOut,         /* Store integers here */
99112  LogEst *aLog,          /* Or, if aOut==0, here */
99113  Index *pIndex          /* Handle extra flags for this index, if not NULL */
99114){
99115  char *z = zIntArray;
99116  int c;
99117  int i;
99118  tRowcnt v;
99119
99120#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99121  if( z==0 ) z = "";
99122#else
99123  assert( z!=0 );
99124#endif
99125  for(i=0; *z && i<nOut; i++){
99126    v = 0;
99127    while( (c=z[0])>='0' && c<='9' ){
99128      v = v*10 + c - '0';
99129      z++;
99130    }
99131#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99132    if( aOut ) aOut[i] = v;
99133    if( aLog ) aLog[i] = sqlite3LogEst(v);
99134#else
99135    assert( aOut==0 );
99136    UNUSED_PARAMETER(aOut);
99137    assert( aLog!=0 );
99138    aLog[i] = sqlite3LogEst(v);
99139#endif
99140    if( *z==' ' ) z++;
99141  }
99142#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
99143  assert( pIndex!=0 ); {
99144#else
99145  if( pIndex ){
99146#endif
99147    pIndex->bUnordered = 0;
99148    pIndex->noSkipScan = 0;
99149    while( z[0] ){
99150      if( sqlite3_strglob("unordered*", z)==0 ){
99151        pIndex->bUnordered = 1;
99152      }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
99153        pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
99154      }else if( sqlite3_strglob("noskipscan*", z)==0 ){
99155        pIndex->noSkipScan = 1;
99156      }
99157#ifdef SQLITE_ENABLE_COSTMULT
99158      else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
99159        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
99160      }
99161#endif
99162      while( z[0]!=0 && z[0]!=' ' ) z++;
99163      while( z[0]==' ' ) z++;
99164    }
99165  }
99166}
99167
99168/*
99169** This callback is invoked once for each index when reading the
99170** sqlite_stat1 table.
99171**
99172**     argv[0] = name of the table
99173**     argv[1] = name of the index (might be NULL)
99174**     argv[2] = results of analysis - on integer for each column
99175**
99176** Entries for which argv[1]==NULL simply record the number of rows in
99177** the table.
99178*/
99179static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
99180  analysisInfo *pInfo = (analysisInfo*)pData;
99181  Index *pIndex;
99182  Table *pTable;
99183  const char *z;
99184
99185  assert( argc==3 );
99186  UNUSED_PARAMETER2(NotUsed, argc);
99187
99188  if( argv==0 || argv[0]==0 || argv[2]==0 ){
99189    return 0;
99190  }
99191  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
99192  if( pTable==0 ){
99193    return 0;
99194  }
99195  if( argv[1]==0 ){
99196    pIndex = 0;
99197  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
99198    pIndex = sqlite3PrimaryKeyIndex(pTable);
99199  }else{
99200    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
99201  }
99202  z = argv[2];
99203
99204  if( pIndex ){
99205    tRowcnt *aiRowEst = 0;
99206    int nCol = pIndex->nKeyCol+1;
99207#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99208    /* Index.aiRowEst may already be set here if there are duplicate
99209    ** sqlite_stat1 entries for this index. In that case just clobber
99210    ** the old data with the new instead of allocating a new array.  */
99211    if( pIndex->aiRowEst==0 ){
99212      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
99213      if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
99214    }
99215    aiRowEst = pIndex->aiRowEst;
99216#endif
99217    pIndex->bUnordered = 0;
99218    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
99219    pIndex->hasStat1 = 1;
99220    if( pIndex->pPartIdxWhere==0 ){
99221      pTable->nRowLogEst = pIndex->aiRowLogEst[0];
99222      pTable->tabFlags |= TF_HasStat1;
99223    }
99224  }else{
99225    Index fakeIdx;
99226    fakeIdx.szIdxRow = pTable->szTabRow;
99227#ifdef SQLITE_ENABLE_COSTMULT
99228    fakeIdx.pTable = pTable;
99229#endif
99230    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
99231    pTable->szTabRow = fakeIdx.szIdxRow;
99232    pTable->tabFlags |= TF_HasStat1;
99233  }
99234
99235  return 0;
99236}
99237
99238/*
99239** If the Index.aSample variable is not NULL, delete the aSample[] array
99240** and its contents.
99241*/
99242SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
99243#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99244  if( pIdx->aSample ){
99245    int j;
99246    for(j=0; j<pIdx->nSample; j++){
99247      IndexSample *p = &pIdx->aSample[j];
99248      sqlite3DbFree(db, p->p);
99249    }
99250    sqlite3DbFree(db, pIdx->aSample);
99251  }
99252  if( db && db->pnBytesFreed==0 ){
99253    pIdx->nSample = 0;
99254    pIdx->aSample = 0;
99255  }
99256#else
99257  UNUSED_PARAMETER(db);
99258  UNUSED_PARAMETER(pIdx);
99259#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
99260}
99261
99262#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99263/*
99264** Populate the pIdx->aAvgEq[] array based on the samples currently
99265** stored in pIdx->aSample[].
99266*/
99267static void initAvgEq(Index *pIdx){
99268  if( pIdx ){
99269    IndexSample *aSample = pIdx->aSample;
99270    IndexSample *pFinal = &aSample[pIdx->nSample-1];
99271    int iCol;
99272    int nCol = 1;
99273    if( pIdx->nSampleCol>1 ){
99274      /* If this is stat4 data, then calculate aAvgEq[] values for all
99275      ** sample columns except the last. The last is always set to 1, as
99276      ** once the trailing PK fields are considered all index keys are
99277      ** unique.  */
99278      nCol = pIdx->nSampleCol-1;
99279      pIdx->aAvgEq[nCol] = 1;
99280    }
99281    for(iCol=0; iCol<nCol; iCol++){
99282      int nSample = pIdx->nSample;
99283      int i;                    /* Used to iterate through samples */
99284      tRowcnt sumEq = 0;        /* Sum of the nEq values */
99285      tRowcnt avgEq = 0;
99286      tRowcnt nRow;             /* Number of rows in index */
99287      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
99288      i64 nDist100;             /* Number of distinct values in index */
99289
99290      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
99291        nRow = pFinal->anLt[iCol];
99292        nDist100 = (i64)100 * pFinal->anDLt[iCol];
99293        nSample--;
99294      }else{
99295        nRow = pIdx->aiRowEst[0];
99296        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
99297      }
99298      pIdx->nRowEst0 = nRow;
99299
99300      /* Set nSum to the number of distinct (iCol+1) field prefixes that
99301      ** occur in the stat4 table for this index. Set sumEq to the sum of
99302      ** the nEq values for column iCol for the same set (adding the value
99303      ** only once where there exist duplicate prefixes).  */
99304      for(i=0; i<nSample; i++){
99305        if( i==(pIdx->nSample-1)
99306         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
99307        ){
99308          sumEq += aSample[i].anEq[iCol];
99309          nSum100 += 100;
99310        }
99311      }
99312
99313      if( nDist100>nSum100 && sumEq<nRow ){
99314        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
99315      }
99316      if( avgEq==0 ) avgEq = 1;
99317      pIdx->aAvgEq[iCol] = avgEq;
99318    }
99319  }
99320}
99321
99322/*
99323** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
99324** is supplied instead, find the PRIMARY KEY index for that table.
99325*/
99326static Index *findIndexOrPrimaryKey(
99327  sqlite3 *db,
99328  const char *zName,
99329  const char *zDb
99330){
99331  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
99332  if( pIdx==0 ){
99333    Table *pTab = sqlite3FindTable(db, zName, zDb);
99334    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
99335  }
99336  return pIdx;
99337}
99338
99339/*
99340** Load the content from either the sqlite_stat4 or sqlite_stat3 table
99341** into the relevant Index.aSample[] arrays.
99342**
99343** Arguments zSql1 and zSql2 must point to SQL statements that return
99344** data equivalent to the following (statements are different for stat3,
99345** see the caller of this function for details):
99346**
99347**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
99348**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
99349**
99350** where %Q is replaced with the database name before the SQL is executed.
99351*/
99352static int loadStatTbl(
99353  sqlite3 *db,                  /* Database handle */
99354  int bStat3,                   /* Assume single column records only */
99355  const char *zSql1,            /* SQL statement 1 (see above) */
99356  const char *zSql2,            /* SQL statement 2 (see above) */
99357  const char *zDb               /* Database name (e.g. "main") */
99358){
99359  int rc;                       /* Result codes from subroutines */
99360  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
99361  char *zSql;                   /* Text of the SQL statement */
99362  Index *pPrevIdx = 0;          /* Previous index in the loop */
99363  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
99364
99365  assert( db->lookaside.bDisable );
99366  zSql = sqlite3MPrintf(db, zSql1, zDb);
99367  if( !zSql ){
99368    return SQLITE_NOMEM_BKPT;
99369  }
99370  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
99371  sqlite3DbFree(db, zSql);
99372  if( rc ) return rc;
99373
99374  while( sqlite3_step(pStmt)==SQLITE_ROW ){
99375    int nIdxCol = 1;              /* Number of columns in stat4 records */
99376
99377    char *zIndex;   /* Index name */
99378    Index *pIdx;    /* Pointer to the index object */
99379    int nSample;    /* Number of samples */
99380    int nByte;      /* Bytes of space required */
99381    int i;          /* Bytes of space required */
99382    tRowcnt *pSpace;
99383
99384    zIndex = (char *)sqlite3_column_text(pStmt, 0);
99385    if( zIndex==0 ) continue;
99386    nSample = sqlite3_column_int(pStmt, 1);
99387    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
99388    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
99389    /* Index.nSample is non-zero at this point if data has already been
99390    ** loaded from the stat4 table. In this case ignore stat3 data.  */
99391    if( pIdx==0 || pIdx->nSample ) continue;
99392    if( bStat3==0 ){
99393      assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
99394      if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
99395        nIdxCol = pIdx->nKeyCol;
99396      }else{
99397        nIdxCol = pIdx->nColumn;
99398      }
99399    }
99400    pIdx->nSampleCol = nIdxCol;
99401    nByte = sizeof(IndexSample) * nSample;
99402    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
99403    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
99404
99405    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
99406    if( pIdx->aSample==0 ){
99407      sqlite3_finalize(pStmt);
99408      return SQLITE_NOMEM_BKPT;
99409    }
99410    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
99411    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
99412    for(i=0; i<nSample; i++){
99413      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
99414      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
99415      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
99416    }
99417    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
99418  }
99419  rc = sqlite3_finalize(pStmt);
99420  if( rc ) return rc;
99421
99422  zSql = sqlite3MPrintf(db, zSql2, zDb);
99423  if( !zSql ){
99424    return SQLITE_NOMEM_BKPT;
99425  }
99426  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
99427  sqlite3DbFree(db, zSql);
99428  if( rc ) return rc;
99429
99430  while( sqlite3_step(pStmt)==SQLITE_ROW ){
99431    char *zIndex;                 /* Index name */
99432    Index *pIdx;                  /* Pointer to the index object */
99433    int nCol = 1;                 /* Number of columns in index */
99434
99435    zIndex = (char *)sqlite3_column_text(pStmt, 0);
99436    if( zIndex==0 ) continue;
99437    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
99438    if( pIdx==0 ) continue;
99439    /* This next condition is true if data has already been loaded from
99440    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
99441    nCol = pIdx->nSampleCol;
99442    if( bStat3 && nCol>1 ) continue;
99443    if( pIdx!=pPrevIdx ){
99444      initAvgEq(pPrevIdx);
99445      pPrevIdx = pIdx;
99446    }
99447    pSample = &pIdx->aSample[pIdx->nSample];
99448    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
99449    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
99450    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
99451
99452    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
99453    ** This is in case the sample record is corrupted. In that case, the
99454    ** sqlite3VdbeRecordCompare() may read up to two varints past the
99455    ** end of the allocated buffer before it realizes it is dealing with
99456    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
99457    ** a buffer overread.  */
99458    pSample->n = sqlite3_column_bytes(pStmt, 4);
99459    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
99460    if( pSample->p==0 ){
99461      sqlite3_finalize(pStmt);
99462      return SQLITE_NOMEM_BKPT;
99463    }
99464    if( pSample->n ){
99465      memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
99466    }
99467    pIdx->nSample++;
99468  }
99469  rc = sqlite3_finalize(pStmt);
99470  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
99471  return rc;
99472}
99473
99474/*
99475** Load content from the sqlite_stat4 and sqlite_stat3 tables into
99476** the Index.aSample[] arrays of all indices.
99477*/
99478static int loadStat4(sqlite3 *db, const char *zDb){
99479  int rc = SQLITE_OK;             /* Result codes from subroutines */
99480
99481  assert( db->lookaside.bDisable );
99482  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
99483    rc = loadStatTbl(db, 0,
99484      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
99485      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
99486      zDb
99487    );
99488  }
99489
99490  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
99491    rc = loadStatTbl(db, 1,
99492      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
99493      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
99494      zDb
99495    );
99496  }
99497
99498  return rc;
99499}
99500#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
99501
99502/*
99503** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
99504** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
99505** arrays. The contents of sqlite_stat3/4 are used to populate the
99506** Index.aSample[] arrays.
99507**
99508** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
99509** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
99510** during compilation and the sqlite_stat3/4 table is present, no data is
99511** read from it.
99512**
99513** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
99514** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
99515** returned. However, in this case, data is read from the sqlite_stat1
99516** table (if it is present) before returning.
99517**
99518** If an OOM error occurs, this function always sets db->mallocFailed.
99519** This means if the caller does not care about other errors, the return
99520** code may be ignored.
99521*/
99522SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
99523  analysisInfo sInfo;
99524  HashElem *i;
99525  char *zSql;
99526  int rc = SQLITE_OK;
99527  Schema *pSchema = db->aDb[iDb].pSchema;
99528
99529  assert( iDb>=0 && iDb<db->nDb );
99530  assert( db->aDb[iDb].pBt!=0 );
99531
99532  /* Clear any prior statistics */
99533  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99534  for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
99535    Table *pTab = sqliteHashData(i);
99536    pTab->tabFlags &= ~TF_HasStat1;
99537  }
99538  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
99539    Index *pIdx = sqliteHashData(i);
99540    pIdx->hasStat1 = 0;
99541#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99542    sqlite3DeleteIndexSamples(db, pIdx);
99543    pIdx->aSample = 0;
99544#endif
99545  }
99546
99547  /* Load new statistics out of the sqlite_stat1 table */
99548  sInfo.db = db;
99549  sInfo.zDatabase = db->aDb[iDb].zDbSName;
99550  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
99551    zSql = sqlite3MPrintf(db,
99552        "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
99553    if( zSql==0 ){
99554      rc = SQLITE_NOMEM_BKPT;
99555    }else{
99556      rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
99557      sqlite3DbFree(db, zSql);
99558    }
99559  }
99560
99561  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
99562  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99563  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
99564    Index *pIdx = sqliteHashData(i);
99565    if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
99566  }
99567
99568  /* Load the statistics from the sqlite_stat4 table. */
99569#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
99570  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
99571    db->lookaside.bDisable++;
99572    rc = loadStat4(db, sInfo.zDatabase);
99573    db->lookaside.bDisable--;
99574  }
99575  for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
99576    Index *pIdx = sqliteHashData(i);
99577    sqlite3_free(pIdx->aiRowEst);
99578    pIdx->aiRowEst = 0;
99579  }
99580#endif
99581
99582  if( rc==SQLITE_NOMEM ){
99583    sqlite3OomFault(db);
99584  }
99585  return rc;
99586}
99587
99588
99589#endif /* SQLITE_OMIT_ANALYZE */
99590
99591/************** End of analyze.c *********************************************/
99592/************** Begin file attach.c ******************************************/
99593/*
99594** 2003 April 6
99595**
99596** The author disclaims copyright to this source code.  In place of
99597** a legal notice, here is a blessing:
99598**
99599**    May you do good and not evil.
99600**    May you find forgiveness for yourself and forgive others.
99601**    May you share freely, never taking more than you give.
99602**
99603*************************************************************************
99604** This file contains code used to implement the ATTACH and DETACH commands.
99605*/
99606/* #include "sqliteInt.h" */
99607
99608#ifndef SQLITE_OMIT_ATTACH
99609/*
99610** Resolve an expression that was part of an ATTACH or DETACH statement. This
99611** is slightly different from resolving a normal SQL expression, because simple
99612** identifiers are treated as strings, not possible column names or aliases.
99613**
99614** i.e. if the parser sees:
99615**
99616**     ATTACH DATABASE abc AS def
99617**
99618** it treats the two expressions as literal strings 'abc' and 'def' instead of
99619** looking for columns of the same name.
99620**
99621** This only applies to the root node of pExpr, so the statement:
99622**
99623**     ATTACH DATABASE abc||def AS 'db2'
99624**
99625** will fail because neither abc or def can be resolved.
99626*/
99627static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
99628{
99629  int rc = SQLITE_OK;
99630  if( pExpr ){
99631    if( pExpr->op!=TK_ID ){
99632      rc = sqlite3ResolveExprNames(pName, pExpr);
99633    }else{
99634      pExpr->op = TK_STRING;
99635    }
99636  }
99637  return rc;
99638}
99639
99640/*
99641** An SQL user-function registered to do the work of an ATTACH statement. The
99642** three arguments to the function come directly from an attach statement:
99643**
99644**     ATTACH DATABASE x AS y KEY z
99645**
99646**     SELECT sqlite_attach(x, y, z)
99647**
99648** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
99649** third argument.
99650*/
99651static void attachFunc(
99652  sqlite3_context *context,
99653  int NotUsed,
99654  sqlite3_value **argv
99655){
99656  int i;
99657  int rc = 0;
99658  sqlite3 *db = sqlite3_context_db_handle(context);
99659  const char *zName;
99660  const char *zFile;
99661  char *zPath = 0;
99662  char *zErr = 0;
99663  unsigned int flags;
99664  Db *aNew;                 /* New array of Db pointers */
99665  Db *pNew;                 /* Db object for the newly attached database */
99666  char *zErrDyn = 0;
99667  sqlite3_vfs *pVfs;
99668
99669  UNUSED_PARAMETER(NotUsed);
99670
99671  zFile = (const char *)sqlite3_value_text(argv[0]);
99672  zName = (const char *)sqlite3_value_text(argv[1]);
99673  if( zFile==0 ) zFile = "";
99674  if( zName==0 ) zName = "";
99675
99676  /* Check for the following errors:
99677  **
99678  **     * Too many attached databases,
99679  **     * Transaction currently open
99680  **     * Specified database name already being used.
99681  */
99682  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
99683    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
99684      db->aLimit[SQLITE_LIMIT_ATTACHED]
99685    );
99686    goto attach_error;
99687  }
99688  if( !db->autoCommit ){
99689    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
99690    goto attach_error;
99691  }
99692  for(i=0; i<db->nDb; i++){
99693    char *z = db->aDb[i].zDbSName;
99694    assert( z && zName );
99695    if( sqlite3StrICmp(z, zName)==0 ){
99696      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
99697      goto attach_error;
99698    }
99699  }
99700
99701  /* Allocate the new entry in the db->aDb[] array and initialize the schema
99702  ** hash tables.
99703  */
99704  if( db->aDb==db->aDbStatic ){
99705    aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
99706    if( aNew==0 ) return;
99707    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
99708  }else{
99709    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
99710    if( aNew==0 ) return;
99711  }
99712  db->aDb = aNew;
99713  pNew = &db->aDb[db->nDb];
99714  memset(pNew, 0, sizeof(*pNew));
99715
99716  /* Open the database file. If the btree is successfully opened, use
99717  ** it to obtain the database schema. At this point the schema may
99718  ** or may not be initialized.
99719  */
99720  flags = db->openFlags;
99721  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
99722  if( rc!=SQLITE_OK ){
99723    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
99724    sqlite3_result_error(context, zErr, -1);
99725    sqlite3_free(zErr);
99726    return;
99727  }
99728  assert( pVfs );
99729  flags |= SQLITE_OPEN_MAIN_DB;
99730  rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
99731  sqlite3_free( zPath );
99732  db->nDb++;
99733  db->skipBtreeMutex = 0;
99734  if( rc==SQLITE_CONSTRAINT ){
99735    rc = SQLITE_ERROR;
99736    zErrDyn = sqlite3MPrintf(db, "database is already attached");
99737  }else if( rc==SQLITE_OK ){
99738    Pager *pPager;
99739    pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
99740    if( !pNew->pSchema ){
99741      rc = SQLITE_NOMEM_BKPT;
99742    }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
99743      zErrDyn = sqlite3MPrintf(db,
99744        "attached databases must use the same text encoding as main database");
99745      rc = SQLITE_ERROR;
99746    }
99747    sqlite3BtreeEnter(pNew->pBt);
99748    pPager = sqlite3BtreePager(pNew->pBt);
99749    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
99750    sqlite3BtreeSecureDelete(pNew->pBt,
99751                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
99752#ifndef SQLITE_OMIT_PAGER_PRAGMAS
99753    sqlite3BtreeSetPagerFlags(pNew->pBt,
99754                      PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
99755#endif
99756    sqlite3BtreeLeave(pNew->pBt);
99757  }
99758  pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
99759  pNew->zDbSName = sqlite3DbStrDup(db, zName);
99760  if( rc==SQLITE_OK && pNew->zDbSName==0 ){
99761    rc = SQLITE_NOMEM_BKPT;
99762  }
99763
99764
99765#ifdef SQLITE_HAS_CODEC
99766  if( rc==SQLITE_OK ){
99767    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
99768    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
99769    int nKey;
99770    char *zKey;
99771    int t = sqlite3_value_type(argv[2]);
99772    switch( t ){
99773      case SQLITE_INTEGER:
99774      case SQLITE_FLOAT:
99775        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
99776        rc = SQLITE_ERROR;
99777        break;
99778
99779      case SQLITE_TEXT:
99780      case SQLITE_BLOB:
99781        nKey = sqlite3_value_bytes(argv[2]);
99782        zKey = (char *)sqlite3_value_blob(argv[2]);
99783        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
99784        break;
99785
99786      case SQLITE_NULL:
99787        /* No key specified.  Use the key from the main database */
99788        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
99789        if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
99790          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
99791        }
99792        break;
99793    }
99794  }
99795#endif
99796
99797  /* If the file was opened successfully, read the schema for the new database.
99798  ** If this fails, or if opening the file failed, then close the file and
99799  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
99800  ** we found it.
99801  */
99802  if( rc==SQLITE_OK ){
99803    sqlite3BtreeEnterAll(db);
99804    rc = sqlite3Init(db, &zErrDyn);
99805    sqlite3BtreeLeaveAll(db);
99806  }
99807#ifdef SQLITE_USER_AUTHENTICATION
99808  if( rc==SQLITE_OK ){
99809    u8 newAuth = 0;
99810    rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
99811    if( newAuth<db->auth.authLevel ){
99812      rc = SQLITE_AUTH_USER;
99813    }
99814  }
99815#endif
99816  if( rc ){
99817    int iDb = db->nDb - 1;
99818    assert( iDb>=2 );
99819    if( db->aDb[iDb].pBt ){
99820      sqlite3BtreeClose(db->aDb[iDb].pBt);
99821      db->aDb[iDb].pBt = 0;
99822      db->aDb[iDb].pSchema = 0;
99823    }
99824    sqlite3ResetAllSchemasOfConnection(db);
99825    db->nDb = iDb;
99826    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
99827      sqlite3OomFault(db);
99828      sqlite3DbFree(db, zErrDyn);
99829      zErrDyn = sqlite3MPrintf(db, "out of memory");
99830    }else if( zErrDyn==0 ){
99831      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
99832    }
99833    goto attach_error;
99834  }
99835
99836  return;
99837
99838attach_error:
99839  /* Return an error if we get here */
99840  if( zErrDyn ){
99841    sqlite3_result_error(context, zErrDyn, -1);
99842    sqlite3DbFree(db, zErrDyn);
99843  }
99844  if( rc ) sqlite3_result_error_code(context, rc);
99845}
99846
99847/*
99848** An SQL user-function registered to do the work of an DETACH statement. The
99849** three arguments to the function come directly from a detach statement:
99850**
99851**     DETACH DATABASE x
99852**
99853**     SELECT sqlite_detach(x)
99854*/
99855static void detachFunc(
99856  sqlite3_context *context,
99857  int NotUsed,
99858  sqlite3_value **argv
99859){
99860  const char *zName = (const char *)sqlite3_value_text(argv[0]);
99861  sqlite3 *db = sqlite3_context_db_handle(context);
99862  int i;
99863  Db *pDb = 0;
99864  char zErr[128];
99865
99866  UNUSED_PARAMETER(NotUsed);
99867
99868  if( zName==0 ) zName = "";
99869  for(i=0; i<db->nDb; i++){
99870    pDb = &db->aDb[i];
99871    if( pDb->pBt==0 ) continue;
99872    if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
99873  }
99874
99875  if( i>=db->nDb ){
99876    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
99877    goto detach_error;
99878  }
99879  if( i<2 ){
99880    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
99881    goto detach_error;
99882  }
99883  if( !db->autoCommit ){
99884    sqlite3_snprintf(sizeof(zErr), zErr,
99885                     "cannot DETACH database within transaction");
99886    goto detach_error;
99887  }
99888  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
99889    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
99890    goto detach_error;
99891  }
99892
99893  sqlite3BtreeClose(pDb->pBt);
99894  pDb->pBt = 0;
99895  pDb->pSchema = 0;
99896  sqlite3CollapseDatabaseArray(db);
99897  return;
99898
99899detach_error:
99900  sqlite3_result_error(context, zErr, -1);
99901}
99902
99903/*
99904** This procedure generates VDBE code for a single invocation of either the
99905** sqlite_detach() or sqlite_attach() SQL user functions.
99906*/
99907static void codeAttach(
99908  Parse *pParse,       /* The parser context */
99909  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
99910  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
99911  Expr *pAuthArg,      /* Expression to pass to authorization callback */
99912  Expr *pFilename,     /* Name of database file */
99913  Expr *pDbname,       /* Name of the database to use internally */
99914  Expr *pKey           /* Database key for encryption extension */
99915){
99916  int rc;
99917  NameContext sName;
99918  Vdbe *v;
99919  sqlite3* db = pParse->db;
99920  int regArgs;
99921
99922  if( pParse->nErr ) goto attach_end;
99923  memset(&sName, 0, sizeof(NameContext));
99924  sName.pParse = pParse;
99925
99926  if(
99927      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
99928      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
99929      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
99930  ){
99931    goto attach_end;
99932  }
99933
99934#ifndef SQLITE_OMIT_AUTHORIZATION
99935  if( pAuthArg ){
99936    char *zAuthArg;
99937    if( pAuthArg->op==TK_STRING ){
99938      zAuthArg = pAuthArg->u.zToken;
99939    }else{
99940      zAuthArg = 0;
99941    }
99942    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
99943    if(rc!=SQLITE_OK ){
99944      goto attach_end;
99945    }
99946  }
99947#endif /* SQLITE_OMIT_AUTHORIZATION */
99948
99949
99950  v = sqlite3GetVdbe(pParse);
99951  regArgs = sqlite3GetTempRange(pParse, 4);
99952  sqlite3ExprCode(pParse, pFilename, regArgs);
99953  sqlite3ExprCode(pParse, pDbname, regArgs+1);
99954  sqlite3ExprCode(pParse, pKey, regArgs+2);
99955
99956  assert( v || db->mallocFailed );
99957  if( v ){
99958    sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
99959                      (char *)pFunc, P4_FUNCDEF);
99960    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
99961    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
99962
99963    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
99964    ** statement only). For DETACH, set it to false (expire all existing
99965    ** statements).
99966    */
99967    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
99968  }
99969
99970attach_end:
99971  sqlite3ExprDelete(db, pFilename);
99972  sqlite3ExprDelete(db, pDbname);
99973  sqlite3ExprDelete(db, pKey);
99974}
99975
99976/*
99977** Called by the parser to compile a DETACH statement.
99978**
99979**     DETACH pDbname
99980*/
99981SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
99982  static const FuncDef detach_func = {
99983    1,                /* nArg */
99984    SQLITE_UTF8,      /* funcFlags */
99985    0,                /* pUserData */
99986    0,                /* pNext */
99987    detachFunc,       /* xSFunc */
99988    0,                /* xFinalize */
99989    "sqlite_detach",  /* zName */
99990    {0}
99991  };
99992  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
99993}
99994
99995/*
99996** Called by the parser to compile an ATTACH statement.
99997**
99998**     ATTACH p AS pDbname KEY pKey
99999*/
100000SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
100001  static const FuncDef attach_func = {
100002    3,                /* nArg */
100003    SQLITE_UTF8,      /* funcFlags */
100004    0,                /* pUserData */
100005    0,                /* pNext */
100006    attachFunc,       /* xSFunc */
100007    0,                /* xFinalize */
100008    "sqlite_attach",  /* zName */
100009    {0}
100010  };
100011  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
100012}
100013#endif /* SQLITE_OMIT_ATTACH */
100014
100015/*
100016** Initialize a DbFixer structure.  This routine must be called prior
100017** to passing the structure to one of the sqliteFixAAAA() routines below.
100018*/
100019SQLITE_PRIVATE void sqlite3FixInit(
100020  DbFixer *pFix,      /* The fixer to be initialized */
100021  Parse *pParse,      /* Error messages will be written here */
100022  int iDb,            /* This is the database that must be used */
100023  const char *zType,  /* "view", "trigger", or "index" */
100024  const Token *pName  /* Name of the view, trigger, or index */
100025){
100026  sqlite3 *db;
100027
100028  db = pParse->db;
100029  assert( db->nDb>iDb );
100030  pFix->pParse = pParse;
100031  pFix->zDb = db->aDb[iDb].zDbSName;
100032  pFix->pSchema = db->aDb[iDb].pSchema;
100033  pFix->zType = zType;
100034  pFix->pName = pName;
100035  pFix->bVarOnly = (iDb==1);
100036}
100037
100038/*
100039** The following set of routines walk through the parse tree and assign
100040** a specific database to all table references where the database name
100041** was left unspecified in the original SQL statement.  The pFix structure
100042** must have been initialized by a prior call to sqlite3FixInit().
100043**
100044** These routines are used to make sure that an index, trigger, or
100045** view in one database does not refer to objects in a different database.
100046** (Exception: indices, triggers, and views in the TEMP database are
100047** allowed to refer to anything.)  If a reference is explicitly made
100048** to an object in a different database, an error message is added to
100049** pParse->zErrMsg and these routines return non-zero.  If everything
100050** checks out, these routines return 0.
100051*/
100052SQLITE_PRIVATE int sqlite3FixSrcList(
100053  DbFixer *pFix,       /* Context of the fixation */
100054  SrcList *pList       /* The Source list to check and modify */
100055){
100056  int i;
100057  const char *zDb;
100058  struct SrcList_item *pItem;
100059
100060  if( NEVER(pList==0) ) return 0;
100061  zDb = pFix->zDb;
100062  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
100063    if( pFix->bVarOnly==0 ){
100064      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
100065        sqlite3ErrorMsg(pFix->pParse,
100066            "%s %T cannot reference objects in database %s",
100067            pFix->zType, pFix->pName, pItem->zDatabase);
100068        return 1;
100069      }
100070      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
100071      pItem->zDatabase = 0;
100072      pItem->pSchema = pFix->pSchema;
100073    }
100074#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
100075    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
100076    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
100077#endif
100078  }
100079  return 0;
100080}
100081#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
100082SQLITE_PRIVATE int sqlite3FixSelect(
100083  DbFixer *pFix,       /* Context of the fixation */
100084  Select *pSelect      /* The SELECT statement to be fixed to one database */
100085){
100086  while( pSelect ){
100087    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
100088      return 1;
100089    }
100090    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
100091      return 1;
100092    }
100093    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
100094      return 1;
100095    }
100096    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
100097      return 1;
100098    }
100099    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
100100      return 1;
100101    }
100102    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
100103      return 1;
100104    }
100105    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
100106      return 1;
100107    }
100108    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
100109      return 1;
100110    }
100111    pSelect = pSelect->pPrior;
100112  }
100113  return 0;
100114}
100115SQLITE_PRIVATE int sqlite3FixExpr(
100116  DbFixer *pFix,     /* Context of the fixation */
100117  Expr *pExpr        /* The expression to be fixed to one database */
100118){
100119  while( pExpr ){
100120    if( pExpr->op==TK_VARIABLE ){
100121      if( pFix->pParse->db->init.busy ){
100122        pExpr->op = TK_NULL;
100123      }else{
100124        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
100125        return 1;
100126      }
100127    }
100128    if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
100129    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
100130      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
100131    }else{
100132      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
100133    }
100134    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
100135      return 1;
100136    }
100137    pExpr = pExpr->pLeft;
100138  }
100139  return 0;
100140}
100141SQLITE_PRIVATE int sqlite3FixExprList(
100142  DbFixer *pFix,     /* Context of the fixation */
100143  ExprList *pList    /* The expression to be fixed to one database */
100144){
100145  int i;
100146  struct ExprList_item *pItem;
100147  if( pList==0 ) return 0;
100148  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
100149    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
100150      return 1;
100151    }
100152  }
100153  return 0;
100154}
100155#endif
100156
100157#ifndef SQLITE_OMIT_TRIGGER
100158SQLITE_PRIVATE int sqlite3FixTriggerStep(
100159  DbFixer *pFix,     /* Context of the fixation */
100160  TriggerStep *pStep /* The trigger step be fixed to one database */
100161){
100162  while( pStep ){
100163    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
100164      return 1;
100165    }
100166    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
100167      return 1;
100168    }
100169    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
100170      return 1;
100171    }
100172    pStep = pStep->pNext;
100173  }
100174  return 0;
100175}
100176#endif
100177
100178/************** End of attach.c **********************************************/
100179/************** Begin file auth.c ********************************************/
100180/*
100181** 2003 January 11
100182**
100183** The author disclaims copyright to this source code.  In place of
100184** a legal notice, here is a blessing:
100185**
100186**    May you do good and not evil.
100187**    May you find forgiveness for yourself and forgive others.
100188**    May you share freely, never taking more than you give.
100189**
100190*************************************************************************
100191** This file contains code used to implement the sqlite3_set_authorizer()
100192** API.  This facility is an optional feature of the library.  Embedded
100193** systems that do not need this facility may omit it by recompiling
100194** the library with -DSQLITE_OMIT_AUTHORIZATION=1
100195*/
100196/* #include "sqliteInt.h" */
100197
100198/*
100199** All of the code in this file may be omitted by defining a single
100200** macro.
100201*/
100202#ifndef SQLITE_OMIT_AUTHORIZATION
100203
100204/*
100205** Set or clear the access authorization function.
100206**
100207** The access authorization function is be called during the compilation
100208** phase to verify that the user has read and/or write access permission on
100209** various fields of the database.  The first argument to the auth function
100210** is a copy of the 3rd argument to this routine.  The second argument
100211** to the auth function is one of these constants:
100212**
100213**       SQLITE_CREATE_INDEX
100214**       SQLITE_CREATE_TABLE
100215**       SQLITE_CREATE_TEMP_INDEX
100216**       SQLITE_CREATE_TEMP_TABLE
100217**       SQLITE_CREATE_TEMP_TRIGGER
100218**       SQLITE_CREATE_TEMP_VIEW
100219**       SQLITE_CREATE_TRIGGER
100220**       SQLITE_CREATE_VIEW
100221**       SQLITE_DELETE
100222**       SQLITE_DROP_INDEX
100223**       SQLITE_DROP_TABLE
100224**       SQLITE_DROP_TEMP_INDEX
100225**       SQLITE_DROP_TEMP_TABLE
100226**       SQLITE_DROP_TEMP_TRIGGER
100227**       SQLITE_DROP_TEMP_VIEW
100228**       SQLITE_DROP_TRIGGER
100229**       SQLITE_DROP_VIEW
100230**       SQLITE_INSERT
100231**       SQLITE_PRAGMA
100232**       SQLITE_READ
100233**       SQLITE_SELECT
100234**       SQLITE_TRANSACTION
100235**       SQLITE_UPDATE
100236**
100237** The third and fourth arguments to the auth function are the name of
100238** the table and the column that are being accessed.  The auth function
100239** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
100240** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
100241** means that the SQL statement will never-run - the sqlite3_exec() call
100242** will return with an error.  SQLITE_IGNORE means that the SQL statement
100243** should run but attempts to read the specified column will return NULL
100244** and attempts to write the column will be ignored.
100245**
100246** Setting the auth function to NULL disables this hook.  The default
100247** setting of the auth function is NULL.
100248*/
100249SQLITE_API int sqlite3_set_authorizer(
100250  sqlite3 *db,
100251  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
100252  void *pArg
100253){
100254#ifdef SQLITE_ENABLE_API_ARMOR
100255  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
100256#endif
100257  sqlite3_mutex_enter(db->mutex);
100258  db->xAuth = (sqlite3_xauth)xAuth;
100259  db->pAuthArg = pArg;
100260  sqlite3ExpirePreparedStatements(db);
100261  sqlite3_mutex_leave(db->mutex);
100262  return SQLITE_OK;
100263}
100264
100265/*
100266** Write an error message into pParse->zErrMsg that explains that the
100267** user-supplied authorization function returned an illegal value.
100268*/
100269static void sqliteAuthBadReturnCode(Parse *pParse){
100270  sqlite3ErrorMsg(pParse, "authorizer malfunction");
100271  pParse->rc = SQLITE_ERROR;
100272}
100273
100274/*
100275** Invoke the authorization callback for permission to read column zCol from
100276** table zTab in database zDb. This function assumes that an authorization
100277** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
100278**
100279** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
100280** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
100281** is treated as SQLITE_DENY. In this case an error is left in pParse.
100282*/
100283SQLITE_PRIVATE int sqlite3AuthReadCol(
100284  Parse *pParse,                  /* The parser context */
100285  const char *zTab,               /* Table name */
100286  const char *zCol,               /* Column name */
100287  int iDb                         /* Index of containing database. */
100288){
100289  sqlite3 *db = pParse->db;          /* Database handle */
100290  char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
100291  int rc;                            /* Auth callback return code */
100292
100293  if( db->init.busy ) return SQLITE_OK;
100294  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
100295#ifdef SQLITE_USER_AUTHENTICATION
100296                 ,db->auth.zAuthUser
100297#endif
100298                );
100299  if( rc==SQLITE_DENY ){
100300    if( db->nDb>2 || iDb!=0 ){
100301      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
100302    }else{
100303      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
100304    }
100305    pParse->rc = SQLITE_AUTH;
100306  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
100307    sqliteAuthBadReturnCode(pParse);
100308  }
100309  return rc;
100310}
100311
100312/*
100313** The pExpr should be a TK_COLUMN expression.  The table referred to
100314** is in pTabList or else it is the NEW or OLD table of a trigger.
100315** Check to see if it is OK to read this particular column.
100316**
100317** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
100318** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
100319** then generate an error.
100320*/
100321SQLITE_PRIVATE void sqlite3AuthRead(
100322  Parse *pParse,        /* The parser context */
100323  Expr *pExpr,          /* The expression to check authorization on */
100324  Schema *pSchema,      /* The schema of the expression */
100325  SrcList *pTabList     /* All table that pExpr might refer to */
100326){
100327  sqlite3 *db = pParse->db;
100328  Table *pTab = 0;      /* The table being read */
100329  const char *zCol;     /* Name of the column of the table */
100330  int iSrc;             /* Index in pTabList->a[] of table being read */
100331  int iDb;              /* The index of the database the expression refers to */
100332  int iCol;             /* Index of column in table */
100333
100334  if( db->xAuth==0 ) return;
100335  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
100336  if( iDb<0 ){
100337    /* An attempt to read a column out of a subquery or other
100338    ** temporary table. */
100339    return;
100340  }
100341
100342  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
100343  if( pExpr->op==TK_TRIGGER ){
100344    pTab = pParse->pTriggerTab;
100345  }else{
100346    assert( pTabList );
100347    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
100348      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
100349        pTab = pTabList->a[iSrc].pTab;
100350        break;
100351      }
100352    }
100353  }
100354  iCol = pExpr->iColumn;
100355  if( NEVER(pTab==0) ) return;
100356
100357  if( iCol>=0 ){
100358    assert( iCol<pTab->nCol );
100359    zCol = pTab->aCol[iCol].zName;
100360  }else if( pTab->iPKey>=0 ){
100361    assert( pTab->iPKey<pTab->nCol );
100362    zCol = pTab->aCol[pTab->iPKey].zName;
100363  }else{
100364    zCol = "ROWID";
100365  }
100366  assert( iDb>=0 && iDb<db->nDb );
100367  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
100368    pExpr->op = TK_NULL;
100369  }
100370}
100371
100372/*
100373** Do an authorization check using the code and arguments given.  Return
100374** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
100375** is returned, then the error count and error message in pParse are
100376** modified appropriately.
100377*/
100378SQLITE_PRIVATE int sqlite3AuthCheck(
100379  Parse *pParse,
100380  int code,
100381  const char *zArg1,
100382  const char *zArg2,
100383  const char *zArg3
100384){
100385  sqlite3 *db = pParse->db;
100386  int rc;
100387
100388  /* Don't do any authorization checks if the database is initialising
100389  ** or if the parser is being invoked from within sqlite3_declare_vtab.
100390  */
100391  if( db->init.busy || IN_DECLARE_VTAB ){
100392    return SQLITE_OK;
100393  }
100394
100395  if( db->xAuth==0 ){
100396    return SQLITE_OK;
100397  }
100398
100399  /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
100400  ** callback are either NULL pointers or zero-terminated strings that
100401  ** contain additional details about the action to be authorized.
100402  **
100403  ** The following testcase() macros show that any of the 3rd through 6th
100404  ** parameters can be either NULL or a string. */
100405  testcase( zArg1==0 );
100406  testcase( zArg2==0 );
100407  testcase( zArg3==0 );
100408  testcase( pParse->zAuthContext==0 );
100409
100410  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
100411#ifdef SQLITE_USER_AUTHENTICATION
100412                 ,db->auth.zAuthUser
100413#endif
100414                );
100415  if( rc==SQLITE_DENY ){
100416    sqlite3ErrorMsg(pParse, "not authorized");
100417    pParse->rc = SQLITE_AUTH;
100418  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
100419    rc = SQLITE_DENY;
100420    sqliteAuthBadReturnCode(pParse);
100421  }
100422  return rc;
100423}
100424
100425/*
100426** Push an authorization context.  After this routine is called, the
100427** zArg3 argument to authorization callbacks will be zContext until
100428** popped.  Or if pParse==0, this routine is a no-op.
100429*/
100430SQLITE_PRIVATE void sqlite3AuthContextPush(
100431  Parse *pParse,
100432  AuthContext *pContext,
100433  const char *zContext
100434){
100435  assert( pParse );
100436  pContext->pParse = pParse;
100437  pContext->zAuthContext = pParse->zAuthContext;
100438  pParse->zAuthContext = zContext;
100439}
100440
100441/*
100442** Pop an authorization context that was previously pushed
100443** by sqlite3AuthContextPush
100444*/
100445SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
100446  if( pContext->pParse ){
100447    pContext->pParse->zAuthContext = pContext->zAuthContext;
100448    pContext->pParse = 0;
100449  }
100450}
100451
100452#endif /* SQLITE_OMIT_AUTHORIZATION */
100453
100454/************** End of auth.c ************************************************/
100455/************** Begin file build.c *******************************************/
100456/*
100457** 2001 September 15
100458**
100459** The author disclaims copyright to this source code.  In place of
100460** a legal notice, here is a blessing:
100461**
100462**    May you do good and not evil.
100463**    May you find forgiveness for yourself and forgive others.
100464**    May you share freely, never taking more than you give.
100465**
100466*************************************************************************
100467** This file contains C code routines that are called by the SQLite parser
100468** when syntax rules are reduced.  The routines in this file handle the
100469** following kinds of SQL syntax:
100470**
100471**     CREATE TABLE
100472**     DROP TABLE
100473**     CREATE INDEX
100474**     DROP INDEX
100475**     creating ID lists
100476**     BEGIN TRANSACTION
100477**     COMMIT
100478**     ROLLBACK
100479*/
100480/* #include "sqliteInt.h" */
100481
100482#ifndef SQLITE_OMIT_SHARED_CACHE
100483/*
100484** The TableLock structure is only used by the sqlite3TableLock() and
100485** codeTableLocks() functions.
100486*/
100487struct TableLock {
100488  int iDb;               /* The database containing the table to be locked */
100489  int iTab;              /* The root page of the table to be locked */
100490  u8 isWriteLock;        /* True for write lock.  False for a read lock */
100491  const char *zLockName; /* Name of the table */
100492};
100493
100494/*
100495** Record the fact that we want to lock a table at run-time.
100496**
100497** The table to be locked has root page iTab and is found in database iDb.
100498** A read or a write lock can be taken depending on isWritelock.
100499**
100500** This routine just records the fact that the lock is desired.  The
100501** code to make the lock occur is generated by a later call to
100502** codeTableLocks() which occurs during sqlite3FinishCoding().
100503*/
100504SQLITE_PRIVATE void sqlite3TableLock(
100505  Parse *pParse,     /* Parsing context */
100506  int iDb,           /* Index of the database containing the table to lock */
100507  int iTab,          /* Root page number of the table to be locked */
100508  u8 isWriteLock,    /* True for a write lock */
100509  const char *zName  /* Name of the table to be locked */
100510){
100511  Parse *pToplevel = sqlite3ParseToplevel(pParse);
100512  int i;
100513  int nBytes;
100514  TableLock *p;
100515  assert( iDb>=0 );
100516
100517  if( iDb==1 ) return;
100518  if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
100519  for(i=0; i<pToplevel->nTableLock; i++){
100520    p = &pToplevel->aTableLock[i];
100521    if( p->iDb==iDb && p->iTab==iTab ){
100522      p->isWriteLock = (p->isWriteLock || isWriteLock);
100523      return;
100524    }
100525  }
100526
100527  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
100528  pToplevel->aTableLock =
100529      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
100530  if( pToplevel->aTableLock ){
100531    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
100532    p->iDb = iDb;
100533    p->iTab = iTab;
100534    p->isWriteLock = isWriteLock;
100535    p->zLockName = zName;
100536  }else{
100537    pToplevel->nTableLock = 0;
100538    sqlite3OomFault(pToplevel->db);
100539  }
100540}
100541
100542/*
100543** Code an OP_TableLock instruction for each table locked by the
100544** statement (configured by calls to sqlite3TableLock()).
100545*/
100546static void codeTableLocks(Parse *pParse){
100547  int i;
100548  Vdbe *pVdbe;
100549
100550  pVdbe = sqlite3GetVdbe(pParse);
100551  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
100552
100553  for(i=0; i<pParse->nTableLock; i++){
100554    TableLock *p = &pParse->aTableLock[i];
100555    int p1 = p->iDb;
100556    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
100557                      p->zLockName, P4_STATIC);
100558  }
100559}
100560#else
100561  #define codeTableLocks(x)
100562#endif
100563
100564/*
100565** Return TRUE if the given yDbMask object is empty - if it contains no
100566** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
100567** macros when SQLITE_MAX_ATTACHED is greater than 30.
100568*/
100569#if SQLITE_MAX_ATTACHED>30
100570SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
100571  int i;
100572  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
100573  return 1;
100574}
100575#endif
100576
100577/*
100578** This routine is called after a single SQL statement has been
100579** parsed and a VDBE program to execute that statement has been
100580** prepared.  This routine puts the finishing touches on the
100581** VDBE program and resets the pParse structure for the next
100582** parse.
100583**
100584** Note that if an error occurred, it might be the case that
100585** no VDBE code was generated.
100586*/
100587SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
100588  sqlite3 *db;
100589  Vdbe *v;
100590
100591  assert( pParse->pToplevel==0 );
100592  db = pParse->db;
100593  if( pParse->nested ) return;
100594  if( db->mallocFailed || pParse->nErr ){
100595    if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
100596    return;
100597  }
100598
100599  /* Begin by generating some termination code at the end of the
100600  ** vdbe program
100601  */
100602  v = sqlite3GetVdbe(pParse);
100603  assert( !pParse->isMultiWrite
100604       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
100605  if( v ){
100606    sqlite3VdbeAddOp0(v, OP_Halt);
100607
100608#if SQLITE_USER_AUTHENTICATION
100609    if( pParse->nTableLock>0 && db->init.busy==0 ){
100610      sqlite3UserAuthInit(db);
100611      if( db->auth.authLevel<UAUTH_User ){
100612        sqlite3ErrorMsg(pParse, "user not authenticated");
100613        pParse->rc = SQLITE_AUTH_USER;
100614        return;
100615      }
100616    }
100617#endif
100618
100619    /* The cookie mask contains one bit for each database file open.
100620    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
100621    ** set for each database that is used.  Generate code to start a
100622    ** transaction on each used database and to verify the schema cookie
100623    ** on each used database.
100624    */
100625    if( db->mallocFailed==0
100626     && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
100627    ){
100628      int iDb, i;
100629      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
100630      sqlite3VdbeJumpHere(v, 0);
100631      for(iDb=0; iDb<db->nDb; iDb++){
100632        Schema *pSchema;
100633        if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
100634        sqlite3VdbeUsesBtree(v, iDb);
100635        pSchema = db->aDb[iDb].pSchema;
100636        sqlite3VdbeAddOp4Int(v,
100637          OP_Transaction,                    /* Opcode */
100638          iDb,                               /* P1 */
100639          DbMaskTest(pParse->writeMask,iDb), /* P2 */
100640          pSchema->schema_cookie,            /* P3 */
100641          pSchema->iGeneration               /* P4 */
100642        );
100643        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
100644        VdbeComment((v,
100645              "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
100646      }
100647#ifndef SQLITE_OMIT_VIRTUALTABLE
100648      for(i=0; i<pParse->nVtabLock; i++){
100649        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
100650        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
100651      }
100652      pParse->nVtabLock = 0;
100653#endif
100654
100655      /* Once all the cookies have been verified and transactions opened,
100656      ** obtain the required table-locks. This is a no-op unless the
100657      ** shared-cache feature is enabled.
100658      */
100659      codeTableLocks(pParse);
100660
100661      /* Initialize any AUTOINCREMENT data structures required.
100662      */
100663      sqlite3AutoincrementBegin(pParse);
100664
100665      /* Code constant expressions that where factored out of inner loops */
100666      if( pParse->pConstExpr ){
100667        ExprList *pEL = pParse->pConstExpr;
100668        pParse->okConstFactor = 0;
100669        for(i=0; i<pEL->nExpr; i++){
100670          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
100671        }
100672      }
100673
100674      /* Finally, jump back to the beginning of the executable code. */
100675      sqlite3VdbeGoto(v, 1);
100676    }
100677  }
100678
100679
100680  /* Get the VDBE program ready for execution
100681  */
100682  if( v && pParse->nErr==0 && !db->mallocFailed ){
100683    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
100684    /* A minimum of one cursor is required if autoincrement is used
100685    *  See ticket [a696379c1f08866] */
100686    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
100687    sqlite3VdbeMakeReady(v, pParse);
100688    pParse->rc = SQLITE_DONE;
100689  }else{
100690    pParse->rc = SQLITE_ERROR;
100691  }
100692}
100693
100694/*
100695** Run the parser and code generator recursively in order to generate
100696** code for the SQL statement given onto the end of the pParse context
100697** currently under construction.  When the parser is run recursively
100698** this way, the final OP_Halt is not appended and other initialization
100699** and finalization steps are omitted because those are handling by the
100700** outermost parser.
100701**
100702** Not everything is nestable.  This facility is designed to permit
100703** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
100704** care if you decide to try to use this routine for some other purposes.
100705*/
100706SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
100707  va_list ap;
100708  char *zSql;
100709  char *zErrMsg = 0;
100710  sqlite3 *db = pParse->db;
100711  char saveBuf[PARSE_TAIL_SZ];
100712
100713  if( pParse->nErr ) return;
100714  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
100715  va_start(ap, zFormat);
100716  zSql = sqlite3VMPrintf(db, zFormat, ap);
100717  va_end(ap);
100718  if( zSql==0 ){
100719    return;   /* A malloc must have failed */
100720  }
100721  pParse->nested++;
100722  memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
100723  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
100724  sqlite3RunParser(pParse, zSql, &zErrMsg);
100725  sqlite3DbFree(db, zErrMsg);
100726  sqlite3DbFree(db, zSql);
100727  memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
100728  pParse->nested--;
100729}
100730
100731#if SQLITE_USER_AUTHENTICATION
100732/*
100733** Return TRUE if zTable is the name of the system table that stores the
100734** list of users and their access credentials.
100735*/
100736SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
100737  return sqlite3_stricmp(zTable, "sqlite_user")==0;
100738}
100739#endif
100740
100741/*
100742** Locate the in-memory structure that describes a particular database
100743** table given the name of that table and (optionally) the name of the
100744** database containing the table.  Return NULL if not found.
100745**
100746** If zDatabase is 0, all databases are searched for the table and the
100747** first matching table is returned.  (No checking for duplicate table
100748** names is done.)  The search order is TEMP first, then MAIN, then any
100749** auxiliary databases added using the ATTACH command.
100750**
100751** See also sqlite3LocateTable().
100752*/
100753SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
100754  Table *p = 0;
100755  int i;
100756
100757  /* All mutexes are required for schema access.  Make sure we hold them. */
100758  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
100759#if SQLITE_USER_AUTHENTICATION
100760  /* Only the admin user is allowed to know that the sqlite_user table
100761  ** exists */
100762  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
100763    return 0;
100764  }
100765#endif
100766  while(1){
100767    for(i=OMIT_TEMPDB; i<db->nDb; i++){
100768      int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
100769      if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
100770        assert( sqlite3SchemaMutexHeld(db, j, 0) );
100771        p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
100772        if( p ) return p;
100773      }
100774    }
100775    /* Not found.  If the name we were looking for was temp.sqlite_master
100776    ** then change the name to sqlite_temp_master and try again. */
100777    if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
100778    if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
100779    zName = TEMP_MASTER_NAME;
100780  }
100781  return 0;
100782}
100783
100784/*
100785** Locate the in-memory structure that describes a particular database
100786** table given the name of that table and (optionally) the name of the
100787** database containing the table.  Return NULL if not found.  Also leave an
100788** error message in pParse->zErrMsg.
100789**
100790** The difference between this routine and sqlite3FindTable() is that this
100791** routine leaves an error message in pParse->zErrMsg where
100792** sqlite3FindTable() does not.
100793*/
100794SQLITE_PRIVATE Table *sqlite3LocateTable(
100795  Parse *pParse,         /* context in which to report errors */
100796  u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
100797  const char *zName,     /* Name of the table we are looking for */
100798  const char *zDbase     /* Name of the database.  Might be NULL */
100799){
100800  Table *p;
100801
100802  /* Read the database schema. If an error occurs, leave an error message
100803  ** and code in pParse and return NULL. */
100804  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100805    return 0;
100806  }
100807
100808  p = sqlite3FindTable(pParse->db, zName, zDbase);
100809  if( p==0 ){
100810    const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
100811#ifndef SQLITE_OMIT_VIRTUALTABLE
100812    if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
100813      /* If zName is the not the name of a table in the schema created using
100814      ** CREATE, then check to see if it is the name of an virtual table that
100815      ** can be an eponymous virtual table. */
100816      Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
100817      if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
100818        pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
100819      }
100820      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
100821        return pMod->pEpoTab;
100822      }
100823    }
100824#endif
100825    if( (flags & LOCATE_NOERR)==0 ){
100826      if( zDbase ){
100827        sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
100828      }else{
100829        sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
100830      }
100831      pParse->checkSchema = 1;
100832    }
100833  }
100834
100835  return p;
100836}
100837
100838/*
100839** Locate the table identified by *p.
100840**
100841** This is a wrapper around sqlite3LocateTable(). The difference between
100842** sqlite3LocateTable() and this function is that this function restricts
100843** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
100844** non-NULL if it is part of a view or trigger program definition. See
100845** sqlite3FixSrcList() for details.
100846*/
100847SQLITE_PRIVATE Table *sqlite3LocateTableItem(
100848  Parse *pParse,
100849  u32 flags,
100850  struct SrcList_item *p
100851){
100852  const char *zDb;
100853  assert( p->pSchema==0 || p->zDatabase==0 );
100854  if( p->pSchema ){
100855    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
100856    zDb = pParse->db->aDb[iDb].zDbSName;
100857  }else{
100858    zDb = p->zDatabase;
100859  }
100860  return sqlite3LocateTable(pParse, flags, p->zName, zDb);
100861}
100862
100863/*
100864** Locate the in-memory structure that describes
100865** a particular index given the name of that index
100866** and the name of the database that contains the index.
100867** Return NULL if not found.
100868**
100869** If zDatabase is 0, all databases are searched for the
100870** table and the first matching index is returned.  (No checking
100871** for duplicate index names is done.)  The search order is
100872** TEMP first, then MAIN, then any auxiliary databases added
100873** using the ATTACH command.
100874*/
100875SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
100876  Index *p = 0;
100877  int i;
100878  /* All mutexes are required for schema access.  Make sure we hold them. */
100879  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
100880  for(i=OMIT_TEMPDB; i<db->nDb; i++){
100881    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
100882    Schema *pSchema = db->aDb[j].pSchema;
100883    assert( pSchema );
100884    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
100885    assert( sqlite3SchemaMutexHeld(db, j, 0) );
100886    p = sqlite3HashFind(&pSchema->idxHash, zName);
100887    if( p ) break;
100888  }
100889  return p;
100890}
100891
100892/*
100893** Reclaim the memory used by an index
100894*/
100895static void freeIndex(sqlite3 *db, Index *p){
100896#ifndef SQLITE_OMIT_ANALYZE
100897  sqlite3DeleteIndexSamples(db, p);
100898#endif
100899  sqlite3ExprDelete(db, p->pPartIdxWhere);
100900  sqlite3ExprListDelete(db, p->aColExpr);
100901  sqlite3DbFree(db, p->zColAff);
100902  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
100903#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
100904  sqlite3_free(p->aiRowEst);
100905#endif
100906  sqlite3DbFree(db, p);
100907}
100908
100909/*
100910** For the index called zIdxName which is found in the database iDb,
100911** unlike that index from its Table then remove the index from
100912** the index hash table and free all memory structures associated
100913** with the index.
100914*/
100915SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
100916  Index *pIndex;
100917  Hash *pHash;
100918
100919  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100920  pHash = &db->aDb[iDb].pSchema->idxHash;
100921  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
100922  if( ALWAYS(pIndex) ){
100923    if( pIndex->pTable->pIndex==pIndex ){
100924      pIndex->pTable->pIndex = pIndex->pNext;
100925    }else{
100926      Index *p;
100927      /* Justification of ALWAYS();  The index must be on the list of
100928      ** indices. */
100929      p = pIndex->pTable->pIndex;
100930      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
100931      if( ALWAYS(p && p->pNext==pIndex) ){
100932        p->pNext = pIndex->pNext;
100933      }
100934    }
100935    freeIndex(db, pIndex);
100936  }
100937  db->flags |= SQLITE_InternChanges;
100938}
100939
100940/*
100941** Look through the list of open database files in db->aDb[] and if
100942** any have been closed, remove them from the list.  Reallocate the
100943** db->aDb[] structure to a smaller size, if possible.
100944**
100945** Entry 0 (the "main" database) and entry 1 (the "temp" database)
100946** are never candidates for being collapsed.
100947*/
100948SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
100949  int i, j;
100950  for(i=j=2; i<db->nDb; i++){
100951    struct Db *pDb = &db->aDb[i];
100952    if( pDb->pBt==0 ){
100953      sqlite3DbFree(db, pDb->zDbSName);
100954      pDb->zDbSName = 0;
100955      continue;
100956    }
100957    if( j<i ){
100958      db->aDb[j] = db->aDb[i];
100959    }
100960    j++;
100961  }
100962  db->nDb = j;
100963  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
100964    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
100965    sqlite3DbFree(db, db->aDb);
100966    db->aDb = db->aDbStatic;
100967  }
100968}
100969
100970/*
100971** Reset the schema for the database at index iDb.  Also reset the
100972** TEMP schema.
100973*/
100974SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
100975  Db *pDb;
100976  assert( iDb<db->nDb );
100977
100978  /* Case 1:  Reset the single schema identified by iDb */
100979  pDb = &db->aDb[iDb];
100980  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100981  assert( pDb->pSchema!=0 );
100982  sqlite3SchemaClear(pDb->pSchema);
100983
100984  /* If any database other than TEMP is reset, then also reset TEMP
100985  ** since TEMP might be holding triggers that reference tables in the
100986  ** other database.
100987  */
100988  if( iDb!=1 ){
100989    pDb = &db->aDb[1];
100990    assert( pDb->pSchema!=0 );
100991    sqlite3SchemaClear(pDb->pSchema);
100992  }
100993  return;
100994}
100995
100996/*
100997** Erase all schema information from all attached databases (including
100998** "main" and "temp") for a single database connection.
100999*/
101000SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
101001  int i;
101002  sqlite3BtreeEnterAll(db);
101003  for(i=0; i<db->nDb; i++){
101004    Db *pDb = &db->aDb[i];
101005    if( pDb->pSchema ){
101006      sqlite3SchemaClear(pDb->pSchema);
101007    }
101008  }
101009  db->flags &= ~SQLITE_InternChanges;
101010  sqlite3VtabUnlockList(db);
101011  sqlite3BtreeLeaveAll(db);
101012  sqlite3CollapseDatabaseArray(db);
101013}
101014
101015/*
101016** This routine is called when a commit occurs.
101017*/
101018SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
101019  db->flags &= ~SQLITE_InternChanges;
101020}
101021
101022/*
101023** Delete memory allocated for the column names of a table or view (the
101024** Table.aCol[] array).
101025*/
101026SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
101027  int i;
101028  Column *pCol;
101029  assert( pTable!=0 );
101030  if( (pCol = pTable->aCol)!=0 ){
101031    for(i=0; i<pTable->nCol; i++, pCol++){
101032      sqlite3DbFree(db, pCol->zName);
101033      sqlite3ExprDelete(db, pCol->pDflt);
101034      sqlite3DbFree(db, pCol->zColl);
101035    }
101036    sqlite3DbFree(db, pTable->aCol);
101037  }
101038}
101039
101040/*
101041** Remove the memory data structures associated with the given
101042** Table.  No changes are made to disk by this routine.
101043**
101044** This routine just deletes the data structure.  It does not unlink
101045** the table data structure from the hash table.  But it does destroy
101046** memory structures of the indices and foreign keys associated with
101047** the table.
101048**
101049** The db parameter is optional.  It is needed if the Table object
101050** contains lookaside memory.  (Table objects in the schema do not use
101051** lookaside memory, but some ephemeral Table objects do.)  Or the
101052** db parameter can be used with db->pnBytesFreed to measure the memory
101053** used by the Table object.
101054*/
101055static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
101056  Index *pIndex, *pNext;
101057  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
101058
101059  /* Record the number of outstanding lookaside allocations in schema Tables
101060  ** prior to doing any free() operations.  Since schema Tables do not use
101061  ** lookaside, this number should not change. */
101062  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
101063                         db->lookaside.nOut : 0 );
101064
101065  /* Delete all indices associated with this table. */
101066  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
101067    pNext = pIndex->pNext;
101068    assert( pIndex->pSchema==pTable->pSchema
101069         || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
101070    if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
101071      char *zName = pIndex->zName;
101072      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
101073         &pIndex->pSchema->idxHash, zName, 0
101074      );
101075      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
101076      assert( pOld==pIndex || pOld==0 );
101077    }
101078    freeIndex(db, pIndex);
101079  }
101080
101081  /* Delete any foreign keys attached to this table. */
101082  sqlite3FkDelete(db, pTable);
101083
101084  /* Delete the Table structure itself.
101085  */
101086  sqlite3DeleteColumnNames(db, pTable);
101087  sqlite3DbFree(db, pTable->zName);
101088  sqlite3DbFree(db, pTable->zColAff);
101089  sqlite3SelectDelete(db, pTable->pSelect);
101090  sqlite3ExprListDelete(db, pTable->pCheck);
101091#ifndef SQLITE_OMIT_VIRTUALTABLE
101092  sqlite3VtabClear(db, pTable);
101093#endif
101094  sqlite3DbFree(db, pTable);
101095
101096  /* Verify that no lookaside memory was used by schema tables */
101097  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
101098}
101099SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
101100  /* Do not delete the table until the reference count reaches zero. */
101101  if( !pTable ) return;
101102  if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
101103  deleteTable(db, pTable);
101104}
101105
101106
101107/*
101108** Unlink the given table from the hash tables and the delete the
101109** table structure with all its indices and foreign keys.
101110*/
101111SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
101112  Table *p;
101113  Db *pDb;
101114
101115  assert( db!=0 );
101116  assert( iDb>=0 && iDb<db->nDb );
101117  assert( zTabName );
101118  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101119  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
101120  pDb = &db->aDb[iDb];
101121  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
101122  sqlite3DeleteTable(db, p);
101123  db->flags |= SQLITE_InternChanges;
101124}
101125
101126/*
101127** Given a token, return a string that consists of the text of that
101128** token.  Space to hold the returned string
101129** is obtained from sqliteMalloc() and must be freed by the calling
101130** function.
101131**
101132** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
101133** surround the body of the token are removed.
101134**
101135** Tokens are often just pointers into the original SQL text and so
101136** are not \000 terminated and are not persistent.  The returned string
101137** is \000 terminated and is persistent.
101138*/
101139SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
101140  char *zName;
101141  if( pName ){
101142    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
101143    sqlite3Dequote(zName);
101144  }else{
101145    zName = 0;
101146  }
101147  return zName;
101148}
101149
101150/*
101151** Open the sqlite_master table stored in database number iDb for
101152** writing. The table is opened using cursor 0.
101153*/
101154SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
101155  Vdbe *v = sqlite3GetVdbe(p);
101156  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
101157  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
101158  if( p->nTab==0 ){
101159    p->nTab = 1;
101160  }
101161}
101162
101163/*
101164** Parameter zName points to a nul-terminated buffer containing the name
101165** of a database ("main", "temp" or the name of an attached db). This
101166** function returns the index of the named database in db->aDb[], or
101167** -1 if the named db cannot be found.
101168*/
101169SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
101170  int i = -1;         /* Database number */
101171  if( zName ){
101172    Db *pDb;
101173    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
101174      if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
101175      /* "main" is always an acceptable alias for the primary database
101176      ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
101177      if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
101178    }
101179  }
101180  return i;
101181}
101182
101183/*
101184** The token *pName contains the name of a database (either "main" or
101185** "temp" or the name of an attached db). This routine returns the
101186** index of the named database in db->aDb[], or -1 if the named db
101187** does not exist.
101188*/
101189SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
101190  int i;                               /* Database number */
101191  char *zName;                         /* Name we are searching for */
101192  zName = sqlite3NameFromToken(db, pName);
101193  i = sqlite3FindDbName(db, zName);
101194  sqlite3DbFree(db, zName);
101195  return i;
101196}
101197
101198/* The table or view or trigger name is passed to this routine via tokens
101199** pName1 and pName2. If the table name was fully qualified, for example:
101200**
101201** CREATE TABLE xxx.yyy (...);
101202**
101203** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
101204** the table name is not fully qualified, i.e.:
101205**
101206** CREATE TABLE yyy(...);
101207**
101208** Then pName1 is set to "yyy" and pName2 is "".
101209**
101210** This routine sets the *ppUnqual pointer to point at the token (pName1 or
101211** pName2) that stores the unqualified table name.  The index of the
101212** database "xxx" is returned.
101213*/
101214SQLITE_PRIVATE int sqlite3TwoPartName(
101215  Parse *pParse,      /* Parsing and code generating context */
101216  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
101217  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
101218  Token **pUnqual     /* Write the unqualified object name here */
101219){
101220  int iDb;                    /* Database holding the object */
101221  sqlite3 *db = pParse->db;
101222
101223  assert( pName2!=0 );
101224  if( pName2->n>0 ){
101225    if( db->init.busy ) {
101226      sqlite3ErrorMsg(pParse, "corrupt database");
101227      return -1;
101228    }
101229    *pUnqual = pName2;
101230    iDb = sqlite3FindDb(db, pName1);
101231    if( iDb<0 ){
101232      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
101233      return -1;
101234    }
101235  }else{
101236    assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0);
101237    iDb = db->init.iDb;
101238    *pUnqual = pName1;
101239  }
101240  return iDb;
101241}
101242
101243/*
101244** This routine is used to check if the UTF-8 string zName is a legal
101245** unqualified name for a new schema object (table, index, view or
101246** trigger). All names are legal except those that begin with the string
101247** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
101248** is reserved for internal use.
101249*/
101250SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
101251  if( !pParse->db->init.busy && pParse->nested==0
101252          && (pParse->db->flags & SQLITE_WriteSchema)==0
101253          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
101254    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
101255    return SQLITE_ERROR;
101256  }
101257  return SQLITE_OK;
101258}
101259
101260/*
101261** Return the PRIMARY KEY index of a table
101262*/
101263SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
101264  Index *p;
101265  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
101266  return p;
101267}
101268
101269/*
101270** Return the column of index pIdx that corresponds to table
101271** column iCol.  Return -1 if not found.
101272*/
101273SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
101274  int i;
101275  for(i=0; i<pIdx->nColumn; i++){
101276    if( iCol==pIdx->aiColumn[i] ) return i;
101277  }
101278  return -1;
101279}
101280
101281/*
101282** Begin constructing a new table representation in memory.  This is
101283** the first of several action routines that get called in response
101284** to a CREATE TABLE statement.  In particular, this routine is called
101285** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
101286** flag is true if the table should be stored in the auxiliary database
101287** file instead of in the main database file.  This is normally the case
101288** when the "TEMP" or "TEMPORARY" keyword occurs in between
101289** CREATE and TABLE.
101290**
101291** The new table record is initialized and put in pParse->pNewTable.
101292** As more of the CREATE TABLE statement is parsed, additional action
101293** routines will be called to add more information to this record.
101294** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
101295** is called to complete the construction of the new table record.
101296*/
101297SQLITE_PRIVATE void sqlite3StartTable(
101298  Parse *pParse,   /* Parser context */
101299  Token *pName1,   /* First part of the name of the table or view */
101300  Token *pName2,   /* Second part of the name of the table or view */
101301  int isTemp,      /* True if this is a TEMP table */
101302  int isView,      /* True if this is a VIEW */
101303  int isVirtual,   /* True if this is a VIRTUAL table */
101304  int noErr        /* Do nothing if table already exists */
101305){
101306  Table *pTable;
101307  char *zName = 0; /* The name of the new table */
101308  sqlite3 *db = pParse->db;
101309  Vdbe *v;
101310  int iDb;         /* Database number to create the table in */
101311  Token *pName;    /* Unqualified name of the table to create */
101312
101313  if( db->init.busy && db->init.newTnum==1 ){
101314    /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
101315    iDb = db->init.iDb;
101316    zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
101317    pName = pName1;
101318  }else{
101319    /* The common case */
101320    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101321    if( iDb<0 ) return;
101322    if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
101323      /* If creating a temp table, the name may not be qualified. Unless
101324      ** the database name is "temp" anyway.  */
101325      sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
101326      return;
101327    }
101328    if( !OMIT_TEMPDB && isTemp ) iDb = 1;
101329    zName = sqlite3NameFromToken(db, pName);
101330  }
101331  pParse->sNameToken = *pName;
101332  if( zName==0 ) return;
101333  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101334    goto begin_table_error;
101335  }
101336  if( db->init.iDb==1 ) isTemp = 1;
101337#ifndef SQLITE_OMIT_AUTHORIZATION
101338  assert( isTemp==0 || isTemp==1 );
101339  assert( isView==0 || isView==1 );
101340  {
101341    static const u8 aCode[] = {
101342       SQLITE_CREATE_TABLE,
101343       SQLITE_CREATE_TEMP_TABLE,
101344       SQLITE_CREATE_VIEW,
101345       SQLITE_CREATE_TEMP_VIEW
101346    };
101347    char *zDb = db->aDb[iDb].zDbSName;
101348    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
101349      goto begin_table_error;
101350    }
101351    if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
101352                                       zName, 0, zDb) ){
101353      goto begin_table_error;
101354    }
101355  }
101356#endif
101357
101358  /* Make sure the new table name does not collide with an existing
101359  ** index or table name in the same database.  Issue an error message if
101360  ** it does. The exception is if the statement being parsed was passed
101361  ** to an sqlite3_declare_vtab() call. In that case only the column names
101362  ** and types will be used, so there is no need to test for namespace
101363  ** collisions.
101364  */
101365  if( !IN_DECLARE_VTAB ){
101366    char *zDb = db->aDb[iDb].zDbSName;
101367    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101368      goto begin_table_error;
101369    }
101370    pTable = sqlite3FindTable(db, zName, zDb);
101371    if( pTable ){
101372      if( !noErr ){
101373        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
101374      }else{
101375        assert( !db->init.busy || CORRUPT_DB );
101376        sqlite3CodeVerifySchema(pParse, iDb);
101377      }
101378      goto begin_table_error;
101379    }
101380    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
101381      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
101382      goto begin_table_error;
101383    }
101384  }
101385
101386  pTable = sqlite3DbMallocZero(db, sizeof(Table));
101387  if( pTable==0 ){
101388    assert( db->mallocFailed );
101389    pParse->rc = SQLITE_NOMEM_BKPT;
101390    pParse->nErr++;
101391    goto begin_table_error;
101392  }
101393  pTable->zName = zName;
101394  pTable->iPKey = -1;
101395  pTable->pSchema = db->aDb[iDb].pSchema;
101396  pTable->nTabRef = 1;
101397#ifdef SQLITE_DEFAULT_ROWEST
101398  pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
101399#else
101400  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
101401#endif
101402  assert( pParse->pNewTable==0 );
101403  pParse->pNewTable = pTable;
101404
101405  /* If this is the magic sqlite_sequence table used by autoincrement,
101406  ** then record a pointer to this table in the main database structure
101407  ** so that INSERT can find the table easily.
101408  */
101409#ifndef SQLITE_OMIT_AUTOINCREMENT
101410  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
101411    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101412    pTable->pSchema->pSeqTab = pTable;
101413  }
101414#endif
101415
101416  /* Begin generating the code that will insert the table record into
101417  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
101418  ** and allocate the record number for the table entry now.  Before any
101419  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
101420  ** indices to be created and the table record must come before the
101421  ** indices.  Hence, the record number for the table must be allocated
101422  ** now.
101423  */
101424  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
101425    int addr1;
101426    int fileFormat;
101427    int reg1, reg2, reg3;
101428    /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
101429    static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
101430    sqlite3BeginWriteOperation(pParse, 1, iDb);
101431
101432#ifndef SQLITE_OMIT_VIRTUALTABLE
101433    if( isVirtual ){
101434      sqlite3VdbeAddOp0(v, OP_VBegin);
101435    }
101436#endif
101437
101438    /* If the file format and encoding in the database have not been set,
101439    ** set them now.
101440    */
101441    reg1 = pParse->regRowid = ++pParse->nMem;
101442    reg2 = pParse->regRoot = ++pParse->nMem;
101443    reg3 = ++pParse->nMem;
101444    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
101445    sqlite3VdbeUsesBtree(v, iDb);
101446    addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
101447    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
101448                  1 : SQLITE_MAX_FILE_FORMAT;
101449    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
101450    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
101451    sqlite3VdbeJumpHere(v, addr1);
101452
101453    /* This just creates a place-holder record in the sqlite_master table.
101454    ** The record created does not contain anything yet.  It will be replaced
101455    ** by the real entry in code generated at sqlite3EndTable().
101456    **
101457    ** The rowid for the new entry is left in register pParse->regRowid.
101458    ** The root page number of the new table is left in reg pParse->regRoot.
101459    ** The rowid and root page number values are needed by the code that
101460    ** sqlite3EndTable will generate.
101461    */
101462#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
101463    if( isView || isVirtual ){
101464      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
101465    }else
101466#endif
101467    {
101468      pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
101469    }
101470    sqlite3OpenMasterTable(pParse, iDb);
101471    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
101472    sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
101473    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
101474    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
101475    sqlite3VdbeAddOp0(v, OP_Close);
101476  }
101477
101478  /* Normal (non-error) return. */
101479  return;
101480
101481  /* If an error occurs, we jump here */
101482begin_table_error:
101483  sqlite3DbFree(db, zName);
101484  return;
101485}
101486
101487/* Set properties of a table column based on the (magical)
101488** name of the column.
101489*/
101490#if SQLITE_ENABLE_HIDDEN_COLUMNS
101491SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
101492  if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
101493    pCol->colFlags |= COLFLAG_HIDDEN;
101494  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
101495    pTab->tabFlags |= TF_OOOHidden;
101496  }
101497}
101498#endif
101499
101500
101501/*
101502** Add a new column to the table currently being constructed.
101503**
101504** The parser calls this routine once for each column declaration
101505** in a CREATE TABLE statement.  sqlite3StartTable() gets called
101506** first to get things going.  Then this routine is called for each
101507** column.
101508*/
101509SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
101510  Table *p;
101511  int i;
101512  char *z;
101513  char *zType;
101514  Column *pCol;
101515  sqlite3 *db = pParse->db;
101516  if( (p = pParse->pNewTable)==0 ) return;
101517#if SQLITE_MAX_COLUMN
101518  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
101519    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
101520    return;
101521  }
101522#endif
101523  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
101524  if( z==0 ) return;
101525  memcpy(z, pName->z, pName->n);
101526  z[pName->n] = 0;
101527  sqlite3Dequote(z);
101528  for(i=0; i<p->nCol; i++){
101529    if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
101530      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
101531      sqlite3DbFree(db, z);
101532      return;
101533    }
101534  }
101535  if( (p->nCol & 0x7)==0 ){
101536    Column *aNew;
101537    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
101538    if( aNew==0 ){
101539      sqlite3DbFree(db, z);
101540      return;
101541    }
101542    p->aCol = aNew;
101543  }
101544  pCol = &p->aCol[p->nCol];
101545  memset(pCol, 0, sizeof(p->aCol[0]));
101546  pCol->zName = z;
101547  sqlite3ColumnPropertiesFromName(p, pCol);
101548
101549  if( pType->n==0 ){
101550    /* If there is no type specified, columns have the default affinity
101551    ** 'BLOB'. */
101552    pCol->affinity = SQLITE_AFF_BLOB;
101553    pCol->szEst = 1;
101554  }else{
101555    zType = z + sqlite3Strlen30(z) + 1;
101556    memcpy(zType, pType->z, pType->n);
101557    zType[pType->n] = 0;
101558    sqlite3Dequote(zType);
101559    pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
101560    pCol->colFlags |= COLFLAG_HASTYPE;
101561  }
101562  p->nCol++;
101563  pParse->constraintName.n = 0;
101564}
101565
101566/*
101567** This routine is called by the parser while in the middle of
101568** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
101569** been seen on a column.  This routine sets the notNull flag on
101570** the column currently under construction.
101571*/
101572SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
101573  Table *p;
101574  p = pParse->pNewTable;
101575  if( p==0 || NEVER(p->nCol<1) ) return;
101576  p->aCol[p->nCol-1].notNull = (u8)onError;
101577  p->tabFlags |= TF_HasNotNull;
101578}
101579
101580/*
101581** Scan the column type name zType (length nType) and return the
101582** associated affinity type.
101583**
101584** This routine does a case-independent search of zType for the
101585** substrings in the following table. If one of the substrings is
101586** found, the corresponding affinity is returned. If zType contains
101587** more than one of the substrings, entries toward the top of
101588** the table take priority. For example, if zType is 'BLOBINT',
101589** SQLITE_AFF_INTEGER is returned.
101590**
101591** Substring     | Affinity
101592** --------------------------------
101593** 'INT'         | SQLITE_AFF_INTEGER
101594** 'CHAR'        | SQLITE_AFF_TEXT
101595** 'CLOB'        | SQLITE_AFF_TEXT
101596** 'TEXT'        | SQLITE_AFF_TEXT
101597** 'BLOB'        | SQLITE_AFF_BLOB
101598** 'REAL'        | SQLITE_AFF_REAL
101599** 'FLOA'        | SQLITE_AFF_REAL
101600** 'DOUB'        | SQLITE_AFF_REAL
101601**
101602** If none of the substrings in the above table are found,
101603** SQLITE_AFF_NUMERIC is returned.
101604*/
101605SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
101606  u32 h = 0;
101607  char aff = SQLITE_AFF_NUMERIC;
101608  const char *zChar = 0;
101609
101610  assert( zIn!=0 );
101611  while( zIn[0] ){
101612    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
101613    zIn++;
101614    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
101615      aff = SQLITE_AFF_TEXT;
101616      zChar = zIn;
101617    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
101618      aff = SQLITE_AFF_TEXT;
101619    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
101620      aff = SQLITE_AFF_TEXT;
101621    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
101622        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
101623      aff = SQLITE_AFF_BLOB;
101624      if( zIn[0]=='(' ) zChar = zIn;
101625#ifndef SQLITE_OMIT_FLOATING_POINT
101626    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
101627        && aff==SQLITE_AFF_NUMERIC ){
101628      aff = SQLITE_AFF_REAL;
101629    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
101630        && aff==SQLITE_AFF_NUMERIC ){
101631      aff = SQLITE_AFF_REAL;
101632    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
101633        && aff==SQLITE_AFF_NUMERIC ){
101634      aff = SQLITE_AFF_REAL;
101635#endif
101636    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
101637      aff = SQLITE_AFF_INTEGER;
101638      break;
101639    }
101640  }
101641
101642  /* If pszEst is not NULL, store an estimate of the field size.  The
101643  ** estimate is scaled so that the size of an integer is 1.  */
101644  if( pszEst ){
101645    *pszEst = 1;   /* default size is approx 4 bytes */
101646    if( aff<SQLITE_AFF_NUMERIC ){
101647      if( zChar ){
101648        while( zChar[0] ){
101649          if( sqlite3Isdigit(zChar[0]) ){
101650            int v = 0;
101651            sqlite3GetInt32(zChar, &v);
101652            v = v/4 + 1;
101653            if( v>255 ) v = 255;
101654            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
101655            break;
101656          }
101657          zChar++;
101658        }
101659      }else{
101660        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
101661      }
101662    }
101663  }
101664  return aff;
101665}
101666
101667/*
101668** The expression is the default value for the most recently added column
101669** of the table currently under construction.
101670**
101671** Default value expressions must be constant.  Raise an exception if this
101672** is not the case.
101673**
101674** This routine is called by the parser while in the middle of
101675** parsing a CREATE TABLE statement.
101676*/
101677SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
101678  Table *p;
101679  Column *pCol;
101680  sqlite3 *db = pParse->db;
101681  p = pParse->pNewTable;
101682  if( p!=0 ){
101683    pCol = &(p->aCol[p->nCol-1]);
101684    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
101685      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
101686          pCol->zName);
101687    }else{
101688      /* A copy of pExpr is used instead of the original, as pExpr contains
101689      ** tokens that point to volatile memory. The 'span' of the expression
101690      ** is required by pragma table_info.
101691      */
101692      Expr x;
101693      sqlite3ExprDelete(db, pCol->pDflt);
101694      memset(&x, 0, sizeof(x));
101695      x.op = TK_SPAN;
101696      x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
101697                                    (int)(pSpan->zEnd - pSpan->zStart));
101698      x.pLeft = pSpan->pExpr;
101699      x.flags = EP_Skip;
101700      pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
101701      sqlite3DbFree(db, x.u.zToken);
101702    }
101703  }
101704  sqlite3ExprDelete(db, pSpan->pExpr);
101705}
101706
101707/*
101708** Backwards Compatibility Hack:
101709**
101710** Historical versions of SQLite accepted strings as column names in
101711** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
101712**
101713**     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
101714**     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
101715**
101716** This is goofy.  But to preserve backwards compatibility we continue to
101717** accept it.  This routine does the necessary conversion.  It converts
101718** the expression given in its argument from a TK_STRING into a TK_ID
101719** if the expression is just a TK_STRING with an optional COLLATE clause.
101720** If the epxression is anything other than TK_STRING, the expression is
101721** unchanged.
101722*/
101723static void sqlite3StringToId(Expr *p){
101724  if( p->op==TK_STRING ){
101725    p->op = TK_ID;
101726  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
101727    p->pLeft->op = TK_ID;
101728  }
101729}
101730
101731/*
101732** Designate the PRIMARY KEY for the table.  pList is a list of names
101733** of columns that form the primary key.  If pList is NULL, then the
101734** most recently added column of the table is the primary key.
101735**
101736** A table can have at most one primary key.  If the table already has
101737** a primary key (and this is the second primary key) then create an
101738** error.
101739**
101740** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
101741** then we will try to use that column as the rowid.  Set the Table.iPKey
101742** field of the table under construction to be the index of the
101743** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
101744** no INTEGER PRIMARY KEY.
101745**
101746** If the key is not an INTEGER PRIMARY KEY, then create a unique
101747** index for the key.  No index is created for INTEGER PRIMARY KEYs.
101748*/
101749SQLITE_PRIVATE void sqlite3AddPrimaryKey(
101750  Parse *pParse,    /* Parsing context */
101751  ExprList *pList,  /* List of field names to be indexed */
101752  int onError,      /* What to do with a uniqueness conflict */
101753  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
101754  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
101755){
101756  Table *pTab = pParse->pNewTable;
101757  Column *pCol = 0;
101758  int iCol = -1, i;
101759  int nTerm;
101760  if( pTab==0 ) goto primary_key_exit;
101761  if( pTab->tabFlags & TF_HasPrimaryKey ){
101762    sqlite3ErrorMsg(pParse,
101763      "table \"%s\" has more than one primary key", pTab->zName);
101764    goto primary_key_exit;
101765  }
101766  pTab->tabFlags |= TF_HasPrimaryKey;
101767  if( pList==0 ){
101768    iCol = pTab->nCol - 1;
101769    pCol = &pTab->aCol[iCol];
101770    pCol->colFlags |= COLFLAG_PRIMKEY;
101771    nTerm = 1;
101772  }else{
101773    nTerm = pList->nExpr;
101774    for(i=0; i<nTerm; i++){
101775      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
101776      assert( pCExpr!=0 );
101777      sqlite3StringToId(pCExpr);
101778      if( pCExpr->op==TK_ID ){
101779        const char *zCName = pCExpr->u.zToken;
101780        for(iCol=0; iCol<pTab->nCol; iCol++){
101781          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
101782            pCol = &pTab->aCol[iCol];
101783            pCol->colFlags |= COLFLAG_PRIMKEY;
101784            break;
101785          }
101786        }
101787      }
101788    }
101789  }
101790  if( nTerm==1
101791   && pCol
101792   && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
101793   && sortOrder!=SQLITE_SO_DESC
101794  ){
101795    pTab->iPKey = iCol;
101796    pTab->keyConf = (u8)onError;
101797    assert( autoInc==0 || autoInc==1 );
101798    pTab->tabFlags |= autoInc*TF_Autoincrement;
101799    if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
101800  }else if( autoInc ){
101801#ifndef SQLITE_OMIT_AUTOINCREMENT
101802    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
101803       "INTEGER PRIMARY KEY");
101804#endif
101805  }else{
101806    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
101807                           0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
101808    pList = 0;
101809  }
101810
101811primary_key_exit:
101812  sqlite3ExprListDelete(pParse->db, pList);
101813  return;
101814}
101815
101816/*
101817** Add a new CHECK constraint to the table currently under construction.
101818*/
101819SQLITE_PRIVATE void sqlite3AddCheckConstraint(
101820  Parse *pParse,    /* Parsing context */
101821  Expr *pCheckExpr  /* The check expression */
101822){
101823#ifndef SQLITE_OMIT_CHECK
101824  Table *pTab = pParse->pNewTable;
101825  sqlite3 *db = pParse->db;
101826  if( pTab && !IN_DECLARE_VTAB
101827   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
101828  ){
101829    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
101830    if( pParse->constraintName.n ){
101831      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
101832    }
101833  }else
101834#endif
101835  {
101836    sqlite3ExprDelete(pParse->db, pCheckExpr);
101837  }
101838}
101839
101840/*
101841** Set the collation function of the most recently parsed table column
101842** to the CollSeq given.
101843*/
101844SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
101845  Table *p;
101846  int i;
101847  char *zColl;              /* Dequoted name of collation sequence */
101848  sqlite3 *db;
101849
101850  if( (p = pParse->pNewTable)==0 ) return;
101851  i = p->nCol-1;
101852  db = pParse->db;
101853  zColl = sqlite3NameFromToken(db, pToken);
101854  if( !zColl ) return;
101855
101856  if( sqlite3LocateCollSeq(pParse, zColl) ){
101857    Index *pIdx;
101858    sqlite3DbFree(db, p->aCol[i].zColl);
101859    p->aCol[i].zColl = zColl;
101860
101861    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
101862    ** then an index may have been created on this column before the
101863    ** collation type was added. Correct this if it is the case.
101864    */
101865    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
101866      assert( pIdx->nKeyCol==1 );
101867      if( pIdx->aiColumn[0]==i ){
101868        pIdx->azColl[0] = p->aCol[i].zColl;
101869      }
101870    }
101871  }else{
101872    sqlite3DbFree(db, zColl);
101873  }
101874}
101875
101876/*
101877** This function returns the collation sequence for database native text
101878** encoding identified by the string zName, length nName.
101879**
101880** If the requested collation sequence is not available, or not available
101881** in the database native encoding, the collation factory is invoked to
101882** request it. If the collation factory does not supply such a sequence,
101883** and the sequence is available in another text encoding, then that is
101884** returned instead.
101885**
101886** If no versions of the requested collations sequence are available, or
101887** another error occurs, NULL is returned and an error message written into
101888** pParse.
101889**
101890** This routine is a wrapper around sqlite3FindCollSeq().  This routine
101891** invokes the collation factory if the named collation cannot be found
101892** and generates an error message.
101893**
101894** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
101895*/
101896SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
101897  sqlite3 *db = pParse->db;
101898  u8 enc = ENC(db);
101899  u8 initbusy = db->init.busy;
101900  CollSeq *pColl;
101901
101902  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
101903  if( !initbusy && (!pColl || !pColl->xCmp) ){
101904    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
101905  }
101906
101907  return pColl;
101908}
101909
101910
101911/*
101912** Generate code that will increment the schema cookie.
101913**
101914** The schema cookie is used to determine when the schema for the
101915** database changes.  After each schema change, the cookie value
101916** changes.  When a process first reads the schema it records the
101917** cookie.  Thereafter, whenever it goes to access the database,
101918** it checks the cookie to make sure the schema has not changed
101919** since it was last read.
101920**
101921** This plan is not completely bullet-proof.  It is possible for
101922** the schema to change multiple times and for the cookie to be
101923** set back to prior value.  But schema changes are infrequent
101924** and the probability of hitting the same cookie value is only
101925** 1 chance in 2^32.  So we're safe enough.
101926**
101927** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
101928** the schema-version whenever the schema changes.
101929*/
101930SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
101931  sqlite3 *db = pParse->db;
101932  Vdbe *v = pParse->pVdbe;
101933  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101934  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
101935                    db->aDb[iDb].pSchema->schema_cookie+1);
101936}
101937
101938/*
101939** Measure the number of characters needed to output the given
101940** identifier.  The number returned includes any quotes used
101941** but does not include the null terminator.
101942**
101943** The estimate is conservative.  It might be larger that what is
101944** really needed.
101945*/
101946static int identLength(const char *z){
101947  int n;
101948  for(n=0; *z; n++, z++){
101949    if( *z=='"' ){ n++; }
101950  }
101951  return n + 2;
101952}
101953
101954/*
101955** The first parameter is a pointer to an output buffer. The second
101956** parameter is a pointer to an integer that contains the offset at
101957** which to write into the output buffer. This function copies the
101958** nul-terminated string pointed to by the third parameter, zSignedIdent,
101959** to the specified offset in the buffer and updates *pIdx to refer
101960** to the first byte after the last byte written before returning.
101961**
101962** If the string zSignedIdent consists entirely of alpha-numeric
101963** characters, does not begin with a digit and is not an SQL keyword,
101964** then it is copied to the output buffer exactly as it is. Otherwise,
101965** it is quoted using double-quotes.
101966*/
101967static void identPut(char *z, int *pIdx, char *zSignedIdent){
101968  unsigned char *zIdent = (unsigned char*)zSignedIdent;
101969  int i, j, needQuote;
101970  i = *pIdx;
101971
101972  for(j=0; zIdent[j]; j++){
101973    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
101974  }
101975  needQuote = sqlite3Isdigit(zIdent[0])
101976            || sqlite3KeywordCode(zIdent, j)!=TK_ID
101977            || zIdent[j]!=0
101978            || j==0;
101979
101980  if( needQuote ) z[i++] = '"';
101981  for(j=0; zIdent[j]; j++){
101982    z[i++] = zIdent[j];
101983    if( zIdent[j]=='"' ) z[i++] = '"';
101984  }
101985  if( needQuote ) z[i++] = '"';
101986  z[i] = 0;
101987  *pIdx = i;
101988}
101989
101990/*
101991** Generate a CREATE TABLE statement appropriate for the given
101992** table.  Memory to hold the text of the statement is obtained
101993** from sqliteMalloc() and must be freed by the calling function.
101994*/
101995static char *createTableStmt(sqlite3 *db, Table *p){
101996  int i, k, n;
101997  char *zStmt;
101998  char *zSep, *zSep2, *zEnd;
101999  Column *pCol;
102000  n = 0;
102001  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
102002    n += identLength(pCol->zName) + 5;
102003  }
102004  n += identLength(p->zName);
102005  if( n<50 ){
102006    zSep = "";
102007    zSep2 = ",";
102008    zEnd = ")";
102009  }else{
102010    zSep = "\n  ";
102011    zSep2 = ",\n  ";
102012    zEnd = "\n)";
102013  }
102014  n += 35 + 6*p->nCol;
102015  zStmt = sqlite3DbMallocRaw(0, n);
102016  if( zStmt==0 ){
102017    sqlite3OomFault(db);
102018    return 0;
102019  }
102020  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
102021  k = sqlite3Strlen30(zStmt);
102022  identPut(zStmt, &k, p->zName);
102023  zStmt[k++] = '(';
102024  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
102025    static const char * const azType[] = {
102026        /* SQLITE_AFF_BLOB    */ "",
102027        /* SQLITE_AFF_TEXT    */ " TEXT",
102028        /* SQLITE_AFF_NUMERIC */ " NUM",
102029        /* SQLITE_AFF_INTEGER */ " INT",
102030        /* SQLITE_AFF_REAL    */ " REAL"
102031    };
102032    int len;
102033    const char *zType;
102034
102035    sqlite3_snprintf(n-k, &zStmt[k], zSep);
102036    k += sqlite3Strlen30(&zStmt[k]);
102037    zSep = zSep2;
102038    identPut(zStmt, &k, pCol->zName);
102039    assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
102040    assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
102041    testcase( pCol->affinity==SQLITE_AFF_BLOB );
102042    testcase( pCol->affinity==SQLITE_AFF_TEXT );
102043    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
102044    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
102045    testcase( pCol->affinity==SQLITE_AFF_REAL );
102046
102047    zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
102048    len = sqlite3Strlen30(zType);
102049    assert( pCol->affinity==SQLITE_AFF_BLOB
102050            || pCol->affinity==sqlite3AffinityType(zType, 0) );
102051    memcpy(&zStmt[k], zType, len);
102052    k += len;
102053    assert( k<=n );
102054  }
102055  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
102056  return zStmt;
102057}
102058
102059/*
102060** Resize an Index object to hold N columns total.  Return SQLITE_OK
102061** on success and SQLITE_NOMEM on an OOM error.
102062*/
102063static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
102064  char *zExtra;
102065  int nByte;
102066  if( pIdx->nColumn>=N ) return SQLITE_OK;
102067  assert( pIdx->isResized==0 );
102068  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
102069  zExtra = sqlite3DbMallocZero(db, nByte);
102070  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
102071  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
102072  pIdx->azColl = (const char**)zExtra;
102073  zExtra += sizeof(char*)*N;
102074  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
102075  pIdx->aiColumn = (i16*)zExtra;
102076  zExtra += sizeof(i16)*N;
102077  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
102078  pIdx->aSortOrder = (u8*)zExtra;
102079  pIdx->nColumn = N;
102080  pIdx->isResized = 1;
102081  return SQLITE_OK;
102082}
102083
102084/*
102085** Estimate the total row width for a table.
102086*/
102087static void estimateTableWidth(Table *pTab){
102088  unsigned wTable = 0;
102089  const Column *pTabCol;
102090  int i;
102091  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
102092    wTable += pTabCol->szEst;
102093  }
102094  if( pTab->iPKey<0 ) wTable++;
102095  pTab->szTabRow = sqlite3LogEst(wTable*4);
102096}
102097
102098/*
102099** Estimate the average size of a row for an index.
102100*/
102101static void estimateIndexWidth(Index *pIdx){
102102  unsigned wIndex = 0;
102103  int i;
102104  const Column *aCol = pIdx->pTable->aCol;
102105  for(i=0; i<pIdx->nColumn; i++){
102106    i16 x = pIdx->aiColumn[i];
102107    assert( x<pIdx->pTable->nCol );
102108    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
102109  }
102110  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
102111}
102112
102113/* Return true if value x is found any of the first nCol entries of aiCol[]
102114*/
102115static int hasColumn(const i16 *aiCol, int nCol, int x){
102116  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
102117  return 0;
102118}
102119
102120/*
102121** This routine runs at the end of parsing a CREATE TABLE statement that
102122** has a WITHOUT ROWID clause.  The job of this routine is to convert both
102123** internal schema data structures and the generated VDBE code so that they
102124** are appropriate for a WITHOUT ROWID table instead of a rowid table.
102125** Changes include:
102126**
102127**     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
102128**     (2)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
102129**          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
102130**          data storage is a covering index btree.
102131**     (3)  Bypass the creation of the sqlite_master table entry
102132**          for the PRIMARY KEY as the primary key index is now
102133**          identified by the sqlite_master table entry of the table itself.
102134**     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
102135**          schema to the rootpage from the main table.
102136**     (5)  Add all table columns to the PRIMARY KEY Index object
102137**          so that the PRIMARY KEY is a covering index.  The surplus
102138**          columns are part of KeyInfo.nXField and are not used for
102139**          sorting or lookup or uniqueness checks.
102140**     (6)  Replace the rowid tail on all automatically generated UNIQUE
102141**          indices with the PRIMARY KEY columns.
102142**
102143** For virtual tables, only (1) is performed.
102144*/
102145static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
102146  Index *pIdx;
102147  Index *pPk;
102148  int nPk;
102149  int i, j;
102150  sqlite3 *db = pParse->db;
102151  Vdbe *v = pParse->pVdbe;
102152
102153  /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
102154  */
102155  if( !db->init.imposterTable ){
102156    for(i=0; i<pTab->nCol; i++){
102157      if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
102158        pTab->aCol[i].notNull = OE_Abort;
102159      }
102160    }
102161  }
102162
102163  /* The remaining transformations only apply to b-tree tables, not to
102164  ** virtual tables */
102165  if( IN_DECLARE_VTAB ) return;
102166
102167  /* Convert the OP_CreateTable opcode that would normally create the
102168  ** root-page for the table into an OP_CreateIndex opcode.  The index
102169  ** created will become the PRIMARY KEY index.
102170  */
102171  if( pParse->addrCrTab ){
102172    assert( v );
102173    sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
102174  }
102175
102176  /* Locate the PRIMARY KEY index.  Or, if this table was originally
102177  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
102178  */
102179  if( pTab->iPKey>=0 ){
102180    ExprList *pList;
102181    Token ipkToken;
102182    sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
102183    pList = sqlite3ExprListAppend(pParse, 0,
102184                  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
102185    if( pList==0 ) return;
102186    pList->a[0].sortOrder = pParse->iPkSortOrder;
102187    assert( pParse->pNewTable==pTab );
102188    sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
102189                       SQLITE_IDXTYPE_PRIMARYKEY);
102190    if( db->mallocFailed ) return;
102191    pPk = sqlite3PrimaryKeyIndex(pTab);
102192    pTab->iPKey = -1;
102193  }else{
102194    pPk = sqlite3PrimaryKeyIndex(pTab);
102195
102196    /*
102197    ** Remove all redundant columns from the PRIMARY KEY.  For example, change
102198    ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
102199    ** code assumes the PRIMARY KEY contains no repeated columns.
102200    */
102201    for(i=j=1; i<pPk->nKeyCol; i++){
102202      if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
102203        pPk->nColumn--;
102204      }else{
102205        pPk->aiColumn[j++] = pPk->aiColumn[i];
102206      }
102207    }
102208    pPk->nKeyCol = j;
102209  }
102210  assert( pPk!=0 );
102211  pPk->isCovering = 1;
102212  if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
102213  nPk = pPk->nKeyCol;
102214
102215  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
102216  ** table entry. This is only required if currently generating VDBE
102217  ** code for a CREATE TABLE (not when parsing one as part of reading
102218  ** a database schema).  */
102219  if( v && pPk->tnum>0 ){
102220    assert( db->init.busy==0 );
102221    sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
102222  }
102223
102224  /* The root page of the PRIMARY KEY is the table root page */
102225  pPk->tnum = pTab->tnum;
102226
102227  /* Update the in-memory representation of all UNIQUE indices by converting
102228  ** the final rowid column into one or more columns of the PRIMARY KEY.
102229  */
102230  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102231    int n;
102232    if( IsPrimaryKeyIndex(pIdx) ) continue;
102233    for(i=n=0; i<nPk; i++){
102234      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
102235    }
102236    if( n==0 ){
102237      /* This index is a superset of the primary key */
102238      pIdx->nColumn = pIdx->nKeyCol;
102239      continue;
102240    }
102241    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
102242    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
102243      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
102244        pIdx->aiColumn[j] = pPk->aiColumn[i];
102245        pIdx->azColl[j] = pPk->azColl[i];
102246        j++;
102247      }
102248    }
102249    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
102250    assert( pIdx->nColumn>=j );
102251  }
102252
102253  /* Add all table columns to the PRIMARY KEY index
102254  */
102255  if( nPk<pTab->nCol ){
102256    if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
102257    for(i=0, j=nPk; i<pTab->nCol; i++){
102258      if( !hasColumn(pPk->aiColumn, j, i) ){
102259        assert( j<pPk->nColumn );
102260        pPk->aiColumn[j] = i;
102261        pPk->azColl[j] = sqlite3StrBINARY;
102262        j++;
102263      }
102264    }
102265    assert( pPk->nColumn==j );
102266    assert( pTab->nCol==j );
102267  }else{
102268    pPk->nColumn = pTab->nCol;
102269  }
102270}
102271
102272/*
102273** This routine is called to report the final ")" that terminates
102274** a CREATE TABLE statement.
102275**
102276** The table structure that other action routines have been building
102277** is added to the internal hash tables, assuming no errors have
102278** occurred.
102279**
102280** An entry for the table is made in the master table on disk, unless
102281** this is a temporary table or db->init.busy==1.  When db->init.busy==1
102282** it means we are reading the sqlite_master table because we just
102283** connected to the database or because the sqlite_master table has
102284** recently changed, so the entry for this table already exists in
102285** the sqlite_master table.  We do not want to create it again.
102286**
102287** If the pSelect argument is not NULL, it means that this routine
102288** was called to create a table generated from a
102289** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
102290** the new table will match the result set of the SELECT.
102291*/
102292SQLITE_PRIVATE void sqlite3EndTable(
102293  Parse *pParse,          /* Parse context */
102294  Token *pCons,           /* The ',' token after the last column defn. */
102295  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
102296  u8 tabOpts,             /* Extra table options. Usually 0. */
102297  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
102298){
102299  Table *p;                 /* The new table */
102300  sqlite3 *db = pParse->db; /* The database connection */
102301  int iDb;                  /* Database in which the table lives */
102302  Index *pIdx;              /* An implied index of the table */
102303
102304  if( pEnd==0 && pSelect==0 ){
102305    return;
102306  }
102307  assert( !db->mallocFailed );
102308  p = pParse->pNewTable;
102309  if( p==0 ) return;
102310
102311  assert( !db->init.busy || !pSelect );
102312
102313  /* If the db->init.busy is 1 it means we are reading the SQL off the
102314  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
102315  ** So do not write to the disk again.  Extract the root page number
102316  ** for the table from the db->init.newTnum field.  (The page number
102317  ** should have been put there by the sqliteOpenCb routine.)
102318  **
102319  ** If the root page number is 1, that means this is the sqlite_master
102320  ** table itself.  So mark it read-only.
102321  */
102322  if( db->init.busy ){
102323    p->tnum = db->init.newTnum;
102324    if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
102325  }
102326
102327  /* Special processing for WITHOUT ROWID Tables */
102328  if( tabOpts & TF_WithoutRowid ){
102329    if( (p->tabFlags & TF_Autoincrement) ){
102330      sqlite3ErrorMsg(pParse,
102331          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
102332      return;
102333    }
102334    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
102335      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
102336    }else{
102337      p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
102338      convertToWithoutRowidTable(pParse, p);
102339    }
102340  }
102341
102342  iDb = sqlite3SchemaToIndex(db, p->pSchema);
102343
102344#ifndef SQLITE_OMIT_CHECK
102345  /* Resolve names in all CHECK constraint expressions.
102346  */
102347  if( p->pCheck ){
102348    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
102349  }
102350#endif /* !defined(SQLITE_OMIT_CHECK) */
102351
102352  /* Estimate the average row size for the table and for all implied indices */
102353  estimateTableWidth(p);
102354  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
102355    estimateIndexWidth(pIdx);
102356  }
102357
102358  /* If not initializing, then create a record for the new table
102359  ** in the SQLITE_MASTER table of the database.
102360  **
102361  ** If this is a TEMPORARY table, write the entry into the auxiliary
102362  ** file instead of into the main database file.
102363  */
102364  if( !db->init.busy ){
102365    int n;
102366    Vdbe *v;
102367    char *zType;    /* "view" or "table" */
102368    char *zType2;   /* "VIEW" or "TABLE" */
102369    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
102370
102371    v = sqlite3GetVdbe(pParse);
102372    if( NEVER(v==0) ) return;
102373
102374    sqlite3VdbeAddOp1(v, OP_Close, 0);
102375
102376    /*
102377    ** Initialize zType for the new view or table.
102378    */
102379    if( p->pSelect==0 ){
102380      /* A regular table */
102381      zType = "table";
102382      zType2 = "TABLE";
102383#ifndef SQLITE_OMIT_VIEW
102384    }else{
102385      /* A view */
102386      zType = "view";
102387      zType2 = "VIEW";
102388#endif
102389    }
102390
102391    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
102392    ** statement to populate the new table. The root-page number for the
102393    ** new table is in register pParse->regRoot.
102394    **
102395    ** Once the SELECT has been coded by sqlite3Select(), it is in a
102396    ** suitable state to query for the column names and types to be used
102397    ** by the new table.
102398    **
102399    ** A shared-cache write-lock is not required to write to the new table,
102400    ** as a schema-lock must have already been obtained to create it. Since
102401    ** a schema-lock excludes all other database users, the write-lock would
102402    ** be redundant.
102403    */
102404    if( pSelect ){
102405      SelectDest dest;    /* Where the SELECT should store results */
102406      int regYield;       /* Register holding co-routine entry-point */
102407      int addrTop;        /* Top of the co-routine */
102408      int regRec;         /* A record to be insert into the new table */
102409      int regRowid;       /* Rowid of the next row to insert */
102410      int addrInsLoop;    /* Top of the loop for inserting rows */
102411      Table *pSelTab;     /* A table that describes the SELECT results */
102412
102413      regYield = ++pParse->nMem;
102414      regRec = ++pParse->nMem;
102415      regRowid = ++pParse->nMem;
102416      assert(pParse->nTab==1);
102417      sqlite3MayAbort(pParse);
102418      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
102419      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
102420      pParse->nTab = 2;
102421      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
102422      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
102423      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
102424      sqlite3Select(pParse, pSelect, &dest);
102425      sqlite3VdbeEndCoroutine(v, regYield);
102426      sqlite3VdbeJumpHere(v, addrTop - 1);
102427      if( pParse->nErr ) return;
102428      pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
102429      if( pSelTab==0 ) return;
102430      assert( p->aCol==0 );
102431      p->nCol = pSelTab->nCol;
102432      p->aCol = pSelTab->aCol;
102433      pSelTab->nCol = 0;
102434      pSelTab->aCol = 0;
102435      sqlite3DeleteTable(db, pSelTab);
102436      addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
102437      VdbeCoverage(v);
102438      sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
102439      sqlite3TableAffinity(v, p, 0);
102440      sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
102441      sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
102442      sqlite3VdbeGoto(v, addrInsLoop);
102443      sqlite3VdbeJumpHere(v, addrInsLoop);
102444      sqlite3VdbeAddOp1(v, OP_Close, 1);
102445    }
102446
102447    /* Compute the complete text of the CREATE statement */
102448    if( pSelect ){
102449      zStmt = createTableStmt(db, p);
102450    }else{
102451      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
102452      n = (int)(pEnd2->z - pParse->sNameToken.z);
102453      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
102454      zStmt = sqlite3MPrintf(db,
102455          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
102456      );
102457    }
102458
102459    /* A slot for the record has already been allocated in the
102460    ** SQLITE_MASTER table.  We just need to update that slot with all
102461    ** the information we've collected.
102462    */
102463    sqlite3NestedParse(pParse,
102464      "UPDATE %Q.%s "
102465         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
102466       "WHERE rowid=#%d",
102467      db->aDb[iDb].zDbSName, MASTER_NAME,
102468      zType,
102469      p->zName,
102470      p->zName,
102471      pParse->regRoot,
102472      zStmt,
102473      pParse->regRowid
102474    );
102475    sqlite3DbFree(db, zStmt);
102476    sqlite3ChangeCookie(pParse, iDb);
102477
102478#ifndef SQLITE_OMIT_AUTOINCREMENT
102479    /* Check to see if we need to create an sqlite_sequence table for
102480    ** keeping track of autoincrement keys.
102481    */
102482    if( (p->tabFlags & TF_Autoincrement)!=0 ){
102483      Db *pDb = &db->aDb[iDb];
102484      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102485      if( pDb->pSchema->pSeqTab==0 ){
102486        sqlite3NestedParse(pParse,
102487          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
102488          pDb->zDbSName
102489        );
102490      }
102491    }
102492#endif
102493
102494    /* Reparse everything to update our internal data structures */
102495    sqlite3VdbeAddParseSchemaOp(v, iDb,
102496           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
102497  }
102498
102499
102500  /* Add the table to the in-memory representation of the database.
102501  */
102502  if( db->init.busy ){
102503    Table *pOld;
102504    Schema *pSchema = p->pSchema;
102505    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102506    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
102507    if( pOld ){
102508      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
102509      sqlite3OomFault(db);
102510      return;
102511    }
102512    pParse->pNewTable = 0;
102513    db->flags |= SQLITE_InternChanges;
102514
102515#ifndef SQLITE_OMIT_ALTERTABLE
102516    if( !p->pSelect ){
102517      const char *zName = (const char *)pParse->sNameToken.z;
102518      int nName;
102519      assert( !pSelect && pCons && pEnd );
102520      if( pCons->z==0 ){
102521        pCons = pEnd;
102522      }
102523      nName = (int)((const char *)pCons->z - zName);
102524      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
102525    }
102526#endif
102527  }
102528}
102529
102530#ifndef SQLITE_OMIT_VIEW
102531/*
102532** The parser calls this routine in order to create a new VIEW
102533*/
102534SQLITE_PRIVATE void sqlite3CreateView(
102535  Parse *pParse,     /* The parsing context */
102536  Token *pBegin,     /* The CREATE token that begins the statement */
102537  Token *pName1,     /* The token that holds the name of the view */
102538  Token *pName2,     /* The token that holds the name of the view */
102539  ExprList *pCNames, /* Optional list of view column names */
102540  Select *pSelect,   /* A SELECT statement that will become the new view */
102541  int isTemp,        /* TRUE for a TEMPORARY view */
102542  int noErr          /* Suppress error messages if VIEW already exists */
102543){
102544  Table *p;
102545  int n;
102546  const char *z;
102547  Token sEnd;
102548  DbFixer sFix;
102549  Token *pName = 0;
102550  int iDb;
102551  sqlite3 *db = pParse->db;
102552
102553  if( pParse->nVar>0 ){
102554    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
102555    goto create_view_fail;
102556  }
102557  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
102558  p = pParse->pNewTable;
102559  if( p==0 || pParse->nErr ) goto create_view_fail;
102560  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
102561  iDb = sqlite3SchemaToIndex(db, p->pSchema);
102562  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
102563  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
102564
102565  /* Make a copy of the entire SELECT statement that defines the view.
102566  ** This will force all the Expr.token.z values to be dynamically
102567  ** allocated rather than point to the input string - which means that
102568  ** they will persist after the current sqlite3_exec() call returns.
102569  */
102570  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
102571  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
102572  if( db->mallocFailed ) goto create_view_fail;
102573
102574  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
102575  ** the end.
102576  */
102577  sEnd = pParse->sLastToken;
102578  assert( sEnd.z[0]!=0 );
102579  if( sEnd.z[0]!=';' ){
102580    sEnd.z += sEnd.n;
102581  }
102582  sEnd.n = 0;
102583  n = (int)(sEnd.z - pBegin->z);
102584  assert( n>0 );
102585  z = pBegin->z;
102586  while( sqlite3Isspace(z[n-1]) ){ n--; }
102587  sEnd.z = &z[n-1];
102588  sEnd.n = 1;
102589
102590  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
102591  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
102592
102593create_view_fail:
102594  sqlite3SelectDelete(db, pSelect);
102595  sqlite3ExprListDelete(db, pCNames);
102596  return;
102597}
102598#endif /* SQLITE_OMIT_VIEW */
102599
102600#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
102601/*
102602** The Table structure pTable is really a VIEW.  Fill in the names of
102603** the columns of the view in the pTable structure.  Return the number
102604** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
102605*/
102606SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
102607  Table *pSelTab;   /* A fake table from which we get the result set */
102608  Select *pSel;     /* Copy of the SELECT that implements the view */
102609  int nErr = 0;     /* Number of errors encountered */
102610  int n;            /* Temporarily holds the number of cursors assigned */
102611  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
102612#ifndef SQLITE_OMIT_AUTHORIZATION
102613  sqlite3_xauth xAuth;       /* Saved xAuth pointer */
102614#endif
102615
102616  assert( pTable );
102617
102618#ifndef SQLITE_OMIT_VIRTUALTABLE
102619  if( sqlite3VtabCallConnect(pParse, pTable) ){
102620    return SQLITE_ERROR;
102621  }
102622  if( IsVirtual(pTable) ) return 0;
102623#endif
102624
102625#ifndef SQLITE_OMIT_VIEW
102626  /* A positive nCol means the columns names for this view are
102627  ** already known.
102628  */
102629  if( pTable->nCol>0 ) return 0;
102630
102631  /* A negative nCol is a special marker meaning that we are currently
102632  ** trying to compute the column names.  If we enter this routine with
102633  ** a negative nCol, it means two or more views form a loop, like this:
102634  **
102635  **     CREATE VIEW one AS SELECT * FROM two;
102636  **     CREATE VIEW two AS SELECT * FROM one;
102637  **
102638  ** Actually, the error above is now caught prior to reaching this point.
102639  ** But the following test is still important as it does come up
102640  ** in the following:
102641  **
102642  **     CREATE TABLE main.ex1(a);
102643  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
102644  **     SELECT * FROM temp.ex1;
102645  */
102646  if( pTable->nCol<0 ){
102647    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
102648    return 1;
102649  }
102650  assert( pTable->nCol>=0 );
102651
102652  /* If we get this far, it means we need to compute the table names.
102653  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
102654  ** "*" elements in the results set of the view and will assign cursors
102655  ** to the elements of the FROM clause.  But we do not want these changes
102656  ** to be permanent.  So the computation is done on a copy of the SELECT
102657  ** statement that defines the view.
102658  */
102659  assert( pTable->pSelect );
102660  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
102661  if( pSel ){
102662    n = pParse->nTab;
102663    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
102664    pTable->nCol = -1;
102665    db->lookaside.bDisable++;
102666#ifndef SQLITE_OMIT_AUTHORIZATION
102667    xAuth = db->xAuth;
102668    db->xAuth = 0;
102669    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
102670    db->xAuth = xAuth;
102671#else
102672    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
102673#endif
102674    pParse->nTab = n;
102675    if( pTable->pCheck ){
102676      /* CREATE VIEW name(arglist) AS ...
102677      ** The names of the columns in the table are taken from
102678      ** arglist which is stored in pTable->pCheck.  The pCheck field
102679      ** normally holds CHECK constraints on an ordinary table, but for
102680      ** a VIEW it holds the list of column names.
102681      */
102682      sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
102683                                 &pTable->nCol, &pTable->aCol);
102684      if( db->mallocFailed==0
102685       && pParse->nErr==0
102686       && pTable->nCol==pSel->pEList->nExpr
102687      ){
102688        sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
102689      }
102690    }else if( pSelTab ){
102691      /* CREATE VIEW name AS...  without an argument list.  Construct
102692      ** the column names from the SELECT statement that defines the view.
102693      */
102694      assert( pTable->aCol==0 );
102695      pTable->nCol = pSelTab->nCol;
102696      pTable->aCol = pSelTab->aCol;
102697      pSelTab->nCol = 0;
102698      pSelTab->aCol = 0;
102699      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
102700    }else{
102701      pTable->nCol = 0;
102702      nErr++;
102703    }
102704    sqlite3DeleteTable(db, pSelTab);
102705    sqlite3SelectDelete(db, pSel);
102706    db->lookaside.bDisable--;
102707  } else {
102708    nErr++;
102709  }
102710  pTable->pSchema->schemaFlags |= DB_UnresetViews;
102711#endif /* SQLITE_OMIT_VIEW */
102712  return nErr;
102713}
102714#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
102715
102716#ifndef SQLITE_OMIT_VIEW
102717/*
102718** Clear the column names from every VIEW in database idx.
102719*/
102720static void sqliteViewResetAll(sqlite3 *db, int idx){
102721  HashElem *i;
102722  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
102723  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
102724  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
102725    Table *pTab = sqliteHashData(i);
102726    if( pTab->pSelect ){
102727      sqlite3DeleteColumnNames(db, pTab);
102728      pTab->aCol = 0;
102729      pTab->nCol = 0;
102730    }
102731  }
102732  DbClearProperty(db, idx, DB_UnresetViews);
102733}
102734#else
102735# define sqliteViewResetAll(A,B)
102736#endif /* SQLITE_OMIT_VIEW */
102737
102738/*
102739** This function is called by the VDBE to adjust the internal schema
102740** used by SQLite when the btree layer moves a table root page. The
102741** root-page of a table or index in database iDb has changed from iFrom
102742** to iTo.
102743**
102744** Ticket #1728:  The symbol table might still contain information
102745** on tables and/or indices that are the process of being deleted.
102746** If you are unlucky, one of those deleted indices or tables might
102747** have the same rootpage number as the real table or index that is
102748** being moved.  So we cannot stop searching after the first match
102749** because the first match might be for one of the deleted indices
102750** or tables and not the table/index that is actually being moved.
102751** We must continue looping until all tables and indices with
102752** rootpage==iFrom have been converted to have a rootpage of iTo
102753** in order to be certain that we got the right one.
102754*/
102755#ifndef SQLITE_OMIT_AUTOVACUUM
102756SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
102757  HashElem *pElem;
102758  Hash *pHash;
102759  Db *pDb;
102760
102761  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
102762  pDb = &db->aDb[iDb];
102763  pHash = &pDb->pSchema->tblHash;
102764  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
102765    Table *pTab = sqliteHashData(pElem);
102766    if( pTab->tnum==iFrom ){
102767      pTab->tnum = iTo;
102768    }
102769  }
102770  pHash = &pDb->pSchema->idxHash;
102771  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
102772    Index *pIdx = sqliteHashData(pElem);
102773    if( pIdx->tnum==iFrom ){
102774      pIdx->tnum = iTo;
102775    }
102776  }
102777}
102778#endif
102779
102780/*
102781** Write code to erase the table with root-page iTable from database iDb.
102782** Also write code to modify the sqlite_master table and internal schema
102783** if a root-page of another table is moved by the btree-layer whilst
102784** erasing iTable (this can happen with an auto-vacuum database).
102785*/
102786static void destroyRootPage(Parse *pParse, int iTable, int iDb){
102787  Vdbe *v = sqlite3GetVdbe(pParse);
102788  int r1 = sqlite3GetTempReg(pParse);
102789  assert( iTable>1 );
102790  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
102791  sqlite3MayAbort(pParse);
102792#ifndef SQLITE_OMIT_AUTOVACUUM
102793  /* OP_Destroy stores an in integer r1. If this integer
102794  ** is non-zero, then it is the root page number of a table moved to
102795  ** location iTable. The following code modifies the sqlite_master table to
102796  ** reflect this.
102797  **
102798  ** The "#NNN" in the SQL is a special constant that means whatever value
102799  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
102800  ** token for additional information.
102801  */
102802  sqlite3NestedParse(pParse,
102803     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
102804     pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
102805#endif
102806  sqlite3ReleaseTempReg(pParse, r1);
102807}
102808
102809/*
102810** Write VDBE code to erase table pTab and all associated indices on disk.
102811** Code to update the sqlite_master tables and internal schema definitions
102812** in case a root-page belonging to another table is moved by the btree layer
102813** is also added (this can happen with an auto-vacuum database).
102814*/
102815static void destroyTable(Parse *pParse, Table *pTab){
102816#ifdef SQLITE_OMIT_AUTOVACUUM
102817  Index *pIdx;
102818  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
102819  destroyRootPage(pParse, pTab->tnum, iDb);
102820  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102821    destroyRootPage(pParse, pIdx->tnum, iDb);
102822  }
102823#else
102824  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
102825  ** is not defined), then it is important to call OP_Destroy on the
102826  ** table and index root-pages in order, starting with the numerically
102827  ** largest root-page number. This guarantees that none of the root-pages
102828  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
102829  ** following were coded:
102830  **
102831  ** OP_Destroy 4 0
102832  ** ...
102833  ** OP_Destroy 5 0
102834  **
102835  ** and root page 5 happened to be the largest root-page number in the
102836  ** database, then root page 5 would be moved to page 4 by the
102837  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
102838  ** a free-list page.
102839  */
102840  int iTab = pTab->tnum;
102841  int iDestroyed = 0;
102842
102843  while( 1 ){
102844    Index *pIdx;
102845    int iLargest = 0;
102846
102847    if( iDestroyed==0 || iTab<iDestroyed ){
102848      iLargest = iTab;
102849    }
102850    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102851      int iIdx = pIdx->tnum;
102852      assert( pIdx->pSchema==pTab->pSchema );
102853      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
102854        iLargest = iIdx;
102855      }
102856    }
102857    if( iLargest==0 ){
102858      return;
102859    }else{
102860      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
102861      assert( iDb>=0 && iDb<pParse->db->nDb );
102862      destroyRootPage(pParse, iLargest, iDb);
102863      iDestroyed = iLargest;
102864    }
102865  }
102866#endif
102867}
102868
102869/*
102870** Remove entries from the sqlite_statN tables (for N in (1,2,3))
102871** after a DROP INDEX or DROP TABLE command.
102872*/
102873static void sqlite3ClearStatTables(
102874  Parse *pParse,         /* The parsing context */
102875  int iDb,               /* The database number */
102876  const char *zType,     /* "idx" or "tbl" */
102877  const char *zName      /* Name of index or table */
102878){
102879  int i;
102880  const char *zDbName = pParse->db->aDb[iDb].zDbSName;
102881  for(i=1; i<=4; i++){
102882    char zTab[24];
102883    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
102884    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
102885      sqlite3NestedParse(pParse,
102886        "DELETE FROM %Q.%s WHERE %s=%Q",
102887        zDbName, zTab, zType, zName
102888      );
102889    }
102890  }
102891}
102892
102893/*
102894** Generate code to drop a table.
102895*/
102896SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
102897  Vdbe *v;
102898  sqlite3 *db = pParse->db;
102899  Trigger *pTrigger;
102900  Db *pDb = &db->aDb[iDb];
102901
102902  v = sqlite3GetVdbe(pParse);
102903  assert( v!=0 );
102904  sqlite3BeginWriteOperation(pParse, 1, iDb);
102905
102906#ifndef SQLITE_OMIT_VIRTUALTABLE
102907  if( IsVirtual(pTab) ){
102908    sqlite3VdbeAddOp0(v, OP_VBegin);
102909  }
102910#endif
102911
102912  /* Drop all triggers associated with the table being dropped. Code
102913  ** is generated to remove entries from sqlite_master and/or
102914  ** sqlite_temp_master if required.
102915  */
102916  pTrigger = sqlite3TriggerList(pParse, pTab);
102917  while( pTrigger ){
102918    assert( pTrigger->pSchema==pTab->pSchema ||
102919        pTrigger->pSchema==db->aDb[1].pSchema );
102920    sqlite3DropTriggerPtr(pParse, pTrigger);
102921    pTrigger = pTrigger->pNext;
102922  }
102923
102924#ifndef SQLITE_OMIT_AUTOINCREMENT
102925  /* Remove any entries of the sqlite_sequence table associated with
102926  ** the table being dropped. This is done before the table is dropped
102927  ** at the btree level, in case the sqlite_sequence table needs to
102928  ** move as a result of the drop (can happen in auto-vacuum mode).
102929  */
102930  if( pTab->tabFlags & TF_Autoincrement ){
102931    sqlite3NestedParse(pParse,
102932      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
102933      pDb->zDbSName, pTab->zName
102934    );
102935  }
102936#endif
102937
102938  /* Drop all SQLITE_MASTER table and index entries that refer to the
102939  ** table. The program name loops through the master table and deletes
102940  ** every row that refers to a table of the same name as the one being
102941  ** dropped. Triggers are handled separately because a trigger can be
102942  ** created in the temp database that refers to a table in another
102943  ** database.
102944  */
102945  sqlite3NestedParse(pParse,
102946      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
102947      pDb->zDbSName, MASTER_NAME, pTab->zName);
102948  if( !isView && !IsVirtual(pTab) ){
102949    destroyTable(pParse, pTab);
102950  }
102951
102952  /* Remove the table entry from SQLite's internal schema and modify
102953  ** the schema cookie.
102954  */
102955  if( IsVirtual(pTab) ){
102956    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
102957  }
102958  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
102959  sqlite3ChangeCookie(pParse, iDb);
102960  sqliteViewResetAll(db, iDb);
102961}
102962
102963/*
102964** This routine is called to do the work of a DROP TABLE statement.
102965** pName is the name of the table to be dropped.
102966*/
102967SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
102968  Table *pTab;
102969  Vdbe *v;
102970  sqlite3 *db = pParse->db;
102971  int iDb;
102972
102973  if( db->mallocFailed ){
102974    goto exit_drop_table;
102975  }
102976  assert( pParse->nErr==0 );
102977  assert( pName->nSrc==1 );
102978  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
102979  if( noErr ) db->suppressErr++;
102980  assert( isView==0 || isView==LOCATE_VIEW );
102981  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
102982  if( noErr ) db->suppressErr--;
102983
102984  if( pTab==0 ){
102985    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
102986    goto exit_drop_table;
102987  }
102988  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102989  assert( iDb>=0 && iDb<db->nDb );
102990
102991  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
102992  ** it is initialized.
102993  */
102994  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
102995    goto exit_drop_table;
102996  }
102997#ifndef SQLITE_OMIT_AUTHORIZATION
102998  {
102999    int code;
103000    const char *zTab = SCHEMA_TABLE(iDb);
103001    const char *zDb = db->aDb[iDb].zDbSName;
103002    const char *zArg2 = 0;
103003    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
103004      goto exit_drop_table;
103005    }
103006    if( isView ){
103007      if( !OMIT_TEMPDB && iDb==1 ){
103008        code = SQLITE_DROP_TEMP_VIEW;
103009      }else{
103010        code = SQLITE_DROP_VIEW;
103011      }
103012#ifndef SQLITE_OMIT_VIRTUALTABLE
103013    }else if( IsVirtual(pTab) ){
103014      code = SQLITE_DROP_VTABLE;
103015      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
103016#endif
103017    }else{
103018      if( !OMIT_TEMPDB && iDb==1 ){
103019        code = SQLITE_DROP_TEMP_TABLE;
103020      }else{
103021        code = SQLITE_DROP_TABLE;
103022      }
103023    }
103024    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
103025      goto exit_drop_table;
103026    }
103027    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
103028      goto exit_drop_table;
103029    }
103030  }
103031#endif
103032  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
103033    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
103034    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
103035    goto exit_drop_table;
103036  }
103037
103038#ifndef SQLITE_OMIT_VIEW
103039  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
103040  ** on a table.
103041  */
103042  if( isView && pTab->pSelect==0 ){
103043    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
103044    goto exit_drop_table;
103045  }
103046  if( !isView && pTab->pSelect ){
103047    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
103048    goto exit_drop_table;
103049  }
103050#endif
103051
103052  /* Generate code to remove the table from the master table
103053  ** on disk.
103054  */
103055  v = sqlite3GetVdbe(pParse);
103056  if( v ){
103057    sqlite3BeginWriteOperation(pParse, 1, iDb);
103058    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
103059    sqlite3FkDropTable(pParse, pName, pTab);
103060    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
103061  }
103062
103063exit_drop_table:
103064  sqlite3SrcListDelete(db, pName);
103065}
103066
103067/*
103068** This routine is called to create a new foreign key on the table
103069** currently under construction.  pFromCol determines which columns
103070** in the current table point to the foreign key.  If pFromCol==0 then
103071** connect the key to the last column inserted.  pTo is the name of
103072** the table referred to (a.k.a the "parent" table).  pToCol is a list
103073** of tables in the parent pTo table.  flags contains all
103074** information about the conflict resolution algorithms specified
103075** in the ON DELETE, ON UPDATE and ON INSERT clauses.
103076**
103077** An FKey structure is created and added to the table currently
103078** under construction in the pParse->pNewTable field.
103079**
103080** The foreign key is set for IMMEDIATE processing.  A subsequent call
103081** to sqlite3DeferForeignKey() might change this to DEFERRED.
103082*/
103083SQLITE_PRIVATE void sqlite3CreateForeignKey(
103084  Parse *pParse,       /* Parsing context */
103085  ExprList *pFromCol,  /* Columns in this table that point to other table */
103086  Token *pTo,          /* Name of the other table */
103087  ExprList *pToCol,    /* Columns in the other table */
103088  int flags            /* Conflict resolution algorithms. */
103089){
103090  sqlite3 *db = pParse->db;
103091#ifndef SQLITE_OMIT_FOREIGN_KEY
103092  FKey *pFKey = 0;
103093  FKey *pNextTo;
103094  Table *p = pParse->pNewTable;
103095  int nByte;
103096  int i;
103097  int nCol;
103098  char *z;
103099
103100  assert( pTo!=0 );
103101  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
103102  if( pFromCol==0 ){
103103    int iCol = p->nCol-1;
103104    if( NEVER(iCol<0) ) goto fk_end;
103105    if( pToCol && pToCol->nExpr!=1 ){
103106      sqlite3ErrorMsg(pParse, "foreign key on %s"
103107         " should reference only one column of table %T",
103108         p->aCol[iCol].zName, pTo);
103109      goto fk_end;
103110    }
103111    nCol = 1;
103112  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
103113    sqlite3ErrorMsg(pParse,
103114        "number of columns in foreign key does not match the number of "
103115        "columns in the referenced table");
103116    goto fk_end;
103117  }else{
103118    nCol = pFromCol->nExpr;
103119  }
103120  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
103121  if( pToCol ){
103122    for(i=0; i<pToCol->nExpr; i++){
103123      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
103124    }
103125  }
103126  pFKey = sqlite3DbMallocZero(db, nByte );
103127  if( pFKey==0 ){
103128    goto fk_end;
103129  }
103130  pFKey->pFrom = p;
103131  pFKey->pNextFrom = p->pFKey;
103132  z = (char*)&pFKey->aCol[nCol];
103133  pFKey->zTo = z;
103134  memcpy(z, pTo->z, pTo->n);
103135  z[pTo->n] = 0;
103136  sqlite3Dequote(z);
103137  z += pTo->n+1;
103138  pFKey->nCol = nCol;
103139  if( pFromCol==0 ){
103140    pFKey->aCol[0].iFrom = p->nCol-1;
103141  }else{
103142    for(i=0; i<nCol; i++){
103143      int j;
103144      for(j=0; j<p->nCol; j++){
103145        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
103146          pFKey->aCol[i].iFrom = j;
103147          break;
103148        }
103149      }
103150      if( j>=p->nCol ){
103151        sqlite3ErrorMsg(pParse,
103152          "unknown column \"%s\" in foreign key definition",
103153          pFromCol->a[i].zName);
103154        goto fk_end;
103155      }
103156    }
103157  }
103158  if( pToCol ){
103159    for(i=0; i<nCol; i++){
103160      int n = sqlite3Strlen30(pToCol->a[i].zName);
103161      pFKey->aCol[i].zCol = z;
103162      memcpy(z, pToCol->a[i].zName, n);
103163      z[n] = 0;
103164      z += n+1;
103165    }
103166  }
103167  pFKey->isDeferred = 0;
103168  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
103169  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
103170
103171  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
103172  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
103173      pFKey->zTo, (void *)pFKey
103174  );
103175  if( pNextTo==pFKey ){
103176    sqlite3OomFault(db);
103177    goto fk_end;
103178  }
103179  if( pNextTo ){
103180    assert( pNextTo->pPrevTo==0 );
103181    pFKey->pNextTo = pNextTo;
103182    pNextTo->pPrevTo = pFKey;
103183  }
103184
103185  /* Link the foreign key to the table as the last step.
103186  */
103187  p->pFKey = pFKey;
103188  pFKey = 0;
103189
103190fk_end:
103191  sqlite3DbFree(db, pFKey);
103192#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
103193  sqlite3ExprListDelete(db, pFromCol);
103194  sqlite3ExprListDelete(db, pToCol);
103195}
103196
103197/*
103198** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
103199** clause is seen as part of a foreign key definition.  The isDeferred
103200** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
103201** The behavior of the most recently created foreign key is adjusted
103202** accordingly.
103203*/
103204SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
103205#ifndef SQLITE_OMIT_FOREIGN_KEY
103206  Table *pTab;
103207  FKey *pFKey;
103208  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
103209  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
103210  pFKey->isDeferred = (u8)isDeferred;
103211#endif
103212}
103213
103214/*
103215** Generate code that will erase and refill index *pIdx.  This is
103216** used to initialize a newly created index or to recompute the
103217** content of an index in response to a REINDEX command.
103218**
103219** if memRootPage is not negative, it means that the index is newly
103220** created.  The register specified by memRootPage contains the
103221** root page number of the index.  If memRootPage is negative, then
103222** the index already exists and must be cleared before being refilled and
103223** the root page number of the index is taken from pIndex->tnum.
103224*/
103225static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
103226  Table *pTab = pIndex->pTable;  /* The table that is indexed */
103227  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
103228  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
103229  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
103230  int addr1;                     /* Address of top of loop */
103231  int addr2;                     /* Address to jump to for next iteration */
103232  int tnum;                      /* Root page of index */
103233  int iPartIdxLabel;             /* Jump to this label to skip a row */
103234  Vdbe *v;                       /* Generate code into this virtual machine */
103235  KeyInfo *pKey;                 /* KeyInfo for index */
103236  int regRecord;                 /* Register holding assembled index record */
103237  sqlite3 *db = pParse->db;      /* The database connection */
103238  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
103239
103240#ifndef SQLITE_OMIT_AUTHORIZATION
103241  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
103242      db->aDb[iDb].zDbSName ) ){
103243    return;
103244  }
103245#endif
103246
103247  /* Require a write-lock on the table to perform this operation */
103248  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
103249
103250  v = sqlite3GetVdbe(pParse);
103251  if( v==0 ) return;
103252  if( memRootPage>=0 ){
103253    tnum = memRootPage;
103254  }else{
103255    tnum = pIndex->tnum;
103256  }
103257  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
103258  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
103259
103260  /* Open the sorter cursor if we are to use one. */
103261  iSorter = pParse->nTab++;
103262  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
103263                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
103264
103265  /* Open the table. Loop through all rows of the table, inserting index
103266  ** records into the sorter. */
103267  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
103268  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
103269  regRecord = sqlite3GetTempReg(pParse);
103270
103271  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
103272  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
103273  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
103274  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
103275  sqlite3VdbeJumpHere(v, addr1);
103276  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
103277  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
103278                    (char *)pKey, P4_KEYINFO);
103279  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
103280
103281  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
103282  if( IsUniqueIndex(pIndex) ){
103283    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
103284    sqlite3VdbeGoto(v, j2);
103285    addr2 = sqlite3VdbeCurrentAddr(v);
103286    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
103287                         pIndex->nKeyCol); VdbeCoverage(v);
103288    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
103289  }else{
103290    addr2 = sqlite3VdbeCurrentAddr(v);
103291  }
103292  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
103293  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
103294  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
103295  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
103296  sqlite3ReleaseTempReg(pParse, regRecord);
103297  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
103298  sqlite3VdbeJumpHere(v, addr1);
103299
103300  sqlite3VdbeAddOp1(v, OP_Close, iTab);
103301  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
103302  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
103303}
103304
103305/*
103306** Allocate heap space to hold an Index object with nCol columns.
103307**
103308** Increase the allocation size to provide an extra nExtra bytes
103309** of 8-byte aligned space after the Index object and return a
103310** pointer to this extra space in *ppExtra.
103311*/
103312SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
103313  sqlite3 *db,         /* Database connection */
103314  i16 nCol,            /* Total number of columns in the index */
103315  int nExtra,          /* Number of bytes of extra space to alloc */
103316  char **ppExtra       /* Pointer to the "extra" space */
103317){
103318  Index *p;            /* Allocated index object */
103319  int nByte;           /* Bytes of space for Index object + arrays */
103320
103321  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
103322          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
103323          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
103324                 sizeof(i16)*nCol +            /* Index.aiColumn   */
103325                 sizeof(u8)*nCol);             /* Index.aSortOrder */
103326  p = sqlite3DbMallocZero(db, nByte + nExtra);
103327  if( p ){
103328    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
103329    p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
103330    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
103331    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
103332    p->aSortOrder = (u8*)pExtra;
103333    p->nColumn = nCol;
103334    p->nKeyCol = nCol - 1;
103335    *ppExtra = ((char*)p) + nByte;
103336  }
103337  return p;
103338}
103339
103340/*
103341** Create a new index for an SQL table.  pName1.pName2 is the name of the index
103342** and pTblList is the name of the table that is to be indexed.  Both will
103343** be NULL for a primary key or an index that is created to satisfy a
103344** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
103345** as the table to be indexed.  pParse->pNewTable is a table that is
103346** currently being constructed by a CREATE TABLE statement.
103347**
103348** pList is a list of columns to be indexed.  pList will be NULL if this
103349** is a primary key or unique-constraint on the most recent column added
103350** to the table currently under construction.
103351*/
103352SQLITE_PRIVATE void sqlite3CreateIndex(
103353  Parse *pParse,     /* All information about this parse */
103354  Token *pName1,     /* First part of index name. May be NULL */
103355  Token *pName2,     /* Second part of index name. May be NULL */
103356  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
103357  ExprList *pList,   /* A list of columns to be indexed */
103358  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
103359  Token *pStart,     /* The CREATE token that begins this statement */
103360  Expr *pPIWhere,    /* WHERE clause for partial indices */
103361  int sortOrder,     /* Sort order of primary key when pList==NULL */
103362  int ifNotExist,    /* Omit error if index already exists */
103363  u8 idxType         /* The index type */
103364){
103365  Table *pTab = 0;     /* Table to be indexed */
103366  Index *pIndex = 0;   /* The index to be created */
103367  char *zName = 0;     /* Name of the index */
103368  int nName;           /* Number of characters in zName */
103369  int i, j;
103370  DbFixer sFix;        /* For assigning database names to pTable */
103371  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
103372  sqlite3 *db = pParse->db;
103373  Db *pDb;             /* The specific table containing the indexed database */
103374  int iDb;             /* Index of the database that is being written */
103375  Token *pName = 0;    /* Unqualified name of the index to create */
103376  struct ExprList_item *pListItem; /* For looping over pList */
103377  int nExtra = 0;                  /* Space allocated for zExtra[] */
103378  int nExtraCol;                   /* Number of extra columns needed */
103379  char *zExtra = 0;                /* Extra space after the Index object */
103380  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
103381
103382  if( db->mallocFailed || pParse->nErr>0 ){
103383    goto exit_create_index;
103384  }
103385  if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
103386    goto exit_create_index;
103387  }
103388  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
103389    goto exit_create_index;
103390  }
103391
103392  /*
103393  ** Find the table that is to be indexed.  Return early if not found.
103394  */
103395  if( pTblName!=0 ){
103396
103397    /* Use the two-part index name to determine the database
103398    ** to search for the table. 'Fix' the table name to this db
103399    ** before looking up the table.
103400    */
103401    assert( pName1 && pName2 );
103402    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
103403    if( iDb<0 ) goto exit_create_index;
103404    assert( pName && pName->z );
103405
103406#ifndef SQLITE_OMIT_TEMPDB
103407    /* If the index name was unqualified, check if the table
103408    ** is a temp table. If so, set the database to 1. Do not do this
103409    ** if initialising a database schema.
103410    */
103411    if( !db->init.busy ){
103412      pTab = sqlite3SrcListLookup(pParse, pTblName);
103413      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
103414        iDb = 1;
103415      }
103416    }
103417#endif
103418
103419    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
103420    if( sqlite3FixSrcList(&sFix, pTblName) ){
103421      /* Because the parser constructs pTblName from a single identifier,
103422      ** sqlite3FixSrcList can never fail. */
103423      assert(0);
103424    }
103425    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
103426    assert( db->mallocFailed==0 || pTab==0 );
103427    if( pTab==0 ) goto exit_create_index;
103428    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
103429      sqlite3ErrorMsg(pParse,
103430           "cannot create a TEMP index on non-TEMP table \"%s\"",
103431           pTab->zName);
103432      goto exit_create_index;
103433    }
103434    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
103435  }else{
103436    assert( pName==0 );
103437    assert( pStart==0 );
103438    pTab = pParse->pNewTable;
103439    if( !pTab ) goto exit_create_index;
103440    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103441  }
103442  pDb = &db->aDb[iDb];
103443
103444  assert( pTab!=0 );
103445  assert( pParse->nErr==0 );
103446  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
103447       && db->init.busy==0
103448#if SQLITE_USER_AUTHENTICATION
103449       && sqlite3UserAuthTable(pTab->zName)==0
103450#endif
103451       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
103452    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
103453    goto exit_create_index;
103454  }
103455#ifndef SQLITE_OMIT_VIEW
103456  if( pTab->pSelect ){
103457    sqlite3ErrorMsg(pParse, "views may not be indexed");
103458    goto exit_create_index;
103459  }
103460#endif
103461#ifndef SQLITE_OMIT_VIRTUALTABLE
103462  if( IsVirtual(pTab) ){
103463    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
103464    goto exit_create_index;
103465  }
103466#endif
103467
103468  /*
103469  ** Find the name of the index.  Make sure there is not already another
103470  ** index or table with the same name.
103471  **
103472  ** Exception:  If we are reading the names of permanent indices from the
103473  ** sqlite_master table (because some other process changed the schema) and
103474  ** one of the index names collides with the name of a temporary table or
103475  ** index, then we will continue to process this index.
103476  **
103477  ** If pName==0 it means that we are
103478  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
103479  ** own name.
103480  */
103481  if( pName ){
103482    zName = sqlite3NameFromToken(db, pName);
103483    if( zName==0 ) goto exit_create_index;
103484    assert( pName->z!=0 );
103485    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
103486      goto exit_create_index;
103487    }
103488    if( !db->init.busy ){
103489      if( sqlite3FindTable(db, zName, 0)!=0 ){
103490        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
103491        goto exit_create_index;
103492      }
103493    }
103494    if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
103495      if( !ifNotExist ){
103496        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
103497      }else{
103498        assert( !db->init.busy );
103499        sqlite3CodeVerifySchema(pParse, iDb);
103500      }
103501      goto exit_create_index;
103502    }
103503  }else{
103504    int n;
103505    Index *pLoop;
103506    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
103507    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
103508    if( zName==0 ){
103509      goto exit_create_index;
103510    }
103511
103512    /* Automatic index names generated from within sqlite3_declare_vtab()
103513    ** must have names that are distinct from normal automatic index names.
103514    ** The following statement converts "sqlite3_autoindex..." into
103515    ** "sqlite3_butoindex..." in order to make the names distinct.
103516    ** The "vtab_err.test" test demonstrates the need of this statement. */
103517    if( IN_DECLARE_VTAB ) zName[7]++;
103518  }
103519
103520  /* Check for authorization to create an index.
103521  */
103522#ifndef SQLITE_OMIT_AUTHORIZATION
103523  {
103524    const char *zDb = pDb->zDbSName;
103525    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
103526      goto exit_create_index;
103527    }
103528    i = SQLITE_CREATE_INDEX;
103529    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
103530    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
103531      goto exit_create_index;
103532    }
103533  }
103534#endif
103535
103536  /* If pList==0, it means this routine was called to make a primary
103537  ** key out of the last column added to the table under construction.
103538  ** So create a fake list to simulate this.
103539  */
103540  if( pList==0 ){
103541    Token prevCol;
103542    sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
103543    pList = sqlite3ExprListAppend(pParse, 0,
103544              sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
103545    if( pList==0 ) goto exit_create_index;
103546    assert( pList->nExpr==1 );
103547    sqlite3ExprListSetSortOrder(pList, sortOrder);
103548  }else{
103549    sqlite3ExprListCheckLength(pParse, pList, "index");
103550  }
103551
103552  /* Figure out how many bytes of space are required to store explicitly
103553  ** specified collation sequence names.
103554  */
103555  for(i=0; i<pList->nExpr; i++){
103556    Expr *pExpr = pList->a[i].pExpr;
103557    assert( pExpr!=0 );
103558    if( pExpr->op==TK_COLLATE ){
103559      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
103560    }
103561  }
103562
103563  /*
103564  ** Allocate the index structure.
103565  */
103566  nName = sqlite3Strlen30(zName);
103567  nExtraCol = pPk ? pPk->nKeyCol : 1;
103568  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
103569                                      nName + nExtra + 1, &zExtra);
103570  if( db->mallocFailed ){
103571    goto exit_create_index;
103572  }
103573  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
103574  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
103575  pIndex->zName = zExtra;
103576  zExtra += nName + 1;
103577  memcpy(pIndex->zName, zName, nName+1);
103578  pIndex->pTable = pTab;
103579  pIndex->onError = (u8)onError;
103580  pIndex->uniqNotNull = onError!=OE_None;
103581  pIndex->idxType = idxType;
103582  pIndex->pSchema = db->aDb[iDb].pSchema;
103583  pIndex->nKeyCol = pList->nExpr;
103584  if( pPIWhere ){
103585    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
103586    pIndex->pPartIdxWhere = pPIWhere;
103587    pPIWhere = 0;
103588  }
103589  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103590
103591  /* Check to see if we should honor DESC requests on index columns
103592  */
103593  if( pDb->pSchema->file_format>=4 ){
103594    sortOrderMask = -1;   /* Honor DESC */
103595  }else{
103596    sortOrderMask = 0;    /* Ignore DESC */
103597  }
103598
103599  /* Analyze the list of expressions that form the terms of the index and
103600  ** report any errors.  In the common case where the expression is exactly
103601  ** a table column, store that column in aiColumn[].  For general expressions,
103602  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
103603  **
103604  ** TODO: Issue a warning if two or more columns of the index are identical.
103605  ** TODO: Issue a warning if the table primary key is used as part of the
103606  ** index key.
103607  */
103608  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
103609    Expr *pCExpr;                  /* The i-th index expression */
103610    int requestedSortOrder;        /* ASC or DESC on the i-th expression */
103611    const char *zColl;             /* Collation sequence name */
103612
103613    sqlite3StringToId(pListItem->pExpr);
103614    sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
103615    if( pParse->nErr ) goto exit_create_index;
103616    pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
103617    if( pCExpr->op!=TK_COLUMN ){
103618      if( pTab==pParse->pNewTable ){
103619        sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
103620                                "UNIQUE constraints");
103621        goto exit_create_index;
103622      }
103623      if( pIndex->aColExpr==0 ){
103624        ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
103625        pIndex->aColExpr = pCopy;
103626        if( !db->mallocFailed ){
103627          assert( pCopy!=0 );
103628          pListItem = &pCopy->a[i];
103629        }
103630      }
103631      j = XN_EXPR;
103632      pIndex->aiColumn[i] = XN_EXPR;
103633      pIndex->uniqNotNull = 0;
103634    }else{
103635      j = pCExpr->iColumn;
103636      assert( j<=0x7fff );
103637      if( j<0 ){
103638        j = pTab->iPKey;
103639      }else if( pTab->aCol[j].notNull==0 ){
103640        pIndex->uniqNotNull = 0;
103641      }
103642      pIndex->aiColumn[i] = (i16)j;
103643    }
103644    zColl = 0;
103645    if( pListItem->pExpr->op==TK_COLLATE ){
103646      int nColl;
103647      zColl = pListItem->pExpr->u.zToken;
103648      nColl = sqlite3Strlen30(zColl) + 1;
103649      assert( nExtra>=nColl );
103650      memcpy(zExtra, zColl, nColl);
103651      zColl = zExtra;
103652      zExtra += nColl;
103653      nExtra -= nColl;
103654    }else if( j>=0 ){
103655      zColl = pTab->aCol[j].zColl;
103656    }
103657    if( !zColl ) zColl = sqlite3StrBINARY;
103658    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
103659      goto exit_create_index;
103660    }
103661    pIndex->azColl[i] = zColl;
103662    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
103663    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
103664  }
103665
103666  /* Append the table key to the end of the index.  For WITHOUT ROWID
103667  ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
103668  ** normal tables (when pPk==0) this will be the rowid.
103669  */
103670  if( pPk ){
103671    for(j=0; j<pPk->nKeyCol; j++){
103672      int x = pPk->aiColumn[j];
103673      assert( x>=0 );
103674      if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
103675        pIndex->nColumn--;
103676      }else{
103677        pIndex->aiColumn[i] = x;
103678        pIndex->azColl[i] = pPk->azColl[j];
103679        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
103680        i++;
103681      }
103682    }
103683    assert( i==pIndex->nColumn );
103684  }else{
103685    pIndex->aiColumn[i] = XN_ROWID;
103686    pIndex->azColl[i] = sqlite3StrBINARY;
103687  }
103688  sqlite3DefaultRowEst(pIndex);
103689  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
103690
103691  /* If this index contains every column of its table, then mark
103692  ** it as a covering index */
103693  assert( HasRowid(pTab)
103694      || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
103695  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
103696    pIndex->isCovering = 1;
103697    for(j=0; j<pTab->nCol; j++){
103698      if( j==pTab->iPKey ) continue;
103699      if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
103700      pIndex->isCovering = 0;
103701      break;
103702    }
103703  }
103704
103705  if( pTab==pParse->pNewTable ){
103706    /* This routine has been called to create an automatic index as a
103707    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
103708    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
103709    ** i.e. one of:
103710    **
103711    ** CREATE TABLE t(x PRIMARY KEY, y);
103712    ** CREATE TABLE t(x, y, UNIQUE(x, y));
103713    **
103714    ** Either way, check to see if the table already has such an index. If
103715    ** so, don't bother creating this one. This only applies to
103716    ** automatically created indices. Users can do as they wish with
103717    ** explicit indices.
103718    **
103719    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
103720    ** (and thus suppressing the second one) even if they have different
103721    ** sort orders.
103722    **
103723    ** If there are different collating sequences or if the columns of
103724    ** the constraint occur in different orders, then the constraints are
103725    ** considered distinct and both result in separate indices.
103726    */
103727    Index *pIdx;
103728    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103729      int k;
103730      assert( IsUniqueIndex(pIdx) );
103731      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
103732      assert( IsUniqueIndex(pIndex) );
103733
103734      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
103735      for(k=0; k<pIdx->nKeyCol; k++){
103736        const char *z1;
103737        const char *z2;
103738        assert( pIdx->aiColumn[k]>=0 );
103739        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
103740        z1 = pIdx->azColl[k];
103741        z2 = pIndex->azColl[k];
103742        if( sqlite3StrICmp(z1, z2) ) break;
103743      }
103744      if( k==pIdx->nKeyCol ){
103745        if( pIdx->onError!=pIndex->onError ){
103746          /* This constraint creates the same index as a previous
103747          ** constraint specified somewhere in the CREATE TABLE statement.
103748          ** However the ON CONFLICT clauses are different. If both this
103749          ** constraint and the previous equivalent constraint have explicit
103750          ** ON CONFLICT clauses this is an error. Otherwise, use the
103751          ** explicitly specified behavior for the index.
103752          */
103753          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
103754            sqlite3ErrorMsg(pParse,
103755                "conflicting ON CONFLICT clauses specified", 0);
103756          }
103757          if( pIdx->onError==OE_Default ){
103758            pIdx->onError = pIndex->onError;
103759          }
103760        }
103761        if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
103762        goto exit_create_index;
103763      }
103764    }
103765  }
103766
103767  /* Link the new Index structure to its table and to the other
103768  ** in-memory database structures.
103769  */
103770  assert( pParse->nErr==0 );
103771  if( db->init.busy ){
103772    Index *p;
103773    assert( !IN_DECLARE_VTAB );
103774    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
103775    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
103776                          pIndex->zName, pIndex);
103777    if( p ){
103778      assert( p==pIndex );  /* Malloc must have failed */
103779      sqlite3OomFault(db);
103780      goto exit_create_index;
103781    }
103782    db->flags |= SQLITE_InternChanges;
103783    if( pTblName!=0 ){
103784      pIndex->tnum = db->init.newTnum;
103785    }
103786  }
103787
103788  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
103789  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
103790  ** emit code to allocate the index rootpage on disk and make an entry for
103791  ** the index in the sqlite_master table and populate the index with
103792  ** content.  But, do not do this if we are simply reading the sqlite_master
103793  ** table to parse the schema, or if this index is the PRIMARY KEY index
103794  ** of a WITHOUT ROWID table.
103795  **
103796  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
103797  ** or UNIQUE index in a CREATE TABLE statement.  Since the table
103798  ** has just been created, it contains no data and the index initialization
103799  ** step can be skipped.
103800  */
103801  else if( HasRowid(pTab) || pTblName!=0 ){
103802    Vdbe *v;
103803    char *zStmt;
103804    int iMem = ++pParse->nMem;
103805
103806    v = sqlite3GetVdbe(pParse);
103807    if( v==0 ) goto exit_create_index;
103808
103809    sqlite3BeginWriteOperation(pParse, 1, iDb);
103810
103811    /* Create the rootpage for the index using CreateIndex. But before
103812    ** doing so, code a Noop instruction and store its address in
103813    ** Index.tnum. This is required in case this index is actually a
103814    ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
103815    ** that case the convertToWithoutRowidTable() routine will replace
103816    ** the Noop with a Goto to jump over the VDBE code generated below. */
103817    pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
103818    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
103819
103820    /* Gather the complete text of the CREATE INDEX statement into
103821    ** the zStmt variable
103822    */
103823    if( pStart ){
103824      int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
103825      if( pName->z[n-1]==';' ) n--;
103826      /* A named index with an explicit CREATE INDEX statement */
103827      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
103828        onError==OE_None ? "" : " UNIQUE", n, pName->z);
103829    }else{
103830      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
103831      /* zStmt = sqlite3MPrintf(""); */
103832      zStmt = 0;
103833    }
103834
103835    /* Add an entry in sqlite_master for this index
103836    */
103837    sqlite3NestedParse(pParse,
103838        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
103839        db->aDb[iDb].zDbSName, MASTER_NAME,
103840        pIndex->zName,
103841        pTab->zName,
103842        iMem,
103843        zStmt
103844    );
103845    sqlite3DbFree(db, zStmt);
103846
103847    /* Fill the index with data and reparse the schema. Code an OP_Expire
103848    ** to invalidate all pre-compiled statements.
103849    */
103850    if( pTblName ){
103851      sqlite3RefillIndex(pParse, pIndex, iMem);
103852      sqlite3ChangeCookie(pParse, iDb);
103853      sqlite3VdbeAddParseSchemaOp(v, iDb,
103854         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
103855      sqlite3VdbeAddOp0(v, OP_Expire);
103856    }
103857
103858    sqlite3VdbeJumpHere(v, pIndex->tnum);
103859  }
103860
103861  /* When adding an index to the list of indices for a table, make
103862  ** sure all indices labeled OE_Replace come after all those labeled
103863  ** OE_Ignore.  This is necessary for the correct constraint check
103864  ** processing (in sqlite3GenerateConstraintChecks()) as part of
103865  ** UPDATE and INSERT statements.
103866  */
103867  if( db->init.busy || pTblName==0 ){
103868    if( onError!=OE_Replace || pTab->pIndex==0
103869         || pTab->pIndex->onError==OE_Replace){
103870      pIndex->pNext = pTab->pIndex;
103871      pTab->pIndex = pIndex;
103872    }else{
103873      Index *pOther = pTab->pIndex;
103874      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
103875        pOther = pOther->pNext;
103876      }
103877      pIndex->pNext = pOther->pNext;
103878      pOther->pNext = pIndex;
103879    }
103880    pIndex = 0;
103881  }
103882
103883  /* Clean up before exiting */
103884exit_create_index:
103885  if( pIndex ) freeIndex(db, pIndex);
103886  sqlite3ExprDelete(db, pPIWhere);
103887  sqlite3ExprListDelete(db, pList);
103888  sqlite3SrcListDelete(db, pTblName);
103889  sqlite3DbFree(db, zName);
103890}
103891
103892/*
103893** Fill the Index.aiRowEst[] array with default information - information
103894** to be used when we have not run the ANALYZE command.
103895**
103896** aiRowEst[0] is supposed to contain the number of elements in the index.
103897** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
103898** number of rows in the table that match any particular value of the
103899** first column of the index.  aiRowEst[2] is an estimate of the number
103900** of rows that match any particular combination of the first 2 columns
103901** of the index.  And so forth.  It must always be the case that
103902*
103903**           aiRowEst[N]<=aiRowEst[N-1]
103904**           aiRowEst[N]>=1
103905**
103906** Apart from that, we have little to go on besides intuition as to
103907** how aiRowEst[] should be initialized.  The numbers generated here
103908** are based on typical values found in actual indices.
103909*/
103910SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
103911  /*                10,  9,  8,  7,  6 */
103912  LogEst aVal[] = { 33, 32, 30, 28, 26 };
103913  LogEst *a = pIdx->aiRowLogEst;
103914  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
103915  int i;
103916
103917  /* Indexes with default row estimates should not have stat1 data */
103918  assert( !pIdx->hasStat1 );
103919
103920  /* Set the first entry (number of rows in the index) to the estimated
103921  ** number of rows in the table, or half the number of rows in the table
103922  ** for a partial index.   But do not let the estimate drop below 10. */
103923  a[0] = pIdx->pTable->nRowLogEst;
103924  if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
103925  if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
103926
103927  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
103928  ** 6 and each subsequent value (if any) is 5.  */
103929  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
103930  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
103931    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
103932  }
103933
103934  assert( 0==sqlite3LogEst(1) );
103935  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
103936}
103937
103938/*
103939** This routine will drop an existing named index.  This routine
103940** implements the DROP INDEX statement.
103941*/
103942SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
103943  Index *pIndex;
103944  Vdbe *v;
103945  sqlite3 *db = pParse->db;
103946  int iDb;
103947
103948  assert( pParse->nErr==0 );   /* Never called with prior errors */
103949  if( db->mallocFailed ){
103950    goto exit_drop_index;
103951  }
103952  assert( pName->nSrc==1 );
103953  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
103954    goto exit_drop_index;
103955  }
103956  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
103957  if( pIndex==0 ){
103958    if( !ifExists ){
103959      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
103960    }else{
103961      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
103962    }
103963    pParse->checkSchema = 1;
103964    goto exit_drop_index;
103965  }
103966  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
103967    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
103968      "or PRIMARY KEY constraint cannot be dropped", 0);
103969    goto exit_drop_index;
103970  }
103971  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
103972#ifndef SQLITE_OMIT_AUTHORIZATION
103973  {
103974    int code = SQLITE_DROP_INDEX;
103975    Table *pTab = pIndex->pTable;
103976    const char *zDb = db->aDb[iDb].zDbSName;
103977    const char *zTab = SCHEMA_TABLE(iDb);
103978    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
103979      goto exit_drop_index;
103980    }
103981    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
103982    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
103983      goto exit_drop_index;
103984    }
103985  }
103986#endif
103987
103988  /* Generate code to remove the index and from the master table */
103989  v = sqlite3GetVdbe(pParse);
103990  if( v ){
103991    sqlite3BeginWriteOperation(pParse, 1, iDb);
103992    sqlite3NestedParse(pParse,
103993       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
103994       db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
103995    );
103996    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
103997    sqlite3ChangeCookie(pParse, iDb);
103998    destroyRootPage(pParse, pIndex->tnum, iDb);
103999    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
104000  }
104001
104002exit_drop_index:
104003  sqlite3SrcListDelete(db, pName);
104004}
104005
104006/*
104007** pArray is a pointer to an array of objects. Each object in the
104008** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
104009** to extend the array so that there is space for a new object at the end.
104010**
104011** When this function is called, *pnEntry contains the current size of
104012** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
104013** in total).
104014**
104015** If the realloc() is successful (i.e. if no OOM condition occurs), the
104016** space allocated for the new object is zeroed, *pnEntry updated to
104017** reflect the new size of the array and a pointer to the new allocation
104018** returned. *pIdx is set to the index of the new array entry in this case.
104019**
104020** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
104021** unchanged and a copy of pArray returned.
104022*/
104023SQLITE_PRIVATE void *sqlite3ArrayAllocate(
104024  sqlite3 *db,      /* Connection to notify of malloc failures */
104025  void *pArray,     /* Array of objects.  Might be reallocated */
104026  int szEntry,      /* Size of each object in the array */
104027  int *pnEntry,     /* Number of objects currently in use */
104028  int *pIdx         /* Write the index of a new slot here */
104029){
104030  char *z;
104031  int n = *pnEntry;
104032  if( (n & (n-1))==0 ){
104033    int sz = (n==0) ? 1 : 2*n;
104034    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
104035    if( pNew==0 ){
104036      *pIdx = -1;
104037      return pArray;
104038    }
104039    pArray = pNew;
104040  }
104041  z = (char*)pArray;
104042  memset(&z[n * szEntry], 0, szEntry);
104043  *pIdx = n;
104044  ++*pnEntry;
104045  return pArray;
104046}
104047
104048/*
104049** Append a new element to the given IdList.  Create a new IdList if
104050** need be.
104051**
104052** A new IdList is returned, or NULL if malloc() fails.
104053*/
104054SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
104055  int i;
104056  if( pList==0 ){
104057    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
104058    if( pList==0 ) return 0;
104059  }
104060  pList->a = sqlite3ArrayAllocate(
104061      db,
104062      pList->a,
104063      sizeof(pList->a[0]),
104064      &pList->nId,
104065      &i
104066  );
104067  if( i<0 ){
104068    sqlite3IdListDelete(db, pList);
104069    return 0;
104070  }
104071  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
104072  return pList;
104073}
104074
104075/*
104076** Delete an IdList.
104077*/
104078SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
104079  int i;
104080  if( pList==0 ) return;
104081  for(i=0; i<pList->nId; i++){
104082    sqlite3DbFree(db, pList->a[i].zName);
104083  }
104084  sqlite3DbFree(db, pList->a);
104085  sqlite3DbFreeNN(db, pList);
104086}
104087
104088/*
104089** Return the index in pList of the identifier named zId.  Return -1
104090** if not found.
104091*/
104092SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
104093  int i;
104094  if( pList==0 ) return -1;
104095  for(i=0; i<pList->nId; i++){
104096    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
104097  }
104098  return -1;
104099}
104100
104101/*
104102** Expand the space allocated for the given SrcList object by
104103** creating nExtra new slots beginning at iStart.  iStart is zero based.
104104** New slots are zeroed.
104105**
104106** For example, suppose a SrcList initially contains two entries: A,B.
104107** To append 3 new entries onto the end, do this:
104108**
104109**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
104110**
104111** After the call above it would contain:  A, B, nil, nil, nil.
104112** If the iStart argument had been 1 instead of 2, then the result
104113** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
104114** the iStart value would be 0.  The result then would
104115** be: nil, nil, nil, A, B.
104116**
104117** If a memory allocation fails the SrcList is unchanged.  The
104118** db->mallocFailed flag will be set to true.
104119*/
104120SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
104121  sqlite3 *db,       /* Database connection to notify of OOM errors */
104122  SrcList *pSrc,     /* The SrcList to be enlarged */
104123  int nExtra,        /* Number of new slots to add to pSrc->a[] */
104124  int iStart         /* Index in pSrc->a[] of first new slot */
104125){
104126  int i;
104127
104128  /* Sanity checking on calling parameters */
104129  assert( iStart>=0 );
104130  assert( nExtra>=1 );
104131  assert( pSrc!=0 );
104132  assert( iStart<=pSrc->nSrc );
104133
104134  /* Allocate additional space if needed */
104135  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
104136    SrcList *pNew;
104137    int nAlloc = pSrc->nSrc*2+nExtra;
104138    int nGot;
104139    pNew = sqlite3DbRealloc(db, pSrc,
104140               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
104141    if( pNew==0 ){
104142      assert( db->mallocFailed );
104143      return pSrc;
104144    }
104145    pSrc = pNew;
104146    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
104147    pSrc->nAlloc = nGot;
104148  }
104149
104150  /* Move existing slots that come after the newly inserted slots
104151  ** out of the way */
104152  for(i=pSrc->nSrc-1; i>=iStart; i--){
104153    pSrc->a[i+nExtra] = pSrc->a[i];
104154  }
104155  pSrc->nSrc += nExtra;
104156
104157  /* Zero the newly allocated slots */
104158  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
104159  for(i=iStart; i<iStart+nExtra; i++){
104160    pSrc->a[i].iCursor = -1;
104161  }
104162
104163  /* Return a pointer to the enlarged SrcList */
104164  return pSrc;
104165}
104166
104167
104168/*
104169** Append a new table name to the given SrcList.  Create a new SrcList if
104170** need be.  A new entry is created in the SrcList even if pTable is NULL.
104171**
104172** A SrcList is returned, or NULL if there is an OOM error.  The returned
104173** SrcList might be the same as the SrcList that was input or it might be
104174** a new one.  If an OOM error does occurs, then the prior value of pList
104175** that is input to this routine is automatically freed.
104176**
104177** If pDatabase is not null, it means that the table has an optional
104178** database name prefix.  Like this:  "database.table".  The pDatabase
104179** points to the table name and the pTable points to the database name.
104180** The SrcList.a[].zName field is filled with the table name which might
104181** come from pTable (if pDatabase is NULL) or from pDatabase.
104182** SrcList.a[].zDatabase is filled with the database name from pTable,
104183** or with NULL if no database is specified.
104184**
104185** In other words, if call like this:
104186**
104187**         sqlite3SrcListAppend(D,A,B,0);
104188**
104189** Then B is a table name and the database name is unspecified.  If called
104190** like this:
104191**
104192**         sqlite3SrcListAppend(D,A,B,C);
104193**
104194** Then C is the table name and B is the database name.  If C is defined
104195** then so is B.  In other words, we never have a case where:
104196**
104197**         sqlite3SrcListAppend(D,A,0,C);
104198**
104199** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
104200** before being added to the SrcList.
104201*/
104202SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
104203  sqlite3 *db,        /* Connection to notify of malloc failures */
104204  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
104205  Token *pTable,      /* Table to append */
104206  Token *pDatabase    /* Database of the table */
104207){
104208  struct SrcList_item *pItem;
104209  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
104210  assert( db!=0 );
104211  if( pList==0 ){
104212    pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
104213    if( pList==0 ) return 0;
104214    pList->nAlloc = 1;
104215    pList->nSrc = 1;
104216    memset(&pList->a[0], 0, sizeof(pList->a[0]));
104217    pList->a[0].iCursor = -1;
104218  }else{
104219    pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
104220  }
104221  if( db->mallocFailed ){
104222    sqlite3SrcListDelete(db, pList);
104223    return 0;
104224  }
104225  pItem = &pList->a[pList->nSrc-1];
104226  if( pDatabase && pDatabase->z==0 ){
104227    pDatabase = 0;
104228  }
104229  if( pDatabase ){
104230    pItem->zName = sqlite3NameFromToken(db, pDatabase);
104231    pItem->zDatabase = sqlite3NameFromToken(db, pTable);
104232  }else{
104233    pItem->zName = sqlite3NameFromToken(db, pTable);
104234    pItem->zDatabase = 0;
104235  }
104236  return pList;
104237}
104238
104239/*
104240** Assign VdbeCursor index numbers to all tables in a SrcList
104241*/
104242SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
104243  int i;
104244  struct SrcList_item *pItem;
104245  assert(pList || pParse->db->mallocFailed );
104246  if( pList ){
104247    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
104248      if( pItem->iCursor>=0 ) break;
104249      pItem->iCursor = pParse->nTab++;
104250      if( pItem->pSelect ){
104251        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
104252      }
104253    }
104254  }
104255}
104256
104257/*
104258** Delete an entire SrcList including all its substructure.
104259*/
104260SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
104261  int i;
104262  struct SrcList_item *pItem;
104263  if( pList==0 ) return;
104264  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
104265    sqlite3DbFree(db, pItem->zDatabase);
104266    sqlite3DbFree(db, pItem->zName);
104267    sqlite3DbFree(db, pItem->zAlias);
104268    if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
104269    if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
104270    sqlite3DeleteTable(db, pItem->pTab);
104271    sqlite3SelectDelete(db, pItem->pSelect);
104272    sqlite3ExprDelete(db, pItem->pOn);
104273    sqlite3IdListDelete(db, pItem->pUsing);
104274  }
104275  sqlite3DbFreeNN(db, pList);
104276}
104277
104278/*
104279** This routine is called by the parser to add a new term to the
104280** end of a growing FROM clause.  The "p" parameter is the part of
104281** the FROM clause that has already been constructed.  "p" is NULL
104282** if this is the first term of the FROM clause.  pTable and pDatabase
104283** are the name of the table and database named in the FROM clause term.
104284** pDatabase is NULL if the database name qualifier is missing - the
104285** usual case.  If the term has an alias, then pAlias points to the
104286** alias token.  If the term is a subquery, then pSubquery is the
104287** SELECT statement that the subquery encodes.  The pTable and
104288** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
104289** parameters are the content of the ON and USING clauses.
104290**
104291** Return a new SrcList which encodes is the FROM with the new
104292** term added.
104293*/
104294SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
104295  Parse *pParse,          /* Parsing context */
104296  SrcList *p,             /* The left part of the FROM clause already seen */
104297  Token *pTable,          /* Name of the table to add to the FROM clause */
104298  Token *pDatabase,       /* Name of the database containing pTable */
104299  Token *pAlias,          /* The right-hand side of the AS subexpression */
104300  Select *pSubquery,      /* A subquery used in place of a table name */
104301  Expr *pOn,              /* The ON clause of a join */
104302  IdList *pUsing          /* The USING clause of a join */
104303){
104304  struct SrcList_item *pItem;
104305  sqlite3 *db = pParse->db;
104306  if( !p && (pOn || pUsing) ){
104307    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
104308      (pOn ? "ON" : "USING")
104309    );
104310    goto append_from_error;
104311  }
104312  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
104313  if( p==0 || NEVER(p->nSrc==0) ){
104314    goto append_from_error;
104315  }
104316  pItem = &p->a[p->nSrc-1];
104317  assert( pAlias!=0 );
104318  if( pAlias->n ){
104319    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
104320  }
104321  pItem->pSelect = pSubquery;
104322  pItem->pOn = pOn;
104323  pItem->pUsing = pUsing;
104324  return p;
104325
104326 append_from_error:
104327  assert( p==0 );
104328  sqlite3ExprDelete(db, pOn);
104329  sqlite3IdListDelete(db, pUsing);
104330  sqlite3SelectDelete(db, pSubquery);
104331  return 0;
104332}
104333
104334/*
104335** Add an INDEXED BY or NOT INDEXED clause to the most recently added
104336** element of the source-list passed as the second argument.
104337*/
104338SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
104339  assert( pIndexedBy!=0 );
104340  if( p && ALWAYS(p->nSrc>0) ){
104341    struct SrcList_item *pItem = &p->a[p->nSrc-1];
104342    assert( pItem->fg.notIndexed==0 );
104343    assert( pItem->fg.isIndexedBy==0 );
104344    assert( pItem->fg.isTabFunc==0 );
104345    if( pIndexedBy->n==1 && !pIndexedBy->z ){
104346      /* A "NOT INDEXED" clause was supplied. See parse.y
104347      ** construct "indexed_opt" for details. */
104348      pItem->fg.notIndexed = 1;
104349    }else{
104350      pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
104351      pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
104352    }
104353  }
104354}
104355
104356/*
104357** Add the list of function arguments to the SrcList entry for a
104358** table-valued-function.
104359*/
104360SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
104361  if( p ){
104362    struct SrcList_item *pItem = &p->a[p->nSrc-1];
104363    assert( pItem->fg.notIndexed==0 );
104364    assert( pItem->fg.isIndexedBy==0 );
104365    assert( pItem->fg.isTabFunc==0 );
104366    pItem->u1.pFuncArg = pList;
104367    pItem->fg.isTabFunc = 1;
104368  }else{
104369    sqlite3ExprListDelete(pParse->db, pList);
104370  }
104371}
104372
104373/*
104374** When building up a FROM clause in the parser, the join operator
104375** is initially attached to the left operand.  But the code generator
104376** expects the join operator to be on the right operand.  This routine
104377** Shifts all join operators from left to right for an entire FROM
104378** clause.
104379**
104380** Example: Suppose the join is like this:
104381**
104382**           A natural cross join B
104383**
104384** The operator is "natural cross join".  The A and B operands are stored
104385** in p->a[0] and p->a[1], respectively.  The parser initially stores the
104386** operator with A.  This routine shifts that operator over to B.
104387*/
104388SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
104389  if( p ){
104390    int i;
104391    for(i=p->nSrc-1; i>0; i--){
104392      p->a[i].fg.jointype = p->a[i-1].fg.jointype;
104393    }
104394    p->a[0].fg.jointype = 0;
104395  }
104396}
104397
104398/*
104399** Generate VDBE code for a BEGIN statement.
104400*/
104401SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
104402  sqlite3 *db;
104403  Vdbe *v;
104404  int i;
104405
104406  assert( pParse!=0 );
104407  db = pParse->db;
104408  assert( db!=0 );
104409  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
104410    return;
104411  }
104412  v = sqlite3GetVdbe(pParse);
104413  if( !v ) return;
104414  if( type!=TK_DEFERRED ){
104415    for(i=0; i<db->nDb; i++){
104416      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
104417      sqlite3VdbeUsesBtree(v, i);
104418    }
104419  }
104420  sqlite3VdbeAddOp0(v, OP_AutoCommit);
104421}
104422
104423/*
104424** Generate VDBE code for a COMMIT or ROLLBACK statement.
104425** Code for ROLLBACK is generated if eType==TK_ROLLBACK.  Otherwise
104426** code is generated for a COMMIT.
104427*/
104428SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
104429  Vdbe *v;
104430  int isRollback;
104431
104432  assert( pParse!=0 );
104433  assert( pParse->db!=0 );
104434  assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
104435  isRollback = eType==TK_ROLLBACK;
104436  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
104437       isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
104438    return;
104439  }
104440  v = sqlite3GetVdbe(pParse);
104441  if( v ){
104442    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
104443  }
104444}
104445
104446/*
104447** This function is called by the parser when it parses a command to create,
104448** release or rollback an SQL savepoint.
104449*/
104450SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
104451  char *zName = sqlite3NameFromToken(pParse->db, pName);
104452  if( zName ){
104453    Vdbe *v = sqlite3GetVdbe(pParse);
104454#ifndef SQLITE_OMIT_AUTHORIZATION
104455    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
104456    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
104457#endif
104458    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
104459      sqlite3DbFree(pParse->db, zName);
104460      return;
104461    }
104462    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
104463  }
104464}
104465
104466/*
104467** Make sure the TEMP database is open and available for use.  Return
104468** the number of errors.  Leave any error messages in the pParse structure.
104469*/
104470SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
104471  sqlite3 *db = pParse->db;
104472  if( db->aDb[1].pBt==0 && !pParse->explain ){
104473    int rc;
104474    Btree *pBt;
104475    static const int flags =
104476          SQLITE_OPEN_READWRITE |
104477          SQLITE_OPEN_CREATE |
104478          SQLITE_OPEN_EXCLUSIVE |
104479          SQLITE_OPEN_DELETEONCLOSE |
104480          SQLITE_OPEN_TEMP_DB;
104481
104482    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
104483    if( rc!=SQLITE_OK ){
104484      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
104485        "file for storing temporary tables");
104486      pParse->rc = rc;
104487      return 1;
104488    }
104489    db->aDb[1].pBt = pBt;
104490    assert( db->aDb[1].pSchema );
104491    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
104492      sqlite3OomFault(db);
104493      return 1;
104494    }
104495  }
104496  return 0;
104497}
104498
104499/*
104500** Record the fact that the schema cookie will need to be verified
104501** for database iDb.  The code to actually verify the schema cookie
104502** will occur at the end of the top-level VDBE and will be generated
104503** later, by sqlite3FinishCoding().
104504*/
104505SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
104506  Parse *pToplevel = sqlite3ParseToplevel(pParse);
104507
104508  assert( iDb>=0 && iDb<pParse->db->nDb );
104509  assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
104510  assert( iDb<SQLITE_MAX_ATTACHED+2 );
104511  assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
104512  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
104513    DbMaskSet(pToplevel->cookieMask, iDb);
104514    if( !OMIT_TEMPDB && iDb==1 ){
104515      sqlite3OpenTempDatabase(pToplevel);
104516    }
104517  }
104518}
104519
104520/*
104521** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
104522** attached database. Otherwise, invoke it for the database named zDb only.
104523*/
104524SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
104525  sqlite3 *db = pParse->db;
104526  int i;
104527  for(i=0; i<db->nDb; i++){
104528    Db *pDb = &db->aDb[i];
104529    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
104530      sqlite3CodeVerifySchema(pParse, i);
104531    }
104532  }
104533}
104534
104535/*
104536** Generate VDBE code that prepares for doing an operation that
104537** might change the database.
104538**
104539** This routine starts a new transaction if we are not already within
104540** a transaction.  If we are already within a transaction, then a checkpoint
104541** is set if the setStatement parameter is true.  A checkpoint should
104542** be set for operations that might fail (due to a constraint) part of
104543** the way through and which will need to undo some writes without having to
104544** rollback the whole transaction.  For operations where all constraints
104545** can be checked before any changes are made to the database, it is never
104546** necessary to undo a write and the checkpoint should not be set.
104547*/
104548SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
104549  Parse *pToplevel = sqlite3ParseToplevel(pParse);
104550  sqlite3CodeVerifySchema(pParse, iDb);
104551  DbMaskSet(pToplevel->writeMask, iDb);
104552  pToplevel->isMultiWrite |= setStatement;
104553}
104554
104555/*
104556** Indicate that the statement currently under construction might write
104557** more than one entry (example: deleting one row then inserting another,
104558** inserting multiple rows in a table, or inserting a row and index entries.)
104559** If an abort occurs after some of these writes have completed, then it will
104560** be necessary to undo the completed writes.
104561*/
104562SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
104563  Parse *pToplevel = sqlite3ParseToplevel(pParse);
104564  pToplevel->isMultiWrite = 1;
104565}
104566
104567/*
104568** The code generator calls this routine if is discovers that it is
104569** possible to abort a statement prior to completion.  In order to
104570** perform this abort without corrupting the database, we need to make
104571** sure that the statement is protected by a statement transaction.
104572**
104573** Technically, we only need to set the mayAbort flag if the
104574** isMultiWrite flag was previously set.  There is a time dependency
104575** such that the abort must occur after the multiwrite.  This makes
104576** some statements involving the REPLACE conflict resolution algorithm
104577** go a little faster.  But taking advantage of this time dependency
104578** makes it more difficult to prove that the code is correct (in
104579** particular, it prevents us from writing an effective
104580** implementation of sqlite3AssertMayAbort()) and so we have chosen
104581** to take the safe route and skip the optimization.
104582*/
104583SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
104584  Parse *pToplevel = sqlite3ParseToplevel(pParse);
104585  pToplevel->mayAbort = 1;
104586}
104587
104588/*
104589** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
104590** error. The onError parameter determines which (if any) of the statement
104591** and/or current transaction is rolled back.
104592*/
104593SQLITE_PRIVATE void sqlite3HaltConstraint(
104594  Parse *pParse,    /* Parsing context */
104595  int errCode,      /* extended error code */
104596  int onError,      /* Constraint type */
104597  char *p4,         /* Error message */
104598  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
104599  u8 p5Errmsg       /* P5_ErrMsg type */
104600){
104601  Vdbe *v = sqlite3GetVdbe(pParse);
104602  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
104603  if( onError==OE_Abort ){
104604    sqlite3MayAbort(pParse);
104605  }
104606  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
104607  sqlite3VdbeChangeP5(v, p5Errmsg);
104608}
104609
104610/*
104611** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
104612*/
104613SQLITE_PRIVATE void sqlite3UniqueConstraint(
104614  Parse *pParse,    /* Parsing context */
104615  int onError,      /* Constraint type */
104616  Index *pIdx       /* The index that triggers the constraint */
104617){
104618  char *zErr;
104619  int j;
104620  StrAccum errMsg;
104621  Table *pTab = pIdx->pTable;
104622
104623  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
104624  if( pIdx->aColExpr ){
104625    sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
104626  }else{
104627    for(j=0; j<pIdx->nKeyCol; j++){
104628      char *zCol;
104629      assert( pIdx->aiColumn[j]>=0 );
104630      zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
104631      if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
104632      sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
104633      sqlite3StrAccumAppend(&errMsg, ".", 1);
104634      sqlite3StrAccumAppendAll(&errMsg, zCol);
104635    }
104636  }
104637  zErr = sqlite3StrAccumFinish(&errMsg);
104638  sqlite3HaltConstraint(pParse,
104639    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
104640                            : SQLITE_CONSTRAINT_UNIQUE,
104641    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
104642}
104643
104644
104645/*
104646** Code an OP_Halt due to non-unique rowid.
104647*/
104648SQLITE_PRIVATE void sqlite3RowidConstraint(
104649  Parse *pParse,    /* Parsing context */
104650  int onError,      /* Conflict resolution algorithm */
104651  Table *pTab       /* The table with the non-unique rowid */
104652){
104653  char *zMsg;
104654  int rc;
104655  if( pTab->iPKey>=0 ){
104656    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
104657                          pTab->aCol[pTab->iPKey].zName);
104658    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
104659  }else{
104660    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
104661    rc = SQLITE_CONSTRAINT_ROWID;
104662  }
104663  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
104664                        P5_ConstraintUnique);
104665}
104666
104667/*
104668** Check to see if pIndex uses the collating sequence pColl.  Return
104669** true if it does and false if it does not.
104670*/
104671#ifndef SQLITE_OMIT_REINDEX
104672static int collationMatch(const char *zColl, Index *pIndex){
104673  int i;
104674  assert( zColl!=0 );
104675  for(i=0; i<pIndex->nColumn; i++){
104676    const char *z = pIndex->azColl[i];
104677    assert( z!=0 || pIndex->aiColumn[i]<0 );
104678    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
104679      return 1;
104680    }
104681  }
104682  return 0;
104683}
104684#endif
104685
104686/*
104687** Recompute all indices of pTab that use the collating sequence pColl.
104688** If pColl==0 then recompute all indices of pTab.
104689*/
104690#ifndef SQLITE_OMIT_REINDEX
104691static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
104692  Index *pIndex;              /* An index associated with pTab */
104693
104694  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
104695    if( zColl==0 || collationMatch(zColl, pIndex) ){
104696      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
104697      sqlite3BeginWriteOperation(pParse, 0, iDb);
104698      sqlite3RefillIndex(pParse, pIndex, -1);
104699    }
104700  }
104701}
104702#endif
104703
104704/*
104705** Recompute all indices of all tables in all databases where the
104706** indices use the collating sequence pColl.  If pColl==0 then recompute
104707** all indices everywhere.
104708*/
104709#ifndef SQLITE_OMIT_REINDEX
104710static void reindexDatabases(Parse *pParse, char const *zColl){
104711  Db *pDb;                    /* A single database */
104712  int iDb;                    /* The database index number */
104713  sqlite3 *db = pParse->db;   /* The database connection */
104714  HashElem *k;                /* For looping over tables in pDb */
104715  Table *pTab;                /* A table in the database */
104716
104717  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
104718  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
104719    assert( pDb!=0 );
104720    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
104721      pTab = (Table*)sqliteHashData(k);
104722      reindexTable(pParse, pTab, zColl);
104723    }
104724  }
104725}
104726#endif
104727
104728/*
104729** Generate code for the REINDEX command.
104730**
104731**        REINDEX                            -- 1
104732**        REINDEX  <collation>               -- 2
104733**        REINDEX  ?<database>.?<tablename>  -- 3
104734**        REINDEX  ?<database>.?<indexname>  -- 4
104735**
104736** Form 1 causes all indices in all attached databases to be rebuilt.
104737** Form 2 rebuilds all indices in all databases that use the named
104738** collating function.  Forms 3 and 4 rebuild the named index or all
104739** indices associated with the named table.
104740*/
104741#ifndef SQLITE_OMIT_REINDEX
104742SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
104743  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
104744  char *z;                    /* Name of a table or index */
104745  const char *zDb;            /* Name of the database */
104746  Table *pTab;                /* A table in the database */
104747  Index *pIndex;              /* An index associated with pTab */
104748  int iDb;                    /* The database index number */
104749  sqlite3 *db = pParse->db;   /* The database connection */
104750  Token *pObjName;            /* Name of the table or index to be reindexed */
104751
104752  /* Read the database schema. If an error occurs, leave an error message
104753  ** and code in pParse and return NULL. */
104754  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
104755    return;
104756  }
104757
104758  if( pName1==0 ){
104759    reindexDatabases(pParse, 0);
104760    return;
104761  }else if( NEVER(pName2==0) || pName2->z==0 ){
104762    char *zColl;
104763    assert( pName1->z );
104764    zColl = sqlite3NameFromToken(pParse->db, pName1);
104765    if( !zColl ) return;
104766    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
104767    if( pColl ){
104768      reindexDatabases(pParse, zColl);
104769      sqlite3DbFree(db, zColl);
104770      return;
104771    }
104772    sqlite3DbFree(db, zColl);
104773  }
104774  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
104775  if( iDb<0 ) return;
104776  z = sqlite3NameFromToken(db, pObjName);
104777  if( z==0 ) return;
104778  zDb = db->aDb[iDb].zDbSName;
104779  pTab = sqlite3FindTable(db, z, zDb);
104780  if( pTab ){
104781    reindexTable(pParse, pTab, 0);
104782    sqlite3DbFree(db, z);
104783    return;
104784  }
104785  pIndex = sqlite3FindIndex(db, z, zDb);
104786  sqlite3DbFree(db, z);
104787  if( pIndex ){
104788    sqlite3BeginWriteOperation(pParse, 0, iDb);
104789    sqlite3RefillIndex(pParse, pIndex, -1);
104790    return;
104791  }
104792  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
104793}
104794#endif
104795
104796/*
104797** Return a KeyInfo structure that is appropriate for the given Index.
104798**
104799** The caller should invoke sqlite3KeyInfoUnref() on the returned object
104800** when it has finished using it.
104801*/
104802SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
104803  int i;
104804  int nCol = pIdx->nColumn;
104805  int nKey = pIdx->nKeyCol;
104806  KeyInfo *pKey;
104807  if( pParse->nErr ) return 0;
104808  if( pIdx->uniqNotNull ){
104809    pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
104810  }else{
104811    pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
104812  }
104813  if( pKey ){
104814    assert( sqlite3KeyInfoIsWriteable(pKey) );
104815    for(i=0; i<nCol; i++){
104816      const char *zColl = pIdx->azColl[i];
104817      pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
104818                        sqlite3LocateCollSeq(pParse, zColl);
104819      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
104820    }
104821    if( pParse->nErr ){
104822      sqlite3KeyInfoUnref(pKey);
104823      pKey = 0;
104824    }
104825  }
104826  return pKey;
104827}
104828
104829#ifndef SQLITE_OMIT_CTE
104830/*
104831** This routine is invoked once per CTE by the parser while parsing a
104832** WITH clause.
104833*/
104834SQLITE_PRIVATE With *sqlite3WithAdd(
104835  Parse *pParse,          /* Parsing context */
104836  With *pWith,            /* Existing WITH clause, or NULL */
104837  Token *pName,           /* Name of the common-table */
104838  ExprList *pArglist,     /* Optional column name list for the table */
104839  Select *pQuery          /* Query used to initialize the table */
104840){
104841  sqlite3 *db = pParse->db;
104842  With *pNew;
104843  char *zName;
104844
104845  /* Check that the CTE name is unique within this WITH clause. If
104846  ** not, store an error in the Parse structure. */
104847  zName = sqlite3NameFromToken(pParse->db, pName);
104848  if( zName && pWith ){
104849    int i;
104850    for(i=0; i<pWith->nCte; i++){
104851      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
104852        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
104853      }
104854    }
104855  }
104856
104857  if( pWith ){
104858    int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
104859    pNew = sqlite3DbRealloc(db, pWith, nByte);
104860  }else{
104861    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
104862  }
104863  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
104864
104865  if( db->mallocFailed ){
104866    sqlite3ExprListDelete(db, pArglist);
104867    sqlite3SelectDelete(db, pQuery);
104868    sqlite3DbFree(db, zName);
104869    pNew = pWith;
104870  }else{
104871    pNew->a[pNew->nCte].pSelect = pQuery;
104872    pNew->a[pNew->nCte].pCols = pArglist;
104873    pNew->a[pNew->nCte].zName = zName;
104874    pNew->a[pNew->nCte].zCteErr = 0;
104875    pNew->nCte++;
104876  }
104877
104878  return pNew;
104879}
104880
104881/*
104882** Free the contents of the With object passed as the second argument.
104883*/
104884SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
104885  if( pWith ){
104886    int i;
104887    for(i=0; i<pWith->nCte; i++){
104888      struct Cte *pCte = &pWith->a[i];
104889      sqlite3ExprListDelete(db, pCte->pCols);
104890      sqlite3SelectDelete(db, pCte->pSelect);
104891      sqlite3DbFree(db, pCte->zName);
104892    }
104893    sqlite3DbFree(db, pWith);
104894  }
104895}
104896#endif /* !defined(SQLITE_OMIT_CTE) */
104897
104898/************** End of build.c ***********************************************/
104899/************** Begin file callback.c ****************************************/
104900/*
104901** 2005 May 23
104902**
104903** The author disclaims copyright to this source code.  In place of
104904** a legal notice, here is a blessing:
104905**
104906**    May you do good and not evil.
104907**    May you find forgiveness for yourself and forgive others.
104908**    May you share freely, never taking more than you give.
104909**
104910*************************************************************************
104911**
104912** This file contains functions used to access the internal hash tables
104913** of user defined functions and collation sequences.
104914*/
104915
104916/* #include "sqliteInt.h" */
104917
104918/*
104919** Invoke the 'collation needed' callback to request a collation sequence
104920** in the encoding enc of name zName, length nName.
104921*/
104922static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
104923  assert( !db->xCollNeeded || !db->xCollNeeded16 );
104924  if( db->xCollNeeded ){
104925    char *zExternal = sqlite3DbStrDup(db, zName);
104926    if( !zExternal ) return;
104927    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
104928    sqlite3DbFree(db, zExternal);
104929  }
104930#ifndef SQLITE_OMIT_UTF16
104931  if( db->xCollNeeded16 ){
104932    char const *zExternal;
104933    sqlite3_value *pTmp = sqlite3ValueNew(db);
104934    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
104935    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
104936    if( zExternal ){
104937      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
104938    }
104939    sqlite3ValueFree(pTmp);
104940  }
104941#endif
104942}
104943
104944/*
104945** This routine is called if the collation factory fails to deliver a
104946** collation function in the best encoding but there may be other versions
104947** of this collation function (for other text encodings) available. Use one
104948** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
104949** possible.
104950*/
104951static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
104952  CollSeq *pColl2;
104953  char *z = pColl->zName;
104954  int i;
104955  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
104956  for(i=0; i<3; i++){
104957    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
104958    if( pColl2->xCmp!=0 ){
104959      memcpy(pColl, pColl2, sizeof(CollSeq));
104960      pColl->xDel = 0;         /* Do not copy the destructor */
104961      return SQLITE_OK;
104962    }
104963  }
104964  return SQLITE_ERROR;
104965}
104966
104967/*
104968** This function is responsible for invoking the collation factory callback
104969** or substituting a collation sequence of a different encoding when the
104970** requested collation sequence is not available in the desired encoding.
104971**
104972** If it is not NULL, then pColl must point to the database native encoding
104973** collation sequence with name zName, length nName.
104974**
104975** The return value is either the collation sequence to be used in database
104976** db for collation type name zName, length nName, or NULL, if no collation
104977** sequence can be found.  If no collation is found, leave an error message.
104978**
104979** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
104980*/
104981SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
104982  Parse *pParse,        /* Parsing context */
104983  u8 enc,               /* The desired encoding for the collating sequence */
104984  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
104985  const char *zName     /* Collating sequence name */
104986){
104987  CollSeq *p;
104988  sqlite3 *db = pParse->db;
104989
104990  p = pColl;
104991  if( !p ){
104992    p = sqlite3FindCollSeq(db, enc, zName, 0);
104993  }
104994  if( !p || !p->xCmp ){
104995    /* No collation sequence of this type for this encoding is registered.
104996    ** Call the collation factory to see if it can supply us with one.
104997    */
104998    callCollNeeded(db, enc, zName);
104999    p = sqlite3FindCollSeq(db, enc, zName, 0);
105000  }
105001  if( p && !p->xCmp && synthCollSeq(db, p) ){
105002    p = 0;
105003  }
105004  assert( !p || p->xCmp );
105005  if( p==0 ){
105006    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
105007  }
105008  return p;
105009}
105010
105011/*
105012** This routine is called on a collation sequence before it is used to
105013** check that it is defined. An undefined collation sequence exists when
105014** a database is loaded that contains references to collation sequences
105015** that have not been defined by sqlite3_create_collation() etc.
105016**
105017** If required, this routine calls the 'collation needed' callback to
105018** request a definition of the collating sequence. If this doesn't work,
105019** an equivalent collating sequence that uses a text encoding different
105020** from the main database is substituted, if one is available.
105021*/
105022SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
105023  if( pColl && pColl->xCmp==0 ){
105024    const char *zName = pColl->zName;
105025    sqlite3 *db = pParse->db;
105026    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
105027    if( !p ){
105028      return SQLITE_ERROR;
105029    }
105030    assert( p==pColl );
105031  }
105032  return SQLITE_OK;
105033}
105034
105035
105036
105037/*
105038** Locate and return an entry from the db.aCollSeq hash table. If the entry
105039** specified by zName and nName is not found and parameter 'create' is
105040** true, then create a new entry. Otherwise return NULL.
105041**
105042** Each pointer stored in the sqlite3.aCollSeq hash table contains an
105043** array of three CollSeq structures. The first is the collation sequence
105044** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
105045**
105046** Stored immediately after the three collation sequences is a copy of
105047** the collation sequence name. A pointer to this string is stored in
105048** each collation sequence structure.
105049*/
105050static CollSeq *findCollSeqEntry(
105051  sqlite3 *db,          /* Database connection */
105052  const char *zName,    /* Name of the collating sequence */
105053  int create            /* Create a new entry if true */
105054){
105055  CollSeq *pColl;
105056  pColl = sqlite3HashFind(&db->aCollSeq, zName);
105057
105058  if( 0==pColl && create ){
105059    int nName = sqlite3Strlen30(zName) + 1;
105060    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
105061    if( pColl ){
105062      CollSeq *pDel = 0;
105063      pColl[0].zName = (char*)&pColl[3];
105064      pColl[0].enc = SQLITE_UTF8;
105065      pColl[1].zName = (char*)&pColl[3];
105066      pColl[1].enc = SQLITE_UTF16LE;
105067      pColl[2].zName = (char*)&pColl[3];
105068      pColl[2].enc = SQLITE_UTF16BE;
105069      memcpy(pColl[0].zName, zName, nName);
105070      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
105071
105072      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
105073      ** return the pColl pointer to be deleted (because it wasn't added
105074      ** to the hash table).
105075      */
105076      assert( pDel==0 || pDel==pColl );
105077      if( pDel!=0 ){
105078        sqlite3OomFault(db);
105079        sqlite3DbFree(db, pDel);
105080        pColl = 0;
105081      }
105082    }
105083  }
105084  return pColl;
105085}
105086
105087/*
105088** Parameter zName points to a UTF-8 encoded string nName bytes long.
105089** Return the CollSeq* pointer for the collation sequence named zName
105090** for the encoding 'enc' from the database 'db'.
105091**
105092** If the entry specified is not found and 'create' is true, then create a
105093** new entry.  Otherwise return NULL.
105094**
105095** A separate function sqlite3LocateCollSeq() is a wrapper around
105096** this routine.  sqlite3LocateCollSeq() invokes the collation factory
105097** if necessary and generates an error message if the collating sequence
105098** cannot be found.
105099**
105100** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
105101*/
105102SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
105103  sqlite3 *db,
105104  u8 enc,
105105  const char *zName,
105106  int create
105107){
105108  CollSeq *pColl;
105109  if( zName ){
105110    pColl = findCollSeqEntry(db, zName, create);
105111  }else{
105112    pColl = db->pDfltColl;
105113  }
105114  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
105115  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
105116  if( pColl ) pColl += enc-1;
105117  return pColl;
105118}
105119
105120/* During the search for the best function definition, this procedure
105121** is called to test how well the function passed as the first argument
105122** matches the request for a function with nArg arguments in a system
105123** that uses encoding enc. The value returned indicates how well the
105124** request is matched. A higher value indicates a better match.
105125**
105126** If nArg is -1 that means to only return a match (non-zero) if p->nArg
105127** is also -1.  In other words, we are searching for a function that
105128** takes a variable number of arguments.
105129**
105130** If nArg is -2 that means that we are searching for any function
105131** regardless of the number of arguments it uses, so return a positive
105132** match score for any
105133**
105134** The returned value is always between 0 and 6, as follows:
105135**
105136** 0: Not a match.
105137** 1: UTF8/16 conversion required and function takes any number of arguments.
105138** 2: UTF16 byte order change required and function takes any number of args.
105139** 3: encoding matches and function takes any number of arguments
105140** 4: UTF8/16 conversion required - argument count matches exactly
105141** 5: UTF16 byte order conversion required - argument count matches exactly
105142** 6: Perfect match:  encoding and argument count match exactly.
105143**
105144** If nArg==(-2) then any function with a non-null xSFunc is
105145** a perfect match and any function with xSFunc NULL is
105146** a non-match.
105147*/
105148#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
105149static int matchQuality(
105150  FuncDef *p,     /* The function we are evaluating for match quality */
105151  int nArg,       /* Desired number of arguments.  (-1)==any */
105152  u8 enc          /* Desired text encoding */
105153){
105154  int match;
105155
105156  /* nArg of -2 is a special case */
105157  if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
105158
105159  /* Wrong number of arguments means "no match" */
105160  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
105161
105162  /* Give a better score to a function with a specific number of arguments
105163  ** than to function that accepts any number of arguments. */
105164  if( p->nArg==nArg ){
105165    match = 4;
105166  }else{
105167    match = 1;
105168  }
105169
105170  /* Bonus points if the text encoding matches */
105171  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
105172    match += 2;  /* Exact encoding match */
105173  }else if( (enc & p->funcFlags & 2)!=0 ){
105174    match += 1;  /* Both are UTF16, but with different byte orders */
105175  }
105176
105177  return match;
105178}
105179
105180/*
105181** Search a FuncDefHash for a function with the given name.  Return
105182** a pointer to the matching FuncDef if found, or 0 if there is no match.
105183*/
105184static FuncDef *functionSearch(
105185  int h,               /* Hash of the name */
105186  const char *zFunc    /* Name of function */
105187){
105188  FuncDef *p;
105189  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
105190    if( sqlite3StrICmp(p->zName, zFunc)==0 ){
105191      return p;
105192    }
105193  }
105194  return 0;
105195}
105196
105197/*
105198** Insert a new FuncDef into a FuncDefHash hash table.
105199*/
105200SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
105201  FuncDef *aDef,      /* List of global functions to be inserted */
105202  int nDef            /* Length of the apDef[] list */
105203){
105204  int i;
105205  for(i=0; i<nDef; i++){
105206    FuncDef *pOther;
105207    const char *zName = aDef[i].zName;
105208    int nName = sqlite3Strlen30(zName);
105209    int h = (zName[0] + nName) % SQLITE_FUNC_HASH_SZ;
105210    assert( zName[0]>='a' && zName[0]<='z' );
105211    pOther = functionSearch(h, zName);
105212    if( pOther ){
105213      assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
105214      aDef[i].pNext = pOther->pNext;
105215      pOther->pNext = &aDef[i];
105216    }else{
105217      aDef[i].pNext = 0;
105218      aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
105219      sqlite3BuiltinFunctions.a[h] = &aDef[i];
105220    }
105221  }
105222}
105223
105224
105225
105226/*
105227** Locate a user function given a name, a number of arguments and a flag
105228** indicating whether the function prefers UTF-16 over UTF-8.  Return a
105229** pointer to the FuncDef structure that defines that function, or return
105230** NULL if the function does not exist.
105231**
105232** If the createFlag argument is true, then a new (blank) FuncDef
105233** structure is created and liked into the "db" structure if a
105234** no matching function previously existed.
105235**
105236** If nArg is -2, then the first valid function found is returned.  A
105237** function is valid if xSFunc is non-zero.  The nArg==(-2)
105238** case is used to see if zName is a valid function name for some number
105239** of arguments.  If nArg is -2, then createFlag must be 0.
105240**
105241** If createFlag is false, then a function with the required name and
105242** number of arguments may be returned even if the eTextRep flag does not
105243** match that requested.
105244*/
105245SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
105246  sqlite3 *db,       /* An open database */
105247  const char *zName, /* Name of the function.  zero-terminated */
105248  int nArg,          /* Number of arguments.  -1 means any number */
105249  u8 enc,            /* Preferred text encoding */
105250  u8 createFlag      /* Create new entry if true and does not otherwise exist */
105251){
105252  FuncDef *p;         /* Iterator variable */
105253  FuncDef *pBest = 0; /* Best match found so far */
105254  int bestScore = 0;  /* Score of best match */
105255  int h;              /* Hash value */
105256  int nName;          /* Length of the name */
105257
105258  assert( nArg>=(-2) );
105259  assert( nArg>=(-1) || createFlag==0 );
105260  nName = sqlite3Strlen30(zName);
105261
105262  /* First search for a match amongst the application-defined functions.
105263  */
105264  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
105265  while( p ){
105266    int score = matchQuality(p, nArg, enc);
105267    if( score>bestScore ){
105268      pBest = p;
105269      bestScore = score;
105270    }
105271    p = p->pNext;
105272  }
105273
105274  /* If no match is found, search the built-in functions.
105275  **
105276  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
105277  ** functions even if a prior app-defined function was found.  And give
105278  ** priority to built-in functions.
105279  **
105280  ** Except, if createFlag is true, that means that we are trying to
105281  ** install a new function.  Whatever FuncDef structure is returned it will
105282  ** have fields overwritten with new information appropriate for the
105283  ** new function.  But the FuncDefs for built-in functions are read-only.
105284  ** So we must not search for built-ins when creating a new function.
105285  */
105286  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
105287    bestScore = 0;
105288    h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
105289    p = functionSearch(h, zName);
105290    while( p ){
105291      int score = matchQuality(p, nArg, enc);
105292      if( score>bestScore ){
105293        pBest = p;
105294        bestScore = score;
105295      }
105296      p = p->pNext;
105297    }
105298  }
105299
105300  /* If the createFlag parameter is true and the search did not reveal an
105301  ** exact match for the name, number of arguments and encoding, then add a
105302  ** new entry to the hash table and return it.
105303  */
105304  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
105305      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
105306    FuncDef *pOther;
105307    pBest->zName = (const char*)&pBest[1];
105308    pBest->nArg = (u16)nArg;
105309    pBest->funcFlags = enc;
105310    memcpy((char*)&pBest[1], zName, nName+1);
105311    pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
105312    if( pOther==pBest ){
105313      sqlite3DbFree(db, pBest);
105314      sqlite3OomFault(db);
105315      return 0;
105316    }else{
105317      pBest->pNext = pOther;
105318    }
105319  }
105320
105321  if( pBest && (pBest->xSFunc || createFlag) ){
105322    return pBest;
105323  }
105324  return 0;
105325}
105326
105327/*
105328** Free all resources held by the schema structure. The void* argument points
105329** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
105330** pointer itself, it just cleans up subsidiary resources (i.e. the contents
105331** of the schema hash tables).
105332**
105333** The Schema.cache_size variable is not cleared.
105334*/
105335SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
105336  Hash temp1;
105337  Hash temp2;
105338  HashElem *pElem;
105339  Schema *pSchema = (Schema *)p;
105340
105341  temp1 = pSchema->tblHash;
105342  temp2 = pSchema->trigHash;
105343  sqlite3HashInit(&pSchema->trigHash);
105344  sqlite3HashClear(&pSchema->idxHash);
105345  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
105346    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
105347  }
105348  sqlite3HashClear(&temp2);
105349  sqlite3HashInit(&pSchema->tblHash);
105350  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
105351    Table *pTab = sqliteHashData(pElem);
105352    sqlite3DeleteTable(0, pTab);
105353  }
105354  sqlite3HashClear(&temp1);
105355  sqlite3HashClear(&pSchema->fkeyHash);
105356  pSchema->pSeqTab = 0;
105357  if( pSchema->schemaFlags & DB_SchemaLoaded ){
105358    pSchema->iGeneration++;
105359    pSchema->schemaFlags &= ~DB_SchemaLoaded;
105360  }
105361}
105362
105363/*
105364** Find and return the schema associated with a BTree.  Create
105365** a new one if necessary.
105366*/
105367SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
105368  Schema * p;
105369  if( pBt ){
105370    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
105371  }else{
105372    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
105373  }
105374  if( !p ){
105375    sqlite3OomFault(db);
105376  }else if ( 0==p->file_format ){
105377    sqlite3HashInit(&p->tblHash);
105378    sqlite3HashInit(&p->idxHash);
105379    sqlite3HashInit(&p->trigHash);
105380    sqlite3HashInit(&p->fkeyHash);
105381    p->enc = SQLITE_UTF8;
105382  }
105383  return p;
105384}
105385
105386/************** End of callback.c ********************************************/
105387/************** Begin file delete.c ******************************************/
105388/*
105389** 2001 September 15
105390**
105391** The author disclaims copyright to this source code.  In place of
105392** a legal notice, here is a blessing:
105393**
105394**    May you do good and not evil.
105395**    May you find forgiveness for yourself and forgive others.
105396**    May you share freely, never taking more than you give.
105397**
105398*************************************************************************
105399** This file contains C code routines that are called by the parser
105400** in order to generate code for DELETE FROM statements.
105401*/
105402/* #include "sqliteInt.h" */
105403
105404/*
105405** While a SrcList can in general represent multiple tables and subqueries
105406** (as in the FROM clause of a SELECT statement) in this case it contains
105407** the name of a single table, as one might find in an INSERT, DELETE,
105408** or UPDATE statement.  Look up that table in the symbol table and
105409** return a pointer.  Set an error message and return NULL if the table
105410** name is not found or if any other error occurs.
105411**
105412** The following fields are initialized appropriate in pSrc:
105413**
105414**    pSrc->a[0].pTab       Pointer to the Table object
105415**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
105416**
105417*/
105418SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
105419  struct SrcList_item *pItem = pSrc->a;
105420  Table *pTab;
105421  assert( pItem && pSrc->nSrc==1 );
105422  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
105423  sqlite3DeleteTable(pParse->db, pItem->pTab);
105424  pItem->pTab = pTab;
105425  if( pTab ){
105426    pTab->nTabRef++;
105427  }
105428  if( sqlite3IndexedByLookup(pParse, pItem) ){
105429    pTab = 0;
105430  }
105431  return pTab;
105432}
105433
105434/*
105435** Check to make sure the given table is writable.  If it is not
105436** writable, generate an error message and return 1.  If it is
105437** writable return 0;
105438*/
105439SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
105440  /* A table is not writable under the following circumstances:
105441  **
105442  **   1) It is a virtual table and no implementation of the xUpdate method
105443  **      has been provided, or
105444  **   2) It is a system table (i.e. sqlite_master), this call is not
105445  **      part of a nested parse and writable_schema pragma has not
105446  **      been specified.
105447  **
105448  ** In either case leave an error message in pParse and return non-zero.
105449  */
105450  if( ( IsVirtual(pTab)
105451     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
105452   || ( (pTab->tabFlags & TF_Readonly)!=0
105453     && (pParse->db->flags & SQLITE_WriteSchema)==0
105454     && pParse->nested==0 )
105455  ){
105456    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
105457    return 1;
105458  }
105459
105460#ifndef SQLITE_OMIT_VIEW
105461  if( !viewOk && pTab->pSelect ){
105462    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
105463    return 1;
105464  }
105465#endif
105466  return 0;
105467}
105468
105469
105470#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
105471/*
105472** Evaluate a view and store its result in an ephemeral table.  The
105473** pWhere argument is an optional WHERE clause that restricts the
105474** set of rows in the view that are to be added to the ephemeral table.
105475*/
105476SQLITE_PRIVATE void sqlite3MaterializeView(
105477  Parse *pParse,       /* Parsing context */
105478  Table *pView,        /* View definition */
105479  Expr *pWhere,        /* Optional WHERE clause to be added */
105480  int iCur             /* Cursor number for ephemeral table */
105481){
105482  SelectDest dest;
105483  Select *pSel;
105484  SrcList *pFrom;
105485  sqlite3 *db = pParse->db;
105486  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
105487  pWhere = sqlite3ExprDup(db, pWhere, 0);
105488  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
105489  if( pFrom ){
105490    assert( pFrom->nSrc==1 );
105491    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
105492    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
105493    assert( pFrom->a[0].pOn==0 );
105494    assert( pFrom->a[0].pUsing==0 );
105495  }
105496  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
105497                          SF_IncludeHidden, 0, 0);
105498  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
105499  sqlite3Select(pParse, pSel, &dest);
105500  sqlite3SelectDelete(db, pSel);
105501}
105502#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
105503
105504#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
105505/*
105506** Generate an expression tree to implement the WHERE, ORDER BY,
105507** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
105508**
105509**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
105510**                            \__________________________/
105511**                               pLimitWhere (pInClause)
105512*/
105513SQLITE_PRIVATE Expr *sqlite3LimitWhere(
105514  Parse *pParse,               /* The parser context */
105515  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
105516  Expr *pWhere,                /* The WHERE clause.  May be null */
105517  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
105518  Expr *pLimit,                /* The LIMIT clause.  May be null */
105519  Expr *pOffset,               /* The OFFSET clause.  May be null */
105520  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
105521){
105522  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
105523  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
105524  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
105525  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
105526  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
105527  Select *pSelect = NULL;      /* Complete SELECT tree */
105528
105529  /* Check that there isn't an ORDER BY without a LIMIT clause.
105530  */
105531  if( pOrderBy && (pLimit == 0) ) {
105532    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
105533    goto limit_where_cleanup;
105534  }
105535
105536  /* We only need to generate a select expression if there
105537  ** is a limit/offset term to enforce.
105538  */
105539  if( pLimit == 0 ) {
105540    /* if pLimit is null, pOffset will always be null as well. */
105541    assert( pOffset == 0 );
105542    return pWhere;
105543  }
105544
105545  /* Generate a select expression tree to enforce the limit/offset
105546  ** term for the DELETE or UPDATE statement.  For example:
105547  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
105548  ** becomes:
105549  **   DELETE FROM table_a WHERE rowid IN (
105550  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
105551  **   );
105552  */
105553
105554  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
105555  if( pSelectRowid == 0 ) goto limit_where_cleanup;
105556  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
105557  if( pEList == 0 ) goto limit_where_cleanup;
105558
105559  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
105560  ** and the SELECT subtree. */
105561  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
105562  if( pSelectSrc == 0 ) {
105563    sqlite3ExprListDelete(pParse->db, pEList);
105564    goto limit_where_cleanup;
105565  }
105566
105567  /* generate the SELECT expression tree. */
105568  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
105569                             pOrderBy,0,pLimit,pOffset);
105570  if( pSelect == 0 ) return 0;
105571
105572  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
105573  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
105574  pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0;
105575  sqlite3PExprAddSelect(pParse, pInClause, pSelect);
105576  return pInClause;
105577
105578limit_where_cleanup:
105579  sqlite3ExprDelete(pParse->db, pWhere);
105580  sqlite3ExprListDelete(pParse->db, pOrderBy);
105581  sqlite3ExprDelete(pParse->db, pLimit);
105582  sqlite3ExprDelete(pParse->db, pOffset);
105583  return 0;
105584}
105585#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
105586       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
105587
105588/*
105589** Generate code for a DELETE FROM statement.
105590**
105591**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
105592**                 \________/       \________________/
105593**                  pTabList              pWhere
105594*/
105595SQLITE_PRIVATE void sqlite3DeleteFrom(
105596  Parse *pParse,         /* The parser context */
105597  SrcList *pTabList,     /* The table from which we should delete things */
105598  Expr *pWhere           /* The WHERE clause.  May be null */
105599){
105600  Vdbe *v;               /* The virtual database engine */
105601  Table *pTab;           /* The table from which records will be deleted */
105602  int i;                 /* Loop counter */
105603  WhereInfo *pWInfo;     /* Information about the WHERE clause */
105604  Index *pIdx;           /* For looping over indices of the table */
105605  int iTabCur;           /* Cursor number for the table */
105606  int iDataCur = 0;      /* VDBE cursor for the canonical data source */
105607  int iIdxCur = 0;       /* Cursor number of the first index */
105608  int nIdx;              /* Number of indices */
105609  sqlite3 *db;           /* Main database structure */
105610  AuthContext sContext;  /* Authorization context */
105611  NameContext sNC;       /* Name context to resolve expressions in */
105612  int iDb;               /* Database number */
105613  int memCnt = -1;       /* Memory cell used for change counting */
105614  int rcauth;            /* Value returned by authorization callback */
105615  int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
105616  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
105617  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
105618  Index *pPk;            /* The PRIMARY KEY index on the table */
105619  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
105620  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
105621  int iKey;              /* Memory cell holding key of row to be deleted */
105622  i16 nKey;              /* Number of memory cells in the row key */
105623  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
105624  int iRowSet = 0;       /* Register for rowset of rows to delete */
105625  int addrBypass = 0;    /* Address of jump over the delete logic */
105626  int addrLoop = 0;      /* Top of the delete loop */
105627  int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
105628  int bComplex;          /* True if there are triggers or FKs or
105629                         ** subqueries in the WHERE clause */
105630
105631#ifndef SQLITE_OMIT_TRIGGER
105632  int isView;                  /* True if attempting to delete from a view */
105633  Trigger *pTrigger;           /* List of table triggers, if required */
105634#endif
105635
105636  memset(&sContext, 0, sizeof(sContext));
105637  db = pParse->db;
105638  if( pParse->nErr || db->mallocFailed ){
105639    goto delete_from_cleanup;
105640  }
105641  assert( pTabList->nSrc==1 );
105642
105643  /* Locate the table which we want to delete.  This table has to be
105644  ** put in an SrcList structure because some of the subroutines we
105645  ** will be calling are designed to work with multiple tables and expect
105646  ** an SrcList* parameter instead of just a Table* parameter.
105647  */
105648  pTab = sqlite3SrcListLookup(pParse, pTabList);
105649  if( pTab==0 )  goto delete_from_cleanup;
105650
105651  /* Figure out if we have any triggers and if the table being
105652  ** deleted from is a view
105653  */
105654#ifndef SQLITE_OMIT_TRIGGER
105655  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
105656  isView = pTab->pSelect!=0;
105657  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
105658#else
105659# define pTrigger 0
105660# define isView 0
105661#endif
105662#ifdef SQLITE_OMIT_VIEW
105663# undef isView
105664# define isView 0
105665#endif
105666
105667  /* If pTab is really a view, make sure it has been initialized.
105668  */
105669  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
105670    goto delete_from_cleanup;
105671  }
105672
105673  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
105674    goto delete_from_cleanup;
105675  }
105676  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105677  assert( iDb<db->nDb );
105678  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
105679                            db->aDb[iDb].zDbSName);
105680  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
105681  if( rcauth==SQLITE_DENY ){
105682    goto delete_from_cleanup;
105683  }
105684  assert(!isView || pTrigger);
105685
105686  /* Assign cursor numbers to the table and all its indices.
105687  */
105688  assert( pTabList->nSrc==1 );
105689  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
105690  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
105691    pParse->nTab++;
105692  }
105693
105694  /* Start the view context
105695  */
105696  if( isView ){
105697    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
105698  }
105699
105700  /* Begin generating code.
105701  */
105702  v = sqlite3GetVdbe(pParse);
105703  if( v==0 ){
105704    goto delete_from_cleanup;
105705  }
105706  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
105707  sqlite3BeginWriteOperation(pParse, 1, iDb);
105708
105709  /* If we are trying to delete from a view, realize that view into
105710  ** an ephemeral table.
105711  */
105712#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
105713  if( isView ){
105714    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
105715    iDataCur = iIdxCur = iTabCur;
105716  }
105717#endif
105718
105719  /* Resolve the column names in the WHERE clause.
105720  */
105721  memset(&sNC, 0, sizeof(sNC));
105722  sNC.pParse = pParse;
105723  sNC.pSrcList = pTabList;
105724  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
105725    goto delete_from_cleanup;
105726  }
105727
105728  /* Initialize the counter of the number of rows deleted, if
105729  ** we are counting rows.
105730  */
105731  if( db->flags & SQLITE_CountRows ){
105732    memCnt = ++pParse->nMem;
105733    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
105734  }
105735
105736#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
105737  /* Special case: A DELETE without a WHERE clause deletes everything.
105738  ** It is easier just to erase the whole table. Prior to version 3.6.5,
105739  ** this optimization caused the row change count (the value returned by
105740  ** API function sqlite3_count_changes) to be set incorrectly.
105741  **
105742  ** The "rcauth==SQLITE_OK" terms is the
105743  ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
105744  ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
105745  ** the truncate optimization is disabled and all rows are deleted
105746  ** individually.
105747  */
105748  if( rcauth==SQLITE_OK
105749   && pWhere==0
105750   && !bComplex
105751   && !IsVirtual(pTab)
105752#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
105753   && db->xPreUpdateCallback==0
105754#endif
105755  ){
105756    assert( !isView );
105757    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
105758    if( HasRowid(pTab) ){
105759      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
105760                        pTab->zName, P4_STATIC);
105761    }
105762    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
105763      assert( pIdx->pSchema==pTab->pSchema );
105764      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
105765    }
105766  }else
105767#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
105768  {
105769    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
105770    if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
105771    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
105772    if( HasRowid(pTab) ){
105773      /* For a rowid table, initialize the RowSet to an empty set */
105774      pPk = 0;
105775      nPk = 1;
105776      iRowSet = ++pParse->nMem;
105777      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
105778    }else{
105779      /* For a WITHOUT ROWID table, create an ephemeral table used to
105780      ** hold all primary keys for rows to be deleted. */
105781      pPk = sqlite3PrimaryKeyIndex(pTab);
105782      assert( pPk!=0 );
105783      nPk = pPk->nKeyCol;
105784      iPk = pParse->nMem+1;
105785      pParse->nMem += nPk;
105786      iEphCur = pParse->nTab++;
105787      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
105788      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
105789    }
105790
105791    /* Construct a query to find the rowid or primary key for every row
105792    ** to be deleted, based on the WHERE clause. Set variable eOnePass
105793    ** to indicate the strategy used to implement this delete:
105794    **
105795    **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
105796    **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
105797    **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
105798    */
105799    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
105800    if( pWInfo==0 ) goto delete_from_cleanup;
105801    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
105802    assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
105803    assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
105804
105805    /* Keep track of the number of rows to be deleted */
105806    if( db->flags & SQLITE_CountRows ){
105807      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
105808    }
105809
105810    /* Extract the rowid or primary key for the current row */
105811    if( pPk ){
105812      for(i=0; i<nPk; i++){
105813        assert( pPk->aiColumn[i]>=0 );
105814        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
105815                                        pPk->aiColumn[i], iPk+i);
105816      }
105817      iKey = iPk;
105818    }else{
105819      iKey = pParse->nMem + 1;
105820      iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
105821      if( iKey>pParse->nMem ) pParse->nMem = iKey;
105822    }
105823
105824    if( eOnePass!=ONEPASS_OFF ){
105825      /* For ONEPASS, no need to store the rowid/primary-key. There is only
105826      ** one, so just keep it in its register(s) and fall through to the
105827      ** delete code.  */
105828      nKey = nPk; /* OP_Found will use an unpacked key */
105829      aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
105830      if( aToOpen==0 ){
105831        sqlite3WhereEnd(pWInfo);
105832        goto delete_from_cleanup;
105833      }
105834      memset(aToOpen, 1, nIdx+1);
105835      aToOpen[nIdx+1] = 0;
105836      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
105837      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
105838      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
105839    }else{
105840      if( pPk ){
105841        /* Add the PK key for this row to the temporary table */
105842        iKey = ++pParse->nMem;
105843        nKey = 0;   /* Zero tells OP_Found to use a composite key */
105844        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
105845            sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
105846        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
105847      }else{
105848        /* Add the rowid of the row to be deleted to the RowSet */
105849        nKey = 1;  /* OP_DeferredSeek always uses a single rowid */
105850        sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
105851      }
105852    }
105853
105854    /* If this DELETE cannot use the ONEPASS strategy, this is the
105855    ** end of the WHERE loop */
105856    if( eOnePass!=ONEPASS_OFF ){
105857      addrBypass = sqlite3VdbeMakeLabel(v);
105858    }else{
105859      sqlite3WhereEnd(pWInfo);
105860    }
105861
105862    /* Unless this is a view, open cursors for the table we are
105863    ** deleting from and all its indices. If this is a view, then the
105864    ** only effect this statement has is to fire the INSTEAD OF
105865    ** triggers.
105866    */
105867    if( !isView ){
105868      int iAddrOnce = 0;
105869      if( eOnePass==ONEPASS_MULTI ){
105870        iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
105871      }
105872      testcase( IsVirtual(pTab) );
105873      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
105874                                 iTabCur, aToOpen, &iDataCur, &iIdxCur);
105875      assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
105876      assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
105877      if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
105878    }
105879
105880    /* Set up a loop over the rowids/primary-keys that were found in the
105881    ** where-clause loop above.
105882    */
105883    if( eOnePass!=ONEPASS_OFF ){
105884      assert( nKey==nPk );  /* OP_Found will use an unpacked key */
105885      if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
105886        assert( pPk!=0 || pTab->pSelect!=0 );
105887        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
105888        VdbeCoverage(v);
105889      }
105890    }else if( pPk ){
105891      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
105892      sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
105893      assert( nKey==0 );  /* OP_Found will use a composite key */
105894    }else{
105895      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
105896      VdbeCoverage(v);
105897      assert( nKey==1 );
105898    }
105899
105900    /* Delete the row */
105901#ifndef SQLITE_OMIT_VIRTUALTABLE
105902    if( IsVirtual(pTab) ){
105903      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
105904      sqlite3VtabMakeWritable(pParse, pTab);
105905      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
105906      sqlite3VdbeChangeP5(v, OE_Abort);
105907      assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
105908      sqlite3MayAbort(pParse);
105909      if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
105910        pParse->isMultiWrite = 0;
105911      }
105912    }else
105913#endif
105914    {
105915      int count = (pParse->nested==0);    /* True to count changes */
105916      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
105917          iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
105918    }
105919
105920    /* End of the loop over all rowids/primary-keys. */
105921    if( eOnePass!=ONEPASS_OFF ){
105922      sqlite3VdbeResolveLabel(v, addrBypass);
105923      sqlite3WhereEnd(pWInfo);
105924    }else if( pPk ){
105925      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
105926      sqlite3VdbeJumpHere(v, addrLoop);
105927    }else{
105928      sqlite3VdbeGoto(v, addrLoop);
105929      sqlite3VdbeJumpHere(v, addrLoop);
105930    }
105931  } /* End non-truncate path */
105932
105933  /* Update the sqlite_sequence table by storing the content of the
105934  ** maximum rowid counter values recorded while inserting into
105935  ** autoincrement tables.
105936  */
105937  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
105938    sqlite3AutoincrementEnd(pParse);
105939  }
105940
105941  /* Return the number of rows that were deleted. If this routine is
105942  ** generating code because of a call to sqlite3NestedParse(), do not
105943  ** invoke the callback function.
105944  */
105945  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
105946    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
105947    sqlite3VdbeSetNumCols(v, 1);
105948    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
105949  }
105950
105951delete_from_cleanup:
105952  sqlite3AuthContextPop(&sContext);
105953  sqlite3SrcListDelete(db, pTabList);
105954  sqlite3ExprDelete(db, pWhere);
105955  sqlite3DbFree(db, aToOpen);
105956  return;
105957}
105958/* Make sure "isView" and other macros defined above are undefined. Otherwise
105959** they may interfere with compilation of other functions in this file
105960** (or in another file, if this file becomes part of the amalgamation).  */
105961#ifdef isView
105962 #undef isView
105963#endif
105964#ifdef pTrigger
105965 #undef pTrigger
105966#endif
105967
105968/*
105969** This routine generates VDBE code that causes a single row of a
105970** single table to be deleted.  Both the original table entry and
105971** all indices are removed.
105972**
105973** Preconditions:
105974**
105975**   1.  iDataCur is an open cursor on the btree that is the canonical data
105976**       store for the table.  (This will be either the table itself,
105977**       in the case of a rowid table, or the PRIMARY KEY index in the case
105978**       of a WITHOUT ROWID table.)
105979**
105980**   2.  Read/write cursors for all indices of pTab must be open as
105981**       cursor number iIdxCur+i for the i-th index.
105982**
105983**   3.  The primary key for the row to be deleted must be stored in a
105984**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
105985**       that a search record formed from OP_MakeRecord is contained in the
105986**       single memory location iPk.
105987**
105988** eMode:
105989**   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
105990**   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
105991**   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
105992**   then this function must seek iDataCur to the entry identified by iPk
105993**   and nPk before reading from it.
105994**
105995**   If eMode is ONEPASS_MULTI, then this call is being made as part
105996**   of a ONEPASS delete that affects multiple rows. In this case, if
105997**   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
105998**   iDataCur, then its position should be preserved following the delete
105999**   operation. Or, if iIdxNoSeek is not a valid cursor number, the
106000**   position of iDataCur should be preserved instead.
106001**
106002** iIdxNoSeek:
106003**   If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
106004**   then it identifies an index cursor (from within array of cursors
106005**   starting at iIdxCur) that already points to the index entry to be deleted.
106006**   Except, this optimization is disabled if there are BEFORE triggers since
106007**   the trigger body might have moved the cursor.
106008*/
106009SQLITE_PRIVATE void sqlite3GenerateRowDelete(
106010  Parse *pParse,     /* Parsing context */
106011  Table *pTab,       /* Table containing the row to be deleted */
106012  Trigger *pTrigger, /* List of triggers to (potentially) fire */
106013  int iDataCur,      /* Cursor from which column data is extracted */
106014  int iIdxCur,       /* First index cursor */
106015  int iPk,           /* First memory cell containing the PRIMARY KEY */
106016  i16 nPk,           /* Number of PRIMARY KEY memory cells */
106017  u8 count,          /* If non-zero, increment the row change counter */
106018  u8 onconf,         /* Default ON CONFLICT policy for triggers */
106019  u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
106020  int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
106021){
106022  Vdbe *v = pParse->pVdbe;        /* Vdbe */
106023  int iOld = 0;                   /* First register in OLD.* array */
106024  int iLabel;                     /* Label resolved to end of generated code */
106025  u8 opSeek;                      /* Seek opcode */
106026
106027  /* Vdbe is guaranteed to have been allocated by this stage. */
106028  assert( v );
106029  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
106030                         iDataCur, iIdxCur, iPk, (int)nPk));
106031
106032  /* Seek cursor iCur to the row to delete. If this row no longer exists
106033  ** (this can happen if a trigger program has already deleted it), do
106034  ** not attempt to delete it or fire any DELETE triggers.  */
106035  iLabel = sqlite3VdbeMakeLabel(v);
106036  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
106037  if( eMode==ONEPASS_OFF ){
106038    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
106039    VdbeCoverageIf(v, opSeek==OP_NotExists);
106040    VdbeCoverageIf(v, opSeek==OP_NotFound);
106041  }
106042
106043  /* If there are any triggers to fire, allocate a range of registers to
106044  ** use for the old.* references in the triggers.  */
106045  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
106046    u32 mask;                     /* Mask of OLD.* columns in use */
106047    int iCol;                     /* Iterator used while populating OLD.* */
106048    int addrStart;                /* Start of BEFORE trigger programs */
106049
106050    /* TODO: Could use temporary registers here. Also could attempt to
106051    ** avoid copying the contents of the rowid register.  */
106052    mask = sqlite3TriggerColmask(
106053        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
106054    );
106055    mask |= sqlite3FkOldmask(pParse, pTab);
106056    iOld = pParse->nMem+1;
106057    pParse->nMem += (1 + pTab->nCol);
106058
106059    /* Populate the OLD.* pseudo-table register array. These values will be
106060    ** used by any BEFORE and AFTER triggers that exist.  */
106061    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
106062    for(iCol=0; iCol<pTab->nCol; iCol++){
106063      testcase( mask!=0xffffffff && iCol==31 );
106064      testcase( mask!=0xffffffff && iCol==32 );
106065      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
106066        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
106067      }
106068    }
106069
106070    /* Invoke BEFORE DELETE trigger programs. */
106071    addrStart = sqlite3VdbeCurrentAddr(v);
106072    sqlite3CodeRowTrigger(pParse, pTrigger,
106073        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
106074    );
106075
106076    /* If any BEFORE triggers were coded, then seek the cursor to the
106077    ** row to be deleted again. It may be that the BEFORE triggers moved
106078    ** the cursor or already deleted the row that the cursor was
106079    ** pointing to.
106080    **
106081    ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
106082    ** may have moved that cursor.
106083    */
106084    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
106085      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
106086      VdbeCoverageIf(v, opSeek==OP_NotExists);
106087      VdbeCoverageIf(v, opSeek==OP_NotFound);
106088      testcase( iIdxNoSeek>=0 );
106089      iIdxNoSeek = -1;
106090    }
106091
106092    /* Do FK processing. This call checks that any FK constraints that
106093    ** refer to this table (i.e. constraints attached to other tables)
106094    ** are not violated by deleting this row.  */
106095    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
106096  }
106097
106098  /* Delete the index and table entries. Skip this step if pTab is really
106099  ** a view (in which case the only effect of the DELETE statement is to
106100  ** fire the INSTEAD OF triggers).
106101  **
106102  ** If variable 'count' is non-zero, then this OP_Delete instruction should
106103  ** invoke the update-hook. The pre-update-hook, on the other hand should
106104  ** be invoked unless table pTab is a system table. The difference is that
106105  ** the update-hook is not invoked for rows removed by REPLACE, but the
106106  ** pre-update-hook is.
106107  */
106108  if( pTab->pSelect==0 ){
106109    u8 p5 = 0;
106110    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
106111    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
106112    if( pParse->nested==0 ){
106113      sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
106114    }
106115    if( eMode!=ONEPASS_OFF ){
106116      sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
106117    }
106118    if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
106119      sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
106120    }
106121    if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
106122    sqlite3VdbeChangeP5(v, p5);
106123  }
106124
106125  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
106126  ** handle rows (possibly in other tables) that refer via a foreign key
106127  ** to the row just deleted. */
106128  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
106129
106130  /* Invoke AFTER DELETE trigger programs. */
106131  sqlite3CodeRowTrigger(pParse, pTrigger,
106132      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
106133  );
106134
106135  /* Jump here if the row had already been deleted before any BEFORE
106136  ** trigger programs were invoked. Or if a trigger program throws a
106137  ** RAISE(IGNORE) exception.  */
106138  sqlite3VdbeResolveLabel(v, iLabel);
106139  VdbeModuleComment((v, "END: GenRowDel()"));
106140}
106141
106142/*
106143** This routine generates VDBE code that causes the deletion of all
106144** index entries associated with a single row of a single table, pTab
106145**
106146** Preconditions:
106147**
106148**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
106149**       btree for the table pTab.  (This will be either the table itself
106150**       for rowid tables or to the primary key index for WITHOUT ROWID
106151**       tables.)
106152**
106153**   2.  Read/write cursors for all indices of pTab must be open as
106154**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
106155**       index is the 0-th index.)
106156**
106157**   3.  The "iDataCur" cursor must be already be positioned on the row
106158**       that is to be deleted.
106159*/
106160SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
106161  Parse *pParse,     /* Parsing and code generating context */
106162  Table *pTab,       /* Table containing the row to be deleted */
106163  int iDataCur,      /* Cursor of table holding data. */
106164  int iIdxCur,       /* First index cursor */
106165  int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
106166  int iIdxNoSeek     /* Do not delete from this cursor */
106167){
106168  int i;             /* Index loop counter */
106169  int r1 = -1;       /* Register holding an index key */
106170  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
106171  Index *pIdx;       /* Current index */
106172  Index *pPrior = 0; /* Prior index */
106173  Vdbe *v;           /* The prepared statement under construction */
106174  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
106175
106176  v = pParse->pVdbe;
106177  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
106178  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
106179    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
106180    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
106181    if( pIdx==pPk ) continue;
106182    if( iIdxCur+i==iIdxNoSeek ) continue;
106183    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
106184    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
106185        &iPartIdxLabel, pPrior, r1);
106186    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
106187        pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
106188    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
106189    pPrior = pIdx;
106190  }
106191}
106192
106193/*
106194** Generate code that will assemble an index key and stores it in register
106195** regOut.  The key with be for index pIdx which is an index on pTab.
106196** iCur is the index of a cursor open on the pTab table and pointing to
106197** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
106198** iCur must be the cursor of the PRIMARY KEY index.
106199**
106200** Return a register number which is the first in a block of
106201** registers that holds the elements of the index key.  The
106202** block of registers has already been deallocated by the time
106203** this routine returns.
106204**
106205** If *piPartIdxLabel is not NULL, fill it in with a label and jump
106206** to that label if pIdx is a partial index that should be skipped.
106207** The label should be resolved using sqlite3ResolvePartIdxLabel().
106208** A partial index should be skipped if its WHERE clause evaluates
106209** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
106210** will be set to zero which is an empty label that is ignored by
106211** sqlite3ResolvePartIdxLabel().
106212**
106213** The pPrior and regPrior parameters are used to implement a cache to
106214** avoid unnecessary register loads.  If pPrior is not NULL, then it is
106215** a pointer to a different index for which an index key has just been
106216** computed into register regPrior.  If the current pIdx index is generating
106217** its key into the same sequence of registers and if pPrior and pIdx share
106218** a column in common, then the register corresponding to that column already
106219** holds the correct value and the loading of that register is skipped.
106220** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
106221** on a table with multiple indices, and especially with the ROWID or
106222** PRIMARY KEY columns of the index.
106223*/
106224SQLITE_PRIVATE int sqlite3GenerateIndexKey(
106225  Parse *pParse,       /* Parsing context */
106226  Index *pIdx,         /* The index for which to generate a key */
106227  int iDataCur,        /* Cursor number from which to take column data */
106228  int regOut,          /* Put the new key into this register if not 0 */
106229  int prefixOnly,      /* Compute only a unique prefix of the key */
106230  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
106231  Index *pPrior,       /* Previously generated index key */
106232  int regPrior         /* Register holding previous generated key */
106233){
106234  Vdbe *v = pParse->pVdbe;
106235  int j;
106236  int regBase;
106237  int nCol;
106238
106239  if( piPartIdxLabel ){
106240    if( pIdx->pPartIdxWhere ){
106241      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
106242      pParse->iSelfTab = iDataCur + 1;
106243      sqlite3ExprCachePush(pParse);
106244      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
106245                            SQLITE_JUMPIFNULL);
106246      pParse->iSelfTab = 0;
106247    }else{
106248      *piPartIdxLabel = 0;
106249    }
106250  }
106251  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
106252  regBase = sqlite3GetTempRange(pParse, nCol);
106253  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
106254  for(j=0; j<nCol; j++){
106255    if( pPrior
106256     && pPrior->aiColumn[j]==pIdx->aiColumn[j]
106257     && pPrior->aiColumn[j]!=XN_EXPR
106258    ){
106259      /* This column was already computed by the previous index */
106260      continue;
106261    }
106262    sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
106263    /* If the column affinity is REAL but the number is an integer, then it
106264    ** might be stored in the table as an integer (using a compact
106265    ** representation) then converted to REAL by an OP_RealAffinity opcode.
106266    ** But we are getting ready to store this value back into an index, where
106267    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
106268    ** opcode if it is present */
106269    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
106270  }
106271  if( regOut ){
106272    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
106273    if( pIdx->pTable->pSelect ){
106274      const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
106275      sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
106276    }
106277  }
106278  sqlite3ReleaseTempRange(pParse, regBase, nCol);
106279  return regBase;
106280}
106281
106282/*
106283** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
106284** because it was a partial index, then this routine should be called to
106285** resolve that label.
106286*/
106287SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
106288  if( iLabel ){
106289    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
106290    sqlite3ExprCachePop(pParse);
106291  }
106292}
106293
106294/************** End of delete.c **********************************************/
106295/************** Begin file func.c ********************************************/
106296/*
106297** 2002 February 23
106298**
106299** The author disclaims copyright to this source code.  In place of
106300** a legal notice, here is a blessing:
106301**
106302**    May you do good and not evil.
106303**    May you find forgiveness for yourself and forgive others.
106304**    May you share freely, never taking more than you give.
106305**
106306*************************************************************************
106307** This file contains the C-language implementations for many of the SQL
106308** functions of SQLite.  (Some function, and in particular the date and
106309** time functions, are implemented separately.)
106310*/
106311/* #include "sqliteInt.h" */
106312/* #include <stdlib.h> */
106313/* #include <assert.h> */
106314/* #include "vdbeInt.h" */
106315
106316/*
106317** Return the collating function associated with a function.
106318*/
106319static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
106320  VdbeOp *pOp;
106321  assert( context->pVdbe!=0 );
106322  pOp = &context->pVdbe->aOp[context->iOp-1];
106323  assert( pOp->opcode==OP_CollSeq );
106324  assert( pOp->p4type==P4_COLLSEQ );
106325  return pOp->p4.pColl;
106326}
106327
106328/*
106329** Indicate that the accumulator load should be skipped on this
106330** iteration of the aggregate loop.
106331*/
106332static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
106333  context->skipFlag = 1;
106334}
106335
106336/*
106337** Implementation of the non-aggregate min() and max() functions
106338*/
106339static void minmaxFunc(
106340  sqlite3_context *context,
106341  int argc,
106342  sqlite3_value **argv
106343){
106344  int i;
106345  int mask;    /* 0 for min() or 0xffffffff for max() */
106346  int iBest;
106347  CollSeq *pColl;
106348
106349  assert( argc>1 );
106350  mask = sqlite3_user_data(context)==0 ? 0 : -1;
106351  pColl = sqlite3GetFuncCollSeq(context);
106352  assert( pColl );
106353  assert( mask==-1 || mask==0 );
106354  iBest = 0;
106355  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
106356  for(i=1; i<argc; i++){
106357    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
106358    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
106359      testcase( mask==0 );
106360      iBest = i;
106361    }
106362  }
106363  sqlite3_result_value(context, argv[iBest]);
106364}
106365
106366/*
106367** Return the type of the argument.
106368*/
106369static void typeofFunc(
106370  sqlite3_context *context,
106371  int NotUsed,
106372  sqlite3_value **argv
106373){
106374  static const char *azType[] = { "integer", "real", "text", "blob", "null" };
106375  int i = sqlite3_value_type(argv[0]) - 1;
106376  UNUSED_PARAMETER(NotUsed);
106377  assert( i>=0 && i<ArraySize(azType) );
106378  assert( SQLITE_INTEGER==1 );
106379  assert( SQLITE_FLOAT==2 );
106380  assert( SQLITE_TEXT==3 );
106381  assert( SQLITE_BLOB==4 );
106382  assert( SQLITE_NULL==5 );
106383  /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
106384  ** the datatype code for the initial datatype of the sqlite3_value object
106385  ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
106386  ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
106387  sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
106388}
106389
106390
106391/*
106392** Implementation of the length() function
106393*/
106394static void lengthFunc(
106395  sqlite3_context *context,
106396  int argc,
106397  sqlite3_value **argv
106398){
106399  int len;
106400
106401  assert( argc==1 );
106402  UNUSED_PARAMETER(argc);
106403  switch( sqlite3_value_type(argv[0]) ){
106404    case SQLITE_BLOB:
106405    case SQLITE_INTEGER:
106406    case SQLITE_FLOAT: {
106407      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
106408      break;
106409    }
106410    case SQLITE_TEXT: {
106411      const unsigned char *z = sqlite3_value_text(argv[0]);
106412      if( z==0 ) return;
106413      len = 0;
106414      while( *z ){
106415        len++;
106416        SQLITE_SKIP_UTF8(z);
106417      }
106418      sqlite3_result_int(context, len);
106419      break;
106420    }
106421    default: {
106422      sqlite3_result_null(context);
106423      break;
106424    }
106425  }
106426}
106427
106428/*
106429** Implementation of the abs() function.
106430**
106431** IMP: R-23979-26855 The abs(X) function returns the absolute value of
106432** the numeric argument X.
106433*/
106434static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106435  assert( argc==1 );
106436  UNUSED_PARAMETER(argc);
106437  switch( sqlite3_value_type(argv[0]) ){
106438    case SQLITE_INTEGER: {
106439      i64 iVal = sqlite3_value_int64(argv[0]);
106440      if( iVal<0 ){
106441        if( iVal==SMALLEST_INT64 ){
106442          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
106443          ** then abs(X) throws an integer overflow error since there is no
106444          ** equivalent positive 64-bit two complement value. */
106445          sqlite3_result_error(context, "integer overflow", -1);
106446          return;
106447        }
106448        iVal = -iVal;
106449      }
106450      sqlite3_result_int64(context, iVal);
106451      break;
106452    }
106453    case SQLITE_NULL: {
106454      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
106455      sqlite3_result_null(context);
106456      break;
106457    }
106458    default: {
106459      /* Because sqlite3_value_double() returns 0.0 if the argument is not
106460      ** something that can be converted into a number, we have:
106461      ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
106462      ** that cannot be converted to a numeric value.
106463      */
106464      double rVal = sqlite3_value_double(argv[0]);
106465      if( rVal<0 ) rVal = -rVal;
106466      sqlite3_result_double(context, rVal);
106467      break;
106468    }
106469  }
106470}
106471
106472/*
106473** Implementation of the instr() function.
106474**
106475** instr(haystack,needle) finds the first occurrence of needle
106476** in haystack and returns the number of previous characters plus 1,
106477** or 0 if needle does not occur within haystack.
106478**
106479** If both haystack and needle are BLOBs, then the result is one more than
106480** the number of bytes in haystack prior to the first occurrence of needle,
106481** or 0 if needle never occurs in haystack.
106482*/
106483static void instrFunc(
106484  sqlite3_context *context,
106485  int argc,
106486  sqlite3_value **argv
106487){
106488  const unsigned char *zHaystack;
106489  const unsigned char *zNeedle;
106490  int nHaystack;
106491  int nNeedle;
106492  int typeHaystack, typeNeedle;
106493  int N = 1;
106494  int isText;
106495
106496  UNUSED_PARAMETER(argc);
106497  typeHaystack = sqlite3_value_type(argv[0]);
106498  typeNeedle = sqlite3_value_type(argv[1]);
106499  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
106500  nHaystack = sqlite3_value_bytes(argv[0]);
106501  nNeedle = sqlite3_value_bytes(argv[1]);
106502  if( nNeedle>0 ){
106503    if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
106504      zHaystack = sqlite3_value_blob(argv[0]);
106505      zNeedle = sqlite3_value_blob(argv[1]);
106506      isText = 0;
106507    }else{
106508      zHaystack = sqlite3_value_text(argv[0]);
106509      zNeedle = sqlite3_value_text(argv[1]);
106510      isText = 1;
106511    }
106512    if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
106513    while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
106514      N++;
106515      do{
106516        nHaystack--;
106517        zHaystack++;
106518      }while( isText && (zHaystack[0]&0xc0)==0x80 );
106519    }
106520    if( nNeedle>nHaystack ) N = 0;
106521  }
106522  sqlite3_result_int(context, N);
106523}
106524
106525/*
106526** Implementation of the printf() function.
106527*/
106528static void printfFunc(
106529  sqlite3_context *context,
106530  int argc,
106531  sqlite3_value **argv
106532){
106533  PrintfArguments x;
106534  StrAccum str;
106535  const char *zFormat;
106536  int n;
106537  sqlite3 *db = sqlite3_context_db_handle(context);
106538
106539  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
106540    x.nArg = argc-1;
106541    x.nUsed = 0;
106542    x.apArg = argv+1;
106543    sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
106544    str.printfFlags = SQLITE_PRINTF_SQLFUNC;
106545    sqlite3XPrintf(&str, zFormat, &x);
106546    n = str.nChar;
106547    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
106548                        SQLITE_DYNAMIC);
106549  }
106550}
106551
106552/*
106553** Implementation of the substr() function.
106554**
106555** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
106556** p1 is 1-indexed.  So substr(x,1,1) returns the first character
106557** of x.  If x is text, then we actually count UTF-8 characters.
106558** If x is a blob, then we count bytes.
106559**
106560** If p1 is negative, then we begin abs(p1) from the end of x[].
106561**
106562** If p2 is negative, return the p2 characters preceding p1.
106563*/
106564static void substrFunc(
106565  sqlite3_context *context,
106566  int argc,
106567  sqlite3_value **argv
106568){
106569  const unsigned char *z;
106570  const unsigned char *z2;
106571  int len;
106572  int p0type;
106573  i64 p1, p2;
106574  int negP2 = 0;
106575
106576  assert( argc==3 || argc==2 );
106577  if( sqlite3_value_type(argv[1])==SQLITE_NULL
106578   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
106579  ){
106580    return;
106581  }
106582  p0type = sqlite3_value_type(argv[0]);
106583  p1 = sqlite3_value_int(argv[1]);
106584  if( p0type==SQLITE_BLOB ){
106585    len = sqlite3_value_bytes(argv[0]);
106586    z = sqlite3_value_blob(argv[0]);
106587    if( z==0 ) return;
106588    assert( len==sqlite3_value_bytes(argv[0]) );
106589  }else{
106590    z = sqlite3_value_text(argv[0]);
106591    if( z==0 ) return;
106592    len = 0;
106593    if( p1<0 ){
106594      for(z2=z; *z2; len++){
106595        SQLITE_SKIP_UTF8(z2);
106596      }
106597    }
106598  }
106599#ifdef SQLITE_SUBSTR_COMPATIBILITY
106600  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
106601  ** as substr(X,1,N) - it returns the first N characters of X.  This
106602  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
106603  ** from 2009-02-02 for compatibility of applications that exploited the
106604  ** old buggy behavior. */
106605  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
106606#endif
106607  if( argc==3 ){
106608    p2 = sqlite3_value_int(argv[2]);
106609    if( p2<0 ){
106610      p2 = -p2;
106611      negP2 = 1;
106612    }
106613  }else{
106614    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
106615  }
106616  if( p1<0 ){
106617    p1 += len;
106618    if( p1<0 ){
106619      p2 += p1;
106620      if( p2<0 ) p2 = 0;
106621      p1 = 0;
106622    }
106623  }else if( p1>0 ){
106624    p1--;
106625  }else if( p2>0 ){
106626    p2--;
106627  }
106628  if( negP2 ){
106629    p1 -= p2;
106630    if( p1<0 ){
106631      p2 += p1;
106632      p1 = 0;
106633    }
106634  }
106635  assert( p1>=0 && p2>=0 );
106636  if( p0type!=SQLITE_BLOB ){
106637    while( *z && p1 ){
106638      SQLITE_SKIP_UTF8(z);
106639      p1--;
106640    }
106641    for(z2=z; *z2 && p2; p2--){
106642      SQLITE_SKIP_UTF8(z2);
106643    }
106644    sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
106645                          SQLITE_UTF8);
106646  }else{
106647    if( p1+p2>len ){
106648      p2 = len-p1;
106649      if( p2<0 ) p2 = 0;
106650    }
106651    sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
106652  }
106653}
106654
106655/*
106656** Implementation of the round() function
106657*/
106658#ifndef SQLITE_OMIT_FLOATING_POINT
106659static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106660  int n = 0;
106661  double r;
106662  char *zBuf;
106663  assert( argc==1 || argc==2 );
106664  if( argc==2 ){
106665    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
106666    n = sqlite3_value_int(argv[1]);
106667    if( n>30 ) n = 30;
106668    if( n<0 ) n = 0;
106669  }
106670  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
106671  r = sqlite3_value_double(argv[0]);
106672  /* If Y==0 and X will fit in a 64-bit int,
106673  ** handle the rounding directly,
106674  ** otherwise use printf.
106675  */
106676  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
106677    r = (double)((sqlite_int64)(r+0.5));
106678  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
106679    r = -(double)((sqlite_int64)((-r)+0.5));
106680  }else{
106681    zBuf = sqlite3_mprintf("%.*f",n,r);
106682    if( zBuf==0 ){
106683      sqlite3_result_error_nomem(context);
106684      return;
106685    }
106686    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
106687    sqlite3_free(zBuf);
106688  }
106689  sqlite3_result_double(context, r);
106690}
106691#endif
106692
106693/*
106694** Allocate nByte bytes of space using sqlite3Malloc(). If the
106695** allocation fails, call sqlite3_result_error_nomem() to notify
106696** the database handle that malloc() has failed and return NULL.
106697** If nByte is larger than the maximum string or blob length, then
106698** raise an SQLITE_TOOBIG exception and return NULL.
106699*/
106700static void *contextMalloc(sqlite3_context *context, i64 nByte){
106701  char *z;
106702  sqlite3 *db = sqlite3_context_db_handle(context);
106703  assert( nByte>0 );
106704  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
106705  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
106706  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
106707    sqlite3_result_error_toobig(context);
106708    z = 0;
106709  }else{
106710    z = sqlite3Malloc(nByte);
106711    if( !z ){
106712      sqlite3_result_error_nomem(context);
106713    }
106714  }
106715  return z;
106716}
106717
106718/*
106719** Implementation of the upper() and lower() SQL functions.
106720*/
106721static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106722  char *z1;
106723  const char *z2;
106724  int i, n;
106725  UNUSED_PARAMETER(argc);
106726  z2 = (char*)sqlite3_value_text(argv[0]);
106727  n = sqlite3_value_bytes(argv[0]);
106728  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
106729  assert( z2==(char*)sqlite3_value_text(argv[0]) );
106730  if( z2 ){
106731    z1 = contextMalloc(context, ((i64)n)+1);
106732    if( z1 ){
106733      for(i=0; i<n; i++){
106734        z1[i] = (char)sqlite3Toupper(z2[i]);
106735      }
106736      sqlite3_result_text(context, z1, n, sqlite3_free);
106737    }
106738  }
106739}
106740static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
106741  char *z1;
106742  const char *z2;
106743  int i, n;
106744  UNUSED_PARAMETER(argc);
106745  z2 = (char*)sqlite3_value_text(argv[0]);
106746  n = sqlite3_value_bytes(argv[0]);
106747  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
106748  assert( z2==(char*)sqlite3_value_text(argv[0]) );
106749  if( z2 ){
106750    z1 = contextMalloc(context, ((i64)n)+1);
106751    if( z1 ){
106752      for(i=0; i<n; i++){
106753        z1[i] = sqlite3Tolower(z2[i]);
106754      }
106755      sqlite3_result_text(context, z1, n, sqlite3_free);
106756    }
106757  }
106758}
106759
106760/*
106761** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
106762** as VDBE code so that unused argument values do not have to be computed.
106763** However, we still need some kind of function implementation for this
106764** routines in the function table.  The noopFunc macro provides this.
106765** noopFunc will never be called so it doesn't matter what the implementation
106766** is.  We might as well use the "version()" function as a substitute.
106767*/
106768#define noopFunc versionFunc   /* Substitute function - never called */
106769
106770/*
106771** Implementation of random().  Return a random integer.
106772*/
106773static void randomFunc(
106774  sqlite3_context *context,
106775  int NotUsed,
106776  sqlite3_value **NotUsed2
106777){
106778  sqlite_int64 r;
106779  UNUSED_PARAMETER2(NotUsed, NotUsed2);
106780  sqlite3_randomness(sizeof(r), &r);
106781  if( r<0 ){
106782    /* We need to prevent a random number of 0x8000000000000000
106783    ** (or -9223372036854775808) since when you do abs() of that
106784    ** number of you get the same value back again.  To do this
106785    ** in a way that is testable, mask the sign bit off of negative
106786    ** values, resulting in a positive value.  Then take the
106787    ** 2s complement of that positive value.  The end result can
106788    ** therefore be no less than -9223372036854775807.
106789    */
106790    r = -(r & LARGEST_INT64);
106791  }
106792  sqlite3_result_int64(context, r);
106793}
106794
106795/*
106796** Implementation of randomblob(N).  Return a random blob
106797** that is N bytes long.
106798*/
106799static void randomBlob(
106800  sqlite3_context *context,
106801  int argc,
106802  sqlite3_value **argv
106803){
106804  int n;
106805  unsigned char *p;
106806  assert( argc==1 );
106807  UNUSED_PARAMETER(argc);
106808  n = sqlite3_value_int(argv[0]);
106809  if( n<1 ){
106810    n = 1;
106811  }
106812  p = contextMalloc(context, n);
106813  if( p ){
106814    sqlite3_randomness(n, p);
106815    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
106816  }
106817}
106818
106819/*
106820** Implementation of the last_insert_rowid() SQL function.  The return
106821** value is the same as the sqlite3_last_insert_rowid() API function.
106822*/
106823static void last_insert_rowid(
106824  sqlite3_context *context,
106825  int NotUsed,
106826  sqlite3_value **NotUsed2
106827){
106828  sqlite3 *db = sqlite3_context_db_handle(context);
106829  UNUSED_PARAMETER2(NotUsed, NotUsed2);
106830  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
106831  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
106832  ** function. */
106833  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
106834}
106835
106836/*
106837** Implementation of the changes() SQL function.
106838**
106839** IMP: R-62073-11209 The changes() SQL function is a wrapper
106840** around the sqlite3_changes() C/C++ function and hence follows the same
106841** rules for counting changes.
106842*/
106843static void changes(
106844  sqlite3_context *context,
106845  int NotUsed,
106846  sqlite3_value **NotUsed2
106847){
106848  sqlite3 *db = sqlite3_context_db_handle(context);
106849  UNUSED_PARAMETER2(NotUsed, NotUsed2);
106850  sqlite3_result_int(context, sqlite3_changes(db));
106851}
106852
106853/*
106854** Implementation of the total_changes() SQL function.  The return value is
106855** the same as the sqlite3_total_changes() API function.
106856*/
106857static void total_changes(
106858  sqlite3_context *context,
106859  int NotUsed,
106860  sqlite3_value **NotUsed2
106861){
106862  sqlite3 *db = sqlite3_context_db_handle(context);
106863  UNUSED_PARAMETER2(NotUsed, NotUsed2);
106864  /* IMP: R-52756-41993 This function is a wrapper around the
106865  ** sqlite3_total_changes() C/C++ interface. */
106866  sqlite3_result_int(context, sqlite3_total_changes(db));
106867}
106868
106869/*
106870** A structure defining how to do GLOB-style comparisons.
106871*/
106872struct compareInfo {
106873  u8 matchAll;          /* "*" or "%" */
106874  u8 matchOne;          /* "?" or "_" */
106875  u8 matchSet;          /* "[" or 0 */
106876  u8 noCase;            /* true to ignore case differences */
106877};
106878
106879/*
106880** For LIKE and GLOB matching on EBCDIC machines, assume that every
106881** character is exactly one byte in size.  Also, provde the Utf8Read()
106882** macro for fast reading of the next character in the common case where
106883** the next character is ASCII.
106884*/
106885#if defined(SQLITE_EBCDIC)
106886# define sqlite3Utf8Read(A)        (*((*A)++))
106887# define Utf8Read(A)               (*(A++))
106888#else
106889# define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
106890#endif
106891
106892static const struct compareInfo globInfo = { '*', '?', '[', 0 };
106893/* The correct SQL-92 behavior is for the LIKE operator to ignore
106894** case.  Thus  'a' LIKE 'A' would be true. */
106895static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
106896/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
106897** is case sensitive causing 'a' LIKE 'A' to be false */
106898static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
106899
106900/*
106901** Possible error returns from patternMatch()
106902*/
106903#define SQLITE_MATCH             0
106904#define SQLITE_NOMATCH           1
106905#define SQLITE_NOWILDCARDMATCH   2
106906
106907/*
106908** Compare two UTF-8 strings for equality where the first string is
106909** a GLOB or LIKE expression.  Return values:
106910**
106911**    SQLITE_MATCH:            Match
106912**    SQLITE_NOMATCH:          No match
106913**    SQLITE_NOWILDCARDMATCH:  No match in spite of having * or % wildcards.
106914**
106915** Globbing rules:
106916**
106917**      '*'       Matches any sequence of zero or more characters.
106918**
106919**      '?'       Matches exactly one character.
106920**
106921**     [...]      Matches one character from the enclosed list of
106922**                characters.
106923**
106924**     [^...]     Matches one character not in the enclosed list.
106925**
106926** With the [...] and [^...] matching, a ']' character can be included
106927** in the list by making it the first character after '[' or '^'.  A
106928** range of characters can be specified using '-'.  Example:
106929** "[a-z]" matches any single lower-case letter.  To match a '-', make
106930** it the last character in the list.
106931**
106932** Like matching rules:
106933**
106934**      '%'       Matches any sequence of zero or more characters
106935**
106936***     '_'       Matches any one character
106937**
106938**      Ec        Where E is the "esc" character and c is any other
106939**                character, including '%', '_', and esc, match exactly c.
106940**
106941** The comments within this routine usually assume glob matching.
106942**
106943** This routine is usually quick, but can be N**2 in the worst case.
106944*/
106945static int patternCompare(
106946  const u8 *zPattern,              /* The glob pattern */
106947  const u8 *zString,               /* The string to compare against the glob */
106948  const struct compareInfo *pInfo, /* Information about how to do the compare */
106949  u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
106950){
106951  u32 c, c2;                       /* Next pattern and input string chars */
106952  u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
106953  u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
106954  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
106955  const u8 *zEscaped = 0;          /* One past the last escaped input char */
106956
106957  while( (c = Utf8Read(zPattern))!=0 ){
106958    if( c==matchAll ){  /* Match "*" */
106959      /* Skip over multiple "*" characters in the pattern.  If there
106960      ** are also "?" characters, skip those as well, but consume a
106961      ** single character of the input string for each "?" skipped */
106962      while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
106963        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
106964          return SQLITE_NOWILDCARDMATCH;
106965        }
106966      }
106967      if( c==0 ){
106968        return SQLITE_MATCH;   /* "*" at the end of the pattern matches */
106969      }else if( c==matchOther ){
106970        if( pInfo->matchSet==0 ){
106971          c = sqlite3Utf8Read(&zPattern);
106972          if( c==0 ) return SQLITE_NOWILDCARDMATCH;
106973        }else{
106974          /* "[...]" immediately follows the "*".  We have to do a slow
106975          ** recursive search in this case, but it is an unusual case. */
106976          assert( matchOther<0x80 );  /* '[' is a single-byte character */
106977          while( *zString ){
106978            int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
106979            if( bMatch!=SQLITE_NOMATCH ) return bMatch;
106980            SQLITE_SKIP_UTF8(zString);
106981          }
106982          return SQLITE_NOWILDCARDMATCH;
106983        }
106984      }
106985
106986      /* At this point variable c contains the first character of the
106987      ** pattern string past the "*".  Search in the input string for the
106988      ** first matching character and recursively continue the match from
106989      ** that point.
106990      **
106991      ** For a case-insensitive search, set variable cx to be the same as
106992      ** c but in the other case and search the input string for either
106993      ** c or cx.
106994      */
106995      if( c<=0x80 ){
106996        u32 cx;
106997        int bMatch;
106998        if( noCase ){
106999          cx = sqlite3Toupper(c);
107000          c = sqlite3Tolower(c);
107001        }else{
107002          cx = c;
107003        }
107004        while( (c2 = *(zString++))!=0 ){
107005          if( c2!=c && c2!=cx ) continue;
107006          bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
107007          if( bMatch!=SQLITE_NOMATCH ) return bMatch;
107008        }
107009      }else{
107010        int bMatch;
107011        while( (c2 = Utf8Read(zString))!=0 ){
107012          if( c2!=c ) continue;
107013          bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
107014          if( bMatch!=SQLITE_NOMATCH ) return bMatch;
107015        }
107016      }
107017      return SQLITE_NOWILDCARDMATCH;
107018    }
107019    if( c==matchOther ){
107020      if( pInfo->matchSet==0 ){
107021        c = sqlite3Utf8Read(&zPattern);
107022        if( c==0 ) return SQLITE_NOMATCH;
107023        zEscaped = zPattern;
107024      }else{
107025        u32 prior_c = 0;
107026        int seen = 0;
107027        int invert = 0;
107028        c = sqlite3Utf8Read(&zString);
107029        if( c==0 ) return SQLITE_NOMATCH;
107030        c2 = sqlite3Utf8Read(&zPattern);
107031        if( c2=='^' ){
107032          invert = 1;
107033          c2 = sqlite3Utf8Read(&zPattern);
107034        }
107035        if( c2==']' ){
107036          if( c==']' ) seen = 1;
107037          c2 = sqlite3Utf8Read(&zPattern);
107038        }
107039        while( c2 && c2!=']' ){
107040          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
107041            c2 = sqlite3Utf8Read(&zPattern);
107042            if( c>=prior_c && c<=c2 ) seen = 1;
107043            prior_c = 0;
107044          }else{
107045            if( c==c2 ){
107046              seen = 1;
107047            }
107048            prior_c = c2;
107049          }
107050          c2 = sqlite3Utf8Read(&zPattern);
107051        }
107052        if( c2==0 || (seen ^ invert)==0 ){
107053          return SQLITE_NOMATCH;
107054        }
107055        continue;
107056      }
107057    }
107058    c2 = Utf8Read(zString);
107059    if( c==c2 ) continue;
107060    if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
107061      continue;
107062    }
107063    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
107064    return SQLITE_NOMATCH;
107065  }
107066  return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
107067}
107068
107069/*
107070** The sqlite3_strglob() interface.  Return 0 on a match (like strcmp()) and
107071** non-zero if there is no match.
107072*/
107073SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
107074  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
107075}
107076
107077/*
107078** The sqlite3_strlike() interface.  Return 0 on a match and non-zero for
107079** a miss - like strcmp().
107080*/
107081SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
107082  return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
107083}
107084
107085/*
107086** Count the number of times that the LIKE operator (or GLOB which is
107087** just a variation of LIKE) gets called.  This is used for testing
107088** only.
107089*/
107090#ifdef SQLITE_TEST
107091SQLITE_API int sqlite3_like_count = 0;
107092#endif
107093
107094
107095/*
107096** Implementation of the like() SQL function.  This function implements
107097** the build-in LIKE operator.  The first argument to the function is the
107098** pattern and the second argument is the string.  So, the SQL statements:
107099**
107100**       A LIKE B
107101**
107102** is implemented as like(B,A).
107103**
107104** This same function (with a different compareInfo structure) computes
107105** the GLOB operator.
107106*/
107107static void likeFunc(
107108  sqlite3_context *context,
107109  int argc,
107110  sqlite3_value **argv
107111){
107112  const unsigned char *zA, *zB;
107113  u32 escape;
107114  int nPat;
107115  sqlite3 *db = sqlite3_context_db_handle(context);
107116  struct compareInfo *pInfo = sqlite3_user_data(context);
107117
107118#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
107119  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
107120   || sqlite3_value_type(argv[1])==SQLITE_BLOB
107121  ){
107122#ifdef SQLITE_TEST
107123    sqlite3_like_count++;
107124#endif
107125    sqlite3_result_int(context, 0);
107126    return;
107127  }
107128#endif
107129  zB = sqlite3_value_text(argv[0]);
107130  zA = sqlite3_value_text(argv[1]);
107131
107132  /* Limit the length of the LIKE or GLOB pattern to avoid problems
107133  ** of deep recursion and N*N behavior in patternCompare().
107134  */
107135  nPat = sqlite3_value_bytes(argv[0]);
107136  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
107137  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
107138  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
107139    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
107140    return;
107141  }
107142  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
107143
107144  if( argc==3 ){
107145    /* The escape character string must consist of a single UTF-8 character.
107146    ** Otherwise, return an error.
107147    */
107148    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
107149    if( zEsc==0 ) return;
107150    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
107151      sqlite3_result_error(context,
107152          "ESCAPE expression must be a single character", -1);
107153      return;
107154    }
107155    escape = sqlite3Utf8Read(&zEsc);
107156  }else{
107157    escape = pInfo->matchSet;
107158  }
107159  if( zA && zB ){
107160#ifdef SQLITE_TEST
107161    sqlite3_like_count++;
107162#endif
107163    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
107164  }
107165}
107166
107167/*
107168** Implementation of the NULLIF(x,y) function.  The result is the first
107169** argument if the arguments are different.  The result is NULL if the
107170** arguments are equal to each other.
107171*/
107172static void nullifFunc(
107173  sqlite3_context *context,
107174  int NotUsed,
107175  sqlite3_value **argv
107176){
107177  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
107178  UNUSED_PARAMETER(NotUsed);
107179  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
107180    sqlite3_result_value(context, argv[0]);
107181  }
107182}
107183
107184/*
107185** Implementation of the sqlite_version() function.  The result is the version
107186** of the SQLite library that is running.
107187*/
107188static void versionFunc(
107189  sqlite3_context *context,
107190  int NotUsed,
107191  sqlite3_value **NotUsed2
107192){
107193  UNUSED_PARAMETER2(NotUsed, NotUsed2);
107194  /* IMP: R-48699-48617 This function is an SQL wrapper around the
107195  ** sqlite3_libversion() C-interface. */
107196  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
107197}
107198
107199/*
107200** Implementation of the sqlite_source_id() function. The result is a string
107201** that identifies the particular version of the source code used to build
107202** SQLite.
107203*/
107204static void sourceidFunc(
107205  sqlite3_context *context,
107206  int NotUsed,
107207  sqlite3_value **NotUsed2
107208){
107209  UNUSED_PARAMETER2(NotUsed, NotUsed2);
107210  /* IMP: R-24470-31136 This function is an SQL wrapper around the
107211  ** sqlite3_sourceid() C interface. */
107212  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
107213}
107214
107215/*
107216** Implementation of the sqlite_log() function.  This is a wrapper around
107217** sqlite3_log().  The return value is NULL.  The function exists purely for
107218** its side-effects.
107219*/
107220static void errlogFunc(
107221  sqlite3_context *context,
107222  int argc,
107223  sqlite3_value **argv
107224){
107225  UNUSED_PARAMETER(argc);
107226  UNUSED_PARAMETER(context);
107227  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
107228}
107229
107230/*
107231** Implementation of the sqlite_compileoption_used() function.
107232** The result is an integer that identifies if the compiler option
107233** was used to build SQLite.
107234*/
107235#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107236static void compileoptionusedFunc(
107237  sqlite3_context *context,
107238  int argc,
107239  sqlite3_value **argv
107240){
107241  const char *zOptName;
107242  assert( argc==1 );
107243  UNUSED_PARAMETER(argc);
107244  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
107245  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
107246  ** function.
107247  */
107248  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
107249    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
107250  }
107251}
107252#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107253
107254/*
107255** Implementation of the sqlite_compileoption_get() function.
107256** The result is a string that identifies the compiler options
107257** used to build SQLite.
107258*/
107259#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
107260static void compileoptiongetFunc(
107261  sqlite3_context *context,
107262  int argc,
107263  sqlite3_value **argv
107264){
107265  int n;
107266  assert( argc==1 );
107267  UNUSED_PARAMETER(argc);
107268  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
107269  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
107270  */
107271  n = sqlite3_value_int(argv[0]);
107272  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
107273}
107274#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
107275
107276/* Array for converting from half-bytes (nybbles) into ASCII hex
107277** digits. */
107278static const char hexdigits[] = {
107279  '0', '1', '2', '3', '4', '5', '6', '7',
107280  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
107281};
107282
107283/*
107284** Implementation of the QUOTE() function.  This function takes a single
107285** argument.  If the argument is numeric, the return value is the same as
107286** the argument.  If the argument is NULL, the return value is the string
107287** "NULL".  Otherwise, the argument is enclosed in single quotes with
107288** single-quote escapes.
107289*/
107290static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
107291  assert( argc==1 );
107292  UNUSED_PARAMETER(argc);
107293  switch( sqlite3_value_type(argv[0]) ){
107294    case SQLITE_FLOAT: {
107295      double r1, r2;
107296      char zBuf[50];
107297      r1 = sqlite3_value_double(argv[0]);
107298      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
107299      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
107300      if( r1!=r2 ){
107301        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
107302      }
107303      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
107304      break;
107305    }
107306    case SQLITE_INTEGER: {
107307      sqlite3_result_value(context, argv[0]);
107308      break;
107309    }
107310    case SQLITE_BLOB: {
107311      char *zText = 0;
107312      char const *zBlob = sqlite3_value_blob(argv[0]);
107313      int nBlob = sqlite3_value_bytes(argv[0]);
107314      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
107315      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
107316      if( zText ){
107317        int i;
107318        for(i=0; i<nBlob; i++){
107319          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
107320          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
107321        }
107322        zText[(nBlob*2)+2] = '\'';
107323        zText[(nBlob*2)+3] = '\0';
107324        zText[0] = 'X';
107325        zText[1] = '\'';
107326        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
107327        sqlite3_free(zText);
107328      }
107329      break;
107330    }
107331    case SQLITE_TEXT: {
107332      int i,j;
107333      u64 n;
107334      const unsigned char *zArg = sqlite3_value_text(argv[0]);
107335      char *z;
107336
107337      if( zArg==0 ) return;
107338      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
107339      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
107340      if( z ){
107341        z[0] = '\'';
107342        for(i=0, j=1; zArg[i]; i++){
107343          z[j++] = zArg[i];
107344          if( zArg[i]=='\'' ){
107345            z[j++] = '\'';
107346          }
107347        }
107348        z[j++] = '\'';
107349        z[j] = 0;
107350        sqlite3_result_text(context, z, j, sqlite3_free);
107351      }
107352      break;
107353    }
107354    default: {
107355      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
107356      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
107357      break;
107358    }
107359  }
107360}
107361
107362/*
107363** The unicode() function.  Return the integer unicode code-point value
107364** for the first character of the input string.
107365*/
107366static void unicodeFunc(
107367  sqlite3_context *context,
107368  int argc,
107369  sqlite3_value **argv
107370){
107371  const unsigned char *z = sqlite3_value_text(argv[0]);
107372  (void)argc;
107373  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
107374}
107375
107376/*
107377** The char() function takes zero or more arguments, each of which is
107378** an integer.  It constructs a string where each character of the string
107379** is the unicode character for the corresponding integer argument.
107380*/
107381static void charFunc(
107382  sqlite3_context *context,
107383  int argc,
107384  sqlite3_value **argv
107385){
107386  unsigned char *z, *zOut;
107387  int i;
107388  zOut = z = sqlite3_malloc64( argc*4+1 );
107389  if( z==0 ){
107390    sqlite3_result_error_nomem(context);
107391    return;
107392  }
107393  for(i=0; i<argc; i++){
107394    sqlite3_int64 x;
107395    unsigned c;
107396    x = sqlite3_value_int64(argv[i]);
107397    if( x<0 || x>0x10ffff ) x = 0xfffd;
107398    c = (unsigned)(x & 0x1fffff);
107399    if( c<0x00080 ){
107400      *zOut++ = (u8)(c&0xFF);
107401    }else if( c<0x00800 ){
107402      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
107403      *zOut++ = 0x80 + (u8)(c & 0x3F);
107404    }else if( c<0x10000 ){
107405      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
107406      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
107407      *zOut++ = 0x80 + (u8)(c & 0x3F);
107408    }else{
107409      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
107410      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
107411      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
107412      *zOut++ = 0x80 + (u8)(c & 0x3F);
107413    }                                                    \
107414  }
107415  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
107416}
107417
107418/*
107419** The hex() function.  Interpret the argument as a blob.  Return
107420** a hexadecimal rendering as text.
107421*/
107422static void hexFunc(
107423  sqlite3_context *context,
107424  int argc,
107425  sqlite3_value **argv
107426){
107427  int i, n;
107428  const unsigned char *pBlob;
107429  char *zHex, *z;
107430  assert( argc==1 );
107431  UNUSED_PARAMETER(argc);
107432  pBlob = sqlite3_value_blob(argv[0]);
107433  n = sqlite3_value_bytes(argv[0]);
107434  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
107435  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
107436  if( zHex ){
107437    for(i=0; i<n; i++, pBlob++){
107438      unsigned char c = *pBlob;
107439      *(z++) = hexdigits[(c>>4)&0xf];
107440      *(z++) = hexdigits[c&0xf];
107441    }
107442    *z = 0;
107443    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
107444  }
107445}
107446
107447/*
107448** The zeroblob(N) function returns a zero-filled blob of size N bytes.
107449*/
107450static void zeroblobFunc(
107451  sqlite3_context *context,
107452  int argc,
107453  sqlite3_value **argv
107454){
107455  i64 n;
107456  int rc;
107457  assert( argc==1 );
107458  UNUSED_PARAMETER(argc);
107459  n = sqlite3_value_int64(argv[0]);
107460  if( n<0 ) n = 0;
107461  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
107462  if( rc ){
107463    sqlite3_result_error_code(context, rc);
107464  }
107465}
107466
107467/*
107468** The replace() function.  Three arguments are all strings: call
107469** them A, B, and C. The result is also a string which is derived
107470** from A by replacing every occurrence of B with C.  The match
107471** must be exact.  Collating sequences are not used.
107472*/
107473static void replaceFunc(
107474  sqlite3_context *context,
107475  int argc,
107476  sqlite3_value **argv
107477){
107478  const unsigned char *zStr;        /* The input string A */
107479  const unsigned char *zPattern;    /* The pattern string B */
107480  const unsigned char *zRep;        /* The replacement string C */
107481  unsigned char *zOut;              /* The output */
107482  int nStr;                /* Size of zStr */
107483  int nPattern;            /* Size of zPattern */
107484  int nRep;                /* Size of zRep */
107485  i64 nOut;                /* Maximum size of zOut */
107486  int loopLimit;           /* Last zStr[] that might match zPattern[] */
107487  int i, j;                /* Loop counters */
107488
107489  assert( argc==3 );
107490  UNUSED_PARAMETER(argc);
107491  zStr = sqlite3_value_text(argv[0]);
107492  if( zStr==0 ) return;
107493  nStr = sqlite3_value_bytes(argv[0]);
107494  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
107495  zPattern = sqlite3_value_text(argv[1]);
107496  if( zPattern==0 ){
107497    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
107498            || sqlite3_context_db_handle(context)->mallocFailed );
107499    return;
107500  }
107501  if( zPattern[0]==0 ){
107502    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
107503    sqlite3_result_value(context, argv[0]);
107504    return;
107505  }
107506  nPattern = sqlite3_value_bytes(argv[1]);
107507  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
107508  zRep = sqlite3_value_text(argv[2]);
107509  if( zRep==0 ) return;
107510  nRep = sqlite3_value_bytes(argv[2]);
107511  assert( zRep==sqlite3_value_text(argv[2]) );
107512  nOut = nStr + 1;
107513  assert( nOut<SQLITE_MAX_LENGTH );
107514  zOut = contextMalloc(context, (i64)nOut);
107515  if( zOut==0 ){
107516    return;
107517  }
107518  loopLimit = nStr - nPattern;
107519  for(i=j=0; i<=loopLimit; i++){
107520    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
107521      zOut[j++] = zStr[i];
107522    }else{
107523      u8 *zOld;
107524      sqlite3 *db = sqlite3_context_db_handle(context);
107525      nOut += nRep - nPattern;
107526      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
107527      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
107528      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
107529        sqlite3_result_error_toobig(context);
107530        sqlite3_free(zOut);
107531        return;
107532      }
107533      zOld = zOut;
107534      zOut = sqlite3_realloc64(zOut, (int)nOut);
107535      if( zOut==0 ){
107536        sqlite3_result_error_nomem(context);
107537        sqlite3_free(zOld);
107538        return;
107539      }
107540      memcpy(&zOut[j], zRep, nRep);
107541      j += nRep;
107542      i += nPattern-1;
107543    }
107544  }
107545  assert( j+nStr-i+1==nOut );
107546  memcpy(&zOut[j], &zStr[i], nStr-i);
107547  j += nStr - i;
107548  assert( j<=nOut );
107549  zOut[j] = 0;
107550  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
107551}
107552
107553/*
107554** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
107555** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
107556*/
107557static void trimFunc(
107558  sqlite3_context *context,
107559  int argc,
107560  sqlite3_value **argv
107561){
107562  const unsigned char *zIn;         /* Input string */
107563  const unsigned char *zCharSet;    /* Set of characters to trim */
107564  int nIn;                          /* Number of bytes in input */
107565  int flags;                        /* 1: trimleft  2: trimright  3: trim */
107566  int i;                            /* Loop counter */
107567  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
107568  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
107569  int nChar;                        /* Number of characters in zCharSet */
107570
107571  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
107572    return;
107573  }
107574  zIn = sqlite3_value_text(argv[0]);
107575  if( zIn==0 ) return;
107576  nIn = sqlite3_value_bytes(argv[0]);
107577  assert( zIn==sqlite3_value_text(argv[0]) );
107578  if( argc==1 ){
107579    static const unsigned char lenOne[] = { 1 };
107580    static unsigned char * const azOne[] = { (u8*)" " };
107581    nChar = 1;
107582    aLen = (u8*)lenOne;
107583    azChar = (unsigned char **)azOne;
107584    zCharSet = 0;
107585  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
107586    return;
107587  }else{
107588    const unsigned char *z;
107589    for(z=zCharSet, nChar=0; *z; nChar++){
107590      SQLITE_SKIP_UTF8(z);
107591    }
107592    if( nChar>0 ){
107593      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
107594      if( azChar==0 ){
107595        return;
107596      }
107597      aLen = (unsigned char*)&azChar[nChar];
107598      for(z=zCharSet, nChar=0; *z; nChar++){
107599        azChar[nChar] = (unsigned char *)z;
107600        SQLITE_SKIP_UTF8(z);
107601        aLen[nChar] = (u8)(z - azChar[nChar]);
107602      }
107603    }
107604  }
107605  if( nChar>0 ){
107606    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
107607    if( flags & 1 ){
107608      while( nIn>0 ){
107609        int len = 0;
107610        for(i=0; i<nChar; i++){
107611          len = aLen[i];
107612          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
107613        }
107614        if( i>=nChar ) break;
107615        zIn += len;
107616        nIn -= len;
107617      }
107618    }
107619    if( flags & 2 ){
107620      while( nIn>0 ){
107621        int len = 0;
107622        for(i=0; i<nChar; i++){
107623          len = aLen[i];
107624          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
107625        }
107626        if( i>=nChar ) break;
107627        nIn -= len;
107628      }
107629    }
107630    if( zCharSet ){
107631      sqlite3_free(azChar);
107632    }
107633  }
107634  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
107635}
107636
107637
107638#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
107639/*
107640** The "unknown" function is automatically substituted in place of
107641** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
107642** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
107643** When the "sqlite3" command-line shell is built using this functionality,
107644** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
107645** involving application-defined functions to be examined in a generic
107646** sqlite3 shell.
107647*/
107648static void unknownFunc(
107649  sqlite3_context *context,
107650  int argc,
107651  sqlite3_value **argv
107652){
107653  /* no-op */
107654}
107655#endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
107656
107657
107658/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
107659** is only available if the SQLITE_SOUNDEX compile-time option is used
107660** when SQLite is built.
107661*/
107662#ifdef SQLITE_SOUNDEX
107663/*
107664** Compute the soundex encoding of a word.
107665**
107666** IMP: R-59782-00072 The soundex(X) function returns a string that is the
107667** soundex encoding of the string X.
107668*/
107669static void soundexFunc(
107670  sqlite3_context *context,
107671  int argc,
107672  sqlite3_value **argv
107673){
107674  char zResult[8];
107675  const u8 *zIn;
107676  int i, j;
107677  static const unsigned char iCode[] = {
107678    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107679    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107680    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107681    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107682    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
107683    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
107684    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
107685    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
107686  };
107687  assert( argc==1 );
107688  zIn = (u8*)sqlite3_value_text(argv[0]);
107689  if( zIn==0 ) zIn = (u8*)"";
107690  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
107691  if( zIn[i] ){
107692    u8 prevcode = iCode[zIn[i]&0x7f];
107693    zResult[0] = sqlite3Toupper(zIn[i]);
107694    for(j=1; j<4 && zIn[i]; i++){
107695      int code = iCode[zIn[i]&0x7f];
107696      if( code>0 ){
107697        if( code!=prevcode ){
107698          prevcode = code;
107699          zResult[j++] = code + '0';
107700        }
107701      }else{
107702        prevcode = 0;
107703      }
107704    }
107705    while( j<4 ){
107706      zResult[j++] = '0';
107707    }
107708    zResult[j] = 0;
107709    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
107710  }else{
107711    /* IMP: R-64894-50321 The string "?000" is returned if the argument
107712    ** is NULL or contains no ASCII alphabetic characters. */
107713    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
107714  }
107715}
107716#endif /* SQLITE_SOUNDEX */
107717
107718#ifndef SQLITE_OMIT_LOAD_EXTENSION
107719/*
107720** A function that loads a shared-library extension then returns NULL.
107721*/
107722static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
107723  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
107724  const char *zProc;
107725  sqlite3 *db = sqlite3_context_db_handle(context);
107726  char *zErrMsg = 0;
107727
107728  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
107729  ** flag is set.  See the sqlite3_enable_load_extension() API.
107730  */
107731  if( (db->flags & SQLITE_LoadExtFunc)==0 ){
107732    sqlite3_result_error(context, "not authorized", -1);
107733    return;
107734  }
107735
107736  if( argc==2 ){
107737    zProc = (const char *)sqlite3_value_text(argv[1]);
107738  }else{
107739    zProc = 0;
107740  }
107741  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
107742    sqlite3_result_error(context, zErrMsg, -1);
107743    sqlite3_free(zErrMsg);
107744  }
107745}
107746#endif
107747
107748
107749/*
107750** An instance of the following structure holds the context of a
107751** sum() or avg() aggregate computation.
107752*/
107753typedef struct SumCtx SumCtx;
107754struct SumCtx {
107755  double rSum;      /* Floating point sum */
107756  i64 iSum;         /* Integer sum */
107757  i64 cnt;          /* Number of elements summed */
107758  u8 overflow;      /* True if integer overflow seen */
107759  u8 approx;        /* True if non-integer value was input to the sum */
107760};
107761
107762/*
107763** Routines used to compute the sum, average, and total.
107764**
107765** The SUM() function follows the (broken) SQL standard which means
107766** that it returns NULL if it sums over no inputs.  TOTAL returns
107767** 0.0 in that case.  In addition, TOTAL always returns a float where
107768** SUM might return an integer if it never encounters a floating point
107769** value.  TOTAL never fails, but SUM might through an exception if
107770** it overflows an integer.
107771*/
107772static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
107773  SumCtx *p;
107774  int type;
107775  assert( argc==1 );
107776  UNUSED_PARAMETER(argc);
107777  p = sqlite3_aggregate_context(context, sizeof(*p));
107778  type = sqlite3_value_numeric_type(argv[0]);
107779  if( p && type!=SQLITE_NULL ){
107780    p->cnt++;
107781    if( type==SQLITE_INTEGER ){
107782      i64 v = sqlite3_value_int64(argv[0]);
107783      p->rSum += v;
107784      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
107785        p->overflow = 1;
107786      }
107787    }else{
107788      p->rSum += sqlite3_value_double(argv[0]);
107789      p->approx = 1;
107790    }
107791  }
107792}
107793static void sumFinalize(sqlite3_context *context){
107794  SumCtx *p;
107795  p = sqlite3_aggregate_context(context, 0);
107796  if( p && p->cnt>0 ){
107797    if( p->overflow ){
107798      sqlite3_result_error(context,"integer overflow",-1);
107799    }else if( p->approx ){
107800      sqlite3_result_double(context, p->rSum);
107801    }else{
107802      sqlite3_result_int64(context, p->iSum);
107803    }
107804  }
107805}
107806static void avgFinalize(sqlite3_context *context){
107807  SumCtx *p;
107808  p = sqlite3_aggregate_context(context, 0);
107809  if( p && p->cnt>0 ){
107810    sqlite3_result_double(context, p->rSum/(double)p->cnt);
107811  }
107812}
107813static void totalFinalize(sqlite3_context *context){
107814  SumCtx *p;
107815  p = sqlite3_aggregate_context(context, 0);
107816  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
107817  sqlite3_result_double(context, p ? p->rSum : (double)0);
107818}
107819
107820/*
107821** The following structure keeps track of state information for the
107822** count() aggregate function.
107823*/
107824typedef struct CountCtx CountCtx;
107825struct CountCtx {
107826  i64 n;
107827};
107828
107829/*
107830** Routines to implement the count() aggregate function.
107831*/
107832static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
107833  CountCtx *p;
107834  p = sqlite3_aggregate_context(context, sizeof(*p));
107835  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
107836    p->n++;
107837  }
107838
107839#ifndef SQLITE_OMIT_DEPRECATED
107840  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
107841  ** sure it still operates correctly, verify that its count agrees with our
107842  ** internal count when using count(*) and when the total count can be
107843  ** expressed as a 32-bit integer. */
107844  assert( argc==1 || p==0 || p->n>0x7fffffff
107845          || p->n==sqlite3_aggregate_count(context) );
107846#endif
107847}
107848static void countFinalize(sqlite3_context *context){
107849  CountCtx *p;
107850  p = sqlite3_aggregate_context(context, 0);
107851  sqlite3_result_int64(context, p ? p->n : 0);
107852}
107853
107854/*
107855** Routines to implement min() and max() aggregate functions.
107856*/
107857static void minmaxStep(
107858  sqlite3_context *context,
107859  int NotUsed,
107860  sqlite3_value **argv
107861){
107862  Mem *pArg  = (Mem *)argv[0];
107863  Mem *pBest;
107864  UNUSED_PARAMETER(NotUsed);
107865
107866  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
107867  if( !pBest ) return;
107868
107869  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
107870    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
107871  }else if( pBest->flags ){
107872    int max;
107873    int cmp;
107874    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
107875    /* This step function is used for both the min() and max() aggregates,
107876    ** the only difference between the two being that the sense of the
107877    ** comparison is inverted. For the max() aggregate, the
107878    ** sqlite3_user_data() function returns (void *)-1. For min() it
107879    ** returns (void *)db, where db is the sqlite3* database pointer.
107880    ** Therefore the next statement sets variable 'max' to 1 for the max()
107881    ** aggregate, or 0 for min().
107882    */
107883    max = sqlite3_user_data(context)!=0;
107884    cmp = sqlite3MemCompare(pBest, pArg, pColl);
107885    if( (max && cmp<0) || (!max && cmp>0) ){
107886      sqlite3VdbeMemCopy(pBest, pArg);
107887    }else{
107888      sqlite3SkipAccumulatorLoad(context);
107889    }
107890  }else{
107891    pBest->db = sqlite3_context_db_handle(context);
107892    sqlite3VdbeMemCopy(pBest, pArg);
107893  }
107894}
107895static void minMaxFinalize(sqlite3_context *context){
107896  sqlite3_value *pRes;
107897  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
107898  if( pRes ){
107899    if( pRes->flags ){
107900      sqlite3_result_value(context, pRes);
107901    }
107902    sqlite3VdbeMemRelease(pRes);
107903  }
107904}
107905
107906/*
107907** group_concat(EXPR, ?SEPARATOR?)
107908*/
107909static void groupConcatStep(
107910  sqlite3_context *context,
107911  int argc,
107912  sqlite3_value **argv
107913){
107914  const char *zVal;
107915  StrAccum *pAccum;
107916  const char *zSep;
107917  int nVal, nSep;
107918  assert( argc==1 || argc==2 );
107919  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
107920  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
107921
107922  if( pAccum ){
107923    sqlite3 *db = sqlite3_context_db_handle(context);
107924    int firstTerm = pAccum->mxAlloc==0;
107925    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
107926    if( !firstTerm ){
107927      if( argc==2 ){
107928        zSep = (char*)sqlite3_value_text(argv[1]);
107929        nSep = sqlite3_value_bytes(argv[1]);
107930      }else{
107931        zSep = ",";
107932        nSep = 1;
107933      }
107934      if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
107935    }
107936    zVal = (char*)sqlite3_value_text(argv[0]);
107937    nVal = sqlite3_value_bytes(argv[0]);
107938    if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
107939  }
107940}
107941static void groupConcatFinalize(sqlite3_context *context){
107942  StrAccum *pAccum;
107943  pAccum = sqlite3_aggregate_context(context, 0);
107944  if( pAccum ){
107945    if( pAccum->accError==STRACCUM_TOOBIG ){
107946      sqlite3_result_error_toobig(context);
107947    }else if( pAccum->accError==STRACCUM_NOMEM ){
107948      sqlite3_result_error_nomem(context);
107949    }else{
107950      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
107951                          sqlite3_free);
107952    }
107953  }
107954}
107955
107956/*
107957** This routine does per-connection function registration.  Most
107958** of the built-in functions above are part of the global function set.
107959** This routine only deals with those that are not global.
107960*/
107961SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
107962  int rc = sqlite3_overload_function(db, "MATCH", 2);
107963  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
107964  if( rc==SQLITE_NOMEM ){
107965    sqlite3OomFault(db);
107966  }
107967}
107968
107969/*
107970** Set the LIKEOPT flag on the 2-argument function with the given name.
107971*/
107972static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
107973  FuncDef *pDef;
107974  pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
107975  if( ALWAYS(pDef) ){
107976    pDef->funcFlags |= flagVal;
107977  }
107978}
107979
107980/*
107981** Register the built-in LIKE and GLOB functions.  The caseSensitive
107982** parameter determines whether or not the LIKE operator is case
107983** sensitive.  GLOB is always case sensitive.
107984*/
107985SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
107986  struct compareInfo *pInfo;
107987  if( caseSensitive ){
107988    pInfo = (struct compareInfo*)&likeInfoAlt;
107989  }else{
107990    pInfo = (struct compareInfo*)&likeInfoNorm;
107991  }
107992  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
107993  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
107994  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
107995      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
107996  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
107997  setLikeOptFlag(db, "like",
107998      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
107999}
108000
108001/*
108002** pExpr points to an expression which implements a function.  If
108003** it is appropriate to apply the LIKE optimization to that function
108004** then set aWc[0] through aWc[2] to the wildcard characters and
108005** return TRUE.  If the function is not a LIKE-style function then
108006** return FALSE.
108007**
108008** *pIsNocase is set to true if uppercase and lowercase are equivalent for
108009** the function (default for LIKE).  If the function makes the distinction
108010** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
108011** false.
108012*/
108013SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
108014  FuncDef *pDef;
108015  if( pExpr->op!=TK_FUNCTION
108016   || !pExpr->x.pList
108017   || pExpr->x.pList->nExpr!=2
108018  ){
108019    return 0;
108020  }
108021  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
108022  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
108023  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
108024    return 0;
108025  }
108026
108027  /* The memcpy() statement assumes that the wildcard characters are
108028  ** the first three statements in the compareInfo structure.  The
108029  ** asserts() that follow verify that assumption
108030  */
108031  memcpy(aWc, pDef->pUserData, 3);
108032  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
108033  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
108034  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
108035  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
108036  return 1;
108037}
108038
108039/*
108040** All of the FuncDef structures in the aBuiltinFunc[] array above
108041** to the global function hash table.  This occurs at start-time (as
108042** a consequence of calling sqlite3_initialize()).
108043**
108044** After this routine runs
108045*/
108046SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
108047  /*
108048  ** The following array holds FuncDef structures for all of the functions
108049  ** defined in this file.
108050  **
108051  ** The array cannot be constant since changes are made to the
108052  ** FuncDef.pHash elements at start-time.  The elements of this array
108053  ** are read-only after initialization is complete.
108054  **
108055  ** For peak efficiency, put the most frequently used function last.
108056  */
108057  static FuncDef aBuiltinFunc[] = {
108058#ifdef SQLITE_SOUNDEX
108059    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
108060#endif
108061#ifndef SQLITE_OMIT_LOAD_EXTENSION
108062    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
108063    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
108064#endif
108065#if SQLITE_USER_AUTHENTICATION
108066    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
108067#endif
108068#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
108069    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
108070    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
108071#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
108072    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
108073    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
108074    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
108075#ifdef SQLITE_DEBUG
108076    FUNCTION2(affinity,          1, 0, 0, noopFunc,  SQLITE_FUNC_AFFINITY),
108077#endif
108078    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
108079    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
108080    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
108081    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
108082    FUNCTION(trim,               1, 3, 0, trimFunc         ),
108083    FUNCTION(trim,               2, 3, 0, trimFunc         ),
108084    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
108085    FUNCTION(min,                0, 0, 1, 0                ),
108086    AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
108087                                          SQLITE_FUNC_MINMAX ),
108088    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
108089    FUNCTION(max,                0, 1, 1, 0                ),
108090    AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
108091                                          SQLITE_FUNC_MINMAX ),
108092    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
108093    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
108094    FUNCTION(instr,              2, 0, 0, instrFunc        ),
108095    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
108096    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
108097    FUNCTION(char,              -1, 0, 0, charFunc         ),
108098    FUNCTION(abs,                1, 0, 0, absFunc          ),
108099#ifndef SQLITE_OMIT_FLOATING_POINT
108100    FUNCTION(round,              1, 0, 0, roundFunc        ),
108101    FUNCTION(round,              2, 0, 0, roundFunc        ),
108102#endif
108103    FUNCTION(upper,              1, 0, 0, upperFunc        ),
108104    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
108105    FUNCTION(hex,                1, 0, 0, hexFunc          ),
108106    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
108107    VFUNCTION(random,            0, 0, 0, randomFunc       ),
108108    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
108109    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
108110    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
108111    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
108112    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
108113    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
108114    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
108115    VFUNCTION(changes,           0, 0, 0, changes          ),
108116    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
108117    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
108118    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
108119    FUNCTION(substr,             2, 0, 0, substrFunc       ),
108120    FUNCTION(substr,             3, 0, 0, substrFunc       ),
108121    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
108122    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
108123    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
108124    AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
108125               SQLITE_FUNC_COUNT  ),
108126    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
108127    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
108128    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
108129
108130    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108131#ifdef SQLITE_CASE_SENSITIVE_LIKE
108132    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108133    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
108134#else
108135    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
108136    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
108137#endif
108138#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
108139    FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
108140#endif
108141    FUNCTION(coalesce,           1, 0, 0, 0                ),
108142    FUNCTION(coalesce,           0, 0, 0, 0                ),
108143    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
108144  };
108145#ifndef SQLITE_OMIT_ALTERTABLE
108146  sqlite3AlterFunctions();
108147#endif
108148#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
108149  sqlite3AnalyzeFunctions();
108150#endif
108151  sqlite3RegisterDateTimeFunctions();
108152  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
108153
108154#if 0  /* Enable to print out how the built-in functions are hashed */
108155  {
108156    int i;
108157    FuncDef *p;
108158    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
108159      printf("FUNC-HASH %02d:", i);
108160      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
108161        int n = sqlite3Strlen30(p->zName);
108162        int h = p->zName[0] + n;
108163        printf(" %s(%d)", p->zName, h);
108164      }
108165      printf("\n");
108166    }
108167  }
108168#endif
108169}
108170
108171/************** End of func.c ************************************************/
108172/************** Begin file fkey.c ********************************************/
108173/*
108174**
108175** The author disclaims copyright to this source code.  In place of
108176** a legal notice, here is a blessing:
108177**
108178**    May you do good and not evil.
108179**    May you find forgiveness for yourself and forgive others.
108180**    May you share freely, never taking more than you give.
108181**
108182*************************************************************************
108183** This file contains code used by the compiler to add foreign key
108184** support to compiled SQL statements.
108185*/
108186/* #include "sqliteInt.h" */
108187
108188#ifndef SQLITE_OMIT_FOREIGN_KEY
108189#ifndef SQLITE_OMIT_TRIGGER
108190
108191/*
108192** Deferred and Immediate FKs
108193** --------------------------
108194**
108195** Foreign keys in SQLite come in two flavours: deferred and immediate.
108196** If an immediate foreign key constraint is violated,
108197** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
108198** statement transaction rolled back. If a
108199** deferred foreign key constraint is violated, no action is taken
108200** immediately. However if the application attempts to commit the
108201** transaction before fixing the constraint violation, the attempt fails.
108202**
108203** Deferred constraints are implemented using a simple counter associated
108204** with the database handle. The counter is set to zero each time a
108205** database transaction is opened. Each time a statement is executed
108206** that causes a foreign key violation, the counter is incremented. Each
108207** time a statement is executed that removes an existing violation from
108208** the database, the counter is decremented. When the transaction is
108209** committed, the commit fails if the current value of the counter is
108210** greater than zero. This scheme has two big drawbacks:
108211**
108212**   * When a commit fails due to a deferred foreign key constraint,
108213**     there is no way to tell which foreign constraint is not satisfied,
108214**     or which row it is not satisfied for.
108215**
108216**   * If the database contains foreign key violations when the
108217**     transaction is opened, this may cause the mechanism to malfunction.
108218**
108219** Despite these problems, this approach is adopted as it seems simpler
108220** than the alternatives.
108221**
108222** INSERT operations:
108223**
108224**   I.1) For each FK for which the table is the child table, search
108225**        the parent table for a match. If none is found increment the
108226**        constraint counter.
108227**
108228**   I.2) For each FK for which the table is the parent table,
108229**        search the child table for rows that correspond to the new
108230**        row in the parent table. Decrement the counter for each row
108231**        found (as the constraint is now satisfied).
108232**
108233** DELETE operations:
108234**
108235**   D.1) For each FK for which the table is the child table,
108236**        search the parent table for a row that corresponds to the
108237**        deleted row in the child table. If such a row is not found,
108238**        decrement the counter.
108239**
108240**   D.2) For each FK for which the table is the parent table, search
108241**        the child table for rows that correspond to the deleted row
108242**        in the parent table. For each found increment the counter.
108243**
108244** UPDATE operations:
108245**
108246**   An UPDATE command requires that all 4 steps above are taken, but only
108247**   for FK constraints for which the affected columns are actually
108248**   modified (values must be compared at runtime).
108249**
108250** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
108251** This simplifies the implementation a bit.
108252**
108253** For the purposes of immediate FK constraints, the OR REPLACE conflict
108254** resolution is considered to delete rows before the new row is inserted.
108255** If a delete caused by OR REPLACE violates an FK constraint, an exception
108256** is thrown, even if the FK constraint would be satisfied after the new
108257** row is inserted.
108258**
108259** Immediate constraints are usually handled similarly. The only difference
108260** is that the counter used is stored as part of each individual statement
108261** object (struct Vdbe). If, after the statement has run, its immediate
108262** constraint counter is greater than zero,
108263** it returns SQLITE_CONSTRAINT_FOREIGNKEY
108264** and the statement transaction is rolled back. An exception is an INSERT
108265** statement that inserts a single row only (no triggers). In this case,
108266** instead of using a counter, an exception is thrown immediately if the
108267** INSERT violates a foreign key constraint. This is necessary as such
108268** an INSERT does not open a statement transaction.
108269**
108270** TODO: How should dropping a table be handled? How should renaming a
108271** table be handled?
108272**
108273**
108274** Query API Notes
108275** ---------------
108276**
108277** Before coding an UPDATE or DELETE row operation, the code-generator
108278** for those two operations needs to know whether or not the operation
108279** requires any FK processing and, if so, which columns of the original
108280** row are required by the FK processing VDBE code (i.e. if FKs were
108281** implemented using triggers, which of the old.* columns would be
108282** accessed). No information is required by the code-generator before
108283** coding an INSERT operation. The functions used by the UPDATE/DELETE
108284** generation code to query for this information are:
108285**
108286**   sqlite3FkRequired() - Test to see if FK processing is required.
108287**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
108288**
108289**
108290** Externally accessible module functions
108291** --------------------------------------
108292**
108293**   sqlite3FkCheck()    - Check for foreign key violations.
108294**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
108295**   sqlite3FkDelete()   - Delete an FKey structure.
108296*/
108297
108298/*
108299** VDBE Calling Convention
108300** -----------------------
108301**
108302** Example:
108303**
108304**   For the following INSERT statement:
108305**
108306**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
108307**     INSERT INTO t1 VALUES(1, 2, 3.1);
108308**
108309**   Register (x):        2    (type integer)
108310**   Register (x+1):      1    (type integer)
108311**   Register (x+2):      NULL (type NULL)
108312**   Register (x+3):      3.1  (type real)
108313*/
108314
108315/*
108316** A foreign key constraint requires that the key columns in the parent
108317** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
108318** Given that pParent is the parent table for foreign key constraint pFKey,
108319** search the schema for a unique index on the parent key columns.
108320**
108321** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
108322** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
108323** is set to point to the unique index.
108324**
108325** If the parent key consists of a single column (the foreign key constraint
108326** is not a composite foreign key), output variable *paiCol is set to NULL.
108327** Otherwise, it is set to point to an allocated array of size N, where
108328** N is the number of columns in the parent key. The first element of the
108329** array is the index of the child table column that is mapped by the FK
108330** constraint to the parent table column stored in the left-most column
108331** of index *ppIdx. The second element of the array is the index of the
108332** child table column that corresponds to the second left-most column of
108333** *ppIdx, and so on.
108334**
108335** If the required index cannot be found, either because:
108336**
108337**   1) The named parent key columns do not exist, or
108338**
108339**   2) The named parent key columns do exist, but are not subject to a
108340**      UNIQUE or PRIMARY KEY constraint, or
108341**
108342**   3) No parent key columns were provided explicitly as part of the
108343**      foreign key definition, and the parent table does not have a
108344**      PRIMARY KEY, or
108345**
108346**   4) No parent key columns were provided explicitly as part of the
108347**      foreign key definition, and the PRIMARY KEY of the parent table
108348**      consists of a different number of columns to the child key in
108349**      the child table.
108350**
108351** then non-zero is returned, and a "foreign key mismatch" error loaded
108352** into pParse. If an OOM error occurs, non-zero is returned and the
108353** pParse->db->mallocFailed flag is set.
108354*/
108355SQLITE_PRIVATE int sqlite3FkLocateIndex(
108356  Parse *pParse,                  /* Parse context to store any error in */
108357  Table *pParent,                 /* Parent table of FK constraint pFKey */
108358  FKey *pFKey,                    /* Foreign key to find index for */
108359  Index **ppIdx,                  /* OUT: Unique index on parent table */
108360  int **paiCol                    /* OUT: Map of index columns in pFKey */
108361){
108362  Index *pIdx = 0;                    /* Value to return via *ppIdx */
108363  int *aiCol = 0;                     /* Value to return via *paiCol */
108364  int nCol = pFKey->nCol;             /* Number of columns in parent key */
108365  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
108366
108367  /* The caller is responsible for zeroing output parameters. */
108368  assert( ppIdx && *ppIdx==0 );
108369  assert( !paiCol || *paiCol==0 );
108370  assert( pParse );
108371
108372  /* If this is a non-composite (single column) foreign key, check if it
108373  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
108374  ** and *paiCol set to zero and return early.
108375  **
108376  ** Otherwise, for a composite foreign key (more than one column), allocate
108377  ** space for the aiCol array (returned via output parameter *paiCol).
108378  ** Non-composite foreign keys do not require the aiCol array.
108379  */
108380  if( nCol==1 ){
108381    /* The FK maps to the IPK if any of the following are true:
108382    **
108383    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
108384    **      mapped to the primary key of table pParent, or
108385    **   2) The FK is explicitly mapped to a column declared as INTEGER
108386    **      PRIMARY KEY.
108387    */
108388    if( pParent->iPKey>=0 ){
108389      if( !zKey ) return 0;
108390      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
108391    }
108392  }else if( paiCol ){
108393    assert( nCol>1 );
108394    aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
108395    if( !aiCol ) return 1;
108396    *paiCol = aiCol;
108397  }
108398
108399  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
108400    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
108401      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
108402      ** of columns. If each indexed column corresponds to a foreign key
108403      ** column of pFKey, then this index is a winner.  */
108404
108405      if( zKey==0 ){
108406        /* If zKey is NULL, then this foreign key is implicitly mapped to
108407        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
108408        ** identified by the test.  */
108409        if( IsPrimaryKeyIndex(pIdx) ){
108410          if( aiCol ){
108411            int i;
108412            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
108413          }
108414          break;
108415        }
108416      }else{
108417        /* If zKey is non-NULL, then this foreign key was declared to
108418        ** map to an explicit list of columns in table pParent. Check if this
108419        ** index matches those columns. Also, check that the index uses
108420        ** the default collation sequences for each column. */
108421        int i, j;
108422        for(i=0; i<nCol; i++){
108423          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
108424          const char *zDfltColl;            /* Def. collation for column */
108425          char *zIdxCol;                    /* Name of indexed column */
108426
108427          if( iCol<0 ) break; /* No foreign keys against expression indexes */
108428
108429          /* If the index uses a collation sequence that is different from
108430          ** the default collation sequence for the column, this index is
108431          ** unusable. Bail out early in this case.  */
108432          zDfltColl = pParent->aCol[iCol].zColl;
108433          if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
108434          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
108435
108436          zIdxCol = pParent->aCol[iCol].zName;
108437          for(j=0; j<nCol; j++){
108438            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
108439              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
108440              break;
108441            }
108442          }
108443          if( j==nCol ) break;
108444        }
108445        if( i==nCol ) break;      /* pIdx is usable */
108446      }
108447    }
108448  }
108449
108450  if( !pIdx ){
108451    if( !pParse->disableTriggers ){
108452      sqlite3ErrorMsg(pParse,
108453           "foreign key mismatch - \"%w\" referencing \"%w\"",
108454           pFKey->pFrom->zName, pFKey->zTo);
108455    }
108456    sqlite3DbFree(pParse->db, aiCol);
108457    return 1;
108458  }
108459
108460  *ppIdx = pIdx;
108461  return 0;
108462}
108463
108464/*
108465** This function is called when a row is inserted into or deleted from the
108466** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
108467** on the child table of pFKey, this function is invoked twice for each row
108468** affected - once to "delete" the old row, and then again to "insert" the
108469** new row.
108470**
108471** Each time it is called, this function generates VDBE code to locate the
108472** row in the parent table that corresponds to the row being inserted into
108473** or deleted from the child table. If the parent row can be found, no
108474** special action is taken. Otherwise, if the parent row can *not* be
108475** found in the parent table:
108476**
108477**   Operation | FK type   | Action taken
108478**   --------------------------------------------------------------------------
108479**   INSERT      immediate   Increment the "immediate constraint counter".
108480**
108481**   DELETE      immediate   Decrement the "immediate constraint counter".
108482**
108483**   INSERT      deferred    Increment the "deferred constraint counter".
108484**
108485**   DELETE      deferred    Decrement the "deferred constraint counter".
108486**
108487** These operations are identified in the comment at the top of this file
108488** (fkey.c) as "I.1" and "D.1".
108489*/
108490static void fkLookupParent(
108491  Parse *pParse,        /* Parse context */
108492  int iDb,              /* Index of database housing pTab */
108493  Table *pTab,          /* Parent table of FK pFKey */
108494  Index *pIdx,          /* Unique index on parent key columns in pTab */
108495  FKey *pFKey,          /* Foreign key constraint */
108496  int *aiCol,           /* Map from parent key columns to child table columns */
108497  int regData,          /* Address of array containing child table row */
108498  int nIncr,            /* Increment constraint counter by this */
108499  int isIgnore          /* If true, pretend pTab contains all NULL values */
108500){
108501  int i;                                    /* Iterator variable */
108502  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
108503  int iCur = pParse->nTab - 1;              /* Cursor number to use */
108504  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
108505
108506  /* If nIncr is less than zero, then check at runtime if there are any
108507  ** outstanding constraints to resolve. If there are not, there is no need
108508  ** to check if deleting this row resolves any outstanding violations.
108509  **
108510  ** Check if any of the key columns in the child table row are NULL. If
108511  ** any are, then the constraint is considered satisfied. No need to
108512  ** search for a matching row in the parent table.  */
108513  if( nIncr<0 ){
108514    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
108515    VdbeCoverage(v);
108516  }
108517  for(i=0; i<pFKey->nCol; i++){
108518    int iReg = aiCol[i] + regData + 1;
108519    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
108520  }
108521
108522  if( isIgnore==0 ){
108523    if( pIdx==0 ){
108524      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
108525      ** column of the parent table (table pTab).  */
108526      int iMustBeInt;               /* Address of MustBeInt instruction */
108527      int regTemp = sqlite3GetTempReg(pParse);
108528
108529      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
108530      ** apply the affinity of the parent key). If this fails, then there
108531      ** is no matching parent key. Before using MustBeInt, make a copy of
108532      ** the value. Otherwise, the value inserted into the child key column
108533      ** will have INTEGER affinity applied to it, which may not be correct.  */
108534      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
108535      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
108536      VdbeCoverage(v);
108537
108538      /* If the parent table is the same as the child table, and we are about
108539      ** to increment the constraint-counter (i.e. this is an INSERT operation),
108540      ** then check if the row being inserted matches itself. If so, do not
108541      ** increment the constraint-counter.  */
108542      if( pTab==pFKey->pFrom && nIncr==1 ){
108543        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
108544        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108545      }
108546
108547      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
108548      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
108549      sqlite3VdbeGoto(v, iOk);
108550      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
108551      sqlite3VdbeJumpHere(v, iMustBeInt);
108552      sqlite3ReleaseTempReg(pParse, regTemp);
108553    }else{
108554      int nCol = pFKey->nCol;
108555      int regTemp = sqlite3GetTempRange(pParse, nCol);
108556      int regRec = sqlite3GetTempReg(pParse);
108557
108558      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
108559      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
108560      for(i=0; i<nCol; i++){
108561        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
108562      }
108563
108564      /* If the parent table is the same as the child table, and we are about
108565      ** to increment the constraint-counter (i.e. this is an INSERT operation),
108566      ** then check if the row being inserted matches itself. If so, do not
108567      ** increment the constraint-counter.
108568      **
108569      ** If any of the parent-key values are NULL, then the row cannot match
108570      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
108571      ** of the parent-key values are NULL (at this point it is known that
108572      ** none of the child key values are).
108573      */
108574      if( pTab==pFKey->pFrom && nIncr==1 ){
108575        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
108576        for(i=0; i<nCol; i++){
108577          int iChild = aiCol[i]+1+regData;
108578          int iParent = pIdx->aiColumn[i]+1+regData;
108579          assert( pIdx->aiColumn[i]>=0 );
108580          assert( aiCol[i]!=pTab->iPKey );
108581          if( pIdx->aiColumn[i]==pTab->iPKey ){
108582            /* The parent key is a composite key that includes the IPK column */
108583            iParent = regData;
108584          }
108585          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
108586          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
108587        }
108588        sqlite3VdbeGoto(v, iOk);
108589      }
108590
108591      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
108592                        sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
108593      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
108594
108595      sqlite3ReleaseTempReg(pParse, regRec);
108596      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
108597    }
108598  }
108599
108600  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
108601   && !pParse->pToplevel
108602   && !pParse->isMultiWrite
108603  ){
108604    /* Special case: If this is an INSERT statement that will insert exactly
108605    ** one row into the table, raise a constraint immediately instead of
108606    ** incrementing a counter. This is necessary as the VM code is being
108607    ** generated for will not open a statement transaction.  */
108608    assert( nIncr==1 );
108609    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
108610        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
108611  }else{
108612    if( nIncr>0 && pFKey->isDeferred==0 ){
108613      sqlite3MayAbort(pParse);
108614    }
108615    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
108616  }
108617
108618  sqlite3VdbeResolveLabel(v, iOk);
108619  sqlite3VdbeAddOp1(v, OP_Close, iCur);
108620}
108621
108622
108623/*
108624** Return an Expr object that refers to a memory register corresponding
108625** to column iCol of table pTab.
108626**
108627** regBase is the first of an array of register that contains the data
108628** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
108629** column.  regBase+2 holds the second column, and so forth.
108630*/
108631static Expr *exprTableRegister(
108632  Parse *pParse,     /* Parsing and code generating context */
108633  Table *pTab,       /* The table whose content is at r[regBase]... */
108634  int regBase,       /* Contents of table pTab */
108635  i16 iCol           /* Which column of pTab is desired */
108636){
108637  Expr *pExpr;
108638  Column *pCol;
108639  const char *zColl;
108640  sqlite3 *db = pParse->db;
108641
108642  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
108643  if( pExpr ){
108644    if( iCol>=0 && iCol!=pTab->iPKey ){
108645      pCol = &pTab->aCol[iCol];
108646      pExpr->iTable = regBase + iCol + 1;
108647      pExpr->affinity = pCol->affinity;
108648      zColl = pCol->zColl;
108649      if( zColl==0 ) zColl = db->pDfltColl->zName;
108650      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
108651    }else{
108652      pExpr->iTable = regBase;
108653      pExpr->affinity = SQLITE_AFF_INTEGER;
108654    }
108655  }
108656  return pExpr;
108657}
108658
108659/*
108660** Return an Expr object that refers to column iCol of table pTab which
108661** has cursor iCur.
108662*/
108663static Expr *exprTableColumn(
108664  sqlite3 *db,      /* The database connection */
108665  Table *pTab,      /* The table whose column is desired */
108666  int iCursor,      /* The open cursor on the table */
108667  i16 iCol          /* The column that is wanted */
108668){
108669  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
108670  if( pExpr ){
108671    pExpr->pTab = pTab;
108672    pExpr->iTable = iCursor;
108673    pExpr->iColumn = iCol;
108674  }
108675  return pExpr;
108676}
108677
108678/*
108679** This function is called to generate code executed when a row is deleted
108680** from the parent table of foreign key constraint pFKey and, if pFKey is
108681** deferred, when a row is inserted into the same table. When generating
108682** code for an SQL UPDATE operation, this function may be called twice -
108683** once to "delete" the old row and once to "insert" the new row.
108684**
108685** Parameter nIncr is passed -1 when inserting a row (as this may decrease
108686** the number of FK violations in the db) or +1 when deleting one (as this
108687** may increase the number of FK constraint problems).
108688**
108689** The code generated by this function scans through the rows in the child
108690** table that correspond to the parent table row being deleted or inserted.
108691** For each child row found, one of the following actions is taken:
108692**
108693**   Operation | FK type   | Action taken
108694**   --------------------------------------------------------------------------
108695**   DELETE      immediate   Increment the "immediate constraint counter".
108696**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
108697**                           throw a "FOREIGN KEY constraint failed" exception.
108698**
108699**   INSERT      immediate   Decrement the "immediate constraint counter".
108700**
108701**   DELETE      deferred    Increment the "deferred constraint counter".
108702**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
108703**                           throw a "FOREIGN KEY constraint failed" exception.
108704**
108705**   INSERT      deferred    Decrement the "deferred constraint counter".
108706**
108707** These operations are identified in the comment at the top of this file
108708** (fkey.c) as "I.2" and "D.2".
108709*/
108710static void fkScanChildren(
108711  Parse *pParse,                  /* Parse context */
108712  SrcList *pSrc,                  /* The child table to be scanned */
108713  Table *pTab,                    /* The parent table */
108714  Index *pIdx,                    /* Index on parent covering the foreign key */
108715  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
108716  int *aiCol,                     /* Map from pIdx cols to child table cols */
108717  int regData,                    /* Parent row data starts here */
108718  int nIncr                       /* Amount to increment deferred counter by */
108719){
108720  sqlite3 *db = pParse->db;       /* Database handle */
108721  int i;                          /* Iterator variable */
108722  Expr *pWhere = 0;               /* WHERE clause to scan with */
108723  NameContext sNameContext;       /* Context used to resolve WHERE clause */
108724  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
108725  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
108726  Vdbe *v = sqlite3GetVdbe(pParse);
108727
108728  assert( pIdx==0 || pIdx->pTable==pTab );
108729  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
108730  assert( pIdx!=0 || pFKey->nCol==1 );
108731  assert( pIdx!=0 || HasRowid(pTab) );
108732
108733  if( nIncr<0 ){
108734    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
108735    VdbeCoverage(v);
108736  }
108737
108738  /* Create an Expr object representing an SQL expression like:
108739  **
108740  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
108741  **
108742  ** The collation sequence used for the comparison should be that of
108743  ** the parent key columns. The affinity of the parent key column should
108744  ** be applied to each child key value before the comparison takes place.
108745  */
108746  for(i=0; i<pFKey->nCol; i++){
108747    Expr *pLeft;                  /* Value from parent table row */
108748    Expr *pRight;                 /* Column ref to child table */
108749    Expr *pEq;                    /* Expression (pLeft = pRight) */
108750    i16 iCol;                     /* Index of column in child table */
108751    const char *zCol;             /* Name of column in child table */
108752
108753    iCol = pIdx ? pIdx->aiColumn[i] : -1;
108754    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
108755    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
108756    assert( iCol>=0 );
108757    zCol = pFKey->pFrom->aCol[iCol].zName;
108758    pRight = sqlite3Expr(db, TK_ID, zCol);
108759    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
108760    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
108761  }
108762
108763  /* If the child table is the same as the parent table, then add terms
108764  ** to the WHERE clause that prevent this entry from being scanned.
108765  ** The added WHERE clause terms are like this:
108766  **
108767  **     $current_rowid!=rowid
108768  **     NOT( $current_a==a AND $current_b==b AND ... )
108769  **
108770  ** The first form is used for rowid tables.  The second form is used
108771  ** for WITHOUT ROWID tables.  In the second form, the primary key is
108772  ** (a,b,...)
108773  */
108774  if( pTab==pFKey->pFrom && nIncr>0 ){
108775    Expr *pNe;                    /* Expression (pLeft != pRight) */
108776    Expr *pLeft;                  /* Value from parent table row */
108777    Expr *pRight;                 /* Column ref to child table */
108778    if( HasRowid(pTab) ){
108779      pLeft = exprTableRegister(pParse, pTab, regData, -1);
108780      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
108781      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
108782    }else{
108783      Expr *pEq, *pAll = 0;
108784      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
108785      assert( pIdx!=0 );
108786      for(i=0; i<pPk->nKeyCol; i++){
108787        i16 iCol = pIdx->aiColumn[i];
108788        assert( iCol>=0 );
108789        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
108790        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
108791        pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
108792        pAll = sqlite3ExprAnd(db, pAll, pEq);
108793      }
108794      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
108795    }
108796    pWhere = sqlite3ExprAnd(db, pWhere, pNe);
108797  }
108798
108799  /* Resolve the references in the WHERE clause. */
108800  memset(&sNameContext, 0, sizeof(NameContext));
108801  sNameContext.pSrcList = pSrc;
108802  sNameContext.pParse = pParse;
108803  sqlite3ResolveExprNames(&sNameContext, pWhere);
108804
108805  /* Create VDBE to loop through the entries in pSrc that match the WHERE
108806  ** clause. For each row found, increment either the deferred or immediate
108807  ** foreign key constraint counter. */
108808  if( pParse->nErr==0 ){
108809    pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
108810    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
108811    if( pWInfo ){
108812      sqlite3WhereEnd(pWInfo);
108813    }
108814  }
108815
108816  /* Clean up the WHERE clause constructed above. */
108817  sqlite3ExprDelete(db, pWhere);
108818  if( iFkIfZero ){
108819    sqlite3VdbeJumpHere(v, iFkIfZero);
108820  }
108821}
108822
108823/*
108824** This function returns a linked list of FKey objects (connected by
108825** FKey.pNextTo) holding all children of table pTab.  For example,
108826** given the following schema:
108827**
108828**   CREATE TABLE t1(a PRIMARY KEY);
108829**   CREATE TABLE t2(b REFERENCES t1(a);
108830**
108831** Calling this function with table "t1" as an argument returns a pointer
108832** to the FKey structure representing the foreign key constraint on table
108833** "t2". Calling this function with "t2" as the argument would return a
108834** NULL pointer (as there are no FK constraints for which t2 is the parent
108835** table).
108836*/
108837SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
108838  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
108839}
108840
108841/*
108842** The second argument is a Trigger structure allocated by the
108843** fkActionTrigger() routine. This function deletes the Trigger structure
108844** and all of its sub-components.
108845**
108846** The Trigger structure or any of its sub-components may be allocated from
108847** the lookaside buffer belonging to database handle dbMem.
108848*/
108849static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
108850  if( p ){
108851    TriggerStep *pStep = p->step_list;
108852    sqlite3ExprDelete(dbMem, pStep->pWhere);
108853    sqlite3ExprListDelete(dbMem, pStep->pExprList);
108854    sqlite3SelectDelete(dbMem, pStep->pSelect);
108855    sqlite3ExprDelete(dbMem, p->pWhen);
108856    sqlite3DbFree(dbMem, p);
108857  }
108858}
108859
108860/*
108861** This function is called to generate code that runs when table pTab is
108862** being dropped from the database. The SrcList passed as the second argument
108863** to this function contains a single entry guaranteed to resolve to
108864** table pTab.
108865**
108866** Normally, no code is required. However, if either
108867**
108868**   (a) The table is the parent table of a FK constraint, or
108869**   (b) The table is the child table of a deferred FK constraint and it is
108870**       determined at runtime that there are outstanding deferred FK
108871**       constraint violations in the database,
108872**
108873** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
108874** the table from the database. Triggers are disabled while running this
108875** DELETE, but foreign key actions are not.
108876*/
108877SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
108878  sqlite3 *db = pParse->db;
108879  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
108880    int iSkip = 0;
108881    Vdbe *v = sqlite3GetVdbe(pParse);
108882
108883    assert( v );                  /* VDBE has already been allocated */
108884    if( sqlite3FkReferences(pTab)==0 ){
108885      /* Search for a deferred foreign key constraint for which this table
108886      ** is the child table. If one cannot be found, return without
108887      ** generating any VDBE code. If one can be found, then jump over
108888      ** the entire DELETE if there are no outstanding deferred constraints
108889      ** when this statement is run.  */
108890      FKey *p;
108891      for(p=pTab->pFKey; p; p=p->pNextFrom){
108892        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
108893      }
108894      if( !p ) return;
108895      iSkip = sqlite3VdbeMakeLabel(v);
108896      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
108897    }
108898
108899    pParse->disableTriggers = 1;
108900    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
108901    pParse->disableTriggers = 0;
108902
108903    /* If the DELETE has generated immediate foreign key constraint
108904    ** violations, halt the VDBE and return an error at this point, before
108905    ** any modifications to the schema are made. This is because statement
108906    ** transactions are not able to rollback schema changes.
108907    **
108908    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
108909    ** the statement transaction will not be rolled back even if FK
108910    ** constraints are violated.
108911    */
108912    if( (db->flags & SQLITE_DeferFKs)==0 ){
108913      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
108914      VdbeCoverage(v);
108915      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
108916          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
108917    }
108918
108919    if( iSkip ){
108920      sqlite3VdbeResolveLabel(v, iSkip);
108921    }
108922  }
108923}
108924
108925
108926/*
108927** The second argument points to an FKey object representing a foreign key
108928** for which pTab is the child table. An UPDATE statement against pTab
108929** is currently being processed. For each column of the table that is
108930** actually updated, the corresponding element in the aChange[] array
108931** is zero or greater (if a column is unmodified the corresponding element
108932** is set to -1). If the rowid column is modified by the UPDATE statement
108933** the bChngRowid argument is non-zero.
108934**
108935** This function returns true if any of the columns that are part of the
108936** child key for FK constraint *p are modified.
108937*/
108938static int fkChildIsModified(
108939  Table *pTab,                    /* Table being updated */
108940  FKey *p,                        /* Foreign key for which pTab is the child */
108941  int *aChange,                   /* Array indicating modified columns */
108942  int bChngRowid                  /* True if rowid is modified by this update */
108943){
108944  int i;
108945  for(i=0; i<p->nCol; i++){
108946    int iChildKey = p->aCol[i].iFrom;
108947    if( aChange[iChildKey]>=0 ) return 1;
108948    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
108949  }
108950  return 0;
108951}
108952
108953/*
108954** The second argument points to an FKey object representing a foreign key
108955** for which pTab is the parent table. An UPDATE statement against pTab
108956** is currently being processed. For each column of the table that is
108957** actually updated, the corresponding element in the aChange[] array
108958** is zero or greater (if a column is unmodified the corresponding element
108959** is set to -1). If the rowid column is modified by the UPDATE statement
108960** the bChngRowid argument is non-zero.
108961**
108962** This function returns true if any of the columns that are part of the
108963** parent key for FK constraint *p are modified.
108964*/
108965static int fkParentIsModified(
108966  Table *pTab,
108967  FKey *p,
108968  int *aChange,
108969  int bChngRowid
108970){
108971  int i;
108972  for(i=0; i<p->nCol; i++){
108973    char *zKey = p->aCol[i].zCol;
108974    int iKey;
108975    for(iKey=0; iKey<pTab->nCol; iKey++){
108976      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
108977        Column *pCol = &pTab->aCol[iKey];
108978        if( zKey ){
108979          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
108980        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
108981          return 1;
108982        }
108983      }
108984    }
108985  }
108986  return 0;
108987}
108988
108989/*
108990** Return true if the parser passed as the first argument is being
108991** used to code a trigger that is really a "SET NULL" action belonging
108992** to trigger pFKey.
108993*/
108994static int isSetNullAction(Parse *pParse, FKey *pFKey){
108995  Parse *pTop = sqlite3ParseToplevel(pParse);
108996  if( pTop->pTriggerPrg ){
108997    Trigger *p = pTop->pTriggerPrg->pTrigger;
108998    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
108999     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
109000    ){
109001      return 1;
109002    }
109003  }
109004  return 0;
109005}
109006
109007/*
109008** This function is called when inserting, deleting or updating a row of
109009** table pTab to generate VDBE code to perform foreign key constraint
109010** processing for the operation.
109011**
109012** For a DELETE operation, parameter regOld is passed the index of the
109013** first register in an array of (pTab->nCol+1) registers containing the
109014** rowid of the row being deleted, followed by each of the column values
109015** of the row being deleted, from left to right. Parameter regNew is passed
109016** zero in this case.
109017**
109018** For an INSERT operation, regOld is passed zero and regNew is passed the
109019** first register of an array of (pTab->nCol+1) registers containing the new
109020** row data.
109021**
109022** For an UPDATE operation, this function is called twice. Once before
109023** the original record is deleted from the table using the calling convention
109024** described for DELETE. Then again after the original record is deleted
109025** but before the new record is inserted using the INSERT convention.
109026*/
109027SQLITE_PRIVATE void sqlite3FkCheck(
109028  Parse *pParse,                  /* Parse context */
109029  Table *pTab,                    /* Row is being deleted from this table */
109030  int regOld,                     /* Previous row data is stored here */
109031  int regNew,                     /* New row data is stored here */
109032  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
109033  int bChngRowid                  /* True if rowid is UPDATEd */
109034){
109035  sqlite3 *db = pParse->db;       /* Database handle */
109036  FKey *pFKey;                    /* Used to iterate through FKs */
109037  int iDb;                        /* Index of database containing pTab */
109038  const char *zDb;                /* Name of database containing pTab */
109039  int isIgnoreErrors = pParse->disableTriggers;
109040
109041  /* Exactly one of regOld and regNew should be non-zero. */
109042  assert( (regOld==0)!=(regNew==0) );
109043
109044  /* If foreign-keys are disabled, this function is a no-op. */
109045  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
109046
109047  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109048  zDb = db->aDb[iDb].zDbSName;
109049
109050  /* Loop through all the foreign key constraints for which pTab is the
109051  ** child table (the table that the foreign key definition is part of).  */
109052  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
109053    Table *pTo;                   /* Parent table of foreign key pFKey */
109054    Index *pIdx = 0;              /* Index on key columns in pTo */
109055    int *aiFree = 0;
109056    int *aiCol;
109057    int iCol;
109058    int i;
109059    int bIgnore = 0;
109060
109061    if( aChange
109062     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
109063     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
109064    ){
109065      continue;
109066    }
109067
109068    /* Find the parent table of this foreign key. Also find a unique index
109069    ** on the parent key columns in the parent table. If either of these
109070    ** schema items cannot be located, set an error in pParse and return
109071    ** early.  */
109072    if( pParse->disableTriggers ){
109073      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
109074    }else{
109075      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
109076    }
109077    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
109078      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
109079      if( !isIgnoreErrors || db->mallocFailed ) return;
109080      if( pTo==0 ){
109081        /* If isIgnoreErrors is true, then a table is being dropped. In this
109082        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
109083        ** before actually dropping it in order to check FK constraints.
109084        ** If the parent table of an FK constraint on the current table is
109085        ** missing, behave as if it is empty. i.e. decrement the relevant
109086        ** FK counter for each row of the current table with non-NULL keys.
109087        */
109088        Vdbe *v = sqlite3GetVdbe(pParse);
109089        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
109090        for(i=0; i<pFKey->nCol; i++){
109091          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
109092          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
109093        }
109094        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
109095      }
109096      continue;
109097    }
109098    assert( pFKey->nCol==1 || (aiFree && pIdx) );
109099
109100    if( aiFree ){
109101      aiCol = aiFree;
109102    }else{
109103      iCol = pFKey->aCol[0].iFrom;
109104      aiCol = &iCol;
109105    }
109106    for(i=0; i<pFKey->nCol; i++){
109107      if( aiCol[i]==pTab->iPKey ){
109108        aiCol[i] = -1;
109109      }
109110      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
109111#ifndef SQLITE_OMIT_AUTHORIZATION
109112      /* Request permission to read the parent key columns. If the
109113      ** authorization callback returns SQLITE_IGNORE, behave as if any
109114      ** values read from the parent table are NULL. */
109115      if( db->xAuth ){
109116        int rcauth;
109117        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
109118        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
109119        bIgnore = (rcauth==SQLITE_IGNORE);
109120      }
109121#endif
109122    }
109123
109124    /* Take a shared-cache advisory read-lock on the parent table. Allocate
109125    ** a cursor to use to search the unique index on the parent key columns
109126    ** in the parent table.  */
109127    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
109128    pParse->nTab++;
109129
109130    if( regOld!=0 ){
109131      /* A row is being removed from the child table. Search for the parent.
109132      ** If the parent does not exist, removing the child row resolves an
109133      ** outstanding foreign key constraint violation. */
109134      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
109135    }
109136    if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
109137      /* A row is being added to the child table. If a parent row cannot
109138      ** be found, adding the child row has violated the FK constraint.
109139      **
109140      ** If this operation is being performed as part of a trigger program
109141      ** that is actually a "SET NULL" action belonging to this very
109142      ** foreign key, then omit this scan altogether. As all child key
109143      ** values are guaranteed to be NULL, it is not possible for adding
109144      ** this row to cause an FK violation.  */
109145      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
109146    }
109147
109148    sqlite3DbFree(db, aiFree);
109149  }
109150
109151  /* Loop through all the foreign key constraints that refer to this table.
109152  ** (the "child" constraints) */
109153  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
109154    Index *pIdx = 0;              /* Foreign key index for pFKey */
109155    SrcList *pSrc;
109156    int *aiCol = 0;
109157
109158    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
109159      continue;
109160    }
109161
109162    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
109163     && !pParse->pToplevel && !pParse->isMultiWrite
109164    ){
109165      assert( regOld==0 && regNew!=0 );
109166      /* Inserting a single row into a parent table cannot cause (or fix)
109167      ** an immediate foreign key violation. So do nothing in this case.  */
109168      continue;
109169    }
109170
109171    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
109172      if( !isIgnoreErrors || db->mallocFailed ) return;
109173      continue;
109174    }
109175    assert( aiCol || pFKey->nCol==1 );
109176
109177    /* Create a SrcList structure containing the child table.  We need the
109178    ** child table as a SrcList for sqlite3WhereBegin() */
109179    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
109180    if( pSrc ){
109181      struct SrcList_item *pItem = pSrc->a;
109182      pItem->pTab = pFKey->pFrom;
109183      pItem->zName = pFKey->pFrom->zName;
109184      pItem->pTab->nTabRef++;
109185      pItem->iCursor = pParse->nTab++;
109186
109187      if( regNew!=0 ){
109188        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
109189      }
109190      if( regOld!=0 ){
109191        int eAction = pFKey->aAction[aChange!=0];
109192        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
109193        /* If this is a deferred FK constraint, or a CASCADE or SET NULL
109194        ** action applies, then any foreign key violations caused by
109195        ** removing the parent key will be rectified by the action trigger.
109196        ** So do not set the "may-abort" flag in this case.
109197        **
109198        ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
109199        ** may-abort flag will eventually be set on this statement anyway
109200        ** (when this function is called as part of processing the UPDATE
109201        ** within the action trigger).
109202        **
109203        ** Note 2: At first glance it may seem like SQLite could simply omit
109204        ** all OP_FkCounter related scans when either CASCADE or SET NULL
109205        ** applies. The trouble starts if the CASCADE or SET NULL action
109206        ** trigger causes other triggers or action rules attached to the
109207        ** child table to fire. In these cases the fk constraint counters
109208        ** might be set incorrectly if any OP_FkCounter related scans are
109209        ** omitted.  */
109210        if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
109211          sqlite3MayAbort(pParse);
109212        }
109213      }
109214      pItem->zName = 0;
109215      sqlite3SrcListDelete(db, pSrc);
109216    }
109217    sqlite3DbFree(db, aiCol);
109218  }
109219}
109220
109221#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
109222
109223/*
109224** This function is called before generating code to update or delete a
109225** row contained in table pTab.
109226*/
109227SQLITE_PRIVATE u32 sqlite3FkOldmask(
109228  Parse *pParse,                  /* Parse context */
109229  Table *pTab                     /* Table being modified */
109230){
109231  u32 mask = 0;
109232  if( pParse->db->flags&SQLITE_ForeignKeys ){
109233    FKey *p;
109234    int i;
109235    for(p=pTab->pFKey; p; p=p->pNextFrom){
109236      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
109237    }
109238    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
109239      Index *pIdx = 0;
109240      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
109241      if( pIdx ){
109242        for(i=0; i<pIdx->nKeyCol; i++){
109243          assert( pIdx->aiColumn[i]>=0 );
109244          mask |= COLUMN_MASK(pIdx->aiColumn[i]);
109245        }
109246      }
109247    }
109248  }
109249  return mask;
109250}
109251
109252
109253/*
109254** This function is called before generating code to update or delete a
109255** row contained in table pTab. If the operation is a DELETE, then
109256** parameter aChange is passed a NULL value. For an UPDATE, aChange points
109257** to an array of size N, where N is the number of columns in table pTab.
109258** If the i'th column is not modified by the UPDATE, then the corresponding
109259** entry in the aChange[] array is set to -1. If the column is modified,
109260** the value is 0 or greater. Parameter chngRowid is set to true if the
109261** UPDATE statement modifies the rowid fields of the table.
109262**
109263** If any foreign key processing will be required, this function returns
109264** non-zero. If there is no foreign key related processing, this function
109265** returns zero.
109266**
109267** For an UPDATE, this function returns 2 if:
109268**
109269**   * There are any FKs for which pTab is the child and the parent table, or
109270**   * the UPDATE modifies one or more parent keys for which the action is
109271**     not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
109272**
109273** Or, assuming some other foreign key processing is required, 1.
109274*/
109275SQLITE_PRIVATE int sqlite3FkRequired(
109276  Parse *pParse,                  /* Parse context */
109277  Table *pTab,                    /* Table being modified */
109278  int *aChange,                   /* Non-NULL for UPDATE operations */
109279  int chngRowid                   /* True for UPDATE that affects rowid */
109280){
109281  int eRet = 0;
109282  if( pParse->db->flags&SQLITE_ForeignKeys ){
109283    if( !aChange ){
109284      /* A DELETE operation. Foreign key processing is required if the
109285      ** table in question is either the child or parent table for any
109286      ** foreign key constraint.  */
109287      eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
109288    }else{
109289      /* This is an UPDATE. Foreign key processing is only required if the
109290      ** operation modifies one or more child or parent key columns. */
109291      FKey *p;
109292
109293      /* Check if any child key columns are being modified. */
109294      for(p=pTab->pFKey; p; p=p->pNextFrom){
109295        if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
109296        if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
109297          eRet = 1;
109298        }
109299      }
109300
109301      /* Check if any parent key columns are being modified. */
109302      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
109303        if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
109304          if( p->aAction[1]!=OE_None ) return 2;
109305          eRet = 1;
109306        }
109307      }
109308    }
109309  }
109310  return eRet;
109311}
109312
109313/*
109314** This function is called when an UPDATE or DELETE operation is being
109315** compiled on table pTab, which is the parent table of foreign-key pFKey.
109316** If the current operation is an UPDATE, then the pChanges parameter is
109317** passed a pointer to the list of columns being modified. If it is a
109318** DELETE, pChanges is passed a NULL pointer.
109319**
109320** It returns a pointer to a Trigger structure containing a trigger
109321** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
109322** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
109323** returned (these actions require no special handling by the triggers
109324** sub-system, code for them is created by fkScanChildren()).
109325**
109326** For example, if pFKey is the foreign key and pTab is table "p" in
109327** the following schema:
109328**
109329**   CREATE TABLE p(pk PRIMARY KEY);
109330**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
109331**
109332** then the returned trigger structure is equivalent to:
109333**
109334**   CREATE TRIGGER ... DELETE ON p BEGIN
109335**     DELETE FROM c WHERE ck = old.pk;
109336**   END;
109337**
109338** The returned pointer is cached as part of the foreign key object. It
109339** is eventually freed along with the rest of the foreign key object by
109340** sqlite3FkDelete().
109341*/
109342static Trigger *fkActionTrigger(
109343  Parse *pParse,                  /* Parse context */
109344  Table *pTab,                    /* Table being updated or deleted from */
109345  FKey *pFKey,                    /* Foreign key to get action for */
109346  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
109347){
109348  sqlite3 *db = pParse->db;       /* Database handle */
109349  int action;                     /* One of OE_None, OE_Cascade etc. */
109350  Trigger *pTrigger;              /* Trigger definition to return */
109351  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
109352
109353  action = pFKey->aAction[iAction];
109354  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
109355    return 0;
109356  }
109357  pTrigger = pFKey->apTrigger[iAction];
109358
109359  if( action!=OE_None && !pTrigger ){
109360    char const *zFrom;            /* Name of child table */
109361    int nFrom;                    /* Length in bytes of zFrom */
109362    Index *pIdx = 0;              /* Parent key index for this FK */
109363    int *aiCol = 0;               /* child table cols -> parent key cols */
109364    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
109365    Expr *pWhere = 0;             /* WHERE clause of trigger step */
109366    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
109367    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
109368    int i;                        /* Iterator variable */
109369    Expr *pWhen = 0;              /* WHEN clause for the trigger */
109370
109371    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
109372    assert( aiCol || pFKey->nCol==1 );
109373
109374    for(i=0; i<pFKey->nCol; i++){
109375      Token tOld = { "old", 3 };  /* Literal "old" token */
109376      Token tNew = { "new", 3 };  /* Literal "new" token */
109377      Token tFromCol;             /* Name of column in child table */
109378      Token tToCol;               /* Name of column in parent table */
109379      int iFromCol;               /* Idx of column in child table */
109380      Expr *pEq;                  /* tFromCol = OLD.tToCol */
109381
109382      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
109383      assert( iFromCol>=0 );
109384      assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
109385      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
109386      sqlite3TokenInit(&tToCol,
109387                   pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
109388      sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
109389
109390      /* Create the expression "OLD.zToCol = zFromCol". It is important
109391      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
109392      ** that the affinity and collation sequence associated with the
109393      ** parent table are used for the comparison. */
109394      pEq = sqlite3PExpr(pParse, TK_EQ,
109395          sqlite3PExpr(pParse, TK_DOT,
109396            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
109397            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
109398          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
109399      );
109400      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
109401
109402      /* For ON UPDATE, construct the next term of the WHEN clause.
109403      ** The final WHEN clause will be like this:
109404      **
109405      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
109406      */
109407      if( pChanges ){
109408        pEq = sqlite3PExpr(pParse, TK_IS,
109409            sqlite3PExpr(pParse, TK_DOT,
109410              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
109411              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
109412            sqlite3PExpr(pParse, TK_DOT,
109413              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
109414              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
109415            );
109416        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
109417      }
109418
109419      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
109420        Expr *pNew;
109421        if( action==OE_Cascade ){
109422          pNew = sqlite3PExpr(pParse, TK_DOT,
109423            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
109424            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
109425        }else if( action==OE_SetDflt ){
109426          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
109427          if( pDflt ){
109428            pNew = sqlite3ExprDup(db, pDflt, 0);
109429          }else{
109430            pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
109431          }
109432        }else{
109433          pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
109434        }
109435        pList = sqlite3ExprListAppend(pParse, pList, pNew);
109436        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
109437      }
109438    }
109439    sqlite3DbFree(db, aiCol);
109440
109441    zFrom = pFKey->pFrom->zName;
109442    nFrom = sqlite3Strlen30(zFrom);
109443
109444    if( action==OE_Restrict ){
109445      Token tFrom;
109446      Expr *pRaise;
109447
109448      tFrom.z = zFrom;
109449      tFrom.n = nFrom;
109450      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
109451      if( pRaise ){
109452        pRaise->affinity = OE_Abort;
109453      }
109454      pSelect = sqlite3SelectNew(pParse,
109455          sqlite3ExprListAppend(pParse, 0, pRaise),
109456          sqlite3SrcListAppend(db, 0, &tFrom, 0),
109457          pWhere,
109458          0, 0, 0, 0, 0, 0
109459      );
109460      pWhere = 0;
109461    }
109462
109463    /* Disable lookaside memory allocation */
109464    db->lookaside.bDisable++;
109465
109466    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
109467        sizeof(Trigger) +         /* struct Trigger */
109468        sizeof(TriggerStep) +     /* Single step in trigger program */
109469        nFrom + 1                 /* Space for pStep->zTarget */
109470    );
109471    if( pTrigger ){
109472      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
109473      pStep->zTarget = (char *)&pStep[1];
109474      memcpy((char *)pStep->zTarget, zFrom, nFrom);
109475
109476      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
109477      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
109478      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
109479      if( pWhen ){
109480        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
109481        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
109482      }
109483    }
109484
109485    /* Re-enable the lookaside buffer, if it was disabled earlier. */
109486    db->lookaside.bDisable--;
109487
109488    sqlite3ExprDelete(db, pWhere);
109489    sqlite3ExprDelete(db, pWhen);
109490    sqlite3ExprListDelete(db, pList);
109491    sqlite3SelectDelete(db, pSelect);
109492    if( db->mallocFailed==1 ){
109493      fkTriggerDelete(db, pTrigger);
109494      return 0;
109495    }
109496    assert( pStep!=0 );
109497
109498    switch( action ){
109499      case OE_Restrict:
109500        pStep->op = TK_SELECT;
109501        break;
109502      case OE_Cascade:
109503        if( !pChanges ){
109504          pStep->op = TK_DELETE;
109505          break;
109506        }
109507      default:
109508        pStep->op = TK_UPDATE;
109509    }
109510    pStep->pTrig = pTrigger;
109511    pTrigger->pSchema = pTab->pSchema;
109512    pTrigger->pTabSchema = pTab->pSchema;
109513    pFKey->apTrigger[iAction] = pTrigger;
109514    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
109515  }
109516
109517  return pTrigger;
109518}
109519
109520/*
109521** This function is called when deleting or updating a row to implement
109522** any required CASCADE, SET NULL or SET DEFAULT actions.
109523*/
109524SQLITE_PRIVATE void sqlite3FkActions(
109525  Parse *pParse,                  /* Parse context */
109526  Table *pTab,                    /* Table being updated or deleted from */
109527  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
109528  int regOld,                     /* Address of array containing old row */
109529  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
109530  int bChngRowid                  /* True if rowid is UPDATEd */
109531){
109532  /* If foreign-key support is enabled, iterate through all FKs that
109533  ** refer to table pTab. If there is an action associated with the FK
109534  ** for this operation (either update or delete), invoke the associated
109535  ** trigger sub-program.  */
109536  if( pParse->db->flags&SQLITE_ForeignKeys ){
109537    FKey *pFKey;                  /* Iterator variable */
109538    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
109539      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
109540        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
109541        if( pAct ){
109542          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
109543        }
109544      }
109545    }
109546  }
109547}
109548
109549#endif /* ifndef SQLITE_OMIT_TRIGGER */
109550
109551/*
109552** Free all memory associated with foreign key definitions attached to
109553** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
109554** hash table.
109555*/
109556SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
109557  FKey *pFKey;                    /* Iterator variable */
109558  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
109559
109560  assert( db==0 || IsVirtual(pTab)
109561         || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
109562  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
109563
109564    /* Remove the FK from the fkeyHash hash table. */
109565    if( !db || db->pnBytesFreed==0 ){
109566      if( pFKey->pPrevTo ){
109567        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
109568      }else{
109569        void *p = (void *)pFKey->pNextTo;
109570        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
109571        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
109572      }
109573      if( pFKey->pNextTo ){
109574        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
109575      }
109576    }
109577
109578    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
109579    ** classified as either immediate or deferred.
109580    */
109581    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
109582
109583    /* Delete any triggers created to implement actions for this FK. */
109584#ifndef SQLITE_OMIT_TRIGGER
109585    fkTriggerDelete(db, pFKey->apTrigger[0]);
109586    fkTriggerDelete(db, pFKey->apTrigger[1]);
109587#endif
109588
109589    pNext = pFKey->pNextFrom;
109590    sqlite3DbFree(db, pFKey);
109591  }
109592}
109593#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
109594
109595/************** End of fkey.c ************************************************/
109596/************** Begin file insert.c ******************************************/
109597/*
109598** 2001 September 15
109599**
109600** The author disclaims copyright to this source code.  In place of
109601** a legal notice, here is a blessing:
109602**
109603**    May you do good and not evil.
109604**    May you find forgiveness for yourself and forgive others.
109605**    May you share freely, never taking more than you give.
109606**
109607*************************************************************************
109608** This file contains C code routines that are called by the parser
109609** to handle INSERT statements in SQLite.
109610*/
109611/* #include "sqliteInt.h" */
109612
109613/*
109614** Generate code that will
109615**
109616**   (1) acquire a lock for table pTab then
109617**   (2) open pTab as cursor iCur.
109618**
109619** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
109620** for that table that is actually opened.
109621*/
109622SQLITE_PRIVATE void sqlite3OpenTable(
109623  Parse *pParse,  /* Generate code into this VDBE */
109624  int iCur,       /* The cursor number of the table */
109625  int iDb,        /* The database index in sqlite3.aDb[] */
109626  Table *pTab,    /* The table to be opened */
109627  int opcode      /* OP_OpenRead or OP_OpenWrite */
109628){
109629  Vdbe *v;
109630  assert( !IsVirtual(pTab) );
109631  v = sqlite3GetVdbe(pParse);
109632  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
109633  sqlite3TableLock(pParse, iDb, pTab->tnum,
109634                   (opcode==OP_OpenWrite)?1:0, pTab->zName);
109635  if( HasRowid(pTab) ){
109636    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
109637    VdbeComment((v, "%s", pTab->zName));
109638  }else{
109639    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
109640    assert( pPk!=0 );
109641    assert( pPk->tnum==pTab->tnum );
109642    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
109643    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
109644    VdbeComment((v, "%s", pTab->zName));
109645  }
109646}
109647
109648/*
109649** Return a pointer to the column affinity string associated with index
109650** pIdx. A column affinity string has one character for each column in
109651** the table, according to the affinity of the column:
109652**
109653**  Character      Column affinity
109654**  ------------------------------
109655**  'A'            BLOB
109656**  'B'            TEXT
109657**  'C'            NUMERIC
109658**  'D'            INTEGER
109659**  'F'            REAL
109660**
109661** An extra 'D' is appended to the end of the string to cover the
109662** rowid that appears as the last column in every index.
109663**
109664** Memory for the buffer containing the column index affinity string
109665** is managed along with the rest of the Index structure. It will be
109666** released when sqlite3DeleteIndex() is called.
109667*/
109668SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
109669  if( !pIdx->zColAff ){
109670    /* The first time a column affinity string for a particular index is
109671    ** required, it is allocated and populated here. It is then stored as
109672    ** a member of the Index structure for subsequent use.
109673    **
109674    ** The column affinity string will eventually be deleted by
109675    ** sqliteDeleteIndex() when the Index structure itself is cleaned
109676    ** up.
109677    */
109678    int n;
109679    Table *pTab = pIdx->pTable;
109680    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
109681    if( !pIdx->zColAff ){
109682      sqlite3OomFault(db);
109683      return 0;
109684    }
109685    for(n=0; n<pIdx->nColumn; n++){
109686      i16 x = pIdx->aiColumn[n];
109687      if( x>=0 ){
109688        pIdx->zColAff[n] = pTab->aCol[x].affinity;
109689      }else if( x==XN_ROWID ){
109690        pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
109691      }else{
109692        char aff;
109693        assert( x==XN_EXPR );
109694        assert( pIdx->aColExpr!=0 );
109695        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
109696        if( aff==0 ) aff = SQLITE_AFF_BLOB;
109697        pIdx->zColAff[n] = aff;
109698      }
109699    }
109700    pIdx->zColAff[n] = 0;
109701  }
109702
109703  return pIdx->zColAff;
109704}
109705
109706/*
109707** Compute the affinity string for table pTab, if it has not already been
109708** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
109709**
109710** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
109711** if iReg>0 then code an OP_Affinity opcode that will set the affinities
109712** for register iReg and following.  Or if affinities exists and iReg==0,
109713** then just set the P4 operand of the previous opcode (which should  be
109714** an OP_MakeRecord) to the affinity string.
109715**
109716** A column affinity string has one character per column:
109717**
109718**  Character      Column affinity
109719**  ------------------------------
109720**  'A'            BLOB
109721**  'B'            TEXT
109722**  'C'            NUMERIC
109723**  'D'            INTEGER
109724**  'E'            REAL
109725*/
109726SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
109727  int i;
109728  char *zColAff = pTab->zColAff;
109729  if( zColAff==0 ){
109730    sqlite3 *db = sqlite3VdbeDb(v);
109731    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
109732    if( !zColAff ){
109733      sqlite3OomFault(db);
109734      return;
109735    }
109736
109737    for(i=0; i<pTab->nCol; i++){
109738      zColAff[i] = pTab->aCol[i].affinity;
109739    }
109740    do{
109741      zColAff[i--] = 0;
109742    }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
109743    pTab->zColAff = zColAff;
109744  }
109745  i = sqlite3Strlen30(zColAff);
109746  if( i ){
109747    if( iReg ){
109748      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
109749    }else{
109750      sqlite3VdbeChangeP4(v, -1, zColAff, i);
109751    }
109752  }
109753}
109754
109755/*
109756** Return non-zero if the table pTab in database iDb or any of its indices
109757** have been opened at any point in the VDBE program. This is used to see if
109758** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
109759** run without using a temporary table for the results of the SELECT.
109760*/
109761static int readsTable(Parse *p, int iDb, Table *pTab){
109762  Vdbe *v = sqlite3GetVdbe(p);
109763  int i;
109764  int iEnd = sqlite3VdbeCurrentAddr(v);
109765#ifndef SQLITE_OMIT_VIRTUALTABLE
109766  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
109767#endif
109768
109769  for(i=1; i<iEnd; i++){
109770    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
109771    assert( pOp!=0 );
109772    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
109773      Index *pIndex;
109774      int tnum = pOp->p2;
109775      if( tnum==pTab->tnum ){
109776        return 1;
109777      }
109778      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
109779        if( tnum==pIndex->tnum ){
109780          return 1;
109781        }
109782      }
109783    }
109784#ifndef SQLITE_OMIT_VIRTUALTABLE
109785    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
109786      assert( pOp->p4.pVtab!=0 );
109787      assert( pOp->p4type==P4_VTAB );
109788      return 1;
109789    }
109790#endif
109791  }
109792  return 0;
109793}
109794
109795#ifndef SQLITE_OMIT_AUTOINCREMENT
109796/*
109797** Locate or create an AutoincInfo structure associated with table pTab
109798** which is in database iDb.  Return the register number for the register
109799** that holds the maximum rowid.  Return zero if pTab is not an AUTOINCREMENT
109800** table.  (Also return zero when doing a VACUUM since we do not want to
109801** update the AUTOINCREMENT counters during a VACUUM.)
109802**
109803** There is at most one AutoincInfo structure per table even if the
109804** same table is autoincremented multiple times due to inserts within
109805** triggers.  A new AutoincInfo structure is created if this is the
109806** first use of table pTab.  On 2nd and subsequent uses, the original
109807** AutoincInfo structure is used.
109808**
109809** Three memory locations are allocated:
109810**
109811**   (1)  Register to hold the name of the pTab table.
109812**   (2)  Register to hold the maximum ROWID of pTab.
109813**   (3)  Register to hold the rowid in sqlite_sequence of pTab
109814**
109815** The 2nd register is the one that is returned.  That is all the
109816** insert routine needs to know about.
109817*/
109818static int autoIncBegin(
109819  Parse *pParse,      /* Parsing context */
109820  int iDb,            /* Index of the database holding pTab */
109821  Table *pTab         /* The table we are writing to */
109822){
109823  int memId = 0;      /* Register holding maximum rowid */
109824  if( (pTab->tabFlags & TF_Autoincrement)!=0
109825   && (pParse->db->flags & SQLITE_Vacuum)==0
109826  ){
109827    Parse *pToplevel = sqlite3ParseToplevel(pParse);
109828    AutoincInfo *pInfo;
109829
109830    pInfo = pToplevel->pAinc;
109831    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
109832    if( pInfo==0 ){
109833      pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
109834      if( pInfo==0 ) return 0;
109835      pInfo->pNext = pToplevel->pAinc;
109836      pToplevel->pAinc = pInfo;
109837      pInfo->pTab = pTab;
109838      pInfo->iDb = iDb;
109839      pToplevel->nMem++;                  /* Register to hold name of table */
109840      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
109841      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
109842    }
109843    memId = pInfo->regCtr;
109844  }
109845  return memId;
109846}
109847
109848/*
109849** This routine generates code that will initialize all of the
109850** register used by the autoincrement tracker.
109851*/
109852SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
109853  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
109854  sqlite3 *db = pParse->db;  /* The database connection */
109855  Db *pDb;                   /* Database only autoinc table */
109856  int memId;                 /* Register holding max rowid */
109857  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
109858
109859  /* This routine is never called during trigger-generation.  It is
109860  ** only called from the top-level */
109861  assert( pParse->pTriggerTab==0 );
109862  assert( sqlite3IsToplevel(pParse) );
109863
109864  assert( v );   /* We failed long ago if this is not so */
109865  for(p = pParse->pAinc; p; p = p->pNext){
109866    static const int iLn = VDBE_OFFSET_LINENO(2);
109867    static const VdbeOpList autoInc[] = {
109868      /* 0  */ {OP_Null,    0,  0, 0},
109869      /* 1  */ {OP_Rewind,  0,  9, 0},
109870      /* 2  */ {OP_Column,  0,  0, 0},
109871      /* 3  */ {OP_Ne,      0,  7, 0},
109872      /* 4  */ {OP_Rowid,   0,  0, 0},
109873      /* 5  */ {OP_Column,  0,  1, 0},
109874      /* 6  */ {OP_Goto,    0,  9, 0},
109875      /* 7  */ {OP_Next,    0,  2, 0},
109876      /* 8  */ {OP_Integer, 0,  0, 0},
109877      /* 9  */ {OP_Close,   0,  0, 0}
109878    };
109879    VdbeOp *aOp;
109880    pDb = &db->aDb[p->iDb];
109881    memId = p->regCtr;
109882    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
109883    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
109884    sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
109885    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
109886    if( aOp==0 ) break;
109887    aOp[0].p2 = memId;
109888    aOp[0].p3 = memId+1;
109889    aOp[2].p3 = memId;
109890    aOp[3].p1 = memId-1;
109891    aOp[3].p3 = memId;
109892    aOp[3].p5 = SQLITE_JUMPIFNULL;
109893    aOp[4].p2 = memId+1;
109894    aOp[5].p3 = memId;
109895    aOp[8].p2 = memId;
109896  }
109897}
109898
109899/*
109900** Update the maximum rowid for an autoincrement calculation.
109901**
109902** This routine should be called when the regRowid register holds a
109903** new rowid that is about to be inserted.  If that new rowid is
109904** larger than the maximum rowid in the memId memory cell, then the
109905** memory cell is updated.
109906*/
109907static void autoIncStep(Parse *pParse, int memId, int regRowid){
109908  if( memId>0 ){
109909    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
109910  }
109911}
109912
109913/*
109914** This routine generates the code needed to write autoincrement
109915** maximum rowid values back into the sqlite_sequence register.
109916** Every statement that might do an INSERT into an autoincrement
109917** table (either directly or through triggers) needs to call this
109918** routine just before the "exit" code.
109919*/
109920static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
109921  AutoincInfo *p;
109922  Vdbe *v = pParse->pVdbe;
109923  sqlite3 *db = pParse->db;
109924
109925  assert( v );
109926  for(p = pParse->pAinc; p; p = p->pNext){
109927    static const int iLn = VDBE_OFFSET_LINENO(2);
109928    static const VdbeOpList autoIncEnd[] = {
109929      /* 0 */ {OP_NotNull,     0, 2, 0},
109930      /* 1 */ {OP_NewRowid,    0, 0, 0},
109931      /* 2 */ {OP_MakeRecord,  0, 2, 0},
109932      /* 3 */ {OP_Insert,      0, 0, 0},
109933      /* 4 */ {OP_Close,       0, 0, 0}
109934    };
109935    VdbeOp *aOp;
109936    Db *pDb = &db->aDb[p->iDb];
109937    int iRec;
109938    int memId = p->regCtr;
109939
109940    iRec = sqlite3GetTempReg(pParse);
109941    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
109942    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
109943    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
109944    if( aOp==0 ) break;
109945    aOp[0].p1 = memId+1;
109946    aOp[1].p2 = memId+1;
109947    aOp[2].p1 = memId-1;
109948    aOp[2].p3 = iRec;
109949    aOp[3].p2 = iRec;
109950    aOp[3].p3 = memId+1;
109951    aOp[3].p5 = OPFLAG_APPEND;
109952    sqlite3ReleaseTempReg(pParse, iRec);
109953  }
109954}
109955SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
109956  if( pParse->pAinc ) autoIncrementEnd(pParse);
109957}
109958#else
109959/*
109960** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
109961** above are all no-ops
109962*/
109963# define autoIncBegin(A,B,C) (0)
109964# define autoIncStep(A,B,C)
109965#endif /* SQLITE_OMIT_AUTOINCREMENT */
109966
109967
109968/* Forward declaration */
109969static int xferOptimization(
109970  Parse *pParse,        /* Parser context */
109971  Table *pDest,         /* The table we are inserting into */
109972  Select *pSelect,      /* A SELECT statement to use as the data source */
109973  int onError,          /* How to handle constraint errors */
109974  int iDbDest           /* The database of pDest */
109975);
109976
109977/*
109978** This routine is called to handle SQL of the following forms:
109979**
109980**    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
109981**    insert into TABLE (IDLIST) select
109982**    insert into TABLE (IDLIST) default values
109983**
109984** The IDLIST following the table name is always optional.  If omitted,
109985** then a list of all (non-hidden) columns for the table is substituted.
109986** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
109987** is omitted.
109988**
109989** For the pSelect parameter holds the values to be inserted for the
109990** first two forms shown above.  A VALUES clause is really just short-hand
109991** for a SELECT statement that omits the FROM clause and everything else
109992** that follows.  If the pSelect parameter is NULL, that means that the
109993** DEFAULT VALUES form of the INSERT statement is intended.
109994**
109995** The code generated follows one of four templates.  For a simple
109996** insert with data coming from a single-row VALUES clause, the code executes
109997** once straight down through.  Pseudo-code follows (we call this
109998** the "1st template"):
109999**
110000**         open write cursor to <table> and its indices
110001**         put VALUES clause expressions into registers
110002**         write the resulting record into <table>
110003**         cleanup
110004**
110005** The three remaining templates assume the statement is of the form
110006**
110007**   INSERT INTO <table> SELECT ...
110008**
110009** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
110010** in other words if the SELECT pulls all columns from a single table
110011** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
110012** if <table2> and <table1> are distinct tables but have identical
110013** schemas, including all the same indices, then a special optimization
110014** is invoked that copies raw records from <table2> over to <table1>.
110015** See the xferOptimization() function for the implementation of this
110016** template.  This is the 2nd template.
110017**
110018**         open a write cursor to <table>
110019**         open read cursor on <table2>
110020**         transfer all records in <table2> over to <table>
110021**         close cursors
110022**         foreach index on <table>
110023**           open a write cursor on the <table> index
110024**           open a read cursor on the corresponding <table2> index
110025**           transfer all records from the read to the write cursors
110026**           close cursors
110027**         end foreach
110028**
110029** The 3rd template is for when the second template does not apply
110030** and the SELECT clause does not read from <table> at any time.
110031** The generated code follows this template:
110032**
110033**         X <- A
110034**         goto B
110035**      A: setup for the SELECT
110036**         loop over the rows in the SELECT
110037**           load values into registers R..R+n
110038**           yield X
110039**         end loop
110040**         cleanup after the SELECT
110041**         end-coroutine X
110042**      B: open write cursor to <table> and its indices
110043**      C: yield X, at EOF goto D
110044**         insert the select result into <table> from R..R+n
110045**         goto C
110046**      D: cleanup
110047**
110048** The 4th template is used if the insert statement takes its
110049** values from a SELECT but the data is being inserted into a table
110050** that is also read as part of the SELECT.  In the third form,
110051** we have to use an intermediate table to store the results of
110052** the select.  The template is like this:
110053**
110054**         X <- A
110055**         goto B
110056**      A: setup for the SELECT
110057**         loop over the tables in the SELECT
110058**           load value into register R..R+n
110059**           yield X
110060**         end loop
110061**         cleanup after the SELECT
110062**         end co-routine R
110063**      B: open temp table
110064**      L: yield X, at EOF goto M
110065**         insert row from R..R+n into temp table
110066**         goto L
110067**      M: open write cursor to <table> and its indices
110068**         rewind temp table
110069**      C: loop over rows of intermediate table
110070**           transfer values form intermediate table into <table>
110071**         end loop
110072**      D: cleanup
110073*/
110074SQLITE_PRIVATE void sqlite3Insert(
110075  Parse *pParse,        /* Parser context */
110076  SrcList *pTabList,    /* Name of table into which we are inserting */
110077  Select *pSelect,      /* A SELECT statement to use as the data source */
110078  IdList *pColumn,      /* Column names corresponding to IDLIST. */
110079  int onError           /* How to handle constraint errors */
110080){
110081  sqlite3 *db;          /* The main database structure */
110082  Table *pTab;          /* The table to insert into.  aka TABLE */
110083  char *zTab;           /* Name of the table into which we are inserting */
110084  int i, j;             /* Loop counters */
110085  Vdbe *v;              /* Generate code into this virtual machine */
110086  Index *pIdx;          /* For looping over indices of the table */
110087  int nColumn;          /* Number of columns in the data */
110088  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
110089  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
110090  int iIdxCur = 0;      /* First index cursor */
110091  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
110092  int endOfLoop;        /* Label for the end of the insertion loop */
110093  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
110094  int addrInsTop = 0;   /* Jump to label "D" */
110095  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
110096  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
110097  int iDb;              /* Index of database holding TABLE */
110098  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
110099  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
110100  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
110101  u8 bIdListInOrder;    /* True if IDLIST is in table order */
110102  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
110103
110104  /* Register allocations */
110105  int regFromSelect = 0;/* Base register for data coming from SELECT */
110106  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
110107  int regRowCount = 0;  /* Memory cell used for the row counter */
110108  int regIns;           /* Block of regs holding rowid+data being inserted */
110109  int regRowid;         /* registers holding insert rowid */
110110  int regData;          /* register holding first column to insert */
110111  int *aRegIdx = 0;     /* One register allocated to each index */
110112
110113#ifndef SQLITE_OMIT_TRIGGER
110114  int isView;                 /* True if attempting to insert into a view */
110115  Trigger *pTrigger;          /* List of triggers on pTab, if required */
110116  int tmask;                  /* Mask of trigger times */
110117#endif
110118
110119  db = pParse->db;
110120  if( pParse->nErr || db->mallocFailed ){
110121    goto insert_cleanup;
110122  }
110123  dest.iSDParm = 0;  /* Suppress a harmless compiler warning */
110124
110125  /* If the Select object is really just a simple VALUES() list with a
110126  ** single row (the common case) then keep that one row of values
110127  ** and discard the other (unused) parts of the pSelect object
110128  */
110129  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
110130    pList = pSelect->pEList;
110131    pSelect->pEList = 0;
110132    sqlite3SelectDelete(db, pSelect);
110133    pSelect = 0;
110134  }
110135
110136  /* Locate the table into which we will be inserting new information.
110137  */
110138  assert( pTabList->nSrc==1 );
110139  zTab = pTabList->a[0].zName;
110140  if( NEVER(zTab==0) ) goto insert_cleanup;
110141  pTab = sqlite3SrcListLookup(pParse, pTabList);
110142  if( pTab==0 ){
110143    goto insert_cleanup;
110144  }
110145  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110146  assert( iDb<db->nDb );
110147  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
110148                       db->aDb[iDb].zDbSName) ){
110149    goto insert_cleanup;
110150  }
110151  withoutRowid = !HasRowid(pTab);
110152
110153  /* Figure out if we have any triggers and if the table being
110154  ** inserted into is a view
110155  */
110156#ifndef SQLITE_OMIT_TRIGGER
110157  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
110158  isView = pTab->pSelect!=0;
110159#else
110160# define pTrigger 0
110161# define tmask 0
110162# define isView 0
110163#endif
110164#ifdef SQLITE_OMIT_VIEW
110165# undef isView
110166# define isView 0
110167#endif
110168  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
110169
110170  /* If pTab is really a view, make sure it has been initialized.
110171  ** ViewGetColumnNames() is a no-op if pTab is not a view.
110172  */
110173  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
110174    goto insert_cleanup;
110175  }
110176
110177  /* Cannot insert into a read-only table.
110178  */
110179  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
110180    goto insert_cleanup;
110181  }
110182
110183  /* Allocate a VDBE
110184  */
110185  v = sqlite3GetVdbe(pParse);
110186  if( v==0 ) goto insert_cleanup;
110187  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
110188  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
110189
110190#ifndef SQLITE_OMIT_XFER_OPT
110191  /* If the statement is of the form
110192  **
110193  **       INSERT INTO <table1> SELECT * FROM <table2>;
110194  **
110195  ** Then special optimizations can be applied that make the transfer
110196  ** very fast and which reduce fragmentation of indices.
110197  **
110198  ** This is the 2nd template.
110199  */
110200  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
110201    assert( !pTrigger );
110202    assert( pList==0 );
110203    goto insert_end;
110204  }
110205#endif /* SQLITE_OMIT_XFER_OPT */
110206
110207  /* If this is an AUTOINCREMENT table, look up the sequence number in the
110208  ** sqlite_sequence table and store it in memory cell regAutoinc.
110209  */
110210  regAutoinc = autoIncBegin(pParse, iDb, pTab);
110211
110212  /* Allocate registers for holding the rowid of the new row,
110213  ** the content of the new row, and the assembled row record.
110214  */
110215  regRowid = regIns = pParse->nMem+1;
110216  pParse->nMem += pTab->nCol + 1;
110217  if( IsVirtual(pTab) ){
110218    regRowid++;
110219    pParse->nMem++;
110220  }
110221  regData = regRowid+1;
110222
110223  /* If the INSERT statement included an IDLIST term, then make sure
110224  ** all elements of the IDLIST really are columns of the table and
110225  ** remember the column indices.
110226  **
110227  ** If the table has an INTEGER PRIMARY KEY column and that column
110228  ** is named in the IDLIST, then record in the ipkColumn variable
110229  ** the index into IDLIST of the primary key column.  ipkColumn is
110230  ** the index of the primary key as it appears in IDLIST, not as
110231  ** is appears in the original table.  (The index of the INTEGER
110232  ** PRIMARY KEY in the original table is pTab->iPKey.)
110233  */
110234  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
110235  if( pColumn ){
110236    for(i=0; i<pColumn->nId; i++){
110237      pColumn->a[i].idx = -1;
110238    }
110239    for(i=0; i<pColumn->nId; i++){
110240      for(j=0; j<pTab->nCol; j++){
110241        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
110242          pColumn->a[i].idx = j;
110243          if( i!=j ) bIdListInOrder = 0;
110244          if( j==pTab->iPKey ){
110245            ipkColumn = i;  assert( !withoutRowid );
110246          }
110247          break;
110248        }
110249      }
110250      if( j>=pTab->nCol ){
110251        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
110252          ipkColumn = i;
110253          bIdListInOrder = 0;
110254        }else{
110255          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
110256              pTabList, 0, pColumn->a[i].zName);
110257          pParse->checkSchema = 1;
110258          goto insert_cleanup;
110259        }
110260      }
110261    }
110262  }
110263
110264  /* Figure out how many columns of data are supplied.  If the data
110265  ** is coming from a SELECT statement, then generate a co-routine that
110266  ** produces a single row of the SELECT on each invocation.  The
110267  ** co-routine is the common header to the 3rd and 4th templates.
110268  */
110269  if( pSelect ){
110270    /* Data is coming from a SELECT or from a multi-row VALUES clause.
110271    ** Generate a co-routine to run the SELECT. */
110272    int regYield;       /* Register holding co-routine entry-point */
110273    int addrTop;        /* Top of the co-routine */
110274    int rc;             /* Result code */
110275
110276    regYield = ++pParse->nMem;
110277    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
110278    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
110279    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
110280    dest.iSdst = bIdListInOrder ? regData : 0;
110281    dest.nSdst = pTab->nCol;
110282    rc = sqlite3Select(pParse, pSelect, &dest);
110283    regFromSelect = dest.iSdst;
110284    if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
110285    sqlite3VdbeEndCoroutine(v, regYield);
110286    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
110287    assert( pSelect->pEList );
110288    nColumn = pSelect->pEList->nExpr;
110289
110290    /* Set useTempTable to TRUE if the result of the SELECT statement
110291    ** should be written into a temporary table (template 4).  Set to
110292    ** FALSE if each output row of the SELECT can be written directly into
110293    ** the destination table (template 3).
110294    **
110295    ** A temp table must be used if the table being updated is also one
110296    ** of the tables being read by the SELECT statement.  Also use a
110297    ** temp table in the case of row triggers.
110298    */
110299    if( pTrigger || readsTable(pParse, iDb, pTab) ){
110300      useTempTable = 1;
110301    }
110302
110303    if( useTempTable ){
110304      /* Invoke the coroutine to extract information from the SELECT
110305      ** and add it to a transient table srcTab.  The code generated
110306      ** here is from the 4th template:
110307      **
110308      **      B: open temp table
110309      **      L: yield X, goto M at EOF
110310      **         insert row from R..R+n into temp table
110311      **         goto L
110312      **      M: ...
110313      */
110314      int regRec;          /* Register to hold packed record */
110315      int regTempRowid;    /* Register to hold temp table ROWID */
110316      int addrL;           /* Label "L" */
110317
110318      srcTab = pParse->nTab++;
110319      regRec = sqlite3GetTempReg(pParse);
110320      regTempRowid = sqlite3GetTempReg(pParse);
110321      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
110322      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
110323      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
110324      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
110325      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
110326      sqlite3VdbeGoto(v, addrL);
110327      sqlite3VdbeJumpHere(v, addrL);
110328      sqlite3ReleaseTempReg(pParse, regRec);
110329      sqlite3ReleaseTempReg(pParse, regTempRowid);
110330    }
110331  }else{
110332    /* This is the case if the data for the INSERT is coming from a
110333    ** single-row VALUES clause
110334    */
110335    NameContext sNC;
110336    memset(&sNC, 0, sizeof(sNC));
110337    sNC.pParse = pParse;
110338    srcTab = -1;
110339    assert( useTempTable==0 );
110340    if( pList ){
110341      nColumn = pList->nExpr;
110342      if( sqlite3ResolveExprListNames(&sNC, pList) ){
110343        goto insert_cleanup;
110344      }
110345    }else{
110346      nColumn = 0;
110347    }
110348  }
110349
110350  /* If there is no IDLIST term but the table has an integer primary
110351  ** key, the set the ipkColumn variable to the integer primary key
110352  ** column index in the original table definition.
110353  */
110354  if( pColumn==0 && nColumn>0 ){
110355    ipkColumn = pTab->iPKey;
110356  }
110357
110358  /* Make sure the number of columns in the source data matches the number
110359  ** of columns to be inserted into the table.
110360  */
110361  for(i=0; i<pTab->nCol; i++){
110362    nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
110363  }
110364  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
110365    sqlite3ErrorMsg(pParse,
110366       "table %S has %d columns but %d values were supplied",
110367       pTabList, 0, pTab->nCol-nHidden, nColumn);
110368    goto insert_cleanup;
110369  }
110370  if( pColumn!=0 && nColumn!=pColumn->nId ){
110371    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
110372    goto insert_cleanup;
110373  }
110374
110375  /* Initialize the count of rows to be inserted
110376  */
110377  if( db->flags & SQLITE_CountRows ){
110378    regRowCount = ++pParse->nMem;
110379    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
110380  }
110381
110382  /* If this is not a view, open the table and and all indices */
110383  if( !isView ){
110384    int nIdx;
110385    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
110386                                      &iDataCur, &iIdxCur);
110387    aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
110388    if( aRegIdx==0 ){
110389      goto insert_cleanup;
110390    }
110391    for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
110392      assert( pIdx );
110393      aRegIdx[i] = ++pParse->nMem;
110394      pParse->nMem += pIdx->nColumn;
110395    }
110396  }
110397
110398  /* This is the top of the main insertion loop */
110399  if( useTempTable ){
110400    /* This block codes the top of loop only.  The complete loop is the
110401    ** following pseudocode (template 4):
110402    **
110403    **         rewind temp table, if empty goto D
110404    **      C: loop over rows of intermediate table
110405    **           transfer values form intermediate table into <table>
110406    **         end loop
110407    **      D: ...
110408    */
110409    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
110410    addrCont = sqlite3VdbeCurrentAddr(v);
110411  }else if( pSelect ){
110412    /* This block codes the top of loop only.  The complete loop is the
110413    ** following pseudocode (template 3):
110414    **
110415    **      C: yield X, at EOF goto D
110416    **         insert the select result into <table> from R..R+n
110417    **         goto C
110418    **      D: ...
110419    */
110420    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
110421    VdbeCoverage(v);
110422  }
110423
110424  /* Run the BEFORE and INSTEAD OF triggers, if there are any
110425  */
110426  endOfLoop = sqlite3VdbeMakeLabel(v);
110427  if( tmask & TRIGGER_BEFORE ){
110428    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
110429
110430    /* build the NEW.* reference row.  Note that if there is an INTEGER
110431    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
110432    ** translated into a unique ID for the row.  But on a BEFORE trigger,
110433    ** we do not know what the unique ID will be (because the insert has
110434    ** not happened yet) so we substitute a rowid of -1
110435    */
110436    if( ipkColumn<0 ){
110437      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
110438    }else{
110439      int addr1;
110440      assert( !withoutRowid );
110441      if( useTempTable ){
110442        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
110443      }else{
110444        assert( pSelect==0 );  /* Otherwise useTempTable is true */
110445        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
110446      }
110447      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
110448      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
110449      sqlite3VdbeJumpHere(v, addr1);
110450      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
110451    }
110452
110453    /* Cannot have triggers on a virtual table. If it were possible,
110454    ** this block would have to account for hidden column.
110455    */
110456    assert( !IsVirtual(pTab) );
110457
110458    /* Create the new column data
110459    */
110460    for(i=j=0; i<pTab->nCol; i++){
110461      if( pColumn ){
110462        for(j=0; j<pColumn->nId; j++){
110463          if( pColumn->a[j].idx==i ) break;
110464        }
110465      }
110466      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
110467            || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
110468        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
110469      }else if( useTempTable ){
110470        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
110471      }else{
110472        assert( pSelect==0 ); /* Otherwise useTempTable is true */
110473        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
110474      }
110475      if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
110476    }
110477
110478    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
110479    ** do not attempt any conversions before assembling the record.
110480    ** If this is a real table, attempt conversions as required by the
110481    ** table column affinities.
110482    */
110483    if( !isView ){
110484      sqlite3TableAffinity(v, pTab, regCols+1);
110485    }
110486
110487    /* Fire BEFORE or INSTEAD OF triggers */
110488    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
110489        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
110490
110491    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
110492  }
110493
110494  /* Compute the content of the next row to insert into a range of
110495  ** registers beginning at regIns.
110496  */
110497  if( !isView ){
110498    if( IsVirtual(pTab) ){
110499      /* The row that the VUpdate opcode will delete: none */
110500      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
110501    }
110502    if( ipkColumn>=0 ){
110503      if( useTempTable ){
110504        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
110505      }else if( pSelect ){
110506        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
110507      }else{
110508        VdbeOp *pOp;
110509        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
110510        pOp = sqlite3VdbeGetOp(v, -1);
110511        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
110512          appendFlag = 1;
110513          pOp->opcode = OP_NewRowid;
110514          pOp->p1 = iDataCur;
110515          pOp->p2 = regRowid;
110516          pOp->p3 = regAutoinc;
110517        }
110518      }
110519      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
110520      ** to generate a unique primary key value.
110521      */
110522      if( !appendFlag ){
110523        int addr1;
110524        if( !IsVirtual(pTab) ){
110525          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
110526          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
110527          sqlite3VdbeJumpHere(v, addr1);
110528        }else{
110529          addr1 = sqlite3VdbeCurrentAddr(v);
110530          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
110531        }
110532        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
110533      }
110534    }else if( IsVirtual(pTab) || withoutRowid ){
110535      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
110536    }else{
110537      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
110538      appendFlag = 1;
110539    }
110540    autoIncStep(pParse, regAutoinc, regRowid);
110541
110542    /* Compute data for all columns of the new entry, beginning
110543    ** with the first column.
110544    */
110545    nHidden = 0;
110546    for(i=0; i<pTab->nCol; i++){
110547      int iRegStore = regRowid+1+i;
110548      if( i==pTab->iPKey ){
110549        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
110550        ** Whenever this column is read, the rowid will be substituted
110551        ** in its place.  Hence, fill this column with a NULL to avoid
110552        ** taking up data space with information that will never be used.
110553        ** As there may be shallow copies of this value, make it a soft-NULL */
110554        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
110555        continue;
110556      }
110557      if( pColumn==0 ){
110558        if( IsHiddenColumn(&pTab->aCol[i]) ){
110559          j = -1;
110560          nHidden++;
110561        }else{
110562          j = i - nHidden;
110563        }
110564      }else{
110565        for(j=0; j<pColumn->nId; j++){
110566          if( pColumn->a[j].idx==i ) break;
110567        }
110568      }
110569      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
110570        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
110571      }else if( useTempTable ){
110572        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
110573      }else if( pSelect ){
110574        if( regFromSelect!=regData ){
110575          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
110576        }
110577      }else{
110578        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
110579      }
110580    }
110581
110582    /* Generate code to check constraints and generate index keys and
110583    ** do the insertion.
110584    */
110585#ifndef SQLITE_OMIT_VIRTUALTABLE
110586    if( IsVirtual(pTab) ){
110587      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
110588      sqlite3VtabMakeWritable(pParse, pTab);
110589      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
110590      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
110591      sqlite3MayAbort(pParse);
110592    }else
110593#endif
110594    {
110595      int isReplace;    /* Set to true if constraints may cause a replace */
110596      int bUseSeek;     /* True to use OPFLAG_SEEKRESULT */
110597      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
110598          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
110599      );
110600      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
110601
110602      /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
110603      ** constraints or (b) there are no triggers and this table is not a
110604      ** parent table in a foreign key constraint. It is safe to set the
110605      ** flag in the second case as if any REPLACE constraint is hit, an
110606      ** OP_Delete or OP_IdxDelete instruction will be executed on each
110607      ** cursor that is disturbed. And these instructions both clear the
110608      ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
110609      ** functionality.  */
110610      bUseSeek = (isReplace==0 || (pTrigger==0 &&
110611          ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
110612      ));
110613      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
110614          regIns, aRegIdx, 0, appendFlag, bUseSeek
110615      );
110616    }
110617  }
110618
110619  /* Update the count of rows that are inserted
110620  */
110621  if( (db->flags & SQLITE_CountRows)!=0 ){
110622    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
110623  }
110624
110625  if( pTrigger ){
110626    /* Code AFTER triggers */
110627    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
110628        pTab, regData-2-pTab->nCol, onError, endOfLoop);
110629  }
110630
110631  /* The bottom of the main insertion loop, if the data source
110632  ** is a SELECT statement.
110633  */
110634  sqlite3VdbeResolveLabel(v, endOfLoop);
110635  if( useTempTable ){
110636    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
110637    sqlite3VdbeJumpHere(v, addrInsTop);
110638    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
110639  }else if( pSelect ){
110640    sqlite3VdbeGoto(v, addrCont);
110641    sqlite3VdbeJumpHere(v, addrInsTop);
110642  }
110643
110644insert_end:
110645  /* Update the sqlite_sequence table by storing the content of the
110646  ** maximum rowid counter values recorded while inserting into
110647  ** autoincrement tables.
110648  */
110649  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
110650    sqlite3AutoincrementEnd(pParse);
110651  }
110652
110653  /*
110654  ** Return the number of rows inserted. If this routine is
110655  ** generating code because of a call to sqlite3NestedParse(), do not
110656  ** invoke the callback function.
110657  */
110658  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
110659    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
110660    sqlite3VdbeSetNumCols(v, 1);
110661    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
110662  }
110663
110664insert_cleanup:
110665  sqlite3SrcListDelete(db, pTabList);
110666  sqlite3ExprListDelete(db, pList);
110667  sqlite3SelectDelete(db, pSelect);
110668  sqlite3IdListDelete(db, pColumn);
110669  sqlite3DbFree(db, aRegIdx);
110670}
110671
110672/* Make sure "isView" and other macros defined above are undefined. Otherwise
110673** they may interfere with compilation of other functions in this file
110674** (or in another file, if this file becomes part of the amalgamation).  */
110675#ifdef isView
110676 #undef isView
110677#endif
110678#ifdef pTrigger
110679 #undef pTrigger
110680#endif
110681#ifdef tmask
110682 #undef tmask
110683#endif
110684
110685/*
110686** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
110687*/
110688#define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
110689#define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
110690
110691/* This is the Walker callback from checkConstraintUnchanged().  Set
110692** bit 0x01 of pWalker->eCode if
110693** pWalker->eCode to 0 if this expression node references any of the
110694** columns that are being modifed by an UPDATE statement.
110695*/
110696static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
110697  if( pExpr->op==TK_COLUMN ){
110698    assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
110699    if( pExpr->iColumn>=0 ){
110700      if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
110701        pWalker->eCode |= CKCNSTRNT_COLUMN;
110702      }
110703    }else{
110704      pWalker->eCode |= CKCNSTRNT_ROWID;
110705    }
110706  }
110707  return WRC_Continue;
110708}
110709
110710/*
110711** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
110712** only columns that are modified by the UPDATE are those for which
110713** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
110714**
110715** Return true if CHECK constraint pExpr does not use any of the
110716** changing columns (or the rowid if it is changing).  In other words,
110717** return true if this CHECK constraint can be skipped when validating
110718** the new row in the UPDATE statement.
110719*/
110720static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
110721  Walker w;
110722  memset(&w, 0, sizeof(w));
110723  w.eCode = 0;
110724  w.xExprCallback = checkConstraintExprNode;
110725  w.u.aiCol = aiChng;
110726  sqlite3WalkExpr(&w, pExpr);
110727  if( !chngRowid ){
110728    testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
110729    w.eCode &= ~CKCNSTRNT_ROWID;
110730  }
110731  testcase( w.eCode==0 );
110732  testcase( w.eCode==CKCNSTRNT_COLUMN );
110733  testcase( w.eCode==CKCNSTRNT_ROWID );
110734  testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
110735  return !w.eCode;
110736}
110737
110738/*
110739** Generate code to do constraint checks prior to an INSERT or an UPDATE
110740** on table pTab.
110741**
110742** The regNewData parameter is the first register in a range that contains
110743** the data to be inserted or the data after the update.  There will be
110744** pTab->nCol+1 registers in this range.  The first register (the one
110745** that regNewData points to) will contain the new rowid, or NULL in the
110746** case of a WITHOUT ROWID table.  The second register in the range will
110747** contain the content of the first table column.  The third register will
110748** contain the content of the second table column.  And so forth.
110749**
110750** The regOldData parameter is similar to regNewData except that it contains
110751** the data prior to an UPDATE rather than afterwards.  regOldData is zero
110752** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
110753** checking regOldData for zero.
110754**
110755** For an UPDATE, the pkChng boolean is true if the true primary key (the
110756** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
110757** might be modified by the UPDATE.  If pkChng is false, then the key of
110758** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
110759**
110760** For an INSERT, the pkChng boolean indicates whether or not the rowid
110761** was explicitly specified as part of the INSERT statement.  If pkChng
110762** is zero, it means that the either rowid is computed automatically or
110763** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
110764** pkChng will only be true if the INSERT statement provides an integer
110765** value for either the rowid column or its INTEGER PRIMARY KEY alias.
110766**
110767** The code generated by this routine will store new index entries into
110768** registers identified by aRegIdx[].  No index entry is created for
110769** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
110770** the same as the order of indices on the linked list of indices
110771** at pTab->pIndex.
110772**
110773** The caller must have already opened writeable cursors on the main
110774** table and all applicable indices (that is to say, all indices for which
110775** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
110776** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
110777** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
110778** for the first index in the pTab->pIndex list.  Cursors for other indices
110779** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
110780**
110781** This routine also generates code to check constraints.  NOT NULL,
110782** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
110783** then the appropriate action is performed.  There are five possible
110784** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
110785**
110786**  Constraint type  Action       What Happens
110787**  ---------------  ----------   ----------------------------------------
110788**  any              ROLLBACK     The current transaction is rolled back and
110789**                                sqlite3_step() returns immediately with a
110790**                                return code of SQLITE_CONSTRAINT.
110791**
110792**  any              ABORT        Back out changes from the current command
110793**                                only (do not do a complete rollback) then
110794**                                cause sqlite3_step() to return immediately
110795**                                with SQLITE_CONSTRAINT.
110796**
110797**  any              FAIL         Sqlite3_step() returns immediately with a
110798**                                return code of SQLITE_CONSTRAINT.  The
110799**                                transaction is not rolled back and any
110800**                                changes to prior rows are retained.
110801**
110802**  any              IGNORE       The attempt in insert or update the current
110803**                                row is skipped, without throwing an error.
110804**                                Processing continues with the next row.
110805**                                (There is an immediate jump to ignoreDest.)
110806**
110807**  NOT NULL         REPLACE      The NULL value is replace by the default
110808**                                value for that column.  If the default value
110809**                                is NULL, the action is the same as ABORT.
110810**
110811**  UNIQUE           REPLACE      The other row that conflicts with the row
110812**                                being inserted is removed.
110813**
110814**  CHECK            REPLACE      Illegal.  The results in an exception.
110815**
110816** Which action to take is determined by the overrideError parameter.
110817** Or if overrideError==OE_Default, then the pParse->onError parameter
110818** is used.  Or if pParse->onError==OE_Default then the onError value
110819** for the constraint is used.
110820*/
110821SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
110822  Parse *pParse,       /* The parser context */
110823  Table *pTab,         /* The table being inserted or updated */
110824  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
110825  int iDataCur,        /* Canonical data cursor (main table or PK index) */
110826  int iIdxCur,         /* First index cursor */
110827  int regNewData,      /* First register in a range holding values to insert */
110828  int regOldData,      /* Previous content.  0 for INSERTs */
110829  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
110830  u8 overrideError,    /* Override onError to this if not OE_Default */
110831  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
110832  int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
110833  int *aiChng          /* column i is unchanged if aiChng[i]<0 */
110834){
110835  Vdbe *v;             /* VDBE under constrution */
110836  Index *pIdx;         /* Pointer to one of the indices */
110837  Index *pPk = 0;      /* The PRIMARY KEY index */
110838  sqlite3 *db;         /* Database connection */
110839  int i;               /* loop counter */
110840  int ix;              /* Index loop counter */
110841  int nCol;            /* Number of columns */
110842  int onError;         /* Conflict resolution strategy */
110843  int addr1;           /* Address of jump instruction */
110844  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
110845  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
110846  int ipkTop = 0;      /* Top of the rowid change constraint check */
110847  int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
110848  u8 isUpdate;         /* True if this is an UPDATE operation */
110849  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
110850
110851  isUpdate = regOldData!=0;
110852  db = pParse->db;
110853  v = sqlite3GetVdbe(pParse);
110854  assert( v!=0 );
110855  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
110856  nCol = pTab->nCol;
110857
110858  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
110859  ** normal rowid tables.  nPkField is the number of key fields in the
110860  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
110861  ** number of fields in the true primary key of the table. */
110862  if( HasRowid(pTab) ){
110863    pPk = 0;
110864    nPkField = 1;
110865  }else{
110866    pPk = sqlite3PrimaryKeyIndex(pTab);
110867    nPkField = pPk->nKeyCol;
110868  }
110869
110870  /* Record that this module has started */
110871  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
110872                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
110873
110874  /* Test all NOT NULL constraints.
110875  */
110876  for(i=0; i<nCol; i++){
110877    if( i==pTab->iPKey ){
110878      continue;        /* ROWID is never NULL */
110879    }
110880    if( aiChng && aiChng[i]<0 ){
110881      /* Don't bother checking for NOT NULL on columns that do not change */
110882      continue;
110883    }
110884    onError = pTab->aCol[i].notNull;
110885    if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
110886    if( overrideError!=OE_Default ){
110887      onError = overrideError;
110888    }else if( onError==OE_Default ){
110889      onError = OE_Abort;
110890    }
110891    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
110892      onError = OE_Abort;
110893    }
110894    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
110895        || onError==OE_Ignore || onError==OE_Replace );
110896    switch( onError ){
110897      case OE_Abort:
110898        sqlite3MayAbort(pParse);
110899        /* Fall through */
110900      case OE_Rollback:
110901      case OE_Fail: {
110902        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
110903                                    pTab->aCol[i].zName);
110904        sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
110905                          regNewData+1+i);
110906        sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
110907        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
110908        VdbeCoverage(v);
110909        break;
110910      }
110911      case OE_Ignore: {
110912        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
110913        VdbeCoverage(v);
110914        break;
110915      }
110916      default: {
110917        assert( onError==OE_Replace );
110918        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
110919           VdbeCoverage(v);
110920        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
110921        sqlite3VdbeJumpHere(v, addr1);
110922        break;
110923      }
110924    }
110925  }
110926
110927  /* Test all CHECK constraints
110928  */
110929#ifndef SQLITE_OMIT_CHECK
110930  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
110931    ExprList *pCheck = pTab->pCheck;
110932    pParse->iSelfTab = -(regNewData+1);
110933    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
110934    for(i=0; i<pCheck->nExpr; i++){
110935      int allOk;
110936      Expr *pExpr = pCheck->a[i].pExpr;
110937      if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
110938      allOk = sqlite3VdbeMakeLabel(v);
110939      sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
110940      if( onError==OE_Ignore ){
110941        sqlite3VdbeGoto(v, ignoreDest);
110942      }else{
110943        char *zName = pCheck->a[i].zName;
110944        if( zName==0 ) zName = pTab->zName;
110945        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
110946        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
110947                              onError, zName, P4_TRANSIENT,
110948                              P5_ConstraintCheck);
110949      }
110950      sqlite3VdbeResolveLabel(v, allOk);
110951    }
110952    pParse->iSelfTab = 0;
110953  }
110954#endif /* !defined(SQLITE_OMIT_CHECK) */
110955
110956  /* If rowid is changing, make sure the new rowid does not previously
110957  ** exist in the table.
110958  */
110959  if( pkChng && pPk==0 ){
110960    int addrRowidOk = sqlite3VdbeMakeLabel(v);
110961
110962    /* Figure out what action to take in case of a rowid collision */
110963    onError = pTab->keyConf;
110964    if( overrideError!=OE_Default ){
110965      onError = overrideError;
110966    }else if( onError==OE_Default ){
110967      onError = OE_Abort;
110968    }
110969
110970    if( isUpdate ){
110971      /* pkChng!=0 does not mean that the rowid has changed, only that
110972      ** it might have changed.  Skip the conflict logic below if the rowid
110973      ** is unchanged. */
110974      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
110975      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
110976      VdbeCoverage(v);
110977    }
110978
110979    /* If the response to a rowid conflict is REPLACE but the response
110980    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
110981    ** to defer the running of the rowid conflict checking until after
110982    ** the UNIQUE constraints have run.
110983    */
110984    if( onError==OE_Replace && overrideError!=OE_Replace ){
110985      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
110986        if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
110987          ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
110988          break;
110989        }
110990      }
110991    }
110992
110993    /* Check to see if the new rowid already exists in the table.  Skip
110994    ** the following conflict logic if it does not. */
110995    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
110996    VdbeCoverage(v);
110997
110998    /* Generate code that deals with a rowid collision */
110999    switch( onError ){
111000      default: {
111001        onError = OE_Abort;
111002        /* Fall thru into the next case */
111003      }
111004      case OE_Rollback:
111005      case OE_Abort:
111006      case OE_Fail: {
111007        sqlite3RowidConstraint(pParse, onError, pTab);
111008        break;
111009      }
111010      case OE_Replace: {
111011        /* If there are DELETE triggers on this table and the
111012        ** recursive-triggers flag is set, call GenerateRowDelete() to
111013        ** remove the conflicting row from the table. This will fire
111014        ** the triggers and remove both the table and index b-tree entries.
111015        **
111016        ** Otherwise, if there are no triggers or the recursive-triggers
111017        ** flag is not set, but the table has one or more indexes, call
111018        ** GenerateRowIndexDelete(). This removes the index b-tree entries
111019        ** only. The table b-tree entry will be replaced by the new entry
111020        ** when it is inserted.
111021        **
111022        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
111023        ** also invoke MultiWrite() to indicate that this VDBE may require
111024        ** statement rollback (if the statement is aborted after the delete
111025        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
111026        ** but being more selective here allows statements like:
111027        **
111028        **   REPLACE INTO t(rowid) VALUES($newrowid)
111029        **
111030        ** to run without a statement journal if there are no indexes on the
111031        ** table.
111032        */
111033        Trigger *pTrigger = 0;
111034        if( db->flags&SQLITE_RecTriggers ){
111035          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
111036        }
111037        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
111038          sqlite3MultiWrite(pParse);
111039          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
111040                                   regNewData, 1, 0, OE_Replace, 1, -1);
111041        }else{
111042#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
111043          if( HasRowid(pTab) ){
111044            /* This OP_Delete opcode fires the pre-update-hook only. It does
111045            ** not modify the b-tree. It is more efficient to let the coming
111046            ** OP_Insert replace the existing entry than it is to delete the
111047            ** existing entry and then insert a new one. */
111048            sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
111049            sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
111050          }
111051#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
111052          if( pTab->pIndex ){
111053            sqlite3MultiWrite(pParse);
111054            sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
111055          }
111056        }
111057        seenReplace = 1;
111058        break;
111059      }
111060      case OE_Ignore: {
111061        /*assert( seenReplace==0 );*/
111062        sqlite3VdbeGoto(v, ignoreDest);
111063        break;
111064      }
111065    }
111066    sqlite3VdbeResolveLabel(v, addrRowidOk);
111067    if( ipkTop ){
111068      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
111069      sqlite3VdbeJumpHere(v, ipkTop);
111070    }
111071  }
111072
111073  /* Test all UNIQUE constraints by creating entries for each UNIQUE
111074  ** index and making sure that duplicate entries do not already exist.
111075  ** Compute the revised record entries for indices as we go.
111076  **
111077  ** This loop also handles the case of the PRIMARY KEY index for a
111078  ** WITHOUT ROWID table.
111079  */
111080  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
111081    int regIdx;          /* Range of registers hold conent for pIdx */
111082    int regR;            /* Range of registers holding conflicting PK */
111083    int iThisCur;        /* Cursor for this UNIQUE index */
111084    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
111085
111086    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
111087    if( bAffinityDone==0 ){
111088      sqlite3TableAffinity(v, pTab, regNewData+1);
111089      bAffinityDone = 1;
111090    }
111091    iThisCur = iIdxCur+ix;
111092    addrUniqueOk = sqlite3VdbeMakeLabel(v);
111093
111094    /* Skip partial indices for which the WHERE clause is not true */
111095    if( pIdx->pPartIdxWhere ){
111096      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
111097      pParse->iSelfTab = -(regNewData+1);
111098      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
111099                            SQLITE_JUMPIFNULL);
111100      pParse->iSelfTab = 0;
111101    }
111102
111103    /* Create a record for this index entry as it should appear after
111104    ** the insert or update.  Store that record in the aRegIdx[ix] register
111105    */
111106    regIdx = aRegIdx[ix]+1;
111107    for(i=0; i<pIdx->nColumn; i++){
111108      int iField = pIdx->aiColumn[i];
111109      int x;
111110      if( iField==XN_EXPR ){
111111        pParse->iSelfTab = -(regNewData+1);
111112        sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
111113        pParse->iSelfTab = 0;
111114        VdbeComment((v, "%s column %d", pIdx->zName, i));
111115      }else{
111116        if( iField==XN_ROWID || iField==pTab->iPKey ){
111117          x = regNewData;
111118        }else{
111119          x = iField + regNewData + 1;
111120        }
111121        sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
111122        VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
111123      }
111124    }
111125    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
111126    VdbeComment((v, "for %s", pIdx->zName));
111127#ifdef SQLITE_ENABLE_NULL_TRIM
111128    if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
111129#endif
111130
111131    /* In an UPDATE operation, if this index is the PRIMARY KEY index
111132    ** of a WITHOUT ROWID table and there has been no change the
111133    ** primary key, then no collision is possible.  The collision detection
111134    ** logic below can all be skipped. */
111135    if( isUpdate && pPk==pIdx && pkChng==0 ){
111136      sqlite3VdbeResolveLabel(v, addrUniqueOk);
111137      continue;
111138    }
111139
111140    /* Find out what action to take in case there is a uniqueness conflict */
111141    onError = pIdx->onError;
111142    if( onError==OE_None ){
111143      sqlite3VdbeResolveLabel(v, addrUniqueOk);
111144      continue;  /* pIdx is not a UNIQUE index */
111145    }
111146    if( overrideError!=OE_Default ){
111147      onError = overrideError;
111148    }else if( onError==OE_Default ){
111149      onError = OE_Abort;
111150    }
111151
111152    /* Collision detection may be omitted if all of the following are true:
111153    **   (1) The conflict resolution algorithm is REPLACE
111154    **   (2) The table is a WITHOUT ROWID table
111155    **   (3) There are no secondary indexes on the table
111156    **   (4) No delete triggers need to be fired if there is a conflict
111157    **   (5) No FK constraint counters need to be updated if a conflict occurs.
111158    */
111159    if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
111160     && pPk==pIdx                                   /* Condition 2 */
111161     && onError==OE_Replace                         /* Condition 1 */
111162     && ( 0==(db->flags&SQLITE_RecTriggers) ||      /* Condition 4 */
111163          0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
111164     && ( 0==(db->flags&SQLITE_ForeignKeys) ||      /* Condition 5 */
111165         (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
111166    ){
111167      sqlite3VdbeResolveLabel(v, addrUniqueOk);
111168      continue;
111169    }
111170
111171    /* Check to see if the new index entry will be unique */
111172    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
111173                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
111174
111175    /* Generate code to handle collisions */
111176    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
111177    if( isUpdate || onError==OE_Replace ){
111178      if( HasRowid(pTab) ){
111179        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
111180        /* Conflict only if the rowid of the existing index entry
111181        ** is different from old-rowid */
111182        if( isUpdate ){
111183          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
111184          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
111185          VdbeCoverage(v);
111186        }
111187      }else{
111188        int x;
111189        /* Extract the PRIMARY KEY from the end of the index entry and
111190        ** store it in registers regR..regR+nPk-1 */
111191        if( pIdx!=pPk ){
111192          for(i=0; i<pPk->nKeyCol; i++){
111193            assert( pPk->aiColumn[i]>=0 );
111194            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
111195            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
111196            VdbeComment((v, "%s.%s", pTab->zName,
111197                         pTab->aCol[pPk->aiColumn[i]].zName));
111198          }
111199        }
111200        if( isUpdate ){
111201          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
111202          ** table, only conflict if the new PRIMARY KEY values are actually
111203          ** different from the old.
111204          **
111205          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
111206          ** of the matched index row are different from the original PRIMARY
111207          ** KEY values of this row before the update.  */
111208          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
111209          int op = OP_Ne;
111210          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
111211
111212          for(i=0; i<pPk->nKeyCol; i++){
111213            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
111214            x = pPk->aiColumn[i];
111215            assert( x>=0 );
111216            if( i==(pPk->nKeyCol-1) ){
111217              addrJump = addrUniqueOk;
111218              op = OP_Eq;
111219            }
111220            sqlite3VdbeAddOp4(v, op,
111221                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
111222            );
111223            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
111224            VdbeCoverageIf(v, op==OP_Eq);
111225            VdbeCoverageIf(v, op==OP_Ne);
111226          }
111227        }
111228      }
111229    }
111230
111231    /* Generate code that executes if the new index entry is not unique */
111232    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
111233        || onError==OE_Ignore || onError==OE_Replace );
111234    switch( onError ){
111235      case OE_Rollback:
111236      case OE_Abort:
111237      case OE_Fail: {
111238        sqlite3UniqueConstraint(pParse, onError, pIdx);
111239        break;
111240      }
111241      case OE_Ignore: {
111242        sqlite3VdbeGoto(v, ignoreDest);
111243        break;
111244      }
111245      default: {
111246        Trigger *pTrigger = 0;
111247        assert( onError==OE_Replace );
111248        sqlite3MultiWrite(pParse);
111249        if( db->flags&SQLITE_RecTriggers ){
111250          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
111251        }
111252        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
111253            regR, nPkField, 0, OE_Replace,
111254            (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
111255        seenReplace = 1;
111256        break;
111257      }
111258    }
111259    sqlite3VdbeResolveLabel(v, addrUniqueOk);
111260    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
111261  }
111262  if( ipkTop ){
111263    sqlite3VdbeGoto(v, ipkTop+1);
111264    sqlite3VdbeJumpHere(v, ipkBottom);
111265  }
111266
111267  *pbMayReplace = seenReplace;
111268  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
111269}
111270
111271#ifdef SQLITE_ENABLE_NULL_TRIM
111272/*
111273** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
111274** to be the number of columns in table pTab that must not be NULL-trimmed.
111275**
111276** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
111277*/
111278SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
111279  u16 i;
111280
111281  /* Records with omitted columns are only allowed for schema format
111282  ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
111283  if( pTab->pSchema->file_format<2 ) return;
111284
111285  for(i=pTab->nCol-1; i>0; i--){
111286    if( pTab->aCol[i].pDflt!=0 ) break;
111287    if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
111288  }
111289  sqlite3VdbeChangeP5(v, i+1);
111290}
111291#endif
111292
111293/*
111294** This routine generates code to finish the INSERT or UPDATE operation
111295** that was started by a prior call to sqlite3GenerateConstraintChecks.
111296** A consecutive range of registers starting at regNewData contains the
111297** rowid and the content to be inserted.
111298**
111299** The arguments to this routine should be the same as the first six
111300** arguments to sqlite3GenerateConstraintChecks.
111301*/
111302SQLITE_PRIVATE void sqlite3CompleteInsertion(
111303  Parse *pParse,      /* The parser context */
111304  Table *pTab,        /* the table into which we are inserting */
111305  int iDataCur,       /* Cursor of the canonical data source */
111306  int iIdxCur,        /* First index cursor */
111307  int regNewData,     /* Range of content */
111308  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
111309  int update_flags,   /* True for UPDATE, False for INSERT */
111310  int appendBias,     /* True if this is likely to be an append */
111311  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
111312){
111313  Vdbe *v;            /* Prepared statements under construction */
111314  Index *pIdx;        /* An index being inserted or updated */
111315  u8 pik_flags;       /* flag values passed to the btree insert */
111316  int regData;        /* Content registers (after the rowid) */
111317  int regRec;         /* Register holding assembled record for the table */
111318  int i;              /* Loop counter */
111319  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
111320
111321  assert( update_flags==0
111322       || update_flags==OPFLAG_ISUPDATE
111323       || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
111324  );
111325
111326  v = sqlite3GetVdbe(pParse);
111327  assert( v!=0 );
111328  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
111329  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111330    if( aRegIdx[i]==0 ) continue;
111331    bAffinityDone = 1;
111332    if( pIdx->pPartIdxWhere ){
111333      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
111334      VdbeCoverage(v);
111335    }
111336    pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
111337    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
111338      assert( pParse->nested==0 );
111339      pik_flags |= OPFLAG_NCHANGE;
111340      pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
111341#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
111342      if( update_flags==0 ){
111343        sqlite3VdbeAddOp4(v, OP_InsertInt,
111344            iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
111345        );
111346        sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
111347      }
111348#endif
111349    }
111350    sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
111351                         aRegIdx[i]+1,
111352                         pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
111353    sqlite3VdbeChangeP5(v, pik_flags);
111354  }
111355  if( !HasRowid(pTab) ) return;
111356  regData = regNewData + 1;
111357  regRec = sqlite3GetTempReg(pParse);
111358  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
111359  sqlite3SetMakeRecordP5(v, pTab);
111360  if( !bAffinityDone ){
111361    sqlite3TableAffinity(v, pTab, 0);
111362    sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
111363  }
111364  if( pParse->nested ){
111365    pik_flags = 0;
111366  }else{
111367    pik_flags = OPFLAG_NCHANGE;
111368    pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
111369  }
111370  if( appendBias ){
111371    pik_flags |= OPFLAG_APPEND;
111372  }
111373  if( useSeekResult ){
111374    pik_flags |= OPFLAG_USESEEKRESULT;
111375  }
111376  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
111377  if( !pParse->nested ){
111378    sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
111379  }
111380  sqlite3VdbeChangeP5(v, pik_flags);
111381}
111382
111383/*
111384** Allocate cursors for the pTab table and all its indices and generate
111385** code to open and initialized those cursors.
111386**
111387** The cursor for the object that contains the complete data (normally
111388** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
111389** ROWID table) is returned in *piDataCur.  The first index cursor is
111390** returned in *piIdxCur.  The number of indices is returned.
111391**
111392** Use iBase as the first cursor (either the *piDataCur for rowid tables
111393** or the first index for WITHOUT ROWID tables) if it is non-negative.
111394** If iBase is negative, then allocate the next available cursor.
111395**
111396** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
111397** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
111398** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
111399** pTab->pIndex list.
111400**
111401** If pTab is a virtual table, then this routine is a no-op and the
111402** *piDataCur and *piIdxCur values are left uninitialized.
111403*/
111404SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
111405  Parse *pParse,   /* Parsing context */
111406  Table *pTab,     /* Table to be opened */
111407  int op,          /* OP_OpenRead or OP_OpenWrite */
111408  u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
111409  int iBase,       /* Use this for the table cursor, if there is one */
111410  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
111411  int *piDataCur,  /* Write the database source cursor number here */
111412  int *piIdxCur    /* Write the first index cursor number here */
111413){
111414  int i;
111415  int iDb;
111416  int iDataCur;
111417  Index *pIdx;
111418  Vdbe *v;
111419
111420  assert( op==OP_OpenRead || op==OP_OpenWrite );
111421  assert( op==OP_OpenWrite || p5==0 );
111422  if( IsVirtual(pTab) ){
111423    /* This routine is a no-op for virtual tables. Leave the output
111424    ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
111425    ** can detect if they are used by mistake in the caller. */
111426    return 0;
111427  }
111428  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
111429  v = sqlite3GetVdbe(pParse);
111430  assert( v!=0 );
111431  if( iBase<0 ) iBase = pParse->nTab;
111432  iDataCur = iBase++;
111433  if( piDataCur ) *piDataCur = iDataCur;
111434  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
111435    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
111436  }else{
111437    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
111438  }
111439  if( piIdxCur ) *piIdxCur = iBase;
111440  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
111441    int iIdxCur = iBase++;
111442    assert( pIdx->pSchema==pTab->pSchema );
111443    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
111444      if( piDataCur ) *piDataCur = iIdxCur;
111445      p5 = 0;
111446    }
111447    if( aToOpen==0 || aToOpen[i+1] ){
111448      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
111449      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
111450      sqlite3VdbeChangeP5(v, p5);
111451      VdbeComment((v, "%s", pIdx->zName));
111452    }
111453  }
111454  if( iBase>pParse->nTab ) pParse->nTab = iBase;
111455  return i;
111456}
111457
111458
111459#ifdef SQLITE_TEST
111460/*
111461** The following global variable is incremented whenever the
111462** transfer optimization is used.  This is used for testing
111463** purposes only - to make sure the transfer optimization really
111464** is happening when it is supposed to.
111465*/
111466SQLITE_API int sqlite3_xferopt_count;
111467#endif /* SQLITE_TEST */
111468
111469
111470#ifndef SQLITE_OMIT_XFER_OPT
111471/*
111472** Check to see if index pSrc is compatible as a source of data
111473** for index pDest in an insert transfer optimization.  The rules
111474** for a compatible index:
111475**
111476**    *   The index is over the same set of columns
111477**    *   The same DESC and ASC markings occurs on all columns
111478**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
111479**    *   The same collating sequence on each column
111480**    *   The index has the exact same WHERE clause
111481*/
111482static int xferCompatibleIndex(Index *pDest, Index *pSrc){
111483  int i;
111484  assert( pDest && pSrc );
111485  assert( pDest->pTable!=pSrc->pTable );
111486  if( pDest->nKeyCol!=pSrc->nKeyCol ){
111487    return 0;   /* Different number of columns */
111488  }
111489  if( pDest->onError!=pSrc->onError ){
111490    return 0;   /* Different conflict resolution strategies */
111491  }
111492  for(i=0; i<pSrc->nKeyCol; i++){
111493    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
111494      return 0;   /* Different columns indexed */
111495    }
111496    if( pSrc->aiColumn[i]==XN_EXPR ){
111497      assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
111498      if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
111499                             pDest->aColExpr->a[i].pExpr, -1)!=0 ){
111500        return 0;   /* Different expressions in the index */
111501      }
111502    }
111503    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
111504      return 0;   /* Different sort orders */
111505    }
111506    if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
111507      return 0;   /* Different collating sequences */
111508    }
111509  }
111510  if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
111511    return 0;     /* Different WHERE clauses */
111512  }
111513
111514  /* If no test above fails then the indices must be compatible */
111515  return 1;
111516}
111517
111518/*
111519** Attempt the transfer optimization on INSERTs of the form
111520**
111521**     INSERT INTO tab1 SELECT * FROM tab2;
111522**
111523** The xfer optimization transfers raw records from tab2 over to tab1.
111524** Columns are not decoded and reassembled, which greatly improves
111525** performance.  Raw index records are transferred in the same way.
111526**
111527** The xfer optimization is only attempted if tab1 and tab2 are compatible.
111528** There are lots of rules for determining compatibility - see comments
111529** embedded in the code for details.
111530**
111531** This routine returns TRUE if the optimization is guaranteed to be used.
111532** Sometimes the xfer optimization will only work if the destination table
111533** is empty - a factor that can only be determined at run-time.  In that
111534** case, this routine generates code for the xfer optimization but also
111535** does a test to see if the destination table is empty and jumps over the
111536** xfer optimization code if the test fails.  In that case, this routine
111537** returns FALSE so that the caller will know to go ahead and generate
111538** an unoptimized transfer.  This routine also returns FALSE if there
111539** is no chance that the xfer optimization can be applied.
111540**
111541** This optimization is particularly useful at making VACUUM run faster.
111542*/
111543static int xferOptimization(
111544  Parse *pParse,        /* Parser context */
111545  Table *pDest,         /* The table we are inserting into */
111546  Select *pSelect,      /* A SELECT statement to use as the data source */
111547  int onError,          /* How to handle constraint errors */
111548  int iDbDest           /* The database of pDest */
111549){
111550  sqlite3 *db = pParse->db;
111551  ExprList *pEList;                /* The result set of the SELECT */
111552  Table *pSrc;                     /* The table in the FROM clause of SELECT */
111553  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
111554  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
111555  int i;                           /* Loop counter */
111556  int iDbSrc;                      /* The database of pSrc */
111557  int iSrc, iDest;                 /* Cursors from source and destination */
111558  int addr1, addr2;                /* Loop addresses */
111559  int emptyDestTest = 0;           /* Address of test for empty pDest */
111560  int emptySrcTest = 0;            /* Address of test for empty pSrc */
111561  Vdbe *v;                         /* The VDBE we are building */
111562  int regAutoinc;                  /* Memory register used by AUTOINC */
111563  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
111564  int regData, regRowid;           /* Registers holding data and rowid */
111565
111566  if( pSelect==0 ){
111567    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
111568  }
111569  if( pParse->pWith || pSelect->pWith ){
111570    /* Do not attempt to process this query if there are an WITH clauses
111571    ** attached to it. Proceeding may generate a false "no such table: xxx"
111572    ** error if pSelect reads from a CTE named "xxx".  */
111573    return 0;
111574  }
111575  if( sqlite3TriggerList(pParse, pDest) ){
111576    return 0;   /* tab1 must not have triggers */
111577  }
111578#ifndef SQLITE_OMIT_VIRTUALTABLE
111579  if( IsVirtual(pDest) ){
111580    return 0;   /* tab1 must not be a virtual table */
111581  }
111582#endif
111583  if( onError==OE_Default ){
111584    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
111585    if( onError==OE_Default ) onError = OE_Abort;
111586  }
111587  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
111588  if( pSelect->pSrc->nSrc!=1 ){
111589    return 0;   /* FROM clause must have exactly one term */
111590  }
111591  if( pSelect->pSrc->a[0].pSelect ){
111592    return 0;   /* FROM clause cannot contain a subquery */
111593  }
111594  if( pSelect->pWhere ){
111595    return 0;   /* SELECT may not have a WHERE clause */
111596  }
111597  if( pSelect->pOrderBy ){
111598    return 0;   /* SELECT may not have an ORDER BY clause */
111599  }
111600  /* Do not need to test for a HAVING clause.  If HAVING is present but
111601  ** there is no ORDER BY, we will get an error. */
111602  if( pSelect->pGroupBy ){
111603    return 0;   /* SELECT may not have a GROUP BY clause */
111604  }
111605  if( pSelect->pLimit ){
111606    return 0;   /* SELECT may not have a LIMIT clause */
111607  }
111608  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
111609  if( pSelect->pPrior ){
111610    return 0;   /* SELECT may not be a compound query */
111611  }
111612  if( pSelect->selFlags & SF_Distinct ){
111613    return 0;   /* SELECT may not be DISTINCT */
111614  }
111615  pEList = pSelect->pEList;
111616  assert( pEList!=0 );
111617  if( pEList->nExpr!=1 ){
111618    return 0;   /* The result set must have exactly one column */
111619  }
111620  assert( pEList->a[0].pExpr );
111621  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
111622    return 0;   /* The result set must be the special operator "*" */
111623  }
111624
111625  /* At this point we have established that the statement is of the
111626  ** correct syntactic form to participate in this optimization.  Now
111627  ** we have to check the semantics.
111628  */
111629  pItem = pSelect->pSrc->a;
111630  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
111631  if( pSrc==0 ){
111632    return 0;   /* FROM clause does not contain a real table */
111633  }
111634  if( pSrc==pDest ){
111635    return 0;   /* tab1 and tab2 may not be the same table */
111636  }
111637  if( HasRowid(pDest)!=HasRowid(pSrc) ){
111638    return 0;   /* source and destination must both be WITHOUT ROWID or not */
111639  }
111640#ifndef SQLITE_OMIT_VIRTUALTABLE
111641  if( IsVirtual(pSrc) ){
111642    return 0;   /* tab2 must not be a virtual table */
111643  }
111644#endif
111645  if( pSrc->pSelect ){
111646    return 0;   /* tab2 may not be a view */
111647  }
111648  if( pDest->nCol!=pSrc->nCol ){
111649    return 0;   /* Number of columns must be the same in tab1 and tab2 */
111650  }
111651  if( pDest->iPKey!=pSrc->iPKey ){
111652    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
111653  }
111654  for(i=0; i<pDest->nCol; i++){
111655    Column *pDestCol = &pDest->aCol[i];
111656    Column *pSrcCol = &pSrc->aCol[i];
111657#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
111658    if( (db->flags & SQLITE_Vacuum)==0
111659     && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
111660    ){
111661      return 0;    /* Neither table may have __hidden__ columns */
111662    }
111663#endif
111664    if( pDestCol->affinity!=pSrcCol->affinity ){
111665      return 0;    /* Affinity must be the same on all columns */
111666    }
111667    if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
111668      return 0;    /* Collating sequence must be the same on all columns */
111669    }
111670    if( pDestCol->notNull && !pSrcCol->notNull ){
111671      return 0;    /* tab2 must be NOT NULL if tab1 is */
111672    }
111673    /* Default values for second and subsequent columns need to match. */
111674    if( i>0 ){
111675      assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
111676      assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
111677      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
111678       || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
111679                                       pSrcCol->pDflt->u.zToken)!=0)
111680      ){
111681        return 0;    /* Default values must be the same for all columns */
111682      }
111683    }
111684  }
111685  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
111686    if( IsUniqueIndex(pDestIdx) ){
111687      destHasUniqueIdx = 1;
111688    }
111689    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
111690      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
111691    }
111692    if( pSrcIdx==0 ){
111693      return 0;    /* pDestIdx has no corresponding index in pSrc */
111694    }
111695  }
111696#ifndef SQLITE_OMIT_CHECK
111697  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
111698    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
111699  }
111700#endif
111701#ifndef SQLITE_OMIT_FOREIGN_KEY
111702  /* Disallow the transfer optimization if the destination table constains
111703  ** any foreign key constraints.  This is more restrictive than necessary.
111704  ** But the main beneficiary of the transfer optimization is the VACUUM
111705  ** command, and the VACUUM command disables foreign key constraints.  So
111706  ** the extra complication to make this rule less restrictive is probably
111707  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
111708  */
111709  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
111710    return 0;
111711  }
111712#endif
111713  if( (db->flags & SQLITE_CountRows)!=0 ){
111714    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
111715  }
111716
111717  /* If we get this far, it means that the xfer optimization is at
111718  ** least a possibility, though it might only work if the destination
111719  ** table (tab1) is initially empty.
111720  */
111721#ifdef SQLITE_TEST
111722  sqlite3_xferopt_count++;
111723#endif
111724  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
111725  v = sqlite3GetVdbe(pParse);
111726  sqlite3CodeVerifySchema(pParse, iDbSrc);
111727  iSrc = pParse->nTab++;
111728  iDest = pParse->nTab++;
111729  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
111730  regData = sqlite3GetTempReg(pParse);
111731  regRowid = sqlite3GetTempReg(pParse);
111732  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
111733  assert( HasRowid(pDest) || destHasUniqueIdx );
111734  if( (db->flags & SQLITE_Vacuum)==0 && (
111735      (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
111736   || destHasUniqueIdx                              /* (2) */
111737   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
111738  )){
111739    /* In some circumstances, we are able to run the xfer optimization
111740    ** only if the destination table is initially empty. Unless the
111741    ** SQLITE_Vacuum flag is set, this block generates code to make
111742    ** that determination. If SQLITE_Vacuum is set, then the destination
111743    ** table is always empty.
111744    **
111745    ** Conditions under which the destination must be empty:
111746    **
111747    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
111748    **     (If the destination is not initially empty, the rowid fields
111749    **     of index entries might need to change.)
111750    **
111751    ** (2) The destination has a unique index.  (The xfer optimization
111752    **     is unable to test uniqueness.)
111753    **
111754    ** (3) onError is something other than OE_Abort and OE_Rollback.
111755    */
111756    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
111757    emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
111758    sqlite3VdbeJumpHere(v, addr1);
111759  }
111760  if( HasRowid(pSrc) ){
111761    u8 insFlags;
111762    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
111763    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
111764    if( pDest->iPKey>=0 ){
111765      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
111766      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
111767      VdbeCoverage(v);
111768      sqlite3RowidConstraint(pParse, onError, pDest);
111769      sqlite3VdbeJumpHere(v, addr2);
111770      autoIncStep(pParse, regAutoinc, regRowid);
111771    }else if( pDest->pIndex==0 ){
111772      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
111773    }else{
111774      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
111775      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
111776    }
111777    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
111778    if( db->flags & SQLITE_Vacuum ){
111779      sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
111780      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
111781                           OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
111782    }else{
111783      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
111784    }
111785    sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
111786                      (char*)pDest, P4_TABLE);
111787    sqlite3VdbeChangeP5(v, insFlags);
111788    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
111789    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
111790    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
111791  }else{
111792    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
111793    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
111794  }
111795  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
111796    u8 idxInsFlags = 0;
111797    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
111798      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
111799    }
111800    assert( pSrcIdx );
111801    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
111802    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
111803    VdbeComment((v, "%s", pSrcIdx->zName));
111804    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
111805    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
111806    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
111807    VdbeComment((v, "%s", pDestIdx->zName));
111808    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
111809    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
111810    if( db->flags & SQLITE_Vacuum ){
111811      /* This INSERT command is part of a VACUUM operation, which guarantees
111812      ** that the destination table is empty. If all indexed columns use
111813      ** collation sequence BINARY, then it can also be assumed that the
111814      ** index will be populated by inserting keys in strictly sorted
111815      ** order. In this case, instead of seeking within the b-tree as part
111816      ** of every OP_IdxInsert opcode, an OP_Last is added before the
111817      ** OP_IdxInsert to seek to the point within the b-tree where each key
111818      ** should be inserted. This is faster.
111819      **
111820      ** If any of the indexed columns use a collation sequence other than
111821      ** BINARY, this optimization is disabled. This is because the user
111822      ** might change the definition of a collation sequence and then run
111823      ** a VACUUM command. In that case keys may not be written in strictly
111824      ** sorted order.  */
111825      for(i=0; i<pSrcIdx->nColumn; i++){
111826        const char *zColl = pSrcIdx->azColl[i];
111827        if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
111828      }
111829      if( i==pSrcIdx->nColumn ){
111830        idxInsFlags = OPFLAG_USESEEKRESULT;
111831        sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
111832      }
111833    }
111834    if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
111835      idxInsFlags |= OPFLAG_NCHANGE;
111836    }
111837    sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
111838    sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
111839    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
111840    sqlite3VdbeJumpHere(v, addr1);
111841    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
111842    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
111843  }
111844  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
111845  sqlite3ReleaseTempReg(pParse, regRowid);
111846  sqlite3ReleaseTempReg(pParse, regData);
111847  if( emptyDestTest ){
111848    sqlite3AutoincrementEnd(pParse);
111849    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
111850    sqlite3VdbeJumpHere(v, emptyDestTest);
111851    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
111852    return 0;
111853  }else{
111854    return 1;
111855  }
111856}
111857#endif /* SQLITE_OMIT_XFER_OPT */
111858
111859/************** End of insert.c **********************************************/
111860/************** Begin file legacy.c ******************************************/
111861/*
111862** 2001 September 15
111863**
111864** The author disclaims copyright to this source code.  In place of
111865** a legal notice, here is a blessing:
111866**
111867**    May you do good and not evil.
111868**    May you find forgiveness for yourself and forgive others.
111869**    May you share freely, never taking more than you give.
111870**
111871*************************************************************************
111872** Main file for the SQLite library.  The routines in this file
111873** implement the programmer interface to the library.  Routines in
111874** other files are for internal use by SQLite and should not be
111875** accessed by users of the library.
111876*/
111877
111878/* #include "sqliteInt.h" */
111879
111880/*
111881** Execute SQL code.  Return one of the SQLITE_ success/failure
111882** codes.  Also write an error message into memory obtained from
111883** malloc() and make *pzErrMsg point to that message.
111884**
111885** If the SQL is a query, then for each row in the query result
111886** the xCallback() function is called.  pArg becomes the first
111887** argument to xCallback().  If xCallback=NULL then no callback
111888** is invoked, even for queries.
111889*/
111890SQLITE_API int sqlite3_exec(
111891  sqlite3 *db,                /* The database on which the SQL executes */
111892  const char *zSql,           /* The SQL to be executed */
111893  sqlite3_callback xCallback, /* Invoke this callback routine */
111894  void *pArg,                 /* First argument to xCallback() */
111895  char **pzErrMsg             /* Write error messages here */
111896){
111897  int rc = SQLITE_OK;         /* Return code */
111898  const char *zLeftover;      /* Tail of unprocessed SQL */
111899  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
111900  char **azCols = 0;          /* Names of result columns */
111901  int callbackIsInit;         /* True if callback data is initialized */
111902
111903  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
111904  if( zSql==0 ) zSql = "";
111905
111906  sqlite3_mutex_enter(db->mutex);
111907  sqlite3Error(db, SQLITE_OK);
111908  while( rc==SQLITE_OK && zSql[0] ){
111909    int nCol;
111910    char **azVals = 0;
111911
111912    pStmt = 0;
111913    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
111914    assert( rc==SQLITE_OK || pStmt==0 );
111915    if( rc!=SQLITE_OK ){
111916      continue;
111917    }
111918    if( !pStmt ){
111919      /* this happens for a comment or white-space */
111920      zSql = zLeftover;
111921      continue;
111922    }
111923
111924    callbackIsInit = 0;
111925    nCol = sqlite3_column_count(pStmt);
111926
111927    while( 1 ){
111928      int i;
111929      rc = sqlite3_step(pStmt);
111930
111931      /* Invoke the callback function if required */
111932      if( xCallback && (SQLITE_ROW==rc ||
111933          (SQLITE_DONE==rc && !callbackIsInit
111934                           && db->flags&SQLITE_NullCallback)) ){
111935        if( !callbackIsInit ){
111936          azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
111937          if( azCols==0 ){
111938            goto exec_out;
111939          }
111940          for(i=0; i<nCol; i++){
111941            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
111942            /* sqlite3VdbeSetColName() installs column names as UTF8
111943            ** strings so there is no way for sqlite3_column_name() to fail. */
111944            assert( azCols[i]!=0 );
111945          }
111946          callbackIsInit = 1;
111947        }
111948        if( rc==SQLITE_ROW ){
111949          azVals = &azCols[nCol];
111950          for(i=0; i<nCol; i++){
111951            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
111952            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
111953              sqlite3OomFault(db);
111954              goto exec_out;
111955            }
111956          }
111957          azVals[i] = 0;
111958        }
111959        if( xCallback(pArg, nCol, azVals, azCols) ){
111960          /* EVIDENCE-OF: R-38229-40159 If the callback function to
111961          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
111962          ** return SQLITE_ABORT. */
111963          rc = SQLITE_ABORT;
111964          sqlite3VdbeFinalize((Vdbe *)pStmt);
111965          pStmt = 0;
111966          sqlite3Error(db, SQLITE_ABORT);
111967          goto exec_out;
111968        }
111969      }
111970
111971      if( rc!=SQLITE_ROW ){
111972        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
111973        pStmt = 0;
111974        zSql = zLeftover;
111975        while( sqlite3Isspace(zSql[0]) ) zSql++;
111976        break;
111977      }
111978    }
111979
111980    sqlite3DbFree(db, azCols);
111981    azCols = 0;
111982  }
111983
111984exec_out:
111985  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
111986  sqlite3DbFree(db, azCols);
111987
111988  rc = sqlite3ApiExit(db, rc);
111989  if( rc!=SQLITE_OK && pzErrMsg ){
111990    *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
111991    if( *pzErrMsg==0 ){
111992      rc = SQLITE_NOMEM_BKPT;
111993      sqlite3Error(db, SQLITE_NOMEM);
111994    }
111995  }else if( pzErrMsg ){
111996    *pzErrMsg = 0;
111997  }
111998
111999  assert( (rc&db->errMask)==rc );
112000  sqlite3_mutex_leave(db->mutex);
112001  return rc;
112002}
112003
112004/************** End of legacy.c **********************************************/
112005/************** Begin file loadext.c *****************************************/
112006/*
112007** 2006 June 7
112008**
112009** The author disclaims copyright to this source code.  In place of
112010** a legal notice, here is a blessing:
112011**
112012**    May you do good and not evil.
112013**    May you find forgiveness for yourself and forgive others.
112014**    May you share freely, never taking more than you give.
112015**
112016*************************************************************************
112017** This file contains code used to dynamically load extensions into
112018** the SQLite library.
112019*/
112020
112021#ifndef SQLITE_CORE
112022  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
112023#endif
112024/************** Include sqlite3ext.h in the middle of loadext.c **************/
112025/************** Begin file sqlite3ext.h **************************************/
112026/*
112027** 2006 June 7
112028**
112029** The author disclaims copyright to this source code.  In place of
112030** a legal notice, here is a blessing:
112031**
112032**    May you do good and not evil.
112033**    May you find forgiveness for yourself and forgive others.
112034**    May you share freely, never taking more than you give.
112035**
112036*************************************************************************
112037** This header file defines the SQLite interface for use by
112038** shared libraries that want to be imported as extensions into
112039** an SQLite instance.  Shared libraries that intend to be loaded
112040** as extensions by SQLite should #include this file instead of
112041** sqlite3.h.
112042*/
112043#ifndef SQLITE3EXT_H
112044#define SQLITE3EXT_H
112045/* #include "sqlite3.h" */
112046
112047/*
112048** The following structure holds pointers to all of the SQLite API
112049** routines.
112050**
112051** WARNING:  In order to maintain backwards compatibility, add new
112052** interfaces to the end of this structure only.  If you insert new
112053** interfaces in the middle of this structure, then older different
112054** versions of SQLite will not be able to load each other's shared
112055** libraries!
112056*/
112057struct sqlite3_api_routines {
112058  void * (*aggregate_context)(sqlite3_context*,int nBytes);
112059  int  (*aggregate_count)(sqlite3_context*);
112060  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
112061  int  (*bind_double)(sqlite3_stmt*,int,double);
112062  int  (*bind_int)(sqlite3_stmt*,int,int);
112063  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
112064  int  (*bind_null)(sqlite3_stmt*,int);
112065  int  (*bind_parameter_count)(sqlite3_stmt*);
112066  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
112067  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
112068  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
112069  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
112070  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
112071  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
112072  int  (*busy_timeout)(sqlite3*,int ms);
112073  int  (*changes)(sqlite3*);
112074  int  (*close)(sqlite3*);
112075  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
112076                           int eTextRep,const char*));
112077  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
112078                             int eTextRep,const void*));
112079  const void * (*column_blob)(sqlite3_stmt*,int iCol);
112080  int  (*column_bytes)(sqlite3_stmt*,int iCol);
112081  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
112082  int  (*column_count)(sqlite3_stmt*pStmt);
112083  const char * (*column_database_name)(sqlite3_stmt*,int);
112084  const void * (*column_database_name16)(sqlite3_stmt*,int);
112085  const char * (*column_decltype)(sqlite3_stmt*,int i);
112086  const void * (*column_decltype16)(sqlite3_stmt*,int);
112087  double  (*column_double)(sqlite3_stmt*,int iCol);
112088  int  (*column_int)(sqlite3_stmt*,int iCol);
112089  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
112090  const char * (*column_name)(sqlite3_stmt*,int);
112091  const void * (*column_name16)(sqlite3_stmt*,int);
112092  const char * (*column_origin_name)(sqlite3_stmt*,int);
112093  const void * (*column_origin_name16)(sqlite3_stmt*,int);
112094  const char * (*column_table_name)(sqlite3_stmt*,int);
112095  const void * (*column_table_name16)(sqlite3_stmt*,int);
112096  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
112097  const void * (*column_text16)(sqlite3_stmt*,int iCol);
112098  int  (*column_type)(sqlite3_stmt*,int iCol);
112099  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
112100  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
112101  int  (*complete)(const char*sql);
112102  int  (*complete16)(const void*sql);
112103  int  (*create_collation)(sqlite3*,const char*,int,void*,
112104                           int(*)(void*,int,const void*,int,const void*));
112105  int  (*create_collation16)(sqlite3*,const void*,int,void*,
112106                             int(*)(void*,int,const void*,int,const void*));
112107  int  (*create_function)(sqlite3*,const char*,int,int,void*,
112108                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112109                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112110                          void (*xFinal)(sqlite3_context*));
112111  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
112112                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112113                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112114                            void (*xFinal)(sqlite3_context*));
112115  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
112116  int  (*data_count)(sqlite3_stmt*pStmt);
112117  sqlite3 * (*db_handle)(sqlite3_stmt*);
112118  int (*declare_vtab)(sqlite3*,const char*);
112119  int  (*enable_shared_cache)(int);
112120  int  (*errcode)(sqlite3*db);
112121  const char * (*errmsg)(sqlite3*);
112122  const void * (*errmsg16)(sqlite3*);
112123  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
112124  int  (*expired)(sqlite3_stmt*);
112125  int  (*finalize)(sqlite3_stmt*pStmt);
112126  void  (*free)(void*);
112127  void  (*free_table)(char**result);
112128  int  (*get_autocommit)(sqlite3*);
112129  void * (*get_auxdata)(sqlite3_context*,int);
112130  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
112131  int  (*global_recover)(void);
112132  void  (*interruptx)(sqlite3*);
112133  sqlite_int64  (*last_insert_rowid)(sqlite3*);
112134  const char * (*libversion)(void);
112135  int  (*libversion_number)(void);
112136  void *(*malloc)(int);
112137  char * (*mprintf)(const char*,...);
112138  int  (*open)(const char*,sqlite3**);
112139  int  (*open16)(const void*,sqlite3**);
112140  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
112141  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
112142  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
112143  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
112144  void *(*realloc)(void*,int);
112145  int  (*reset)(sqlite3_stmt*pStmt);
112146  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
112147  void  (*result_double)(sqlite3_context*,double);
112148  void  (*result_error)(sqlite3_context*,const char*,int);
112149  void  (*result_error16)(sqlite3_context*,const void*,int);
112150  void  (*result_int)(sqlite3_context*,int);
112151  void  (*result_int64)(sqlite3_context*,sqlite_int64);
112152  void  (*result_null)(sqlite3_context*);
112153  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
112154  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
112155  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
112156  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
112157  void  (*result_value)(sqlite3_context*,sqlite3_value*);
112158  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
112159  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
112160                         const char*,const char*),void*);
112161  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
112162  char * (*snprintf)(int,char*,const char*,...);
112163  int  (*step)(sqlite3_stmt*);
112164  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
112165                                char const**,char const**,int*,int*,int*);
112166  void  (*thread_cleanup)(void);
112167  int  (*total_changes)(sqlite3*);
112168  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
112169  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
112170  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
112171                                         sqlite_int64),void*);
112172  void * (*user_data)(sqlite3_context*);
112173  const void * (*value_blob)(sqlite3_value*);
112174  int  (*value_bytes)(sqlite3_value*);
112175  int  (*value_bytes16)(sqlite3_value*);
112176  double  (*value_double)(sqlite3_value*);
112177  int  (*value_int)(sqlite3_value*);
112178  sqlite_int64  (*value_int64)(sqlite3_value*);
112179  int  (*value_numeric_type)(sqlite3_value*);
112180  const unsigned char * (*value_text)(sqlite3_value*);
112181  const void * (*value_text16)(sqlite3_value*);
112182  const void * (*value_text16be)(sqlite3_value*);
112183  const void * (*value_text16le)(sqlite3_value*);
112184  int  (*value_type)(sqlite3_value*);
112185  char *(*vmprintf)(const char*,va_list);
112186  /* Added ??? */
112187  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
112188  /* Added by 3.3.13 */
112189  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
112190  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
112191  int (*clear_bindings)(sqlite3_stmt*);
112192  /* Added by 3.4.1 */
112193  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
112194                          void (*xDestroy)(void *));
112195  /* Added by 3.5.0 */
112196  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
112197  int (*blob_bytes)(sqlite3_blob*);
112198  int (*blob_close)(sqlite3_blob*);
112199  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
112200                   int,sqlite3_blob**);
112201  int (*blob_read)(sqlite3_blob*,void*,int,int);
112202  int (*blob_write)(sqlite3_blob*,const void*,int,int);
112203  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
112204                             int(*)(void*,int,const void*,int,const void*),
112205                             void(*)(void*));
112206  int (*file_control)(sqlite3*,const char*,int,void*);
112207  sqlite3_int64 (*memory_highwater)(int);
112208  sqlite3_int64 (*memory_used)(void);
112209  sqlite3_mutex *(*mutex_alloc)(int);
112210  void (*mutex_enter)(sqlite3_mutex*);
112211  void (*mutex_free)(sqlite3_mutex*);
112212  void (*mutex_leave)(sqlite3_mutex*);
112213  int (*mutex_try)(sqlite3_mutex*);
112214  int (*open_v2)(const char*,sqlite3**,int,const char*);
112215  int (*release_memory)(int);
112216  void (*result_error_nomem)(sqlite3_context*);
112217  void (*result_error_toobig)(sqlite3_context*);
112218  int (*sleep)(int);
112219  void (*soft_heap_limit)(int);
112220  sqlite3_vfs *(*vfs_find)(const char*);
112221  int (*vfs_register)(sqlite3_vfs*,int);
112222  int (*vfs_unregister)(sqlite3_vfs*);
112223  int (*xthreadsafe)(void);
112224  void (*result_zeroblob)(sqlite3_context*,int);
112225  void (*result_error_code)(sqlite3_context*,int);
112226  int (*test_control)(int, ...);
112227  void (*randomness)(int,void*);
112228  sqlite3 *(*context_db_handle)(sqlite3_context*);
112229  int (*extended_result_codes)(sqlite3*,int);
112230  int (*limit)(sqlite3*,int,int);
112231  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
112232  const char *(*sql)(sqlite3_stmt*);
112233  int (*status)(int,int*,int*,int);
112234  int (*backup_finish)(sqlite3_backup*);
112235  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
112236  int (*backup_pagecount)(sqlite3_backup*);
112237  int (*backup_remaining)(sqlite3_backup*);
112238  int (*backup_step)(sqlite3_backup*,int);
112239  const char *(*compileoption_get)(int);
112240  int (*compileoption_used)(const char*);
112241  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
112242                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
112243                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
112244                            void (*xFinal)(sqlite3_context*),
112245                            void(*xDestroy)(void*));
112246  int (*db_config)(sqlite3*,int,...);
112247  sqlite3_mutex *(*db_mutex)(sqlite3*);
112248  int (*db_status)(sqlite3*,int,int*,int*,int);
112249  int (*extended_errcode)(sqlite3*);
112250  void (*log)(int,const char*,...);
112251  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
112252  const char *(*sourceid)(void);
112253  int (*stmt_status)(sqlite3_stmt*,int,int);
112254  int (*strnicmp)(const char*,const char*,int);
112255  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
112256  int (*wal_autocheckpoint)(sqlite3*,int);
112257  int (*wal_checkpoint)(sqlite3*,const char*);
112258  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
112259  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
112260  int (*vtab_config)(sqlite3*,int op,...);
112261  int (*vtab_on_conflict)(sqlite3*);
112262  /* Version 3.7.16 and later */
112263  int (*close_v2)(sqlite3*);
112264  const char *(*db_filename)(sqlite3*,const char*);
112265  int (*db_readonly)(sqlite3*,const char*);
112266  int (*db_release_memory)(sqlite3*);
112267  const char *(*errstr)(int);
112268  int (*stmt_busy)(sqlite3_stmt*);
112269  int (*stmt_readonly)(sqlite3_stmt*);
112270  int (*stricmp)(const char*,const char*);
112271  int (*uri_boolean)(const char*,const char*,int);
112272  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
112273  const char *(*uri_parameter)(const char*,const char*);
112274  char *(*vsnprintf)(int,char*,const char*,va_list);
112275  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
112276  /* Version 3.8.7 and later */
112277  int (*auto_extension)(void(*)(void));
112278  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
112279                     void(*)(void*));
112280  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
112281                      void(*)(void*),unsigned char);
112282  int (*cancel_auto_extension)(void(*)(void));
112283  int (*load_extension)(sqlite3*,const char*,const char*,char**);
112284  void *(*malloc64)(sqlite3_uint64);
112285  sqlite3_uint64 (*msize)(void*);
112286  void *(*realloc64)(void*,sqlite3_uint64);
112287  void (*reset_auto_extension)(void);
112288  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
112289                        void(*)(void*));
112290  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
112291                         void(*)(void*), unsigned char);
112292  int (*strglob)(const char*,const char*);
112293  /* Version 3.8.11 and later */
112294  sqlite3_value *(*value_dup)(const sqlite3_value*);
112295  void (*value_free)(sqlite3_value*);
112296  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
112297  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
112298  /* Version 3.9.0 and later */
112299  unsigned int (*value_subtype)(sqlite3_value*);
112300  void (*result_subtype)(sqlite3_context*,unsigned int);
112301  /* Version 3.10.0 and later */
112302  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
112303  int (*strlike)(const char*,const char*,unsigned int);
112304  int (*db_cacheflush)(sqlite3*);
112305  /* Version 3.12.0 and later */
112306  int (*system_errno)(sqlite3*);
112307  /* Version 3.14.0 and later */
112308  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
112309  char *(*expanded_sql)(sqlite3_stmt*);
112310  /* Version 3.18.0 and later */
112311  void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
112312  /* Version 3.20.0 and later */
112313  int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
112314                    sqlite3_stmt**,const char**);
112315  int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
112316                      sqlite3_stmt**,const void**);
112317  int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
112318  void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
112319  void *(*value_pointer)(sqlite3_value*,const char*);
112320};
112321
112322/*
112323** This is the function signature used for all extension entry points.  It
112324** is also defined in the file "loadext.c".
112325*/
112326typedef int (*sqlite3_loadext_entry)(
112327  sqlite3 *db,                       /* Handle to the database. */
112328  char **pzErrMsg,                   /* Used to set error string on failure. */
112329  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
112330);
112331
112332/*
112333** The following macros redefine the API routines so that they are
112334** redirected through the global sqlite3_api structure.
112335**
112336** This header file is also used by the loadext.c source file
112337** (part of the main SQLite library - not an extension) so that
112338** it can get access to the sqlite3_api_routines structure
112339** definition.  But the main library does not want to redefine
112340** the API.  So the redefinition macros are only valid if the
112341** SQLITE_CORE macros is undefined.
112342*/
112343#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
112344#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
112345#ifndef SQLITE_OMIT_DEPRECATED
112346#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
112347#endif
112348#define sqlite3_bind_blob              sqlite3_api->bind_blob
112349#define sqlite3_bind_double            sqlite3_api->bind_double
112350#define sqlite3_bind_int               sqlite3_api->bind_int
112351#define sqlite3_bind_int64             sqlite3_api->bind_int64
112352#define sqlite3_bind_null              sqlite3_api->bind_null
112353#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
112354#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
112355#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
112356#define sqlite3_bind_text              sqlite3_api->bind_text
112357#define sqlite3_bind_text16            sqlite3_api->bind_text16
112358#define sqlite3_bind_value             sqlite3_api->bind_value
112359#define sqlite3_busy_handler           sqlite3_api->busy_handler
112360#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
112361#define sqlite3_changes                sqlite3_api->changes
112362#define sqlite3_close                  sqlite3_api->close
112363#define sqlite3_collation_needed       sqlite3_api->collation_needed
112364#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
112365#define sqlite3_column_blob            sqlite3_api->column_blob
112366#define sqlite3_column_bytes           sqlite3_api->column_bytes
112367#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
112368#define sqlite3_column_count           sqlite3_api->column_count
112369#define sqlite3_column_database_name   sqlite3_api->column_database_name
112370#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
112371#define sqlite3_column_decltype        sqlite3_api->column_decltype
112372#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
112373#define sqlite3_column_double          sqlite3_api->column_double
112374#define sqlite3_column_int             sqlite3_api->column_int
112375#define sqlite3_column_int64           sqlite3_api->column_int64
112376#define sqlite3_column_name            sqlite3_api->column_name
112377#define sqlite3_column_name16          sqlite3_api->column_name16
112378#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
112379#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
112380#define sqlite3_column_table_name      sqlite3_api->column_table_name
112381#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
112382#define sqlite3_column_text            sqlite3_api->column_text
112383#define sqlite3_column_text16          sqlite3_api->column_text16
112384#define sqlite3_column_type            sqlite3_api->column_type
112385#define sqlite3_column_value           sqlite3_api->column_value
112386#define sqlite3_commit_hook            sqlite3_api->commit_hook
112387#define sqlite3_complete               sqlite3_api->complete
112388#define sqlite3_complete16             sqlite3_api->complete16
112389#define sqlite3_create_collation       sqlite3_api->create_collation
112390#define sqlite3_create_collation16     sqlite3_api->create_collation16
112391#define sqlite3_create_function        sqlite3_api->create_function
112392#define sqlite3_create_function16      sqlite3_api->create_function16
112393#define sqlite3_create_module          sqlite3_api->create_module
112394#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
112395#define sqlite3_data_count             sqlite3_api->data_count
112396#define sqlite3_db_handle              sqlite3_api->db_handle
112397#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
112398#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
112399#define sqlite3_errcode                sqlite3_api->errcode
112400#define sqlite3_errmsg                 sqlite3_api->errmsg
112401#define sqlite3_errmsg16               sqlite3_api->errmsg16
112402#define sqlite3_exec                   sqlite3_api->exec
112403#ifndef SQLITE_OMIT_DEPRECATED
112404#define sqlite3_expired                sqlite3_api->expired
112405#endif
112406#define sqlite3_finalize               sqlite3_api->finalize
112407#define sqlite3_free                   sqlite3_api->free
112408#define sqlite3_free_table             sqlite3_api->free_table
112409#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
112410#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
112411#define sqlite3_get_table              sqlite3_api->get_table
112412#ifndef SQLITE_OMIT_DEPRECATED
112413#define sqlite3_global_recover         sqlite3_api->global_recover
112414#endif
112415#define sqlite3_interrupt              sqlite3_api->interruptx
112416#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
112417#define sqlite3_libversion             sqlite3_api->libversion
112418#define sqlite3_libversion_number      sqlite3_api->libversion_number
112419#define sqlite3_malloc                 sqlite3_api->malloc
112420#define sqlite3_mprintf                sqlite3_api->mprintf
112421#define sqlite3_open                   sqlite3_api->open
112422#define sqlite3_open16                 sqlite3_api->open16
112423#define sqlite3_prepare                sqlite3_api->prepare
112424#define sqlite3_prepare16              sqlite3_api->prepare16
112425#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
112426#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
112427#define sqlite3_profile                sqlite3_api->profile
112428#define sqlite3_progress_handler       sqlite3_api->progress_handler
112429#define sqlite3_realloc                sqlite3_api->realloc
112430#define sqlite3_reset                  sqlite3_api->reset
112431#define sqlite3_result_blob            sqlite3_api->result_blob
112432#define sqlite3_result_double          sqlite3_api->result_double
112433#define sqlite3_result_error           sqlite3_api->result_error
112434#define sqlite3_result_error16         sqlite3_api->result_error16
112435#define sqlite3_result_int             sqlite3_api->result_int
112436#define sqlite3_result_int64           sqlite3_api->result_int64
112437#define sqlite3_result_null            sqlite3_api->result_null
112438#define sqlite3_result_text            sqlite3_api->result_text
112439#define sqlite3_result_text16          sqlite3_api->result_text16
112440#define sqlite3_result_text16be        sqlite3_api->result_text16be
112441#define sqlite3_result_text16le        sqlite3_api->result_text16le
112442#define sqlite3_result_value           sqlite3_api->result_value
112443#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
112444#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
112445#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
112446#define sqlite3_snprintf               sqlite3_api->snprintf
112447#define sqlite3_step                   sqlite3_api->step
112448#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
112449#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
112450#define sqlite3_total_changes          sqlite3_api->total_changes
112451#define sqlite3_trace                  sqlite3_api->trace
112452#ifndef SQLITE_OMIT_DEPRECATED
112453#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
112454#endif
112455#define sqlite3_update_hook            sqlite3_api->update_hook
112456#define sqlite3_user_data              sqlite3_api->user_data
112457#define sqlite3_value_blob             sqlite3_api->value_blob
112458#define sqlite3_value_bytes            sqlite3_api->value_bytes
112459#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
112460#define sqlite3_value_double           sqlite3_api->value_double
112461#define sqlite3_value_int              sqlite3_api->value_int
112462#define sqlite3_value_int64            sqlite3_api->value_int64
112463#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
112464#define sqlite3_value_text             sqlite3_api->value_text
112465#define sqlite3_value_text16           sqlite3_api->value_text16
112466#define sqlite3_value_text16be         sqlite3_api->value_text16be
112467#define sqlite3_value_text16le         sqlite3_api->value_text16le
112468#define sqlite3_value_type             sqlite3_api->value_type
112469#define sqlite3_vmprintf               sqlite3_api->vmprintf
112470#define sqlite3_vsnprintf              sqlite3_api->vsnprintf
112471#define sqlite3_overload_function      sqlite3_api->overload_function
112472#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
112473#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
112474#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
112475#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
112476#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
112477#define sqlite3_blob_close             sqlite3_api->blob_close
112478#define sqlite3_blob_open              sqlite3_api->blob_open
112479#define sqlite3_blob_read              sqlite3_api->blob_read
112480#define sqlite3_blob_write             sqlite3_api->blob_write
112481#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
112482#define sqlite3_file_control           sqlite3_api->file_control
112483#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
112484#define sqlite3_memory_used            sqlite3_api->memory_used
112485#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
112486#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
112487#define sqlite3_mutex_free             sqlite3_api->mutex_free
112488#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
112489#define sqlite3_mutex_try              sqlite3_api->mutex_try
112490#define sqlite3_open_v2                sqlite3_api->open_v2
112491#define sqlite3_release_memory         sqlite3_api->release_memory
112492#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
112493#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
112494#define sqlite3_sleep                  sqlite3_api->sleep
112495#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
112496#define sqlite3_vfs_find               sqlite3_api->vfs_find
112497#define sqlite3_vfs_register           sqlite3_api->vfs_register
112498#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
112499#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
112500#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
112501#define sqlite3_result_error_code      sqlite3_api->result_error_code
112502#define sqlite3_test_control           sqlite3_api->test_control
112503#define sqlite3_randomness             sqlite3_api->randomness
112504#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
112505#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
112506#define sqlite3_limit                  sqlite3_api->limit
112507#define sqlite3_next_stmt              sqlite3_api->next_stmt
112508#define sqlite3_sql                    sqlite3_api->sql
112509#define sqlite3_status                 sqlite3_api->status
112510#define sqlite3_backup_finish          sqlite3_api->backup_finish
112511#define sqlite3_backup_init            sqlite3_api->backup_init
112512#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
112513#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
112514#define sqlite3_backup_step            sqlite3_api->backup_step
112515#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
112516#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
112517#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
112518#define sqlite3_db_config              sqlite3_api->db_config
112519#define sqlite3_db_mutex               sqlite3_api->db_mutex
112520#define sqlite3_db_status              sqlite3_api->db_status
112521#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
112522#define sqlite3_log                    sqlite3_api->log
112523#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
112524#define sqlite3_sourceid               sqlite3_api->sourceid
112525#define sqlite3_stmt_status            sqlite3_api->stmt_status
112526#define sqlite3_strnicmp               sqlite3_api->strnicmp
112527#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
112528#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
112529#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
112530#define sqlite3_wal_hook               sqlite3_api->wal_hook
112531#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
112532#define sqlite3_vtab_config            sqlite3_api->vtab_config
112533#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
112534/* Version 3.7.16 and later */
112535#define sqlite3_close_v2               sqlite3_api->close_v2
112536#define sqlite3_db_filename            sqlite3_api->db_filename
112537#define sqlite3_db_readonly            sqlite3_api->db_readonly
112538#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
112539#define sqlite3_errstr                 sqlite3_api->errstr
112540#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
112541#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
112542#define sqlite3_stricmp                sqlite3_api->stricmp
112543#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
112544#define sqlite3_uri_int64              sqlite3_api->uri_int64
112545#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
112546#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
112547#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
112548/* Version 3.8.7 and later */
112549#define sqlite3_auto_extension         sqlite3_api->auto_extension
112550#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
112551#define sqlite3_bind_text64            sqlite3_api->bind_text64
112552#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
112553#define sqlite3_load_extension         sqlite3_api->load_extension
112554#define sqlite3_malloc64               sqlite3_api->malloc64
112555#define sqlite3_msize                  sqlite3_api->msize
112556#define sqlite3_realloc64              sqlite3_api->realloc64
112557#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
112558#define sqlite3_result_blob64          sqlite3_api->result_blob64
112559#define sqlite3_result_text64          sqlite3_api->result_text64
112560#define sqlite3_strglob                sqlite3_api->strglob
112561/* Version 3.8.11 and later */
112562#define sqlite3_value_dup              sqlite3_api->value_dup
112563#define sqlite3_value_free             sqlite3_api->value_free
112564#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
112565#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
112566/* Version 3.9.0 and later */
112567#define sqlite3_value_subtype          sqlite3_api->value_subtype
112568#define sqlite3_result_subtype         sqlite3_api->result_subtype
112569/* Version 3.10.0 and later */
112570#define sqlite3_status64               sqlite3_api->status64
112571#define sqlite3_strlike                sqlite3_api->strlike
112572#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
112573/* Version 3.12.0 and later */
112574#define sqlite3_system_errno           sqlite3_api->system_errno
112575/* Version 3.14.0 and later */
112576#define sqlite3_trace_v2               sqlite3_api->trace_v2
112577#define sqlite3_expanded_sql           sqlite3_api->expanded_sql
112578/* Version 3.18.0 and later */
112579#define sqlite3_set_last_insert_rowid  sqlite3_api->set_last_insert_rowid
112580/* Version 3.20.0 and later */
112581#define sqlite3_prepare_v3             sqlite3_api->prepare_v3
112582#define sqlite3_prepare16_v3           sqlite3_api->prepare16_v3
112583#define sqlite3_bind_pointer           sqlite3_api->bind_pointer
112584#define sqlite3_result_pointer         sqlite3_api->result_pointer
112585#define sqlite3_value_pointer          sqlite3_api->value_pointer
112586#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
112587
112588#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
112589  /* This case when the file really is being compiled as a loadable
112590  ** extension */
112591# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
112592# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
112593# define SQLITE_EXTENSION_INIT3     \
112594    extern const sqlite3_api_routines *sqlite3_api;
112595#else
112596  /* This case when the file is being statically linked into the
112597  ** application */
112598# define SQLITE_EXTENSION_INIT1     /*no-op*/
112599# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
112600# define SQLITE_EXTENSION_INIT3     /*no-op*/
112601#endif
112602
112603#endif /* SQLITE3EXT_H */
112604
112605/************** End of sqlite3ext.h ******************************************/
112606/************** Continuing where we left off in loadext.c ********************/
112607/* #include "sqliteInt.h" */
112608
112609#ifndef SQLITE_OMIT_LOAD_EXTENSION
112610/*
112611** Some API routines are omitted when various features are
112612** excluded from a build of SQLite.  Substitute a NULL pointer
112613** for any missing APIs.
112614*/
112615#ifndef SQLITE_ENABLE_COLUMN_METADATA
112616# define sqlite3_column_database_name   0
112617# define sqlite3_column_database_name16 0
112618# define sqlite3_column_table_name      0
112619# define sqlite3_column_table_name16    0
112620# define sqlite3_column_origin_name     0
112621# define sqlite3_column_origin_name16   0
112622#endif
112623
112624#ifdef SQLITE_OMIT_AUTHORIZATION
112625# define sqlite3_set_authorizer         0
112626#endif
112627
112628#ifdef SQLITE_OMIT_UTF16
112629# define sqlite3_bind_text16            0
112630# define sqlite3_collation_needed16     0
112631# define sqlite3_column_decltype16      0
112632# define sqlite3_column_name16          0
112633# define sqlite3_column_text16          0
112634# define sqlite3_complete16             0
112635# define sqlite3_create_collation16     0
112636# define sqlite3_create_function16      0
112637# define sqlite3_errmsg16               0
112638# define sqlite3_open16                 0
112639# define sqlite3_prepare16              0
112640# define sqlite3_prepare16_v2           0
112641# define sqlite3_prepare16_v3           0
112642# define sqlite3_result_error16         0
112643# define sqlite3_result_text16          0
112644# define sqlite3_result_text16be        0
112645# define sqlite3_result_text16le        0
112646# define sqlite3_value_text16           0
112647# define sqlite3_value_text16be         0
112648# define sqlite3_value_text16le         0
112649# define sqlite3_column_database_name16 0
112650# define sqlite3_column_table_name16    0
112651# define sqlite3_column_origin_name16   0
112652#endif
112653
112654#ifdef SQLITE_OMIT_COMPLETE
112655# define sqlite3_complete 0
112656# define sqlite3_complete16 0
112657#endif
112658
112659#ifdef SQLITE_OMIT_DECLTYPE
112660# define sqlite3_column_decltype16      0
112661# define sqlite3_column_decltype        0
112662#endif
112663
112664#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
112665# define sqlite3_progress_handler 0
112666#endif
112667
112668#ifdef SQLITE_OMIT_VIRTUALTABLE
112669# define sqlite3_create_module 0
112670# define sqlite3_create_module_v2 0
112671# define sqlite3_declare_vtab 0
112672# define sqlite3_vtab_config 0
112673# define sqlite3_vtab_on_conflict 0
112674#endif
112675
112676#ifdef SQLITE_OMIT_SHARED_CACHE
112677# define sqlite3_enable_shared_cache 0
112678#endif
112679
112680#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
112681# define sqlite3_profile       0
112682# define sqlite3_trace         0
112683#endif
112684
112685#ifdef SQLITE_OMIT_GET_TABLE
112686# define sqlite3_free_table    0
112687# define sqlite3_get_table     0
112688#endif
112689
112690#ifdef SQLITE_OMIT_INCRBLOB
112691#define sqlite3_bind_zeroblob  0
112692#define sqlite3_blob_bytes     0
112693#define sqlite3_blob_close     0
112694#define sqlite3_blob_open      0
112695#define sqlite3_blob_read      0
112696#define sqlite3_blob_write     0
112697#define sqlite3_blob_reopen    0
112698#endif
112699
112700#if defined(SQLITE_OMIT_TRACE)
112701# define sqlite3_trace_v2      0
112702#endif
112703
112704/*
112705** The following structure contains pointers to all SQLite API routines.
112706** A pointer to this structure is passed into extensions when they are
112707** loaded so that the extension can make calls back into the SQLite
112708** library.
112709**
112710** When adding new APIs, add them to the bottom of this structure
112711** in order to preserve backwards compatibility.
112712**
112713** Extensions that use newer APIs should first call the
112714** sqlite3_libversion_number() to make sure that the API they
112715** intend to use is supported by the library.  Extensions should
112716** also check to make sure that the pointer to the function is
112717** not NULL before calling it.
112718*/
112719static const sqlite3_api_routines sqlite3Apis = {
112720  sqlite3_aggregate_context,
112721#ifndef SQLITE_OMIT_DEPRECATED
112722  sqlite3_aggregate_count,
112723#else
112724  0,
112725#endif
112726  sqlite3_bind_blob,
112727  sqlite3_bind_double,
112728  sqlite3_bind_int,
112729  sqlite3_bind_int64,
112730  sqlite3_bind_null,
112731  sqlite3_bind_parameter_count,
112732  sqlite3_bind_parameter_index,
112733  sqlite3_bind_parameter_name,
112734  sqlite3_bind_text,
112735  sqlite3_bind_text16,
112736  sqlite3_bind_value,
112737  sqlite3_busy_handler,
112738  sqlite3_busy_timeout,
112739  sqlite3_changes,
112740  sqlite3_close,
112741  sqlite3_collation_needed,
112742  sqlite3_collation_needed16,
112743  sqlite3_column_blob,
112744  sqlite3_column_bytes,
112745  sqlite3_column_bytes16,
112746  sqlite3_column_count,
112747  sqlite3_column_database_name,
112748  sqlite3_column_database_name16,
112749  sqlite3_column_decltype,
112750  sqlite3_column_decltype16,
112751  sqlite3_column_double,
112752  sqlite3_column_int,
112753  sqlite3_column_int64,
112754  sqlite3_column_name,
112755  sqlite3_column_name16,
112756  sqlite3_column_origin_name,
112757  sqlite3_column_origin_name16,
112758  sqlite3_column_table_name,
112759  sqlite3_column_table_name16,
112760  sqlite3_column_text,
112761  sqlite3_column_text16,
112762  sqlite3_column_type,
112763  sqlite3_column_value,
112764  sqlite3_commit_hook,
112765  sqlite3_complete,
112766  sqlite3_complete16,
112767  sqlite3_create_collation,
112768  sqlite3_create_collation16,
112769  sqlite3_create_function,
112770  sqlite3_create_function16,
112771  sqlite3_create_module,
112772  sqlite3_data_count,
112773  sqlite3_db_handle,
112774  sqlite3_declare_vtab,
112775  sqlite3_enable_shared_cache,
112776  sqlite3_errcode,
112777  sqlite3_errmsg,
112778  sqlite3_errmsg16,
112779  sqlite3_exec,
112780#ifndef SQLITE_OMIT_DEPRECATED
112781  sqlite3_expired,
112782#else
112783  0,
112784#endif
112785  sqlite3_finalize,
112786  sqlite3_free,
112787  sqlite3_free_table,
112788  sqlite3_get_autocommit,
112789  sqlite3_get_auxdata,
112790  sqlite3_get_table,
112791  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
112792  sqlite3_interrupt,
112793  sqlite3_last_insert_rowid,
112794  sqlite3_libversion,
112795  sqlite3_libversion_number,
112796  sqlite3_malloc,
112797  sqlite3_mprintf,
112798  sqlite3_open,
112799  sqlite3_open16,
112800  sqlite3_prepare,
112801  sqlite3_prepare16,
112802  sqlite3_profile,
112803  sqlite3_progress_handler,
112804  sqlite3_realloc,
112805  sqlite3_reset,
112806  sqlite3_result_blob,
112807  sqlite3_result_double,
112808  sqlite3_result_error,
112809  sqlite3_result_error16,
112810  sqlite3_result_int,
112811  sqlite3_result_int64,
112812  sqlite3_result_null,
112813  sqlite3_result_text,
112814  sqlite3_result_text16,
112815  sqlite3_result_text16be,
112816  sqlite3_result_text16le,
112817  sqlite3_result_value,
112818  sqlite3_rollback_hook,
112819  sqlite3_set_authorizer,
112820  sqlite3_set_auxdata,
112821  sqlite3_snprintf,
112822  sqlite3_step,
112823  sqlite3_table_column_metadata,
112824#ifndef SQLITE_OMIT_DEPRECATED
112825  sqlite3_thread_cleanup,
112826#else
112827  0,
112828#endif
112829  sqlite3_total_changes,
112830  sqlite3_trace,
112831#ifndef SQLITE_OMIT_DEPRECATED
112832  sqlite3_transfer_bindings,
112833#else
112834  0,
112835#endif
112836  sqlite3_update_hook,
112837  sqlite3_user_data,
112838  sqlite3_value_blob,
112839  sqlite3_value_bytes,
112840  sqlite3_value_bytes16,
112841  sqlite3_value_double,
112842  sqlite3_value_int,
112843  sqlite3_value_int64,
112844  sqlite3_value_numeric_type,
112845  sqlite3_value_text,
112846  sqlite3_value_text16,
112847  sqlite3_value_text16be,
112848  sqlite3_value_text16le,
112849  sqlite3_value_type,
112850  sqlite3_vmprintf,
112851  /*
112852  ** The original API set ends here.  All extensions can call any
112853  ** of the APIs above provided that the pointer is not NULL.  But
112854  ** before calling APIs that follow, extension should check the
112855  ** sqlite3_libversion_number() to make sure they are dealing with
112856  ** a library that is new enough to support that API.
112857  *************************************************************************
112858  */
112859  sqlite3_overload_function,
112860
112861  /*
112862  ** Added after 3.3.13
112863  */
112864  sqlite3_prepare_v2,
112865  sqlite3_prepare16_v2,
112866  sqlite3_clear_bindings,
112867
112868  /*
112869  ** Added for 3.4.1
112870  */
112871  sqlite3_create_module_v2,
112872
112873  /*
112874  ** Added for 3.5.0
112875  */
112876  sqlite3_bind_zeroblob,
112877  sqlite3_blob_bytes,
112878  sqlite3_blob_close,
112879  sqlite3_blob_open,
112880  sqlite3_blob_read,
112881  sqlite3_blob_write,
112882  sqlite3_create_collation_v2,
112883  sqlite3_file_control,
112884  sqlite3_memory_highwater,
112885  sqlite3_memory_used,
112886#ifdef SQLITE_MUTEX_OMIT
112887  0,
112888  0,
112889  0,
112890  0,
112891  0,
112892#else
112893  sqlite3_mutex_alloc,
112894  sqlite3_mutex_enter,
112895  sqlite3_mutex_free,
112896  sqlite3_mutex_leave,
112897  sqlite3_mutex_try,
112898#endif
112899  sqlite3_open_v2,
112900  sqlite3_release_memory,
112901  sqlite3_result_error_nomem,
112902  sqlite3_result_error_toobig,
112903  sqlite3_sleep,
112904  sqlite3_soft_heap_limit,
112905  sqlite3_vfs_find,
112906  sqlite3_vfs_register,
112907  sqlite3_vfs_unregister,
112908
112909  /*
112910  ** Added for 3.5.8
112911  */
112912  sqlite3_threadsafe,
112913  sqlite3_result_zeroblob,
112914  sqlite3_result_error_code,
112915  sqlite3_test_control,
112916  sqlite3_randomness,
112917  sqlite3_context_db_handle,
112918
112919  /*
112920  ** Added for 3.6.0
112921  */
112922  sqlite3_extended_result_codes,
112923  sqlite3_limit,
112924  sqlite3_next_stmt,
112925  sqlite3_sql,
112926  sqlite3_status,
112927
112928  /*
112929  ** Added for 3.7.4
112930  */
112931  sqlite3_backup_finish,
112932  sqlite3_backup_init,
112933  sqlite3_backup_pagecount,
112934  sqlite3_backup_remaining,
112935  sqlite3_backup_step,
112936#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
112937  sqlite3_compileoption_get,
112938  sqlite3_compileoption_used,
112939#else
112940  0,
112941  0,
112942#endif
112943  sqlite3_create_function_v2,
112944  sqlite3_db_config,
112945  sqlite3_db_mutex,
112946  sqlite3_db_status,
112947  sqlite3_extended_errcode,
112948  sqlite3_log,
112949  sqlite3_soft_heap_limit64,
112950  sqlite3_sourceid,
112951  sqlite3_stmt_status,
112952  sqlite3_strnicmp,
112953#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
112954  sqlite3_unlock_notify,
112955#else
112956  0,
112957#endif
112958#ifndef SQLITE_OMIT_WAL
112959  sqlite3_wal_autocheckpoint,
112960  sqlite3_wal_checkpoint,
112961  sqlite3_wal_hook,
112962#else
112963  0,
112964  0,
112965  0,
112966#endif
112967  sqlite3_blob_reopen,
112968  sqlite3_vtab_config,
112969  sqlite3_vtab_on_conflict,
112970  sqlite3_close_v2,
112971  sqlite3_db_filename,
112972  sqlite3_db_readonly,
112973  sqlite3_db_release_memory,
112974  sqlite3_errstr,
112975  sqlite3_stmt_busy,
112976  sqlite3_stmt_readonly,
112977  sqlite3_stricmp,
112978  sqlite3_uri_boolean,
112979  sqlite3_uri_int64,
112980  sqlite3_uri_parameter,
112981  sqlite3_vsnprintf,
112982  sqlite3_wal_checkpoint_v2,
112983  /* Version 3.8.7 and later */
112984  sqlite3_auto_extension,
112985  sqlite3_bind_blob64,
112986  sqlite3_bind_text64,
112987  sqlite3_cancel_auto_extension,
112988  sqlite3_load_extension,
112989  sqlite3_malloc64,
112990  sqlite3_msize,
112991  sqlite3_realloc64,
112992  sqlite3_reset_auto_extension,
112993  sqlite3_result_blob64,
112994  sqlite3_result_text64,
112995  sqlite3_strglob,
112996  /* Version 3.8.11 and later */
112997  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
112998  sqlite3_value_free,
112999  sqlite3_result_zeroblob64,
113000  sqlite3_bind_zeroblob64,
113001  /* Version 3.9.0 and later */
113002  sqlite3_value_subtype,
113003  sqlite3_result_subtype,
113004  /* Version 3.10.0 and later */
113005  sqlite3_status64,
113006  sqlite3_strlike,
113007  sqlite3_db_cacheflush,
113008  /* Version 3.12.0 and later */
113009  sqlite3_system_errno,
113010  /* Version 3.14.0 and later */
113011  sqlite3_trace_v2,
113012  sqlite3_expanded_sql,
113013  /* Version 3.18.0 and later */
113014  sqlite3_set_last_insert_rowid,
113015  /* Version 3.20.0 and later */
113016  sqlite3_prepare_v3,
113017  sqlite3_prepare16_v3,
113018  sqlite3_bind_pointer,
113019  sqlite3_result_pointer,
113020  sqlite3_value_pointer
113021};
113022
113023/*
113024** Attempt to load an SQLite extension library contained in the file
113025** zFile.  The entry point is zProc.  zProc may be 0 in which case a
113026** default entry point name (sqlite3_extension_init) is used.  Use
113027** of the default name is recommended.
113028**
113029** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
113030**
113031** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
113032** error message text.  The calling function should free this memory
113033** by calling sqlite3DbFree(db, ).
113034*/
113035static int sqlite3LoadExtension(
113036  sqlite3 *db,          /* Load the extension into this database connection */
113037  const char *zFile,    /* Name of the shared library containing extension */
113038  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
113039  char **pzErrMsg       /* Put error message here if not 0 */
113040){
113041  sqlite3_vfs *pVfs = db->pVfs;
113042  void *handle;
113043  sqlite3_loadext_entry xInit;
113044  char *zErrmsg = 0;
113045  const char *zEntry;
113046  char *zAltEntry = 0;
113047  void **aHandle;
113048  u64 nMsg = 300 + sqlite3Strlen30(zFile);
113049  int ii;
113050  int rc;
113051
113052  /* Shared library endings to try if zFile cannot be loaded as written */
113053  static const char *azEndings[] = {
113054#if SQLITE_OS_WIN
113055     "dll"
113056#elif defined(__APPLE__)
113057     "dylib"
113058#else
113059     "so"
113060#endif
113061  };
113062
113063
113064  if( pzErrMsg ) *pzErrMsg = 0;
113065
113066  /* Ticket #1863.  To avoid a creating security problems for older
113067  ** applications that relink against newer versions of SQLite, the
113068  ** ability to run load_extension is turned off by default.  One
113069  ** must call either sqlite3_enable_load_extension(db) or
113070  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
113071  ** to turn on extension loading.
113072  */
113073  if( (db->flags & SQLITE_LoadExtension)==0 ){
113074    if( pzErrMsg ){
113075      *pzErrMsg = sqlite3_mprintf("not authorized");
113076    }
113077    return SQLITE_ERROR;
113078  }
113079
113080  zEntry = zProc ? zProc : "sqlite3_extension_init";
113081
113082  handle = sqlite3OsDlOpen(pVfs, zFile);
113083#if SQLITE_OS_UNIX || SQLITE_OS_WIN
113084  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
113085    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
113086    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
113087    handle = sqlite3OsDlOpen(pVfs, zAltFile);
113088    sqlite3_free(zAltFile);
113089  }
113090#endif
113091  if( handle==0 ){
113092    if( pzErrMsg ){
113093      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
113094      if( zErrmsg ){
113095        sqlite3_snprintf(nMsg, zErrmsg,
113096            "unable to open shared library [%s]", zFile);
113097        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
113098      }
113099    }
113100    return SQLITE_ERROR;
113101  }
113102  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
113103
113104  /* If no entry point was specified and the default legacy
113105  ** entry point name "sqlite3_extension_init" was not found, then
113106  ** construct an entry point name "sqlite3_X_init" where the X is
113107  ** replaced by the lowercase value of every ASCII alphabetic
113108  ** character in the filename after the last "/" upto the first ".",
113109  ** and eliding the first three characters if they are "lib".
113110  ** Examples:
113111  **
113112  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
113113  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
113114  */
113115  if( xInit==0 && zProc==0 ){
113116    int iFile, iEntry, c;
113117    int ncFile = sqlite3Strlen30(zFile);
113118    zAltEntry = sqlite3_malloc64(ncFile+30);
113119    if( zAltEntry==0 ){
113120      sqlite3OsDlClose(pVfs, handle);
113121      return SQLITE_NOMEM_BKPT;
113122    }
113123    memcpy(zAltEntry, "sqlite3_", 8);
113124    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
113125    iFile++;
113126    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
113127    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
113128      if( sqlite3Isalpha(c) ){
113129        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
113130      }
113131    }
113132    memcpy(zAltEntry+iEntry, "_init", 6);
113133    zEntry = zAltEntry;
113134    xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
113135  }
113136  if( xInit==0 ){
113137    if( pzErrMsg ){
113138      nMsg += sqlite3Strlen30(zEntry);
113139      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
113140      if( zErrmsg ){
113141        sqlite3_snprintf(nMsg, zErrmsg,
113142            "no entry point [%s] in shared library [%s]", zEntry, zFile);
113143        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
113144      }
113145    }
113146    sqlite3OsDlClose(pVfs, handle);
113147    sqlite3_free(zAltEntry);
113148    return SQLITE_ERROR;
113149  }
113150  sqlite3_free(zAltEntry);
113151  rc = xInit(db, &zErrmsg, &sqlite3Apis);
113152  if( rc ){
113153    if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
113154    if( pzErrMsg ){
113155      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
113156    }
113157    sqlite3_free(zErrmsg);
113158    sqlite3OsDlClose(pVfs, handle);
113159    return SQLITE_ERROR;
113160  }
113161
113162  /* Append the new shared library handle to the db->aExtension array. */
113163  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
113164  if( aHandle==0 ){
113165    return SQLITE_NOMEM_BKPT;
113166  }
113167  if( db->nExtension>0 ){
113168    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
113169  }
113170  sqlite3DbFree(db, db->aExtension);
113171  db->aExtension = aHandle;
113172
113173  db->aExtension[db->nExtension++] = handle;
113174  return SQLITE_OK;
113175}
113176SQLITE_API int sqlite3_load_extension(
113177  sqlite3 *db,          /* Load the extension into this database connection */
113178  const char *zFile,    /* Name of the shared library containing extension */
113179  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
113180  char **pzErrMsg       /* Put error message here if not 0 */
113181){
113182  int rc;
113183  sqlite3_mutex_enter(db->mutex);
113184  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
113185  rc = sqlite3ApiExit(db, rc);
113186  sqlite3_mutex_leave(db->mutex);
113187  return rc;
113188}
113189
113190/*
113191** Call this routine when the database connection is closing in order
113192** to clean up loaded extensions
113193*/
113194SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
113195  int i;
113196  assert( sqlite3_mutex_held(db->mutex) );
113197  for(i=0; i<db->nExtension; i++){
113198    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
113199  }
113200  sqlite3DbFree(db, db->aExtension);
113201}
113202
113203/*
113204** Enable or disable extension loading.  Extension loading is disabled by
113205** default so as not to open security holes in older applications.
113206*/
113207SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
113208  sqlite3_mutex_enter(db->mutex);
113209  if( onoff ){
113210    db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
113211  }else{
113212    db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
113213  }
113214  sqlite3_mutex_leave(db->mutex);
113215  return SQLITE_OK;
113216}
113217
113218#endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
113219
113220/*
113221** The following object holds the list of automatically loaded
113222** extensions.
113223**
113224** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
113225** mutex must be held while accessing this list.
113226*/
113227typedef struct sqlite3AutoExtList sqlite3AutoExtList;
113228static SQLITE_WSD struct sqlite3AutoExtList {
113229  u32 nExt;              /* Number of entries in aExt[] */
113230  void (**aExt)(void);   /* Pointers to the extension init functions */
113231} sqlite3Autoext = { 0, 0 };
113232
113233/* The "wsdAutoext" macro will resolve to the autoextension
113234** state vector.  If writable static data is unsupported on the target,
113235** we have to locate the state vector at run-time.  In the more common
113236** case where writable static data is supported, wsdStat can refer directly
113237** to the "sqlite3Autoext" state vector declared above.
113238*/
113239#ifdef SQLITE_OMIT_WSD
113240# define wsdAutoextInit \
113241  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
113242# define wsdAutoext x[0]
113243#else
113244# define wsdAutoextInit
113245# define wsdAutoext sqlite3Autoext
113246#endif
113247
113248
113249/*
113250** Register a statically linked extension that is automatically
113251** loaded by every new database connection.
113252*/
113253SQLITE_API int sqlite3_auto_extension(
113254  void (*xInit)(void)
113255){
113256  int rc = SQLITE_OK;
113257#ifndef SQLITE_OMIT_AUTOINIT
113258  rc = sqlite3_initialize();
113259  if( rc ){
113260    return rc;
113261  }else
113262#endif
113263  {
113264    u32 i;
113265#if SQLITE_THREADSAFE
113266    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113267#endif
113268    wsdAutoextInit;
113269    sqlite3_mutex_enter(mutex);
113270    for(i=0; i<wsdAutoext.nExt; i++){
113271      if( wsdAutoext.aExt[i]==xInit ) break;
113272    }
113273    if( i==wsdAutoext.nExt ){
113274      u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
113275      void (**aNew)(void);
113276      aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
113277      if( aNew==0 ){
113278        rc = SQLITE_NOMEM_BKPT;
113279      }else{
113280        wsdAutoext.aExt = aNew;
113281        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
113282        wsdAutoext.nExt++;
113283      }
113284    }
113285    sqlite3_mutex_leave(mutex);
113286    assert( (rc&0xff)==rc );
113287    return rc;
113288  }
113289}
113290
113291/*
113292** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
113293** set of routines that is invoked for each new database connection, if it
113294** is currently on the list.  If xInit is not on the list, then this
113295** routine is a no-op.
113296**
113297** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
113298** was not on the list.
113299*/
113300SQLITE_API int sqlite3_cancel_auto_extension(
113301  void (*xInit)(void)
113302){
113303#if SQLITE_THREADSAFE
113304  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113305#endif
113306  int i;
113307  int n = 0;
113308  wsdAutoextInit;
113309  sqlite3_mutex_enter(mutex);
113310  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
113311    if( wsdAutoext.aExt[i]==xInit ){
113312      wsdAutoext.nExt--;
113313      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
113314      n++;
113315      break;
113316    }
113317  }
113318  sqlite3_mutex_leave(mutex);
113319  return n;
113320}
113321
113322/*
113323** Reset the automatic extension loading mechanism.
113324*/
113325SQLITE_API void sqlite3_reset_auto_extension(void){
113326#ifndef SQLITE_OMIT_AUTOINIT
113327  if( sqlite3_initialize()==SQLITE_OK )
113328#endif
113329  {
113330#if SQLITE_THREADSAFE
113331    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113332#endif
113333    wsdAutoextInit;
113334    sqlite3_mutex_enter(mutex);
113335    sqlite3_free(wsdAutoext.aExt);
113336    wsdAutoext.aExt = 0;
113337    wsdAutoext.nExt = 0;
113338    sqlite3_mutex_leave(mutex);
113339  }
113340}
113341
113342/*
113343** Load all automatic extensions.
113344**
113345** If anything goes wrong, set an error in the database connection.
113346*/
113347SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
113348  u32 i;
113349  int go = 1;
113350  int rc;
113351  sqlite3_loadext_entry xInit;
113352
113353  wsdAutoextInit;
113354  if( wsdAutoext.nExt==0 ){
113355    /* Common case: early out without every having to acquire a mutex */
113356    return;
113357  }
113358  for(i=0; go; i++){
113359    char *zErrmsg;
113360#if SQLITE_THREADSAFE
113361    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
113362#endif
113363#ifdef SQLITE_OMIT_LOAD_EXTENSION
113364    const sqlite3_api_routines *pThunk = 0;
113365#else
113366    const sqlite3_api_routines *pThunk = &sqlite3Apis;
113367#endif
113368    sqlite3_mutex_enter(mutex);
113369    if( i>=wsdAutoext.nExt ){
113370      xInit = 0;
113371      go = 0;
113372    }else{
113373      xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
113374    }
113375    sqlite3_mutex_leave(mutex);
113376    zErrmsg = 0;
113377    if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
113378      sqlite3ErrorWithMsg(db, rc,
113379            "automatic extension loading failed: %s", zErrmsg);
113380      go = 0;
113381    }
113382    sqlite3_free(zErrmsg);
113383  }
113384}
113385
113386/************** End of loadext.c *********************************************/
113387/************** Begin file pragma.c ******************************************/
113388/*
113389** 2003 April 6
113390**
113391** The author disclaims copyright to this source code.  In place of
113392** a legal notice, here is a blessing:
113393**
113394**    May you do good and not evil.
113395**    May you find forgiveness for yourself and forgive others.
113396**    May you share freely, never taking more than you give.
113397**
113398*************************************************************************
113399** This file contains code used to implement the PRAGMA command.
113400*/
113401/* #include "sqliteInt.h" */
113402
113403#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
113404#  if defined(__APPLE__)
113405#    define SQLITE_ENABLE_LOCKING_STYLE 1
113406#  else
113407#    define SQLITE_ENABLE_LOCKING_STYLE 0
113408#  endif
113409#endif
113410
113411/***************************************************************************
113412** The "pragma.h" include file is an automatically generated file that
113413** that includes the PragType_XXXX macro definitions and the aPragmaName[]
113414** object.  This ensures that the aPragmaName[] table is arranged in
113415** lexicographical order to facility a binary search of the pragma name.
113416** Do not edit pragma.h directly.  Edit and rerun the script in at
113417** ../tool/mkpragmatab.tcl. */
113418/************** Include pragma.h in the middle of pragma.c *******************/
113419/************** Begin file pragma.h ******************************************/
113420/* DO NOT EDIT!
113421** This file is automatically generated by the script at
113422** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
113423** that script and rerun it.
113424*/
113425
113426/* The various pragma types */
113427#define PragTyp_HEADER_VALUE                   0
113428#define PragTyp_AUTO_VACUUM                    1
113429#define PragTyp_FLAG                           2
113430#define PragTyp_BUSY_TIMEOUT                   3
113431#define PragTyp_CACHE_SIZE                     4
113432#define PragTyp_CACHE_SPILL                    5
113433#define PragTyp_CASE_SENSITIVE_LIKE            6
113434#define PragTyp_COLLATION_LIST                 7
113435#define PragTyp_COMPILE_OPTIONS                8
113436#define PragTyp_DATA_STORE_DIRECTORY           9
113437#define PragTyp_DATABASE_LIST                 10
113438#define PragTyp_DEFAULT_CACHE_SIZE            11
113439#define PragTyp_ENCODING                      12
113440#define PragTyp_FOREIGN_KEY_CHECK             13
113441#define PragTyp_FOREIGN_KEY_LIST              14
113442#define PragTyp_FUNCTION_LIST                 15
113443#define PragTyp_INCREMENTAL_VACUUM            16
113444#define PragTyp_INDEX_INFO                    17
113445#define PragTyp_INDEX_LIST                    18
113446#define PragTyp_INTEGRITY_CHECK               19
113447#define PragTyp_JOURNAL_MODE                  20
113448#define PragTyp_JOURNAL_SIZE_LIMIT            21
113449#define PragTyp_LOCK_PROXY_FILE               22
113450#define PragTyp_LOCKING_MODE                  23
113451#define PragTyp_PAGE_COUNT                    24
113452#define PragTyp_MMAP_SIZE                     25
113453#define PragTyp_MODULE_LIST                   26
113454#define PragTyp_OPTIMIZE                      27
113455#define PragTyp_PAGE_SIZE                     28
113456#define PragTyp_PRAGMA_LIST                   29
113457#define PragTyp_SECURE_DELETE                 30
113458#define PragTyp_SHRINK_MEMORY                 31
113459#define PragTyp_SOFT_HEAP_LIMIT               32
113460#define PragTyp_SYNCHRONOUS                   33
113461#define PragTyp_TABLE_INFO                    34
113462#define PragTyp_TEMP_STORE                    35
113463#define PragTyp_TEMP_STORE_DIRECTORY          36
113464#define PragTyp_THREADS                       37
113465#define PragTyp_WAL_AUTOCHECKPOINT            38
113466#define PragTyp_WAL_CHECKPOINT                39
113467#define PragTyp_ACTIVATE_EXTENSIONS           40
113468#define PragTyp_HEXKEY                        41
113469#define PragTyp_KEY                           42
113470#define PragTyp_REKEY                         43
113471#define PragTyp_LOCK_STATUS                   44
113472#define PragTyp_PARSER_TRACE                  45
113473#define PragTyp_STATS                         46
113474
113475/* Property flags associated with various pragma. */
113476#define PragFlg_NeedSchema 0x01 /* Force schema load before running */
113477#define PragFlg_NoColumns  0x02 /* OP_ResultRow called with zero columns */
113478#define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
113479#define PragFlg_ReadOnly   0x08 /* Read-only HEADER_VALUE */
113480#define PragFlg_Result0    0x10 /* Acts as query when no argument */
113481#define PragFlg_Result1    0x20 /* Acts as query when has one argument */
113482#define PragFlg_SchemaOpt  0x40 /* Schema restricts name search if present */
113483#define PragFlg_SchemaReq  0x80 /* Schema required - "main" is default */
113484
113485/* Names of columns for pragmas that return multi-column result
113486** or that return single-column results where the name of the
113487** result column is different from the name of the pragma
113488*/
113489static const char *const pragCName[] = {
113490  /*   0 */ "cache_size",  /* Used by: default_cache_size */
113491  /*   1 */ "cid",         /* Used by: table_info */
113492  /*   2 */ "name",
113493  /*   3 */ "type",
113494  /*   4 */ "notnull",
113495  /*   5 */ "dflt_value",
113496  /*   6 */ "pk",
113497  /*   7 */ "tbl",         /* Used by: stats */
113498  /*   8 */ "idx",
113499  /*   9 */ "wdth",
113500  /*  10 */ "hght",
113501  /*  11 */ "flgs",
113502  /*  12 */ "seqno",       /* Used by: index_info */
113503  /*  13 */ "cid",
113504  /*  14 */ "name",
113505  /*  15 */ "seqno",       /* Used by: index_xinfo */
113506  /*  16 */ "cid",
113507  /*  17 */ "name",
113508  /*  18 */ "desc",
113509  /*  19 */ "coll",
113510  /*  20 */ "key",
113511  /*  21 */ "seq",         /* Used by: index_list */
113512  /*  22 */ "name",
113513  /*  23 */ "unique",
113514  /*  24 */ "origin",
113515  /*  25 */ "partial",
113516  /*  26 */ "seq",         /* Used by: database_list */
113517  /*  27 */ "name",
113518  /*  28 */ "file",
113519  /*  29 */ "name",        /* Used by: function_list */
113520  /*  30 */ "builtin",
113521  /*  31 */ "name",        /* Used by: module_list pragma_list */
113522  /*  32 */ "seq",         /* Used by: collation_list */
113523  /*  33 */ "name",
113524  /*  34 */ "id",          /* Used by: foreign_key_list */
113525  /*  35 */ "seq",
113526  /*  36 */ "table",
113527  /*  37 */ "from",
113528  /*  38 */ "to",
113529  /*  39 */ "on_update",
113530  /*  40 */ "on_delete",
113531  /*  41 */ "match",
113532  /*  42 */ "table",       /* Used by: foreign_key_check */
113533  /*  43 */ "rowid",
113534  /*  44 */ "parent",
113535  /*  45 */ "fkid",
113536  /*  46 */ "busy",        /* Used by: wal_checkpoint */
113537  /*  47 */ "log",
113538  /*  48 */ "checkpointed",
113539  /*  49 */ "timeout",     /* Used by: busy_timeout */
113540  /*  50 */ "database",    /* Used by: lock_status */
113541  /*  51 */ "status",
113542};
113543
113544/* Definitions of all built-in pragmas */
113545typedef struct PragmaName {
113546  const char *const zName; /* Name of pragma */
113547  u8 ePragTyp;             /* PragTyp_XXX value */
113548  u8 mPragFlg;             /* Zero or more PragFlg_XXX values */
113549  u8 iPragCName;           /* Start of column names in pragCName[] */
113550  u8 nPragCName;           /* Num of col names. 0 means use pragma name */
113551  u32 iArg;                /* Extra argument */
113552} PragmaName;
113553static const PragmaName aPragmaName[] = {
113554#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
113555 {/* zName:     */ "activate_extensions",
113556  /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
113557  /* ePragFlg:  */ 0,
113558  /* ColNames:  */ 0, 0,
113559  /* iArg:      */ 0 },
113560#endif
113561#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113562 {/* zName:     */ "application_id",
113563  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
113564  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
113565  /* ColNames:  */ 0, 0,
113566  /* iArg:      */ BTREE_APPLICATION_ID },
113567#endif
113568#if !defined(SQLITE_OMIT_AUTOVACUUM)
113569 {/* zName:     */ "auto_vacuum",
113570  /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
113571  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113572  /* ColNames:  */ 0, 0,
113573  /* iArg:      */ 0 },
113574#endif
113575#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113576#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
113577 {/* zName:     */ "automatic_index",
113578  /* ePragTyp:  */ PragTyp_FLAG,
113579  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113580  /* ColNames:  */ 0, 0,
113581  /* iArg:      */ SQLITE_AutoIndex },
113582#endif
113583#endif
113584 {/* zName:     */ "busy_timeout",
113585  /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
113586  /* ePragFlg:  */ PragFlg_Result0,
113587  /* ColNames:  */ 49, 1,
113588  /* iArg:      */ 0 },
113589#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113590 {/* zName:     */ "cache_size",
113591  /* ePragTyp:  */ PragTyp_CACHE_SIZE,
113592  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113593  /* ColNames:  */ 0, 0,
113594  /* iArg:      */ 0 },
113595#endif
113596#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113597 {/* zName:     */ "cache_spill",
113598  /* ePragTyp:  */ PragTyp_CACHE_SPILL,
113599  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113600  /* ColNames:  */ 0, 0,
113601  /* iArg:      */ 0 },
113602#endif
113603 {/* zName:     */ "case_sensitive_like",
113604  /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
113605  /* ePragFlg:  */ PragFlg_NoColumns,
113606  /* ColNames:  */ 0, 0,
113607  /* iArg:      */ 0 },
113608 {/* zName:     */ "cell_size_check",
113609  /* ePragTyp:  */ PragTyp_FLAG,
113610  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113611  /* ColNames:  */ 0, 0,
113612  /* iArg:      */ SQLITE_CellSizeCk },
113613#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113614 {/* zName:     */ "checkpoint_fullfsync",
113615  /* ePragTyp:  */ PragTyp_FLAG,
113616  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113617  /* ColNames:  */ 0, 0,
113618  /* iArg:      */ SQLITE_CkptFullFSync },
113619#endif
113620#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113621 {/* zName:     */ "collation_list",
113622  /* ePragTyp:  */ PragTyp_COLLATION_LIST,
113623  /* ePragFlg:  */ PragFlg_Result0,
113624  /* ColNames:  */ 32, 2,
113625  /* iArg:      */ 0 },
113626#endif
113627#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
113628 {/* zName:     */ "compile_options",
113629  /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
113630  /* ePragFlg:  */ PragFlg_Result0,
113631  /* ColNames:  */ 0, 0,
113632  /* iArg:      */ 0 },
113633#endif
113634#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113635 {/* zName:     */ "count_changes",
113636  /* ePragTyp:  */ PragTyp_FLAG,
113637  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113638  /* ColNames:  */ 0, 0,
113639  /* iArg:      */ SQLITE_CountRows },
113640#endif
113641#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
113642 {/* zName:     */ "data_store_directory",
113643  /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
113644  /* ePragFlg:  */ PragFlg_NoColumns1,
113645  /* ColNames:  */ 0, 0,
113646  /* iArg:      */ 0 },
113647#endif
113648#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113649 {/* zName:     */ "data_version",
113650  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
113651  /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
113652  /* ColNames:  */ 0, 0,
113653  /* iArg:      */ BTREE_DATA_VERSION },
113654#endif
113655#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113656 {/* zName:     */ "database_list",
113657  /* ePragTyp:  */ PragTyp_DATABASE_LIST,
113658  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
113659  /* ColNames:  */ 26, 3,
113660  /* iArg:      */ 0 },
113661#endif
113662#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
113663 {/* zName:     */ "default_cache_size",
113664  /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
113665  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113666  /* ColNames:  */ 0, 1,
113667  /* iArg:      */ 0 },
113668#endif
113669#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113670#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113671 {/* zName:     */ "defer_foreign_keys",
113672  /* ePragTyp:  */ PragTyp_FLAG,
113673  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113674  /* ColNames:  */ 0, 0,
113675  /* iArg:      */ SQLITE_DeferFKs },
113676#endif
113677#endif
113678#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113679 {/* zName:     */ "empty_result_callbacks",
113680  /* ePragTyp:  */ PragTyp_FLAG,
113681  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113682  /* ColNames:  */ 0, 0,
113683  /* iArg:      */ SQLITE_NullCallback },
113684#endif
113685#if !defined(SQLITE_OMIT_UTF16)
113686 {/* zName:     */ "encoding",
113687  /* ePragTyp:  */ PragTyp_ENCODING,
113688  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113689  /* ColNames:  */ 0, 0,
113690  /* iArg:      */ 0 },
113691#endif
113692#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113693 {/* zName:     */ "foreign_key_check",
113694  /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
113695  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
113696  /* ColNames:  */ 42, 4,
113697  /* iArg:      */ 0 },
113698#endif
113699#if !defined(SQLITE_OMIT_FOREIGN_KEY)
113700 {/* zName:     */ "foreign_key_list",
113701  /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
113702  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
113703  /* ColNames:  */ 34, 8,
113704  /* iArg:      */ 0 },
113705#endif
113706#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113707#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
113708 {/* zName:     */ "foreign_keys",
113709  /* ePragTyp:  */ PragTyp_FLAG,
113710  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113711  /* ColNames:  */ 0, 0,
113712  /* iArg:      */ SQLITE_ForeignKeys },
113713#endif
113714#endif
113715#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113716 {/* zName:     */ "freelist_count",
113717  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
113718  /* ePragFlg:  */ PragFlg_ReadOnly|PragFlg_Result0,
113719  /* ColNames:  */ 0, 0,
113720  /* iArg:      */ BTREE_FREE_PAGE_COUNT },
113721#endif
113722#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113723 {/* zName:     */ "full_column_names",
113724  /* ePragTyp:  */ PragTyp_FLAG,
113725  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113726  /* ColNames:  */ 0, 0,
113727  /* iArg:      */ SQLITE_FullColNames },
113728 {/* zName:     */ "fullfsync",
113729  /* ePragTyp:  */ PragTyp_FLAG,
113730  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113731  /* ColNames:  */ 0, 0,
113732  /* iArg:      */ SQLITE_FullFSync },
113733#endif
113734#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113735#if defined(SQLITE_INTROSPECTION_PRAGMAS)
113736 {/* zName:     */ "function_list",
113737  /* ePragTyp:  */ PragTyp_FUNCTION_LIST,
113738  /* ePragFlg:  */ PragFlg_Result0,
113739  /* ColNames:  */ 29, 2,
113740  /* iArg:      */ 0 },
113741#endif
113742#endif
113743#if defined(SQLITE_HAS_CODEC)
113744 {/* zName:     */ "hexkey",
113745  /* ePragTyp:  */ PragTyp_HEXKEY,
113746  /* ePragFlg:  */ 0,
113747  /* ColNames:  */ 0, 0,
113748  /* iArg:      */ 0 },
113749 {/* zName:     */ "hexrekey",
113750  /* ePragTyp:  */ PragTyp_HEXKEY,
113751  /* ePragFlg:  */ 0,
113752  /* ColNames:  */ 0, 0,
113753  /* iArg:      */ 0 },
113754#endif
113755#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113756#if !defined(SQLITE_OMIT_CHECK)
113757 {/* zName:     */ "ignore_check_constraints",
113758  /* ePragTyp:  */ PragTyp_FLAG,
113759  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113760  /* ColNames:  */ 0, 0,
113761  /* iArg:      */ SQLITE_IgnoreChecks },
113762#endif
113763#endif
113764#if !defined(SQLITE_OMIT_AUTOVACUUM)
113765 {/* zName:     */ "incremental_vacuum",
113766  /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
113767  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_NoColumns,
113768  /* ColNames:  */ 0, 0,
113769  /* iArg:      */ 0 },
113770#endif
113771#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113772 {/* zName:     */ "index_info",
113773  /* ePragTyp:  */ PragTyp_INDEX_INFO,
113774  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
113775  /* ColNames:  */ 12, 3,
113776  /* iArg:      */ 0 },
113777 {/* zName:     */ "index_list",
113778  /* ePragTyp:  */ PragTyp_INDEX_LIST,
113779  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
113780  /* ColNames:  */ 21, 5,
113781  /* iArg:      */ 0 },
113782 {/* zName:     */ "index_xinfo",
113783  /* ePragTyp:  */ PragTyp_INDEX_INFO,
113784  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
113785  /* ColNames:  */ 15, 6,
113786  /* iArg:      */ 1 },
113787#endif
113788#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
113789 {/* zName:     */ "integrity_check",
113790  /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
113791  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
113792  /* ColNames:  */ 0, 0,
113793  /* iArg:      */ 0 },
113794#endif
113795#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113796 {/* zName:     */ "journal_mode",
113797  /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
113798  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
113799  /* ColNames:  */ 0, 0,
113800  /* iArg:      */ 0 },
113801 {/* zName:     */ "journal_size_limit",
113802  /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
113803  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
113804  /* ColNames:  */ 0, 0,
113805  /* iArg:      */ 0 },
113806#endif
113807#if defined(SQLITE_HAS_CODEC)
113808 {/* zName:     */ "key",
113809  /* ePragTyp:  */ PragTyp_KEY,
113810  /* ePragFlg:  */ 0,
113811  /* ColNames:  */ 0, 0,
113812  /* iArg:      */ 0 },
113813#endif
113814#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113815 {/* zName:     */ "legacy_file_format",
113816  /* ePragTyp:  */ PragTyp_FLAG,
113817  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113818  /* ColNames:  */ 0, 0,
113819  /* iArg:      */ SQLITE_LegacyFileFmt },
113820#endif
113821#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
113822 {/* zName:     */ "lock_proxy_file",
113823  /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
113824  /* ePragFlg:  */ PragFlg_NoColumns1,
113825  /* ColNames:  */ 0, 0,
113826  /* iArg:      */ 0 },
113827#endif
113828#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
113829 {/* zName:     */ "lock_status",
113830  /* ePragTyp:  */ PragTyp_LOCK_STATUS,
113831  /* ePragFlg:  */ PragFlg_Result0,
113832  /* ColNames:  */ 50, 2,
113833  /* iArg:      */ 0 },
113834#endif
113835#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113836 {/* zName:     */ "locking_mode",
113837  /* ePragTyp:  */ PragTyp_LOCKING_MODE,
113838  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq,
113839  /* ColNames:  */ 0, 0,
113840  /* iArg:      */ 0 },
113841 {/* zName:     */ "max_page_count",
113842  /* ePragTyp:  */ PragTyp_PAGE_COUNT,
113843  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
113844  /* ColNames:  */ 0, 0,
113845  /* iArg:      */ 0 },
113846 {/* zName:     */ "mmap_size",
113847  /* ePragTyp:  */ PragTyp_MMAP_SIZE,
113848  /* ePragFlg:  */ 0,
113849  /* ColNames:  */ 0, 0,
113850  /* iArg:      */ 0 },
113851#endif
113852#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113853#if !defined(SQLITE_OMIT_VIRTUALTABLE)
113854#if defined(SQLITE_INTROSPECTION_PRAGMAS)
113855 {/* zName:     */ "module_list",
113856  /* ePragTyp:  */ PragTyp_MODULE_LIST,
113857  /* ePragFlg:  */ PragFlg_Result0,
113858  /* ColNames:  */ 31, 1,
113859  /* iArg:      */ 0 },
113860#endif
113861#endif
113862#endif
113863 {/* zName:     */ "optimize",
113864  /* ePragTyp:  */ PragTyp_OPTIMIZE,
113865  /* ePragFlg:  */ PragFlg_Result1|PragFlg_NeedSchema,
113866  /* ColNames:  */ 0, 0,
113867  /* iArg:      */ 0 },
113868#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113869 {/* zName:     */ "page_count",
113870  /* ePragTyp:  */ PragTyp_PAGE_COUNT,
113871  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
113872  /* ColNames:  */ 0, 0,
113873  /* iArg:      */ 0 },
113874 {/* zName:     */ "page_size",
113875  /* ePragTyp:  */ PragTyp_PAGE_SIZE,
113876  /* ePragFlg:  */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113877  /* ColNames:  */ 0, 0,
113878  /* iArg:      */ 0 },
113879#endif
113880#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
113881 {/* zName:     */ "parser_trace",
113882  /* ePragTyp:  */ PragTyp_PARSER_TRACE,
113883  /* ePragFlg:  */ 0,
113884  /* ColNames:  */ 0, 0,
113885  /* iArg:      */ 0 },
113886#endif
113887#if defined(SQLITE_INTROSPECTION_PRAGMAS)
113888 {/* zName:     */ "pragma_list",
113889  /* ePragTyp:  */ PragTyp_PRAGMA_LIST,
113890  /* ePragFlg:  */ PragFlg_Result0,
113891  /* ColNames:  */ 31, 1,
113892  /* iArg:      */ 0 },
113893#endif
113894#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113895 {/* zName:     */ "query_only",
113896  /* ePragTyp:  */ PragTyp_FLAG,
113897  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113898  /* ColNames:  */ 0, 0,
113899  /* iArg:      */ SQLITE_QueryOnly },
113900#endif
113901#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
113902 {/* zName:     */ "quick_check",
113903  /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
113904  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
113905  /* ColNames:  */ 0, 0,
113906  /* iArg:      */ 0 },
113907#endif
113908#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113909 {/* zName:     */ "read_uncommitted",
113910  /* ePragTyp:  */ PragTyp_FLAG,
113911  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113912  /* ColNames:  */ 0, 0,
113913  /* iArg:      */ SQLITE_ReadUncommit },
113914 {/* zName:     */ "recursive_triggers",
113915  /* ePragTyp:  */ PragTyp_FLAG,
113916  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113917  /* ColNames:  */ 0, 0,
113918  /* iArg:      */ SQLITE_RecTriggers },
113919#endif
113920#if defined(SQLITE_HAS_CODEC)
113921 {/* zName:     */ "rekey",
113922  /* ePragTyp:  */ PragTyp_REKEY,
113923  /* ePragFlg:  */ 0,
113924  /* ColNames:  */ 0, 0,
113925  /* iArg:      */ 0 },
113926#endif
113927#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113928 {/* zName:     */ "reverse_unordered_selects",
113929  /* ePragTyp:  */ PragTyp_FLAG,
113930  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113931  /* ColNames:  */ 0, 0,
113932  /* iArg:      */ SQLITE_ReverseOrder },
113933#endif
113934#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
113935 {/* zName:     */ "schema_version",
113936  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
113937  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
113938  /* ColNames:  */ 0, 0,
113939  /* iArg:      */ BTREE_SCHEMA_VERSION },
113940#endif
113941#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113942 {/* zName:     */ "secure_delete",
113943  /* ePragTyp:  */ PragTyp_SECURE_DELETE,
113944  /* ePragFlg:  */ PragFlg_Result0,
113945  /* ColNames:  */ 0, 0,
113946  /* iArg:      */ 0 },
113947#endif
113948#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113949 {/* zName:     */ "short_column_names",
113950  /* ePragTyp:  */ PragTyp_FLAG,
113951  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113952  /* ColNames:  */ 0, 0,
113953  /* iArg:      */ SQLITE_ShortColNames },
113954#endif
113955 {/* zName:     */ "shrink_memory",
113956  /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
113957  /* ePragFlg:  */ PragFlg_NoColumns,
113958  /* ColNames:  */ 0, 0,
113959  /* iArg:      */ 0 },
113960 {/* zName:     */ "soft_heap_limit",
113961  /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
113962  /* ePragFlg:  */ PragFlg_Result0,
113963  /* ColNames:  */ 0, 0,
113964  /* iArg:      */ 0 },
113965#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
113966#if defined(SQLITE_DEBUG)
113967 {/* zName:     */ "sql_trace",
113968  /* ePragTyp:  */ PragTyp_FLAG,
113969  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113970  /* ColNames:  */ 0, 0,
113971  /* iArg:      */ SQLITE_SqlTrace },
113972#endif
113973#endif
113974#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
113975 {/* zName:     */ "stats",
113976  /* ePragTyp:  */ PragTyp_STATS,
113977  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
113978  /* ColNames:  */ 7, 5,
113979  /* iArg:      */ 0 },
113980#endif
113981#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113982 {/* zName:     */ "synchronous",
113983  /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
113984  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
113985  /* ColNames:  */ 0, 0,
113986  /* iArg:      */ 0 },
113987#endif
113988#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
113989 {/* zName:     */ "table_info",
113990  /* ePragTyp:  */ PragTyp_TABLE_INFO,
113991  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
113992  /* ColNames:  */ 1, 6,
113993  /* iArg:      */ 0 },
113994#endif
113995#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
113996 {/* zName:     */ "temp_store",
113997  /* ePragTyp:  */ PragTyp_TEMP_STORE,
113998  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
113999  /* ColNames:  */ 0, 0,
114000  /* iArg:      */ 0 },
114001 {/* zName:     */ "temp_store_directory",
114002  /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
114003  /* ePragFlg:  */ PragFlg_NoColumns1,
114004  /* ColNames:  */ 0, 0,
114005  /* iArg:      */ 0 },
114006#endif
114007 {/* zName:     */ "threads",
114008  /* ePragTyp:  */ PragTyp_THREADS,
114009  /* ePragFlg:  */ PragFlg_Result0,
114010  /* ColNames:  */ 0, 0,
114011  /* iArg:      */ 0 },
114012#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
114013 {/* zName:     */ "user_version",
114014  /* ePragTyp:  */ PragTyp_HEADER_VALUE,
114015  /* ePragFlg:  */ PragFlg_NoColumns1|PragFlg_Result0,
114016  /* ColNames:  */ 0, 0,
114017  /* iArg:      */ BTREE_USER_VERSION },
114018#endif
114019#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114020#if defined(SQLITE_DEBUG)
114021 {/* zName:     */ "vdbe_addoptrace",
114022  /* ePragTyp:  */ PragTyp_FLAG,
114023  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114024  /* ColNames:  */ 0, 0,
114025  /* iArg:      */ SQLITE_VdbeAddopTrace },
114026 {/* zName:     */ "vdbe_debug",
114027  /* ePragTyp:  */ PragTyp_FLAG,
114028  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114029  /* ColNames:  */ 0, 0,
114030  /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
114031 {/* zName:     */ "vdbe_eqp",
114032  /* ePragTyp:  */ PragTyp_FLAG,
114033  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114034  /* ColNames:  */ 0, 0,
114035  /* iArg:      */ SQLITE_VdbeEQP },
114036 {/* zName:     */ "vdbe_listing",
114037  /* ePragTyp:  */ PragTyp_FLAG,
114038  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114039  /* ColNames:  */ 0, 0,
114040  /* iArg:      */ SQLITE_VdbeListing },
114041 {/* zName:     */ "vdbe_trace",
114042  /* ePragTyp:  */ PragTyp_FLAG,
114043  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114044  /* ColNames:  */ 0, 0,
114045  /* iArg:      */ SQLITE_VdbeTrace },
114046#endif
114047#endif
114048#if !defined(SQLITE_OMIT_WAL)
114049 {/* zName:     */ "wal_autocheckpoint",
114050  /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
114051  /* ePragFlg:  */ 0,
114052  /* ColNames:  */ 0, 0,
114053  /* iArg:      */ 0 },
114054 {/* zName:     */ "wal_checkpoint",
114055  /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
114056  /* ePragFlg:  */ PragFlg_NeedSchema,
114057  /* ColNames:  */ 46, 3,
114058  /* iArg:      */ 0 },
114059#endif
114060#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
114061 {/* zName:     */ "writable_schema",
114062  /* ePragTyp:  */ PragTyp_FLAG,
114063  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
114064  /* ColNames:  */ 0, 0,
114065  /* iArg:      */ SQLITE_WriteSchema },
114066#endif
114067};
114068/* Number of pragmas: 60 on by default, 77 total. */
114069
114070/************** End of pragma.h **********************************************/
114071/************** Continuing where we left off in pragma.c *********************/
114072
114073/*
114074** Interpret the given string as a safety level.  Return 0 for OFF,
114075** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or
114076** unrecognized string argument.  The FULL and EXTRA option is disallowed
114077** if the omitFull parameter it 1.
114078**
114079** Note that the values returned are one less that the values that
114080** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
114081** to support legacy SQL code.  The safety level used to be boolean
114082** and older scripts may have used numbers 0 for OFF and 1 for ON.
114083*/
114084static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
114085                             /* 123456789 123456789 123 */
114086  static const char zText[] = "onoffalseyestruextrafull";
114087  static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
114088  static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
114089  static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
114090                            /* on no off false yes true extra full */
114091  int i, n;
114092  if( sqlite3Isdigit(*z) ){
114093    return (u8)sqlite3Atoi(z);
114094  }
114095  n = sqlite3Strlen30(z);
114096  for(i=0; i<ArraySize(iLength); i++){
114097    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
114098     && (!omitFull || iValue[i]<=1)
114099    ){
114100      return iValue[i];
114101    }
114102  }
114103  return dflt;
114104}
114105
114106/*
114107** Interpret the given string as a boolean value.
114108*/
114109SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
114110  return getSafetyLevel(z,1,dflt)!=0;
114111}
114112
114113/* The sqlite3GetBoolean() function is used by other modules but the
114114** remainder of this file is specific to PRAGMA processing.  So omit
114115** the rest of the file if PRAGMAs are omitted from the build.
114116*/
114117#if !defined(SQLITE_OMIT_PRAGMA)
114118
114119/*
114120** Interpret the given string as a locking mode value.
114121*/
114122static int getLockingMode(const char *z){
114123  if( z ){
114124    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
114125    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
114126  }
114127  return PAGER_LOCKINGMODE_QUERY;
114128}
114129
114130#ifndef SQLITE_OMIT_AUTOVACUUM
114131/*
114132** Interpret the given string as an auto-vacuum mode value.
114133**
114134** The following strings, "none", "full" and "incremental" are
114135** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
114136*/
114137static int getAutoVacuum(const char *z){
114138  int i;
114139  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
114140  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
114141  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
114142  i = sqlite3Atoi(z);
114143  return (u8)((i>=0&&i<=2)?i:0);
114144}
114145#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
114146
114147#ifndef SQLITE_OMIT_PAGER_PRAGMAS
114148/*
114149** Interpret the given string as a temp db location. Return 1 for file
114150** backed temporary databases, 2 for the Red-Black tree in memory database
114151** and 0 to use the compile-time default.
114152*/
114153static int getTempStore(const char *z){
114154  if( z[0]>='0' && z[0]<='2' ){
114155    return z[0] - '0';
114156  }else if( sqlite3StrICmp(z, "file")==0 ){
114157    return 1;
114158  }else if( sqlite3StrICmp(z, "memory")==0 ){
114159    return 2;
114160  }else{
114161    return 0;
114162  }
114163}
114164#endif /* SQLITE_PAGER_PRAGMAS */
114165
114166#ifndef SQLITE_OMIT_PAGER_PRAGMAS
114167/*
114168** Invalidate temp storage, either when the temp storage is changed
114169** from default, or when 'file' and the temp_store_directory has changed
114170*/
114171static int invalidateTempStorage(Parse *pParse){
114172  sqlite3 *db = pParse->db;
114173  if( db->aDb[1].pBt!=0 ){
114174    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
114175      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
114176        "from within a transaction");
114177      return SQLITE_ERROR;
114178    }
114179    sqlite3BtreeClose(db->aDb[1].pBt);
114180    db->aDb[1].pBt = 0;
114181    sqlite3ResetAllSchemasOfConnection(db);
114182  }
114183  return SQLITE_OK;
114184}
114185#endif /* SQLITE_PAGER_PRAGMAS */
114186
114187#ifndef SQLITE_OMIT_PAGER_PRAGMAS
114188/*
114189** If the TEMP database is open, close it and mark the database schema
114190** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
114191** or DEFAULT_TEMP_STORE pragmas.
114192*/
114193static int changeTempStorage(Parse *pParse, const char *zStorageType){
114194  int ts = getTempStore(zStorageType);
114195  sqlite3 *db = pParse->db;
114196  if( db->temp_store==ts ) return SQLITE_OK;
114197  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
114198    return SQLITE_ERROR;
114199  }
114200  db->temp_store = (u8)ts;
114201  return SQLITE_OK;
114202}
114203#endif /* SQLITE_PAGER_PRAGMAS */
114204
114205/*
114206** Set result column names for a pragma.
114207*/
114208static void setPragmaResultColumnNames(
114209  Vdbe *v,                     /* The query under construction */
114210  const PragmaName *pPragma    /* The pragma */
114211){
114212  u8 n = pPragma->nPragCName;
114213  sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
114214  if( n==0 ){
114215    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
114216  }else{
114217    int i, j;
114218    for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
114219      sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
114220    }
114221  }
114222}
114223
114224/*
114225** Generate code to return a single integer value.
114226*/
114227static void returnSingleInt(Vdbe *v, i64 value){
114228  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
114229  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114230}
114231
114232/*
114233** Generate code to return a single text value.
114234*/
114235static void returnSingleText(
114236  Vdbe *v,                /* Prepared statement under construction */
114237  const char *zValue      /* Value to be returned */
114238){
114239  if( zValue ){
114240    sqlite3VdbeLoadString(v, 1, (const char*)zValue);
114241    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114242  }
114243}
114244
114245
114246/*
114247** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
114248** set these values for all pagers.
114249*/
114250#ifndef SQLITE_OMIT_PAGER_PRAGMAS
114251static void setAllPagerFlags(sqlite3 *db){
114252  if( db->autoCommit ){
114253    Db *pDb = db->aDb;
114254    int n = db->nDb;
114255    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
114256    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
114257    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
114258    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
114259             ==  PAGER_FLAGS_MASK );
114260    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
114261    while( (n--) > 0 ){
114262      if( pDb->pBt ){
114263        sqlite3BtreeSetPagerFlags(pDb->pBt,
114264                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
114265      }
114266      pDb++;
114267    }
114268  }
114269}
114270#else
114271# define setAllPagerFlags(X)  /* no-op */
114272#endif
114273
114274
114275/*
114276** Return a human-readable name for a constraint resolution action.
114277*/
114278#ifndef SQLITE_OMIT_FOREIGN_KEY
114279static const char *actionName(u8 action){
114280  const char *zName;
114281  switch( action ){
114282    case OE_SetNull:  zName = "SET NULL";        break;
114283    case OE_SetDflt:  zName = "SET DEFAULT";     break;
114284    case OE_Cascade:  zName = "CASCADE";         break;
114285    case OE_Restrict: zName = "RESTRICT";        break;
114286    default:          zName = "NO ACTION";
114287                      assert( action==OE_None ); break;
114288  }
114289  return zName;
114290}
114291#endif
114292
114293
114294/*
114295** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
114296** defined in pager.h. This function returns the associated lowercase
114297** journal-mode name.
114298*/
114299SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
114300  static char * const azModeName[] = {
114301    "delete", "persist", "off", "truncate", "memory"
114302#ifndef SQLITE_OMIT_WAL
114303     , "wal"
114304#endif
114305  };
114306  assert( PAGER_JOURNALMODE_DELETE==0 );
114307  assert( PAGER_JOURNALMODE_PERSIST==1 );
114308  assert( PAGER_JOURNALMODE_OFF==2 );
114309  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
114310  assert( PAGER_JOURNALMODE_MEMORY==4 );
114311  assert( PAGER_JOURNALMODE_WAL==5 );
114312  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
114313
114314  if( eMode==ArraySize(azModeName) ) return 0;
114315  return azModeName[eMode];
114316}
114317
114318/*
114319** Locate a pragma in the aPragmaName[] array.
114320*/
114321static const PragmaName *pragmaLocate(const char *zName){
114322  int upr, lwr, mid = 0, rc;
114323  lwr = 0;
114324  upr = ArraySize(aPragmaName)-1;
114325  while( lwr<=upr ){
114326    mid = (lwr+upr)/2;
114327    rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
114328    if( rc==0 ) break;
114329    if( rc<0 ){
114330      upr = mid - 1;
114331    }else{
114332      lwr = mid + 1;
114333    }
114334  }
114335  return lwr>upr ? 0 : &aPragmaName[mid];
114336}
114337
114338/*
114339** Helper subroutine for PRAGMA integrity_check:
114340**
114341** Generate code to output a single-column result row with the result
114342** held in register regResult.  Decrement the result count and halt if
114343** the maximum number of result rows have been issued.
114344*/
114345static int integrityCheckResultRow(Vdbe *v, int regResult){
114346  int addr;
114347  sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 1);
114348  addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
114349  VdbeCoverage(v);
114350  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
114351  return addr;
114352}
114353
114354/*
114355** Process a pragma statement.
114356**
114357** Pragmas are of this form:
114358**
114359**      PRAGMA [schema.]id [= value]
114360**
114361** The identifier might also be a string.  The value is a string, and
114362** identifier, or a number.  If minusFlag is true, then the value is
114363** a number that was preceded by a minus sign.
114364**
114365** If the left side is "database.id" then pId1 is the database name
114366** and pId2 is the id.  If the left side is just "id" then pId1 is the
114367** id and pId2 is any empty string.
114368*/
114369SQLITE_PRIVATE void sqlite3Pragma(
114370  Parse *pParse,
114371  Token *pId1,        /* First part of [schema.]id field */
114372  Token *pId2,        /* Second part of [schema.]id field, or NULL */
114373  Token *pValue,      /* Token for <value>, or NULL */
114374  int minusFlag       /* True if a '-' sign preceded <value> */
114375){
114376  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
114377  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
114378  const char *zDb = 0;   /* The database name */
114379  Token *pId;            /* Pointer to <id> token */
114380  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
114381  int iDb;               /* Database index for <database> */
114382  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
114383  sqlite3 *db = pParse->db;    /* The database connection */
114384  Db *pDb;                     /* The specific database being pragmaed */
114385  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
114386  const PragmaName *pPragma;   /* The pragma */
114387
114388  if( v==0 ) return;
114389  sqlite3VdbeRunOnlyOnce(v);
114390  pParse->nMem = 2;
114391
114392  /* Interpret the [schema.] part of the pragma statement. iDb is the
114393  ** index of the database this pragma is being applied to in db.aDb[]. */
114394  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
114395  if( iDb<0 ) return;
114396  pDb = &db->aDb[iDb];
114397
114398  /* If the temp database has been explicitly named as part of the
114399  ** pragma, make sure it is open.
114400  */
114401  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
114402    return;
114403  }
114404
114405  zLeft = sqlite3NameFromToken(db, pId);
114406  if( !zLeft ) return;
114407  if( minusFlag ){
114408    zRight = sqlite3MPrintf(db, "-%T", pValue);
114409  }else{
114410    zRight = sqlite3NameFromToken(db, pValue);
114411  }
114412
114413  assert( pId2 );
114414  zDb = pId2->n>0 ? pDb->zDbSName : 0;
114415  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
114416    goto pragma_out;
114417  }
114418
114419  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
114420  ** connection.  If it returns SQLITE_OK, then assume that the VFS
114421  ** handled the pragma and generate a no-op prepared statement.
114422  **
114423  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
114424  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
114425  ** object corresponding to the database file to which the pragma
114426  ** statement refers.
114427  **
114428  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
114429  ** file control is an array of pointers to strings (char**) in which the
114430  ** second element of the array is the name of the pragma and the third
114431  ** element is the argument to the pragma or NULL if the pragma has no
114432  ** argument.
114433  */
114434  aFcntl[0] = 0;
114435  aFcntl[1] = zLeft;
114436  aFcntl[2] = zRight;
114437  aFcntl[3] = 0;
114438  db->busyHandler.nBusy = 0;
114439  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
114440  if( rc==SQLITE_OK ){
114441    sqlite3VdbeSetNumCols(v, 1);
114442    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
114443    returnSingleText(v, aFcntl[0]);
114444    sqlite3_free(aFcntl[0]);
114445    goto pragma_out;
114446  }
114447  if( rc!=SQLITE_NOTFOUND ){
114448    if( aFcntl[0] ){
114449      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
114450      sqlite3_free(aFcntl[0]);
114451    }
114452    pParse->nErr++;
114453    pParse->rc = rc;
114454    goto pragma_out;
114455  }
114456
114457  /* Locate the pragma in the lookup table */
114458  pPragma = pragmaLocate(zLeft);
114459  if( pPragma==0 ) goto pragma_out;
114460
114461  /* Make sure the database schema is loaded if the pragma requires that */
114462  if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
114463    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
114464  }
114465
114466  /* Register the result column names for pragmas that return results */
114467  if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
114468   && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
114469  ){
114470    setPragmaResultColumnNames(v, pPragma);
114471  }
114472
114473  /* Jump to the appropriate pragma handler */
114474  switch( pPragma->ePragTyp ){
114475
114476#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
114477  /*
114478  **  PRAGMA [schema.]default_cache_size
114479  **  PRAGMA [schema.]default_cache_size=N
114480  **
114481  ** The first form reports the current persistent setting for the
114482  ** page cache size.  The value returned is the maximum number of
114483  ** pages in the page cache.  The second form sets both the current
114484  ** page cache size value and the persistent page cache size value
114485  ** stored in the database file.
114486  **
114487  ** Older versions of SQLite would set the default cache size to a
114488  ** negative number to indicate synchronous=OFF.  These days, synchronous
114489  ** is always on by default regardless of the sign of the default cache
114490  ** size.  But continue to take the absolute value of the default cache
114491  ** size of historical compatibility.
114492  */
114493  case PragTyp_DEFAULT_CACHE_SIZE: {
114494    static const int iLn = VDBE_OFFSET_LINENO(2);
114495    static const VdbeOpList getCacheSize[] = {
114496      { OP_Transaction, 0, 0,        0},                         /* 0 */
114497      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
114498      { OP_IfPos,       1, 8,        0},
114499      { OP_Integer,     0, 2,        0},
114500      { OP_Subtract,    1, 2,        1},
114501      { OP_IfPos,       1, 8,        0},
114502      { OP_Integer,     0, 1,        0},                         /* 6 */
114503      { OP_Noop,        0, 0,        0},
114504      { OP_ResultRow,   1, 1,        0},
114505    };
114506    VdbeOp *aOp;
114507    sqlite3VdbeUsesBtree(v, iDb);
114508    if( !zRight ){
114509      pParse->nMem += 2;
114510      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
114511      aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
114512      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
114513      aOp[0].p1 = iDb;
114514      aOp[1].p1 = iDb;
114515      aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
114516    }else{
114517      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
114518      sqlite3BeginWriteOperation(pParse, 0, iDb);
114519      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
114520      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114521      pDb->pSchema->cache_size = size;
114522      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
114523    }
114524    break;
114525  }
114526#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
114527
114528#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
114529  /*
114530  **  PRAGMA [schema.]page_size
114531  **  PRAGMA [schema.]page_size=N
114532  **
114533  ** The first form reports the current setting for the
114534  ** database page size in bytes.  The second form sets the
114535  ** database page size value.  The value can only be set if
114536  ** the database has not yet been created.
114537  */
114538  case PragTyp_PAGE_SIZE: {
114539    Btree *pBt = pDb->pBt;
114540    assert( pBt!=0 );
114541    if( !zRight ){
114542      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
114543      returnSingleInt(v, size);
114544    }else{
114545      /* Malloc may fail when setting the page-size, as there is an internal
114546      ** buffer that the pager module resizes using sqlite3_realloc().
114547      */
114548      db->nextPagesize = sqlite3Atoi(zRight);
114549      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
114550        sqlite3OomFault(db);
114551      }
114552    }
114553    break;
114554  }
114555
114556  /*
114557  **  PRAGMA [schema.]secure_delete
114558  **  PRAGMA [schema.]secure_delete=ON/OFF/FAST
114559  **
114560  ** The first form reports the current setting for the
114561  ** secure_delete flag.  The second form changes the secure_delete
114562  ** flag setting and reports the new value.
114563  */
114564  case PragTyp_SECURE_DELETE: {
114565    Btree *pBt = pDb->pBt;
114566    int b = -1;
114567    assert( pBt!=0 );
114568    if( zRight ){
114569      if( sqlite3_stricmp(zRight, "fast")==0 ){
114570        b = 2;
114571      }else{
114572        b = sqlite3GetBoolean(zRight, 0);
114573      }
114574    }
114575    if( pId2->n==0 && b>=0 ){
114576      int ii;
114577      for(ii=0; ii<db->nDb; ii++){
114578        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
114579      }
114580    }
114581    b = sqlite3BtreeSecureDelete(pBt, b);
114582    returnSingleInt(v, b);
114583    break;
114584  }
114585
114586  /*
114587  **  PRAGMA [schema.]max_page_count
114588  **  PRAGMA [schema.]max_page_count=N
114589  **
114590  ** The first form reports the current setting for the
114591  ** maximum number of pages in the database file.  The
114592  ** second form attempts to change this setting.  Both
114593  ** forms return the current setting.
114594  **
114595  ** The absolute value of N is used.  This is undocumented and might
114596  ** change.  The only purpose is to provide an easy way to test
114597  ** the sqlite3AbsInt32() function.
114598  **
114599  **  PRAGMA [schema.]page_count
114600  **
114601  ** Return the number of pages in the specified database.
114602  */
114603  case PragTyp_PAGE_COUNT: {
114604    int iReg;
114605    sqlite3CodeVerifySchema(pParse, iDb);
114606    iReg = ++pParse->nMem;
114607    if( sqlite3Tolower(zLeft[0])=='p' ){
114608      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
114609    }else{
114610      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
114611                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
114612    }
114613    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
114614    break;
114615  }
114616
114617  /*
114618  **  PRAGMA [schema.]locking_mode
114619  **  PRAGMA [schema.]locking_mode = (normal|exclusive)
114620  */
114621  case PragTyp_LOCKING_MODE: {
114622    const char *zRet = "normal";
114623    int eMode = getLockingMode(zRight);
114624
114625    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
114626      /* Simple "PRAGMA locking_mode;" statement. This is a query for
114627      ** the current default locking mode (which may be different to
114628      ** the locking-mode of the main database).
114629      */
114630      eMode = db->dfltLockMode;
114631    }else{
114632      Pager *pPager;
114633      if( pId2->n==0 ){
114634        /* This indicates that no database name was specified as part
114635        ** of the PRAGMA command. In this case the locking-mode must be
114636        ** set on all attached databases, as well as the main db file.
114637        **
114638        ** Also, the sqlite3.dfltLockMode variable is set so that
114639        ** any subsequently attached databases also use the specified
114640        ** locking mode.
114641        */
114642        int ii;
114643        assert(pDb==&db->aDb[0]);
114644        for(ii=2; ii<db->nDb; ii++){
114645          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
114646          sqlite3PagerLockingMode(pPager, eMode);
114647        }
114648        db->dfltLockMode = (u8)eMode;
114649      }
114650      pPager = sqlite3BtreePager(pDb->pBt);
114651      eMode = sqlite3PagerLockingMode(pPager, eMode);
114652    }
114653
114654    assert( eMode==PAGER_LOCKINGMODE_NORMAL
114655            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
114656    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
114657      zRet = "exclusive";
114658    }
114659    returnSingleText(v, zRet);
114660    break;
114661  }
114662
114663  /*
114664  **  PRAGMA [schema.]journal_mode
114665  **  PRAGMA [schema.]journal_mode =
114666  **                      (delete|persist|off|truncate|memory|wal|off)
114667  */
114668  case PragTyp_JOURNAL_MODE: {
114669    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
114670    int ii;           /* Loop counter */
114671
114672    if( zRight==0 ){
114673      /* If there is no "=MODE" part of the pragma, do a query for the
114674      ** current mode */
114675      eMode = PAGER_JOURNALMODE_QUERY;
114676    }else{
114677      const char *zMode;
114678      int n = sqlite3Strlen30(zRight);
114679      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
114680        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
114681      }
114682      if( !zMode ){
114683        /* If the "=MODE" part does not match any known journal mode,
114684        ** then do a query */
114685        eMode = PAGER_JOURNALMODE_QUERY;
114686      }
114687    }
114688    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
114689      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
114690      iDb = 0;
114691      pId2->n = 1;
114692    }
114693    for(ii=db->nDb-1; ii>=0; ii--){
114694      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
114695        sqlite3VdbeUsesBtree(v, ii);
114696        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
114697      }
114698    }
114699    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
114700    break;
114701  }
114702
114703  /*
114704  **  PRAGMA [schema.]journal_size_limit
114705  **  PRAGMA [schema.]journal_size_limit=N
114706  **
114707  ** Get or set the size limit on rollback journal files.
114708  */
114709  case PragTyp_JOURNAL_SIZE_LIMIT: {
114710    Pager *pPager = sqlite3BtreePager(pDb->pBt);
114711    i64 iLimit = -2;
114712    if( zRight ){
114713      sqlite3DecOrHexToI64(zRight, &iLimit);
114714      if( iLimit<-1 ) iLimit = -1;
114715    }
114716    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
114717    returnSingleInt(v, iLimit);
114718    break;
114719  }
114720
114721#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
114722
114723  /*
114724  **  PRAGMA [schema.]auto_vacuum
114725  **  PRAGMA [schema.]auto_vacuum=N
114726  **
114727  ** Get or set the value of the database 'auto-vacuum' parameter.
114728  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
114729  */
114730#ifndef SQLITE_OMIT_AUTOVACUUM
114731  case PragTyp_AUTO_VACUUM: {
114732    Btree *pBt = pDb->pBt;
114733    assert( pBt!=0 );
114734    if( !zRight ){
114735      returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
114736    }else{
114737      int eAuto = getAutoVacuum(zRight);
114738      assert( eAuto>=0 && eAuto<=2 );
114739      db->nextAutovac = (u8)eAuto;
114740      /* Call SetAutoVacuum() to set initialize the internal auto and
114741      ** incr-vacuum flags. This is required in case this connection
114742      ** creates the database file. It is important that it is created
114743      ** as an auto-vacuum capable db.
114744      */
114745      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
114746      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
114747        /* When setting the auto_vacuum mode to either "full" or
114748        ** "incremental", write the value of meta[6] in the database
114749        ** file. Before writing to meta[6], check that meta[3] indicates
114750        ** that this really is an auto-vacuum capable database.
114751        */
114752        static const int iLn = VDBE_OFFSET_LINENO(2);
114753        static const VdbeOpList setMeta6[] = {
114754          { OP_Transaction,    0,         1,                 0},    /* 0 */
114755          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
114756          { OP_If,             1,         0,                 0},    /* 2 */
114757          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
114758          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
114759        };
114760        VdbeOp *aOp;
114761        int iAddr = sqlite3VdbeCurrentAddr(v);
114762        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
114763        aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
114764        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
114765        aOp[0].p1 = iDb;
114766        aOp[1].p1 = iDb;
114767        aOp[2].p2 = iAddr+4;
114768        aOp[4].p1 = iDb;
114769        aOp[4].p3 = eAuto - 1;
114770        sqlite3VdbeUsesBtree(v, iDb);
114771      }
114772    }
114773    break;
114774  }
114775#endif
114776
114777  /*
114778  **  PRAGMA [schema.]incremental_vacuum(N)
114779  **
114780  ** Do N steps of incremental vacuuming on a database.
114781  */
114782#ifndef SQLITE_OMIT_AUTOVACUUM
114783  case PragTyp_INCREMENTAL_VACUUM: {
114784    int iLimit, addr;
114785    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
114786      iLimit = 0x7fffffff;
114787    }
114788    sqlite3BeginWriteOperation(pParse, 0, iDb);
114789    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
114790    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
114791    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
114792    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
114793    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
114794    sqlite3VdbeJumpHere(v, addr);
114795    break;
114796  }
114797#endif
114798
114799#ifndef SQLITE_OMIT_PAGER_PRAGMAS
114800  /*
114801  **  PRAGMA [schema.]cache_size
114802  **  PRAGMA [schema.]cache_size=N
114803  **
114804  ** The first form reports the current local setting for the
114805  ** page cache size. The second form sets the local
114806  ** page cache size value.  If N is positive then that is the
114807  ** number of pages in the cache.  If N is negative, then the
114808  ** number of pages is adjusted so that the cache uses -N kibibytes
114809  ** of memory.
114810  */
114811  case PragTyp_CACHE_SIZE: {
114812    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114813    if( !zRight ){
114814      returnSingleInt(v, pDb->pSchema->cache_size);
114815    }else{
114816      int size = sqlite3Atoi(zRight);
114817      pDb->pSchema->cache_size = size;
114818      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
114819    }
114820    break;
114821  }
114822
114823  /*
114824  **  PRAGMA [schema.]cache_spill
114825  **  PRAGMA cache_spill=BOOLEAN
114826  **  PRAGMA [schema.]cache_spill=N
114827  **
114828  ** The first form reports the current local setting for the
114829  ** page cache spill size. The second form turns cache spill on
114830  ** or off.  When turnning cache spill on, the size is set to the
114831  ** current cache_size.  The third form sets a spill size that
114832  ** may be different form the cache size.
114833  ** If N is positive then that is the
114834  ** number of pages in the cache.  If N is negative, then the
114835  ** number of pages is adjusted so that the cache uses -N kibibytes
114836  ** of memory.
114837  **
114838  ** If the number of cache_spill pages is less then the number of
114839  ** cache_size pages, no spilling occurs until the page count exceeds
114840  ** the number of cache_size pages.
114841  **
114842  ** The cache_spill=BOOLEAN setting applies to all attached schemas,
114843  ** not just the schema specified.
114844  */
114845  case PragTyp_CACHE_SPILL: {
114846    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114847    if( !zRight ){
114848      returnSingleInt(v,
114849         (db->flags & SQLITE_CacheSpill)==0 ? 0 :
114850            sqlite3BtreeSetSpillSize(pDb->pBt,0));
114851    }else{
114852      int size = 1;
114853      if( sqlite3GetInt32(zRight, &size) ){
114854        sqlite3BtreeSetSpillSize(pDb->pBt, size);
114855      }
114856      if( sqlite3GetBoolean(zRight, size!=0) ){
114857        db->flags |= SQLITE_CacheSpill;
114858      }else{
114859        db->flags &= ~SQLITE_CacheSpill;
114860      }
114861      setAllPagerFlags(db);
114862    }
114863    break;
114864  }
114865
114866  /*
114867  **  PRAGMA [schema.]mmap_size(N)
114868  **
114869  ** Used to set mapping size limit. The mapping size limit is
114870  ** used to limit the aggregate size of all memory mapped regions of the
114871  ** database file. If this parameter is set to zero, then memory mapping
114872  ** is not used at all.  If N is negative, then the default memory map
114873  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
114874  ** The parameter N is measured in bytes.
114875  **
114876  ** This value is advisory.  The underlying VFS is free to memory map
114877  ** as little or as much as it wants.  Except, if N is set to 0 then the
114878  ** upper layers will never invoke the xFetch interfaces to the VFS.
114879  */
114880  case PragTyp_MMAP_SIZE: {
114881    sqlite3_int64 sz;
114882#if SQLITE_MAX_MMAP_SIZE>0
114883    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
114884    if( zRight ){
114885      int ii;
114886      sqlite3DecOrHexToI64(zRight, &sz);
114887      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
114888      if( pId2->n==0 ) db->szMmap = sz;
114889      for(ii=db->nDb-1; ii>=0; ii--){
114890        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
114891          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
114892        }
114893      }
114894    }
114895    sz = -1;
114896    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
114897#else
114898    sz = 0;
114899    rc = SQLITE_OK;
114900#endif
114901    if( rc==SQLITE_OK ){
114902      returnSingleInt(v, sz);
114903    }else if( rc!=SQLITE_NOTFOUND ){
114904      pParse->nErr++;
114905      pParse->rc = rc;
114906    }
114907    break;
114908  }
114909
114910  /*
114911  **   PRAGMA temp_store
114912  **   PRAGMA temp_store = "default"|"memory"|"file"
114913  **
114914  ** Return or set the local value of the temp_store flag.  Changing
114915  ** the local value does not make changes to the disk file and the default
114916  ** value will be restored the next time the database is opened.
114917  **
114918  ** Note that it is possible for the library compile-time options to
114919  ** override this setting
114920  */
114921  case PragTyp_TEMP_STORE: {
114922    if( !zRight ){
114923      returnSingleInt(v, db->temp_store);
114924    }else{
114925      changeTempStorage(pParse, zRight);
114926    }
114927    break;
114928  }
114929
114930  /*
114931  **   PRAGMA temp_store_directory
114932  **   PRAGMA temp_store_directory = ""|"directory_name"
114933  **
114934  ** Return or set the local value of the temp_store_directory flag.  Changing
114935  ** the value sets a specific directory to be used for temporary files.
114936  ** Setting to a null string reverts to the default temporary directory search.
114937  ** If temporary directory is changed, then invalidateTempStorage.
114938  **
114939  */
114940  case PragTyp_TEMP_STORE_DIRECTORY: {
114941    if( !zRight ){
114942      returnSingleText(v, sqlite3_temp_directory);
114943    }else{
114944#ifndef SQLITE_OMIT_WSD
114945      if( zRight[0] ){
114946        int res;
114947        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
114948        if( rc!=SQLITE_OK || res==0 ){
114949          sqlite3ErrorMsg(pParse, "not a writable directory");
114950          goto pragma_out;
114951        }
114952      }
114953      if( SQLITE_TEMP_STORE==0
114954       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
114955       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
114956      ){
114957        invalidateTempStorage(pParse);
114958      }
114959      sqlite3_free(sqlite3_temp_directory);
114960      if( zRight[0] ){
114961        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
114962      }else{
114963        sqlite3_temp_directory = 0;
114964      }
114965#endif /* SQLITE_OMIT_WSD */
114966    }
114967    break;
114968  }
114969
114970#if SQLITE_OS_WIN
114971  /*
114972  **   PRAGMA data_store_directory
114973  **   PRAGMA data_store_directory = ""|"directory_name"
114974  **
114975  ** Return or set the local value of the data_store_directory flag.  Changing
114976  ** the value sets a specific directory to be used for database files that
114977  ** were specified with a relative pathname.  Setting to a null string reverts
114978  ** to the default database directory, which for database files specified with
114979  ** a relative path will probably be based on the current directory for the
114980  ** process.  Database file specified with an absolute path are not impacted
114981  ** by this setting, regardless of its value.
114982  **
114983  */
114984  case PragTyp_DATA_STORE_DIRECTORY: {
114985    if( !zRight ){
114986      returnSingleText(v, sqlite3_data_directory);
114987    }else{
114988#ifndef SQLITE_OMIT_WSD
114989      if( zRight[0] ){
114990        int res;
114991        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
114992        if( rc!=SQLITE_OK || res==0 ){
114993          sqlite3ErrorMsg(pParse, "not a writable directory");
114994          goto pragma_out;
114995        }
114996      }
114997      sqlite3_free(sqlite3_data_directory);
114998      if( zRight[0] ){
114999        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
115000      }else{
115001        sqlite3_data_directory = 0;
115002      }
115003#endif /* SQLITE_OMIT_WSD */
115004    }
115005    break;
115006  }
115007#endif
115008
115009#if SQLITE_ENABLE_LOCKING_STYLE
115010  /*
115011  **   PRAGMA [schema.]lock_proxy_file
115012  **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
115013  **
115014  ** Return or set the value of the lock_proxy_file flag.  Changing
115015  ** the value sets a specific file to be used for database access locks.
115016  **
115017  */
115018  case PragTyp_LOCK_PROXY_FILE: {
115019    if( !zRight ){
115020      Pager *pPager = sqlite3BtreePager(pDb->pBt);
115021      char *proxy_file_path = NULL;
115022      sqlite3_file *pFile = sqlite3PagerFile(pPager);
115023      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
115024                           &proxy_file_path);
115025      returnSingleText(v, proxy_file_path);
115026    }else{
115027      Pager *pPager = sqlite3BtreePager(pDb->pBt);
115028      sqlite3_file *pFile = sqlite3PagerFile(pPager);
115029      int res;
115030      if( zRight[0] ){
115031        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
115032                                     zRight);
115033      } else {
115034        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
115035                                     NULL);
115036      }
115037      if( res!=SQLITE_OK ){
115038        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
115039        goto pragma_out;
115040      }
115041    }
115042    break;
115043  }
115044#endif /* SQLITE_ENABLE_LOCKING_STYLE */
115045
115046  /*
115047  **   PRAGMA [schema.]synchronous
115048  **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
115049  **
115050  ** Return or set the local value of the synchronous flag.  Changing
115051  ** the local value does not make changes to the disk file and the
115052  ** default value will be restored the next time the database is
115053  ** opened.
115054  */
115055  case PragTyp_SYNCHRONOUS: {
115056    if( !zRight ){
115057      returnSingleInt(v, pDb->safety_level-1);
115058    }else{
115059      if( !db->autoCommit ){
115060        sqlite3ErrorMsg(pParse,
115061            "Safety level may not be changed inside a transaction");
115062      }else if( iDb!=1 ){
115063        int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
115064        if( iLevel==0 ) iLevel = 1;
115065        pDb->safety_level = iLevel;
115066        pDb->bSyncSet = 1;
115067        setAllPagerFlags(db);
115068      }
115069    }
115070    break;
115071  }
115072#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
115073
115074#ifndef SQLITE_OMIT_FLAG_PRAGMAS
115075  case PragTyp_FLAG: {
115076    if( zRight==0 ){
115077      setPragmaResultColumnNames(v, pPragma);
115078      returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
115079    }else{
115080      int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
115081      if( db->autoCommit==0 ){
115082        /* Foreign key support may not be enabled or disabled while not
115083        ** in auto-commit mode.  */
115084        mask &= ~(SQLITE_ForeignKeys);
115085      }
115086#if SQLITE_USER_AUTHENTICATION
115087      if( db->auth.authLevel==UAUTH_User ){
115088        /* Do not allow non-admin users to modify the schema arbitrarily */
115089        mask &= ~(SQLITE_WriteSchema);
115090      }
115091#endif
115092
115093      if( sqlite3GetBoolean(zRight, 0) ){
115094        db->flags |= mask;
115095      }else{
115096        db->flags &= ~mask;
115097        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
115098      }
115099
115100      /* Many of the flag-pragmas modify the code generated by the SQL
115101      ** compiler (eg. count_changes). So add an opcode to expire all
115102      ** compiled SQL statements after modifying a pragma value.
115103      */
115104      sqlite3VdbeAddOp0(v, OP_Expire);
115105      setAllPagerFlags(db);
115106    }
115107    break;
115108  }
115109#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
115110
115111#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
115112  /*
115113  **   PRAGMA table_info(<table>)
115114  **
115115  ** Return a single row for each column of the named table. The columns of
115116  ** the returned data set are:
115117  **
115118  ** cid:        Column id (numbered from left to right, starting at 0)
115119  ** name:       Column name
115120  ** type:       Column declaration type.
115121  ** notnull:    True if 'NOT NULL' is part of column declaration
115122  ** dflt_value: The default value for the column, if any.
115123  */
115124  case PragTyp_TABLE_INFO: if( zRight ){
115125    Table *pTab;
115126    pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
115127    if( pTab ){
115128      int i, k;
115129      int nHidden = 0;
115130      Column *pCol;
115131      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
115132      pParse->nMem = 6;
115133      sqlite3CodeVerifySchema(pParse, iDb);
115134      sqlite3ViewGetColumnNames(pParse, pTab);
115135      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
115136        if( IsHiddenColumn(pCol) ){
115137          nHidden++;
115138          continue;
115139        }
115140        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
115141          k = 0;
115142        }else if( pPk==0 ){
115143          k = 1;
115144        }else{
115145          for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
115146        }
115147        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
115148        sqlite3VdbeMultiLoad(v, 1, "issisi",
115149               i-nHidden,
115150               pCol->zName,
115151               sqlite3ColumnType(pCol,""),
115152               pCol->notNull ? 1 : 0,
115153               pCol->pDflt ? pCol->pDflt->u.zToken : 0,
115154               k);
115155      }
115156    }
115157  }
115158  break;
115159
115160#ifdef SQLITE_DEBUG
115161  case PragTyp_STATS: {
115162    Index *pIdx;
115163    HashElem *i;
115164    pParse->nMem = 5;
115165    sqlite3CodeVerifySchema(pParse, iDb);
115166    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
115167      Table *pTab = sqliteHashData(i);
115168      sqlite3VdbeMultiLoad(v, 1, "ssiii",
115169           pTab->zName,
115170           0,
115171           pTab->szTabRow,
115172           pTab->nRowLogEst,
115173           pTab->tabFlags);
115174      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115175        sqlite3VdbeMultiLoad(v, 2, "siiiX",
115176           pIdx->zName,
115177           pIdx->szIdxRow,
115178           pIdx->aiRowLogEst[0],
115179           pIdx->hasStat1);
115180        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
115181      }
115182    }
115183  }
115184  break;
115185#endif
115186
115187  case PragTyp_INDEX_INFO: if( zRight ){
115188    Index *pIdx;
115189    Table *pTab;
115190    pIdx = sqlite3FindIndex(db, zRight, zDb);
115191    if( pIdx ){
115192      int i;
115193      int mx;
115194      if( pPragma->iArg ){
115195        /* PRAGMA index_xinfo (newer version with more rows and columns) */
115196        mx = pIdx->nColumn;
115197        pParse->nMem = 6;
115198      }else{
115199        /* PRAGMA index_info (legacy version) */
115200        mx = pIdx->nKeyCol;
115201        pParse->nMem = 3;
115202      }
115203      pTab = pIdx->pTable;
115204      sqlite3CodeVerifySchema(pParse, iDb);
115205      assert( pParse->nMem<=pPragma->nPragCName );
115206      for(i=0; i<mx; i++){
115207        i16 cnum = pIdx->aiColumn[i];
115208        sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
115209                             cnum<0 ? 0 : pTab->aCol[cnum].zName);
115210        if( pPragma->iArg ){
115211          sqlite3VdbeMultiLoad(v, 4, "isiX",
115212            pIdx->aSortOrder[i],
115213            pIdx->azColl[i],
115214            i<pIdx->nKeyCol);
115215        }
115216        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
115217      }
115218    }
115219  }
115220  break;
115221
115222  case PragTyp_INDEX_LIST: if( zRight ){
115223    Index *pIdx;
115224    Table *pTab;
115225    int i;
115226    pTab = sqlite3FindTable(db, zRight, zDb);
115227    if( pTab ){
115228      pParse->nMem = 5;
115229      sqlite3CodeVerifySchema(pParse, iDb);
115230      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
115231        const char *azOrigin[] = { "c", "u", "pk" };
115232        sqlite3VdbeMultiLoad(v, 1, "isisi",
115233           i,
115234           pIdx->zName,
115235           IsUniqueIndex(pIdx),
115236           azOrigin[pIdx->idxType],
115237           pIdx->pPartIdxWhere!=0);
115238      }
115239    }
115240  }
115241  break;
115242
115243  case PragTyp_DATABASE_LIST: {
115244    int i;
115245    pParse->nMem = 3;
115246    for(i=0; i<db->nDb; i++){
115247      if( db->aDb[i].pBt==0 ) continue;
115248      assert( db->aDb[i].zDbSName!=0 );
115249      sqlite3VdbeMultiLoad(v, 1, "iss",
115250         i,
115251         db->aDb[i].zDbSName,
115252         sqlite3BtreeGetFilename(db->aDb[i].pBt));
115253    }
115254  }
115255  break;
115256
115257  case PragTyp_COLLATION_LIST: {
115258    int i = 0;
115259    HashElem *p;
115260    pParse->nMem = 2;
115261    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
115262      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
115263      sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
115264    }
115265  }
115266  break;
115267
115268#ifdef SQLITE_INTROSPECTION_PRAGMAS
115269  case PragTyp_FUNCTION_LIST: {
115270    int i;
115271    HashElem *j;
115272    FuncDef *p;
115273    pParse->nMem = 2;
115274    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
115275      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
115276        sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
115277        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
115278      }
115279    }
115280    for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
115281      p = (FuncDef*)sqliteHashData(j);
115282      sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
115283      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
115284    }
115285  }
115286  break;
115287
115288#ifndef SQLITE_OMIT_VIRTUALTABLE
115289  case PragTyp_MODULE_LIST: {
115290    HashElem *j;
115291    pParse->nMem = 1;
115292    for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
115293      Module *pMod = (Module*)sqliteHashData(j);
115294      sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
115295      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
115296    }
115297  }
115298  break;
115299#endif /* SQLITE_OMIT_VIRTUALTABLE */
115300
115301  case PragTyp_PRAGMA_LIST: {
115302    int i;
115303    for(i=0; i<ArraySize(aPragmaName); i++){
115304      sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
115305      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
115306    }
115307  }
115308  break;
115309#endif /* SQLITE_INTROSPECTION_PRAGMAS */
115310
115311#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
115312
115313#ifndef SQLITE_OMIT_FOREIGN_KEY
115314  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
115315    FKey *pFK;
115316    Table *pTab;
115317    pTab = sqlite3FindTable(db, zRight, zDb);
115318    if( pTab ){
115319      pFK = pTab->pFKey;
115320      if( pFK ){
115321        int i = 0;
115322        pParse->nMem = 8;
115323        sqlite3CodeVerifySchema(pParse, iDb);
115324        while(pFK){
115325          int j;
115326          for(j=0; j<pFK->nCol; j++){
115327            sqlite3VdbeMultiLoad(v, 1, "iissssss",
115328                   i,
115329                   j,
115330                   pFK->zTo,
115331                   pTab->aCol[pFK->aCol[j].iFrom].zName,
115332                   pFK->aCol[j].zCol,
115333                   actionName(pFK->aAction[1]),  /* ON UPDATE */
115334                   actionName(pFK->aAction[0]),  /* ON DELETE */
115335                   "NONE");
115336          }
115337          ++i;
115338          pFK = pFK->pNextFrom;
115339        }
115340      }
115341    }
115342  }
115343  break;
115344#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
115345
115346#ifndef SQLITE_OMIT_FOREIGN_KEY
115347#ifndef SQLITE_OMIT_TRIGGER
115348  case PragTyp_FOREIGN_KEY_CHECK: {
115349    FKey *pFK;             /* A foreign key constraint */
115350    Table *pTab;           /* Child table contain "REFERENCES" keyword */
115351    Table *pParent;        /* Parent table that child points to */
115352    Index *pIdx;           /* Index in the parent table */
115353    int i;                 /* Loop counter:  Foreign key number for pTab */
115354    int j;                 /* Loop counter:  Field of the foreign key */
115355    HashElem *k;           /* Loop counter:  Next table in schema */
115356    int x;                 /* result variable */
115357    int regResult;         /* 3 registers to hold a result row */
115358    int regKey;            /* Register to hold key for checking the FK */
115359    int regRow;            /* Registers to hold a row from pTab */
115360    int addrTop;           /* Top of a loop checking foreign keys */
115361    int addrOk;            /* Jump here if the key is OK */
115362    int *aiCols;           /* child to parent column mapping */
115363
115364    regResult = pParse->nMem+1;
115365    pParse->nMem += 4;
115366    regKey = ++pParse->nMem;
115367    regRow = ++pParse->nMem;
115368    sqlite3CodeVerifySchema(pParse, iDb);
115369    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
115370    while( k ){
115371      if( zRight ){
115372        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
115373        k = 0;
115374      }else{
115375        pTab = (Table*)sqliteHashData(k);
115376        k = sqliteHashNext(k);
115377      }
115378      if( pTab==0 || pTab->pFKey==0 ) continue;
115379      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
115380      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
115381      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
115382      sqlite3VdbeLoadString(v, regResult, pTab->zName);
115383      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
115384        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
115385        if( pParent==0 ) continue;
115386        pIdx = 0;
115387        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
115388        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
115389        if( x==0 ){
115390          if( pIdx==0 ){
115391            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
115392          }else{
115393            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
115394            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
115395          }
115396        }else{
115397          k = 0;
115398          break;
115399        }
115400      }
115401      assert( pParse->nErr>0 || pFK==0 );
115402      if( pFK ) break;
115403      if( pParse->nTab<i ) pParse->nTab = i;
115404      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
115405      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
115406        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
115407        pIdx = 0;
115408        aiCols = 0;
115409        if( pParent ){
115410          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
115411          assert( x==0 );
115412        }
115413        addrOk = sqlite3VdbeMakeLabel(v);
115414
115415        /* Generate code to read the child key values into registers
115416        ** regRow..regRow+n. If any of the child key values are NULL, this
115417        ** row cannot cause an FK violation. Jump directly to addrOk in
115418        ** this case. */
115419        for(j=0; j<pFK->nCol; j++){
115420          int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
115421          sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
115422          sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
115423        }
115424
115425        /* Generate code to query the parent index for a matching parent
115426        ** key. If a match is found, jump to addrOk. */
115427        if( pIdx ){
115428          sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
115429              sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
115430          sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
115431          VdbeCoverage(v);
115432        }else if( pParent ){
115433          int jmp = sqlite3VdbeCurrentAddr(v)+2;
115434          sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
115435          sqlite3VdbeGoto(v, addrOk);
115436          assert( pFK->nCol==1 );
115437        }
115438
115439        /* Generate code to report an FK violation to the caller. */
115440        if( HasRowid(pTab) ){
115441          sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
115442        }else{
115443          sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
115444        }
115445        sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
115446        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
115447        sqlite3VdbeResolveLabel(v, addrOk);
115448        sqlite3DbFree(db, aiCols);
115449      }
115450      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
115451      sqlite3VdbeJumpHere(v, addrTop);
115452    }
115453  }
115454  break;
115455#endif /* !defined(SQLITE_OMIT_TRIGGER) */
115456#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
115457
115458#ifndef NDEBUG
115459  case PragTyp_PARSER_TRACE: {
115460    if( zRight ){
115461      if( sqlite3GetBoolean(zRight, 0) ){
115462        sqlite3ParserTrace(stdout, "parser: ");
115463      }else{
115464        sqlite3ParserTrace(0, 0);
115465      }
115466    }
115467  }
115468  break;
115469#endif
115470
115471  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
115472  ** used will be case sensitive or not depending on the RHS.
115473  */
115474  case PragTyp_CASE_SENSITIVE_LIKE: {
115475    if( zRight ){
115476      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
115477    }
115478  }
115479  break;
115480
115481#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
115482# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
115483#endif
115484
115485#ifndef SQLITE_OMIT_INTEGRITY_CHECK
115486  /*    PRAGMA integrity_check
115487  **    PRAGMA integrity_check(N)
115488  **    PRAGMA quick_check
115489  **    PRAGMA quick_check(N)
115490  **
115491  ** Verify the integrity of the database.
115492  **
115493  ** The "quick_check" is reduced version of
115494  ** integrity_check designed to detect most database corruption
115495  ** without the overhead of cross-checking indexes.  Quick_check
115496  ** is linear time wherease integrity_check is O(NlogN).
115497  */
115498  case PragTyp_INTEGRITY_CHECK: {
115499    int i, j, addr, mxErr;
115500
115501    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
115502
115503    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
115504    ** then iDb is set to the index of the database identified by <db>.
115505    ** In this case, the integrity of database iDb only is verified by
115506    ** the VDBE created below.
115507    **
115508    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
115509    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
115510    ** to -1 here, to indicate that the VDBE should verify the integrity
115511    ** of all attached databases.  */
115512    assert( iDb>=0 );
115513    assert( iDb==0 || pId2->z );
115514    if( pId2->z==0 ) iDb = -1;
115515
115516    /* Initialize the VDBE program */
115517    pParse->nMem = 6;
115518
115519    /* Set the maximum error count */
115520    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
115521    if( zRight ){
115522      sqlite3GetInt32(zRight, &mxErr);
115523      if( mxErr<=0 ){
115524        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
115525      }
115526    }
115527    sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
115528
115529    /* Do an integrity check on each database file */
115530    for(i=0; i<db->nDb; i++){
115531      HashElem *x;
115532      Hash *pTbls;
115533      int *aRoot;
115534      int cnt = 0;
115535      int mxIdx = 0;
115536      int nIdx;
115537
115538      if( OMIT_TEMPDB && i==1 ) continue;
115539      if( iDb>=0 && i!=iDb ) continue;
115540
115541      sqlite3CodeVerifySchema(pParse, i);
115542
115543      /* Do an integrity check of the B-Tree
115544      **
115545      ** Begin by finding the root pages numbers
115546      ** for all tables and indices in the database.
115547      */
115548      assert( sqlite3SchemaMutexHeld(db, i, 0) );
115549      pTbls = &db->aDb[i].pSchema->tblHash;
115550      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115551        Table *pTab = sqliteHashData(x);
115552        Index *pIdx;
115553        if( HasRowid(pTab) ) cnt++;
115554        for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
115555        if( nIdx>mxIdx ) mxIdx = nIdx;
115556      }
115557      aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
115558      if( aRoot==0 ) break;
115559      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115560        Table *pTab = sqliteHashData(x);
115561        Index *pIdx;
115562        if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
115563        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115564          aRoot[cnt++] = pIdx->tnum;
115565        }
115566      }
115567      aRoot[cnt] = 0;
115568
115569      /* Make sure sufficient number of registers have been allocated */
115570      pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
115571      sqlite3ClearTempRegCache(pParse);
115572
115573      /* Do the b-tree integrity checks */
115574      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
115575      sqlite3VdbeChangeP5(v, (u8)i);
115576      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
115577      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
115578         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
115579         P4_DYNAMIC);
115580      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
115581      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
115582      integrityCheckResultRow(v, 2);
115583      sqlite3VdbeJumpHere(v, addr);
115584
115585      /* Make sure all the indices are constructed correctly.
115586      */
115587      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
115588        Table *pTab = sqliteHashData(x);
115589        Index *pIdx, *pPk;
115590        Index *pPrior = 0;
115591        int loopTop;
115592        int iDataCur, iIdxCur;
115593        int r1 = -1;
115594
115595        if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
115596        if( pTab->pCheck==0
115597         && (pTab->tabFlags & TF_HasNotNull)==0
115598         && (pTab->pIndex==0 || isQuick)
115599        ){
115600          continue;  /* No additional checks needed for this table */
115601        }
115602        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
115603        sqlite3ExprCacheClear(pParse);
115604        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
115605                                   1, 0, &iDataCur, &iIdxCur);
115606        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
115607        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115608          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
115609        }
115610        assert( pParse->nMem>=8+j );
115611        assert( sqlite3NoTempsInRange(pParse,1,7+j) );
115612        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
115613        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
115614        /* Verify that all NOT NULL columns really are NOT NULL */
115615        for(j=0; j<pTab->nCol; j++){
115616          char *zErr;
115617          int jmp2;
115618          if( j==pTab->iPKey ) continue;
115619          if( pTab->aCol[j].notNull==0 ) continue;
115620          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
115621          sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
115622          jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
115623          zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
115624                              pTab->aCol[j].zName);
115625          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
115626          integrityCheckResultRow(v, 3);
115627          sqlite3VdbeJumpHere(v, jmp2);
115628        }
115629        /* Verify CHECK constraints */
115630        if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
115631          ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
115632          if( db->mallocFailed==0 ){
115633            int addrCkFault = sqlite3VdbeMakeLabel(v);
115634            int addrCkOk = sqlite3VdbeMakeLabel(v);
115635            char *zErr;
115636            int k;
115637            pParse->iSelfTab = iDataCur + 1;
115638            sqlite3ExprCachePush(pParse);
115639            for(k=pCheck->nExpr-1; k>0; k--){
115640              sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
115641            }
115642            sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
115643                SQLITE_JUMPIFNULL);
115644            sqlite3VdbeResolveLabel(v, addrCkFault);
115645            pParse->iSelfTab = 0;
115646            zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
115647                pTab->zName);
115648            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
115649            integrityCheckResultRow(v, 3);
115650            sqlite3VdbeResolveLabel(v, addrCkOk);
115651            sqlite3ExprCachePop(pParse);
115652          }
115653          sqlite3ExprListDelete(db, pCheck);
115654        }
115655        /* Validate index entries for the current row */
115656        for(j=0, pIdx=pTab->pIndex; pIdx && !isQuick; pIdx=pIdx->pNext, j++){
115657          int jmp2, jmp3, jmp4, jmp5;
115658          int ckUniq = sqlite3VdbeMakeLabel(v);
115659          if( pPk==pIdx ) continue;
115660          r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
115661                                       pPrior, r1);
115662          pPrior = pIdx;
115663          sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
115664          /* Verify that an index entry exists for the current table row */
115665          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
115666                                      pIdx->nColumn); VdbeCoverage(v);
115667          sqlite3VdbeLoadString(v, 3, "row ");
115668          sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
115669          sqlite3VdbeLoadString(v, 4, " missing from index ");
115670          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
115671          jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
115672          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
115673          jmp4 = integrityCheckResultRow(v, 3);
115674          sqlite3VdbeJumpHere(v, jmp2);
115675          /* For UNIQUE indexes, verify that only one entry exists with the
115676          ** current key.  The entry is unique if (1) any column is NULL
115677          ** or (2) the next entry has a different key */
115678          if( IsUniqueIndex(pIdx) ){
115679            int uniqOk = sqlite3VdbeMakeLabel(v);
115680            int jmp6;
115681            int kk;
115682            for(kk=0; kk<pIdx->nKeyCol; kk++){
115683              int iCol = pIdx->aiColumn[kk];
115684              assert( iCol!=XN_ROWID && iCol<pTab->nCol );
115685              if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
115686              sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
115687              VdbeCoverage(v);
115688            }
115689            jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
115690            sqlite3VdbeGoto(v, uniqOk);
115691            sqlite3VdbeJumpHere(v, jmp6);
115692            sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
115693                                 pIdx->nKeyCol); VdbeCoverage(v);
115694            sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
115695            sqlite3VdbeGoto(v, jmp5);
115696            sqlite3VdbeResolveLabel(v, uniqOk);
115697          }
115698          sqlite3VdbeJumpHere(v, jmp4);
115699          sqlite3ResolvePartIdxLabel(pParse, jmp3);
115700        }
115701        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
115702        sqlite3VdbeJumpHere(v, loopTop-1);
115703#ifndef SQLITE_OMIT_BTREECOUNT
115704        if( !isQuick ){
115705          sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
115706          for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
115707            if( pPk==pIdx ) continue;
115708            sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
115709            addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
115710            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
115711            sqlite3VdbeLoadString(v, 3, pIdx->zName);
115712            sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
115713            integrityCheckResultRow(v, 7);
115714            sqlite3VdbeJumpHere(v, addr);
115715          }
115716        }
115717#endif /* SQLITE_OMIT_BTREECOUNT */
115718      }
115719    }
115720    {
115721      static const int iLn = VDBE_OFFSET_LINENO(2);
115722      static const VdbeOpList endCode[] = {
115723        { OP_AddImm,      1, 0,        0},    /* 0 */
115724        { OP_IfNotZero,   1, 4,        0},    /* 1 */
115725        { OP_String8,     0, 3,        0},    /* 2 */
115726        { OP_ResultRow,   3, 1,        0},    /* 3 */
115727      };
115728      VdbeOp *aOp;
115729
115730      aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
115731      if( aOp ){
115732        aOp[0].p2 = 1-mxErr;
115733        aOp[2].p4type = P4_STATIC;
115734        aOp[2].p4.z = "ok";
115735      }
115736    }
115737  }
115738  break;
115739#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
115740
115741#ifndef SQLITE_OMIT_UTF16
115742  /*
115743  **   PRAGMA encoding
115744  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
115745  **
115746  ** In its first form, this pragma returns the encoding of the main
115747  ** database. If the database is not initialized, it is initialized now.
115748  **
115749  ** The second form of this pragma is a no-op if the main database file
115750  ** has not already been initialized. In this case it sets the default
115751  ** encoding that will be used for the main database file if a new file
115752  ** is created. If an existing main database file is opened, then the
115753  ** default text encoding for the existing database is used.
115754  **
115755  ** In all cases new databases created using the ATTACH command are
115756  ** created to use the same default text encoding as the main database. If
115757  ** the main database has not been initialized and/or created when ATTACH
115758  ** is executed, this is done before the ATTACH operation.
115759  **
115760  ** In the second form this pragma sets the text encoding to be used in
115761  ** new database files created using this database handle. It is only
115762  ** useful if invoked immediately after the main database i
115763  */
115764  case PragTyp_ENCODING: {
115765    static const struct EncName {
115766      char *zName;
115767      u8 enc;
115768    } encnames[] = {
115769      { "UTF8",     SQLITE_UTF8        },
115770      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
115771      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
115772      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
115773      { "UTF16le",  SQLITE_UTF16LE     },
115774      { "UTF16be",  SQLITE_UTF16BE     },
115775      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
115776      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
115777      { 0, 0 }
115778    };
115779    const struct EncName *pEnc;
115780    if( !zRight ){    /* "PRAGMA encoding" */
115781      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
115782      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
115783      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
115784      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
115785      returnSingleText(v, encnames[ENC(pParse->db)].zName);
115786    }else{                        /* "PRAGMA encoding = XXX" */
115787      /* Only change the value of sqlite.enc if the database handle is not
115788      ** initialized. If the main database exists, the new sqlite.enc value
115789      ** will be overwritten when the schema is next loaded. If it does not
115790      ** already exists, it will be created to use the new encoding value.
115791      */
115792      if(
115793        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
115794        DbHasProperty(db, 0, DB_Empty)
115795      ){
115796        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
115797          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
115798            SCHEMA_ENC(db) = ENC(db) =
115799                pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
115800            break;
115801          }
115802        }
115803        if( !pEnc->zName ){
115804          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
115805        }
115806      }
115807    }
115808  }
115809  break;
115810#endif /* SQLITE_OMIT_UTF16 */
115811
115812#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
115813  /*
115814  **   PRAGMA [schema.]schema_version
115815  **   PRAGMA [schema.]schema_version = <integer>
115816  **
115817  **   PRAGMA [schema.]user_version
115818  **   PRAGMA [schema.]user_version = <integer>
115819  **
115820  **   PRAGMA [schema.]freelist_count
115821  **
115822  **   PRAGMA [schema.]data_version
115823  **
115824  **   PRAGMA [schema.]application_id
115825  **   PRAGMA [schema.]application_id = <integer>
115826  **
115827  ** The pragma's schema_version and user_version are used to set or get
115828  ** the value of the schema-version and user-version, respectively. Both
115829  ** the schema-version and the user-version are 32-bit signed integers
115830  ** stored in the database header.
115831  **
115832  ** The schema-cookie is usually only manipulated internally by SQLite. It
115833  ** is incremented by SQLite whenever the database schema is modified (by
115834  ** creating or dropping a table or index). The schema version is used by
115835  ** SQLite each time a query is executed to ensure that the internal cache
115836  ** of the schema used when compiling the SQL query matches the schema of
115837  ** the database against which the compiled query is actually executed.
115838  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
115839  ** the schema-version is potentially dangerous and may lead to program
115840  ** crashes or database corruption. Use with caution!
115841  **
115842  ** The user-version is not used internally by SQLite. It may be used by
115843  ** applications for any purpose.
115844  */
115845  case PragTyp_HEADER_VALUE: {
115846    int iCookie = pPragma->iArg;  /* Which cookie to read or write */
115847    sqlite3VdbeUsesBtree(v, iDb);
115848    if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
115849      /* Write the specified cookie value */
115850      static const VdbeOpList setCookie[] = {
115851        { OP_Transaction,    0,  1,  0},    /* 0 */
115852        { OP_SetCookie,      0,  0,  0},    /* 1 */
115853      };
115854      VdbeOp *aOp;
115855      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
115856      aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
115857      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
115858      aOp[0].p1 = iDb;
115859      aOp[1].p1 = iDb;
115860      aOp[1].p2 = iCookie;
115861      aOp[1].p3 = sqlite3Atoi(zRight);
115862    }else{
115863      /* Read the specified cookie value */
115864      static const VdbeOpList readCookie[] = {
115865        { OP_Transaction,     0,  0,  0},    /* 0 */
115866        { OP_ReadCookie,      0,  1,  0},    /* 1 */
115867        { OP_ResultRow,       1,  1,  0}
115868      };
115869      VdbeOp *aOp;
115870      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
115871      aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
115872      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
115873      aOp[0].p1 = iDb;
115874      aOp[1].p1 = iDb;
115875      aOp[1].p3 = iCookie;
115876      sqlite3VdbeReusable(v);
115877    }
115878  }
115879  break;
115880#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
115881
115882#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
115883  /*
115884  **   PRAGMA compile_options
115885  **
115886  ** Return the names of all compile-time options used in this build,
115887  ** one option per row.
115888  */
115889  case PragTyp_COMPILE_OPTIONS: {
115890    int i = 0;
115891    const char *zOpt;
115892    pParse->nMem = 1;
115893    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
115894      sqlite3VdbeLoadString(v, 1, zOpt);
115895      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
115896    }
115897    sqlite3VdbeReusable(v);
115898  }
115899  break;
115900#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
115901
115902#ifndef SQLITE_OMIT_WAL
115903  /*
115904  **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
115905  **
115906  ** Checkpoint the database.
115907  */
115908  case PragTyp_WAL_CHECKPOINT: {
115909    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
115910    int eMode = SQLITE_CHECKPOINT_PASSIVE;
115911    if( zRight ){
115912      if( sqlite3StrICmp(zRight, "full")==0 ){
115913        eMode = SQLITE_CHECKPOINT_FULL;
115914      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
115915        eMode = SQLITE_CHECKPOINT_RESTART;
115916      }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
115917        eMode = SQLITE_CHECKPOINT_TRUNCATE;
115918      }
115919    }
115920    pParse->nMem = 3;
115921    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
115922    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
115923  }
115924  break;
115925
115926  /*
115927  **   PRAGMA wal_autocheckpoint
115928  **   PRAGMA wal_autocheckpoint = N
115929  **
115930  ** Configure a database connection to automatically checkpoint a database
115931  ** after accumulating N frames in the log. Or query for the current value
115932  ** of N.
115933  */
115934  case PragTyp_WAL_AUTOCHECKPOINT: {
115935    if( zRight ){
115936      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
115937    }
115938    returnSingleInt(v,
115939       db->xWalCallback==sqlite3WalDefaultHook ?
115940           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
115941  }
115942  break;
115943#endif
115944
115945  /*
115946  **  PRAGMA shrink_memory
115947  **
115948  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
115949  ** connection on which it is invoked to free up as much memory as it
115950  ** can, by calling sqlite3_db_release_memory().
115951  */
115952  case PragTyp_SHRINK_MEMORY: {
115953    sqlite3_db_release_memory(db);
115954    break;
115955  }
115956
115957  /*
115958  **  PRAGMA optimize
115959  **  PRAGMA optimize(MASK)
115960  **  PRAGMA schema.optimize
115961  **  PRAGMA schema.optimize(MASK)
115962  **
115963  ** Attempt to optimize the database.  All schemas are optimized in the first
115964  ** two forms, and only the specified schema is optimized in the latter two.
115965  **
115966  ** The details of optimizations performed by this pragma are expected
115967  ** to change and improve over time.  Applications should anticipate that
115968  ** this pragma will perform new optimizations in future releases.
115969  **
115970  ** The optional argument is a bitmask of optimizations to perform:
115971  **
115972  **    0x0001    Debugging mode.  Do not actually perform any optimizations
115973  **              but instead return one line of text for each optimization
115974  **              that would have been done.  Off by default.
115975  **
115976  **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
115977  **              See below for additional information.
115978  **
115979  **    0x0004    (Not yet implemented) Record usage and performance
115980  **              information from the current session in the
115981  **              database file so that it will be available to "optimize"
115982  **              pragmas run by future database connections.
115983  **
115984  **    0x0008    (Not yet implemented) Create indexes that might have
115985  **              been helpful to recent queries
115986  **
115987  ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all
115988  ** of the optimizations listed above except Debug Mode, including new
115989  ** optimizations that have not yet been invented.  If new optimizations are
115990  ** ever added that should be off by default, those off-by-default
115991  ** optimizations will have bitmasks of 0x10000 or larger.
115992  **
115993  ** DETERMINATION OF WHEN TO RUN ANALYZE
115994  **
115995  ** In the current implementation, a table is analyzed if only if all of
115996  ** the following are true:
115997  **
115998  ** (1) MASK bit 0x02 is set.
115999  **
116000  ** (2) The query planner used sqlite_stat1-style statistics for one or
116001  **     more indexes of the table at some point during the lifetime of
116002  **     the current connection.
116003  **
116004  ** (3) One or more indexes of the table are currently unanalyzed OR
116005  **     the number of rows in the table has increased by 25 times or more
116006  **     since the last time ANALYZE was run.
116007  **
116008  ** The rules for when tables are analyzed are likely to change in
116009  ** future releases.
116010  */
116011  case PragTyp_OPTIMIZE: {
116012    int iDbLast;           /* Loop termination point for the schema loop */
116013    int iTabCur;           /* Cursor for a table whose size needs checking */
116014    HashElem *k;           /* Loop over tables of a schema */
116015    Schema *pSchema;       /* The current schema */
116016    Table *pTab;           /* A table in the schema */
116017    Index *pIdx;           /* An index of the table */
116018    LogEst szThreshold;    /* Size threshold above which reanalysis is needd */
116019    char *zSubSql;         /* SQL statement for the OP_SqlExec opcode */
116020    u32 opMask;            /* Mask of operations to perform */
116021
116022    if( zRight ){
116023      opMask = (u32)sqlite3Atoi(zRight);
116024      if( (opMask & 0x02)==0 ) break;
116025    }else{
116026      opMask = 0xfffe;
116027    }
116028    iTabCur = pParse->nTab++;
116029    for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
116030      if( iDb==1 ) continue;
116031      sqlite3CodeVerifySchema(pParse, iDb);
116032      pSchema = db->aDb[iDb].pSchema;
116033      for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
116034        pTab = (Table*)sqliteHashData(k);
116035
116036        /* If table pTab has not been used in a way that would benefit from
116037        ** having analysis statistics during the current session, then skip it.
116038        ** This also has the effect of skipping virtual tables and views */
116039        if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
116040
116041        /* Reanalyze if the table is 25 times larger than the last analysis */
116042        szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
116043        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
116044          if( !pIdx->hasStat1 ){
116045            szThreshold = 0; /* Always analyze if any index lacks statistics */
116046            break;
116047          }
116048        }
116049        if( szThreshold ){
116050          sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
116051          sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
116052                         sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
116053          VdbeCoverage(v);
116054        }
116055        zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
116056                                 db->aDb[iDb].zDbSName, pTab->zName);
116057        if( opMask & 0x01 ){
116058          int r1 = sqlite3GetTempReg(pParse);
116059          sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
116060          sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
116061        }else{
116062          sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
116063        }
116064      }
116065    }
116066    sqlite3VdbeAddOp0(v, OP_Expire);
116067    break;
116068  }
116069
116070  /*
116071  **   PRAGMA busy_timeout
116072  **   PRAGMA busy_timeout = N
116073  **
116074  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
116075  ** if one is set.  If no busy handler or a different busy handler is set
116076  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
116077  ** disables the timeout.
116078  */
116079  /*case PragTyp_BUSY_TIMEOUT*/ default: {
116080    assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
116081    if( zRight ){
116082      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
116083    }
116084    returnSingleInt(v, db->busyTimeout);
116085    break;
116086  }
116087
116088  /*
116089  **   PRAGMA soft_heap_limit
116090  **   PRAGMA soft_heap_limit = N
116091  **
116092  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
116093  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
116094  ** specified and is a non-negative integer.
116095  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
116096  ** returns the same integer that would be returned by the
116097  ** sqlite3_soft_heap_limit64(-1) C-language function.
116098  */
116099  case PragTyp_SOFT_HEAP_LIMIT: {
116100    sqlite3_int64 N;
116101    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
116102      sqlite3_soft_heap_limit64(N);
116103    }
116104    returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
116105    break;
116106  }
116107
116108  /*
116109  **   PRAGMA threads
116110  **   PRAGMA threads = N
116111  **
116112  ** Configure the maximum number of worker threads.  Return the new
116113  ** maximum, which might be less than requested.
116114  */
116115  case PragTyp_THREADS: {
116116    sqlite3_int64 N;
116117    if( zRight
116118     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
116119     && N>=0
116120    ){
116121      sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
116122    }
116123    returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
116124    break;
116125  }
116126
116127#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
116128  /*
116129  ** Report the current state of file logs for all databases
116130  */
116131  case PragTyp_LOCK_STATUS: {
116132    static const char *const azLockName[] = {
116133      "unlocked", "shared", "reserved", "pending", "exclusive"
116134    };
116135    int i;
116136    pParse->nMem = 2;
116137    for(i=0; i<db->nDb; i++){
116138      Btree *pBt;
116139      const char *zState = "unknown";
116140      int j;
116141      if( db->aDb[i].zDbSName==0 ) continue;
116142      pBt = db->aDb[i].pBt;
116143      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
116144        zState = "closed";
116145      }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
116146                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
116147         zState = azLockName[j];
116148      }
116149      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
116150    }
116151    break;
116152  }
116153#endif
116154
116155#ifdef SQLITE_HAS_CODEC
116156  case PragTyp_KEY: {
116157    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
116158    break;
116159  }
116160  case PragTyp_REKEY: {
116161    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
116162    break;
116163  }
116164  case PragTyp_HEXKEY: {
116165    if( zRight ){
116166      u8 iByte;
116167      int i;
116168      char zKey[40];
116169      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
116170        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
116171        if( (i&1)!=0 ) zKey[i/2] = iByte;
116172      }
116173      if( (zLeft[3] & 0xf)==0xb ){
116174        sqlite3_key_v2(db, zDb, zKey, i/2);
116175      }else{
116176        sqlite3_rekey_v2(db, zDb, zKey, i/2);
116177      }
116178    }
116179    break;
116180  }
116181#endif
116182#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
116183  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
116184#ifdef SQLITE_HAS_CODEC
116185    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
116186      sqlite3_activate_see(&zRight[4]);
116187    }
116188#endif
116189#ifdef SQLITE_ENABLE_CEROD
116190    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
116191      sqlite3_activate_cerod(&zRight[6]);
116192    }
116193#endif
116194  }
116195  break;
116196#endif
116197
116198  } /* End of the PRAGMA switch */
116199
116200  /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
116201  ** purpose is to execute assert() statements to verify that if the
116202  ** PragFlg_NoColumns1 flag is set and the caller specified an argument
116203  ** to the PRAGMA, the implementation has not added any OP_ResultRow
116204  ** instructions to the VM.  */
116205  if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
116206    sqlite3VdbeVerifyNoResultRow(v);
116207  }
116208
116209pragma_out:
116210  sqlite3DbFree(db, zLeft);
116211  sqlite3DbFree(db, zRight);
116212}
116213#ifndef SQLITE_OMIT_VIRTUALTABLE
116214/*****************************************************************************
116215** Implementation of an eponymous virtual table that runs a pragma.
116216**
116217*/
116218typedef struct PragmaVtab PragmaVtab;
116219typedef struct PragmaVtabCursor PragmaVtabCursor;
116220struct PragmaVtab {
116221  sqlite3_vtab base;        /* Base class.  Must be first */
116222  sqlite3 *db;              /* The database connection to which it belongs */
116223  const PragmaName *pName;  /* Name of the pragma */
116224  u8 nHidden;               /* Number of hidden columns */
116225  u8 iHidden;               /* Index of the first hidden column */
116226};
116227struct PragmaVtabCursor {
116228  sqlite3_vtab_cursor base; /* Base class.  Must be first */
116229  sqlite3_stmt *pPragma;    /* The pragma statement to run */
116230  sqlite_int64 iRowid;      /* Current rowid */
116231  char *azArg[2];           /* Value of the argument and schema */
116232};
116233
116234/*
116235** Pragma virtual table module xConnect method.
116236*/
116237static int pragmaVtabConnect(
116238  sqlite3 *db,
116239  void *pAux,
116240  int argc, const char *const*argv,
116241  sqlite3_vtab **ppVtab,
116242  char **pzErr
116243){
116244  const PragmaName *pPragma = (const PragmaName*)pAux;
116245  PragmaVtab *pTab = 0;
116246  int rc;
116247  int i, j;
116248  char cSep = '(';
116249  StrAccum acc;
116250  char zBuf[200];
116251
116252  UNUSED_PARAMETER(argc);
116253  UNUSED_PARAMETER(argv);
116254  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
116255  sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
116256  for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
116257    sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
116258    cSep = ',';
116259  }
116260  if( i==0 ){
116261    sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
116262    cSep = ',';
116263    i++;
116264  }
116265  j = 0;
116266  if( pPragma->mPragFlg & PragFlg_Result1 ){
116267    sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
116268    j++;
116269  }
116270  if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
116271    sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
116272    j++;
116273  }
116274  sqlite3StrAccumAppend(&acc, ")", 1);
116275  sqlite3StrAccumFinish(&acc);
116276  assert( strlen(zBuf) < sizeof(zBuf)-1 );
116277  rc = sqlite3_declare_vtab(db, zBuf);
116278  if( rc==SQLITE_OK ){
116279    pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
116280    if( pTab==0 ){
116281      rc = SQLITE_NOMEM;
116282    }else{
116283      memset(pTab, 0, sizeof(PragmaVtab));
116284      pTab->pName = pPragma;
116285      pTab->db = db;
116286      pTab->iHidden = i;
116287      pTab->nHidden = j;
116288    }
116289  }else{
116290    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
116291  }
116292
116293  *ppVtab = (sqlite3_vtab*)pTab;
116294  return rc;
116295}
116296
116297/*
116298** Pragma virtual table module xDisconnect method.
116299*/
116300static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
116301  PragmaVtab *pTab = (PragmaVtab*)pVtab;
116302  sqlite3_free(pTab);
116303  return SQLITE_OK;
116304}
116305
116306/* Figure out the best index to use to search a pragma virtual table.
116307**
116308** There are not really any index choices.  But we want to encourage the
116309** query planner to give == constraints on as many hidden parameters as
116310** possible, and especially on the first hidden parameter.  So return a
116311** high cost if hidden parameters are unconstrained.
116312*/
116313static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
116314  PragmaVtab *pTab = (PragmaVtab*)tab;
116315  const struct sqlite3_index_constraint *pConstraint;
116316  int i, j;
116317  int seen[2];
116318
116319  pIdxInfo->estimatedCost = (double)1;
116320  if( pTab->nHidden==0 ){ return SQLITE_OK; }
116321  pConstraint = pIdxInfo->aConstraint;
116322  seen[0] = 0;
116323  seen[1] = 0;
116324  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
116325    if( pConstraint->usable==0 ) continue;
116326    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
116327    if( pConstraint->iColumn < pTab->iHidden ) continue;
116328    j = pConstraint->iColumn - pTab->iHidden;
116329    assert( j < 2 );
116330    seen[j] = i+1;
116331  }
116332  if( seen[0]==0 ){
116333    pIdxInfo->estimatedCost = (double)2147483647;
116334    pIdxInfo->estimatedRows = 2147483647;
116335    return SQLITE_OK;
116336  }
116337  j = seen[0]-1;
116338  pIdxInfo->aConstraintUsage[j].argvIndex = 1;
116339  pIdxInfo->aConstraintUsage[j].omit = 1;
116340  if( seen[1]==0 ) return SQLITE_OK;
116341  pIdxInfo->estimatedCost = (double)20;
116342  pIdxInfo->estimatedRows = 20;
116343  j = seen[1]-1;
116344  pIdxInfo->aConstraintUsage[j].argvIndex = 2;
116345  pIdxInfo->aConstraintUsage[j].omit = 1;
116346  return SQLITE_OK;
116347}
116348
116349/* Create a new cursor for the pragma virtual table */
116350static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
116351  PragmaVtabCursor *pCsr;
116352  pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
116353  if( pCsr==0 ) return SQLITE_NOMEM;
116354  memset(pCsr, 0, sizeof(PragmaVtabCursor));
116355  pCsr->base.pVtab = pVtab;
116356  *ppCursor = &pCsr->base;
116357  return SQLITE_OK;
116358}
116359
116360/* Clear all content from pragma virtual table cursor. */
116361static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
116362  int i;
116363  sqlite3_finalize(pCsr->pPragma);
116364  pCsr->pPragma = 0;
116365  for(i=0; i<ArraySize(pCsr->azArg); i++){
116366    sqlite3_free(pCsr->azArg[i]);
116367    pCsr->azArg[i] = 0;
116368  }
116369}
116370
116371/* Close a pragma virtual table cursor */
116372static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
116373  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
116374  pragmaVtabCursorClear(pCsr);
116375  sqlite3_free(pCsr);
116376  return SQLITE_OK;
116377}
116378
116379/* Advance the pragma virtual table cursor to the next row */
116380static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
116381  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116382  int rc = SQLITE_OK;
116383
116384  /* Increment the xRowid value */
116385  pCsr->iRowid++;
116386  assert( pCsr->pPragma );
116387  if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
116388    rc = sqlite3_finalize(pCsr->pPragma);
116389    pCsr->pPragma = 0;
116390    pragmaVtabCursorClear(pCsr);
116391  }
116392  return rc;
116393}
116394
116395/*
116396** Pragma virtual table module xFilter method.
116397*/
116398static int pragmaVtabFilter(
116399  sqlite3_vtab_cursor *pVtabCursor,
116400  int idxNum, const char *idxStr,
116401  int argc, sqlite3_value **argv
116402){
116403  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116404  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
116405  int rc;
116406  int i, j;
116407  StrAccum acc;
116408  char *zSql;
116409
116410  UNUSED_PARAMETER(idxNum);
116411  UNUSED_PARAMETER(idxStr);
116412  pragmaVtabCursorClear(pCsr);
116413  j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
116414  for(i=0; i<argc; i++, j++){
116415    const char *zText = (const char*)sqlite3_value_text(argv[i]);
116416    assert( j<ArraySize(pCsr->azArg) );
116417    assert( pCsr->azArg[j]==0 );
116418    if( zText ){
116419      pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
116420      if( pCsr->azArg[j]==0 ){
116421        return SQLITE_NOMEM;
116422      }
116423    }
116424  }
116425  sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
116426  sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
116427  if( pCsr->azArg[1] ){
116428    sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
116429  }
116430  sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
116431  if( pCsr->azArg[0] ){
116432    sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
116433  }
116434  zSql = sqlite3StrAccumFinish(&acc);
116435  if( zSql==0 ) return SQLITE_NOMEM;
116436  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
116437  sqlite3_free(zSql);
116438  if( rc!=SQLITE_OK ){
116439    pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
116440    return rc;
116441  }
116442  return pragmaVtabNext(pVtabCursor);
116443}
116444
116445/*
116446** Pragma virtual table module xEof method.
116447*/
116448static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
116449  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116450  return (pCsr->pPragma==0);
116451}
116452
116453/* The xColumn method simply returns the corresponding column from
116454** the PRAGMA.
116455*/
116456static int pragmaVtabColumn(
116457  sqlite3_vtab_cursor *pVtabCursor,
116458  sqlite3_context *ctx,
116459  int i
116460){
116461  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116462  PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
116463  if( i<pTab->iHidden ){
116464    sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
116465  }else{
116466    sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
116467  }
116468  return SQLITE_OK;
116469}
116470
116471/*
116472** Pragma virtual table module xRowid method.
116473*/
116474static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
116475  PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
116476  *p = pCsr->iRowid;
116477  return SQLITE_OK;
116478}
116479
116480/* The pragma virtual table object */
116481static const sqlite3_module pragmaVtabModule = {
116482  0,                           /* iVersion */
116483  0,                           /* xCreate - create a table */
116484  pragmaVtabConnect,           /* xConnect - connect to an existing table */
116485  pragmaVtabBestIndex,         /* xBestIndex - Determine search strategy */
116486  pragmaVtabDisconnect,        /* xDisconnect - Disconnect from a table */
116487  0,                           /* xDestroy - Drop a table */
116488  pragmaVtabOpen,              /* xOpen - open a cursor */
116489  pragmaVtabClose,             /* xClose - close a cursor */
116490  pragmaVtabFilter,            /* xFilter - configure scan constraints */
116491  pragmaVtabNext,              /* xNext - advance a cursor */
116492  pragmaVtabEof,               /* xEof */
116493  pragmaVtabColumn,            /* xColumn - read data */
116494  pragmaVtabRowid,             /* xRowid - read data */
116495  0,                           /* xUpdate - write data */
116496  0,                           /* xBegin - begin transaction */
116497  0,                           /* xSync - sync transaction */
116498  0,                           /* xCommit - commit transaction */
116499  0,                           /* xRollback - rollback transaction */
116500  0,                           /* xFindFunction - function overloading */
116501  0,                           /* xRename - rename the table */
116502  0,                           /* xSavepoint */
116503  0,                           /* xRelease */
116504  0                            /* xRollbackTo */
116505};
116506
116507/*
116508** Check to see if zTabName is really the name of a pragma.  If it is,
116509** then register an eponymous virtual table for that pragma and return
116510** a pointer to the Module object for the new virtual table.
116511*/
116512SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
116513  const PragmaName *pName;
116514  assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
116515  pName = pragmaLocate(zName+7);
116516  if( pName==0 ) return 0;
116517  if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
116518  assert( sqlite3HashFind(&db->aModule, zName)==0 );
116519  return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
116520}
116521
116522#endif /* SQLITE_OMIT_VIRTUALTABLE */
116523
116524#endif /* SQLITE_OMIT_PRAGMA */
116525
116526/************** End of pragma.c **********************************************/
116527/************** Begin file prepare.c *****************************************/
116528/*
116529** 2005 May 25
116530**
116531** The author disclaims copyright to this source code.  In place of
116532** a legal notice, here is a blessing:
116533**
116534**    May you do good and not evil.
116535**    May you find forgiveness for yourself and forgive others.
116536**    May you share freely, never taking more than you give.
116537**
116538*************************************************************************
116539** This file contains the implementation of the sqlite3_prepare()
116540** interface, and routines that contribute to loading the database schema
116541** from disk.
116542*/
116543/* #include "sqliteInt.h" */
116544
116545/*
116546** Fill the InitData structure with an error message that indicates
116547** that the database is corrupt.
116548*/
116549static void corruptSchema(
116550  InitData *pData,     /* Initialization context */
116551  const char *zObj,    /* Object being parsed at the point of error */
116552  const char *zExtra   /* Error information */
116553){
116554  sqlite3 *db = pData->db;
116555  if( !db->mallocFailed && (db->flags & SQLITE_WriteSchema)==0 ){
116556    char *z;
116557    if( zObj==0 ) zObj = "?";
116558    z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
116559    if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
116560    sqlite3DbFree(db, *pData->pzErrMsg);
116561    *pData->pzErrMsg = z;
116562  }
116563  pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
116564}
116565
116566/*
116567** This is the callback routine for the code that initializes the
116568** database.  See sqlite3Init() below for additional information.
116569** This routine is also called from the OP_ParseSchema opcode of the VDBE.
116570**
116571** Each callback contains the following information:
116572**
116573**     argv[0] = name of thing being created
116574**     argv[1] = root page number for table or index. 0 for trigger or view.
116575**     argv[2] = SQL text for the CREATE statement.
116576**
116577*/
116578SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
116579  InitData *pData = (InitData*)pInit;
116580  sqlite3 *db = pData->db;
116581  int iDb = pData->iDb;
116582
116583  assert( argc==3 );
116584  UNUSED_PARAMETER2(NotUsed, argc);
116585  assert( sqlite3_mutex_held(db->mutex) );
116586  DbClearProperty(db, iDb, DB_Empty);
116587  if( db->mallocFailed ){
116588    corruptSchema(pData, argv[0], 0);
116589    return 1;
116590  }
116591
116592  assert( iDb>=0 && iDb<db->nDb );
116593  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
116594  if( argv[1]==0 ){
116595    corruptSchema(pData, argv[0], 0);
116596  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
116597    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
116598    ** But because db->init.busy is set to 1, no VDBE code is generated
116599    ** or executed.  All the parser does is build the internal data
116600    ** structures that describe the table, index, or view.
116601    */
116602    int rc;
116603    u8 saved_iDb = db->init.iDb;
116604    sqlite3_stmt *pStmt;
116605    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
116606
116607    assert( db->init.busy );
116608    db->init.iDb = iDb;
116609    db->init.newTnum = sqlite3Atoi(argv[1]);
116610    db->init.orphanTrigger = 0;
116611    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
116612    rc = db->errCode;
116613    assert( (rc&0xFF)==(rcp&0xFF) );
116614    db->init.iDb = saved_iDb;
116615    assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 );
116616    if( SQLITE_OK!=rc ){
116617      if( db->init.orphanTrigger ){
116618        assert( iDb==1 );
116619      }else{
116620        pData->rc = rc;
116621        if( rc==SQLITE_NOMEM ){
116622          sqlite3OomFault(db);
116623        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
116624          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
116625        }
116626      }
116627    }
116628    sqlite3_finalize(pStmt);
116629  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
116630    corruptSchema(pData, argv[0], 0);
116631  }else{
116632    /* If the SQL column is blank it means this is an index that
116633    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
116634    ** constraint for a CREATE TABLE.  The index should have already
116635    ** been created when we processed the CREATE TABLE.  All we have
116636    ** to do here is record the root page number for that index.
116637    */
116638    Index *pIndex;
116639    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
116640    if( pIndex==0 ){
116641      /* This can occur if there exists an index on a TEMP table which
116642      ** has the same name as another index on a permanent index.  Since
116643      ** the permanent table is hidden by the TEMP table, we can also
116644      ** safely ignore the index on the permanent table.
116645      */
116646      /* Do Nothing */;
116647    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
116648      corruptSchema(pData, argv[0], "invalid rootpage");
116649    }
116650  }
116651  return 0;
116652}
116653
116654/*
116655** Attempt to read the database schema and initialize internal
116656** data structures for a single database file.  The index of the
116657** database file is given by iDb.  iDb==0 is used for the main
116658** database.  iDb==1 should never be used.  iDb>=2 is used for
116659** auxiliary databases.  Return one of the SQLITE_ error codes to
116660** indicate success or failure.
116661*/
116662static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
116663  int rc;
116664  int i;
116665#ifndef SQLITE_OMIT_DEPRECATED
116666  int size;
116667#endif
116668  Db *pDb;
116669  char const *azArg[4];
116670  int meta[5];
116671  InitData initData;
116672  const char *zMasterName;
116673  int openedTransaction = 0;
116674
116675  assert( iDb>=0 && iDb<db->nDb );
116676  assert( db->aDb[iDb].pSchema );
116677  assert( sqlite3_mutex_held(db->mutex) );
116678  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
116679
116680  /* Construct the in-memory representation schema tables (sqlite_master or
116681  ** sqlite_temp_master) by invoking the parser directly.  The appropriate
116682  ** table name will be inserted automatically by the parser so we can just
116683  ** use the abbreviation "x" here.  The parser will also automatically tag
116684  ** the schema table as read-only. */
116685  azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
116686  azArg[1] = "1";
116687  azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
116688                            "rootpage integer,sql text)";
116689  azArg[3] = 0;
116690  initData.db = db;
116691  initData.iDb = iDb;
116692  initData.rc = SQLITE_OK;
116693  initData.pzErrMsg = pzErrMsg;
116694  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
116695  if( initData.rc ){
116696    rc = initData.rc;
116697    goto error_out;
116698  }
116699
116700  /* Create a cursor to hold the database open
116701  */
116702  pDb = &db->aDb[iDb];
116703  if( pDb->pBt==0 ){
116704    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
116705      DbSetProperty(db, 1, DB_SchemaLoaded);
116706    }
116707    return SQLITE_OK;
116708  }
116709
116710  /* If there is not already a read-only (or read-write) transaction opened
116711  ** on the b-tree database, open one now. If a transaction is opened, it
116712  ** will be closed before this function returns.  */
116713  sqlite3BtreeEnter(pDb->pBt);
116714  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
116715    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
116716    if( rc!=SQLITE_OK ){
116717      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
116718      goto initone_error_out;
116719    }
116720    openedTransaction = 1;
116721  }
116722
116723  /* Get the database meta information.
116724  **
116725  ** Meta values are as follows:
116726  **    meta[0]   Schema cookie.  Changes with each schema change.
116727  **    meta[1]   File format of schema layer.
116728  **    meta[2]   Size of the page cache.
116729  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
116730  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
116731  **    meta[5]   User version
116732  **    meta[6]   Incremental vacuum mode
116733  **    meta[7]   unused
116734  **    meta[8]   unused
116735  **    meta[9]   unused
116736  **
116737  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
116738  ** the possible values of meta[4].
116739  */
116740  for(i=0; i<ArraySize(meta); i++){
116741    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
116742  }
116743  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
116744
116745  /* If opening a non-empty database, check the text encoding. For the
116746  ** main database, set sqlite3.enc to the encoding of the main database.
116747  ** For an attached db, it is an error if the encoding is not the same
116748  ** as sqlite3.enc.
116749  */
116750  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
116751    if( iDb==0 ){
116752#ifndef SQLITE_OMIT_UTF16
116753      u8 encoding;
116754      /* If opening the main database, set ENC(db). */
116755      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
116756      if( encoding==0 ) encoding = SQLITE_UTF8;
116757      ENC(db) = encoding;
116758#else
116759      ENC(db) = SQLITE_UTF8;
116760#endif
116761    }else{
116762      /* If opening an attached database, the encoding much match ENC(db) */
116763      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
116764        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
116765            " text encoding as main database");
116766        rc = SQLITE_ERROR;
116767        goto initone_error_out;
116768      }
116769    }
116770  }else{
116771    DbSetProperty(db, iDb, DB_Empty);
116772  }
116773  pDb->pSchema->enc = ENC(db);
116774
116775  if( pDb->pSchema->cache_size==0 ){
116776#ifndef SQLITE_OMIT_DEPRECATED
116777    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
116778    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
116779    pDb->pSchema->cache_size = size;
116780#else
116781    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
116782#endif
116783    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
116784  }
116785
116786  /*
116787  ** file_format==1    Version 3.0.0.
116788  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
116789  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
116790  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
116791  */
116792  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
116793  if( pDb->pSchema->file_format==0 ){
116794    pDb->pSchema->file_format = 1;
116795  }
116796  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
116797    sqlite3SetString(pzErrMsg, db, "unsupported file format");
116798    rc = SQLITE_ERROR;
116799    goto initone_error_out;
116800  }
116801
116802  /* Ticket #2804:  When we open a database in the newer file format,
116803  ** clear the legacy_file_format pragma flag so that a VACUUM will
116804  ** not downgrade the database and thus invalidate any descending
116805  ** indices that the user might have created.
116806  */
116807  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
116808    db->flags &= ~SQLITE_LegacyFileFmt;
116809  }
116810
116811  /* Read the schema information out of the schema tables
116812  */
116813  assert( db->init.busy );
116814  {
116815    char *zSql;
116816    zSql = sqlite3MPrintf(db,
116817        "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
116818        db->aDb[iDb].zDbSName, zMasterName);
116819#ifndef SQLITE_OMIT_AUTHORIZATION
116820    {
116821      sqlite3_xauth xAuth;
116822      xAuth = db->xAuth;
116823      db->xAuth = 0;
116824#endif
116825      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
116826#ifndef SQLITE_OMIT_AUTHORIZATION
116827      db->xAuth = xAuth;
116828    }
116829#endif
116830    if( rc==SQLITE_OK ) rc = initData.rc;
116831    sqlite3DbFree(db, zSql);
116832#ifndef SQLITE_OMIT_ANALYZE
116833    if( rc==SQLITE_OK ){
116834      sqlite3AnalysisLoad(db, iDb);
116835    }
116836#endif
116837  }
116838  if( db->mallocFailed ){
116839    rc = SQLITE_NOMEM_BKPT;
116840    sqlite3ResetAllSchemasOfConnection(db);
116841  }
116842  if( rc==SQLITE_OK || (db->flags&SQLITE_WriteSchema)){
116843    /* Black magic: If the SQLITE_WriteSchema flag is set, then consider
116844    ** the schema loaded, even if errors occurred. In this situation the
116845    ** current sqlite3_prepare() operation will fail, but the following one
116846    ** will attempt to compile the supplied statement against whatever subset
116847    ** of the schema was loaded before the error occurred. The primary
116848    ** purpose of this is to allow access to the sqlite_master table
116849    ** even when its contents have been corrupted.
116850    */
116851    DbSetProperty(db, iDb, DB_SchemaLoaded);
116852    rc = SQLITE_OK;
116853  }
116854
116855  /* Jump here for an error that occurs after successfully allocating
116856  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
116857  ** before that point, jump to error_out.
116858  */
116859initone_error_out:
116860  if( openedTransaction ){
116861    sqlite3BtreeCommit(pDb->pBt);
116862  }
116863  sqlite3BtreeLeave(pDb->pBt);
116864
116865error_out:
116866  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
116867    sqlite3OomFault(db);
116868  }
116869  return rc;
116870}
116871
116872/*
116873** Initialize all database files - the main database file, the file
116874** used to store temporary tables, and any additional database files
116875** created using ATTACH statements.  Return a success code.  If an
116876** error occurs, write an error message into *pzErrMsg.
116877**
116878** After a database is initialized, the DB_SchemaLoaded bit is set
116879** bit is set in the flags field of the Db structure. If the database
116880** file was of zero-length, then the DB_Empty flag is also set.
116881*/
116882SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
116883  int i, rc;
116884  int commit_internal = !(db->flags&SQLITE_InternChanges);
116885
116886  assert( sqlite3_mutex_held(db->mutex) );
116887  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
116888  assert( db->init.busy==0 );
116889  rc = SQLITE_OK;
116890  db->init.busy = 1;
116891  ENC(db) = SCHEMA_ENC(db);
116892  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
116893    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
116894    rc = sqlite3InitOne(db, i, pzErrMsg);
116895    if( rc ){
116896      sqlite3ResetOneSchema(db, i);
116897    }
116898  }
116899
116900  /* Once all the other databases have been initialized, load the schema
116901  ** for the TEMP database. This is loaded last, as the TEMP database
116902  ** schema may contain references to objects in other databases.
116903  */
116904#ifndef SQLITE_OMIT_TEMPDB
116905  assert( db->nDb>1 );
116906  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
116907    rc = sqlite3InitOne(db, 1, pzErrMsg);
116908    if( rc ){
116909      sqlite3ResetOneSchema(db, 1);
116910    }
116911  }
116912#endif
116913
116914  db->init.busy = 0;
116915  if( rc==SQLITE_OK && commit_internal ){
116916    sqlite3CommitInternalChanges(db);
116917  }
116918
116919  return rc;
116920}
116921
116922/*
116923** This routine is a no-op if the database schema is already initialized.
116924** Otherwise, the schema is loaded. An error code is returned.
116925*/
116926SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
116927  int rc = SQLITE_OK;
116928  sqlite3 *db = pParse->db;
116929  assert( sqlite3_mutex_held(db->mutex) );
116930  if( !db->init.busy ){
116931    rc = sqlite3Init(db, &pParse->zErrMsg);
116932  }
116933  if( rc!=SQLITE_OK ){
116934    pParse->rc = rc;
116935    pParse->nErr++;
116936  }
116937  return rc;
116938}
116939
116940
116941/*
116942** Check schema cookies in all databases.  If any cookie is out
116943** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
116944** make no changes to pParse->rc.
116945*/
116946static void schemaIsValid(Parse *pParse){
116947  sqlite3 *db = pParse->db;
116948  int iDb;
116949  int rc;
116950  int cookie;
116951
116952  assert( pParse->checkSchema );
116953  assert( sqlite3_mutex_held(db->mutex) );
116954  for(iDb=0; iDb<db->nDb; iDb++){
116955    int openedTransaction = 0;         /* True if a transaction is opened */
116956    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
116957    if( pBt==0 ) continue;
116958
116959    /* If there is not already a read-only (or read-write) transaction opened
116960    ** on the b-tree database, open one now. If a transaction is opened, it
116961    ** will be closed immediately after reading the meta-value. */
116962    if( !sqlite3BtreeIsInReadTrans(pBt) ){
116963      rc = sqlite3BtreeBeginTrans(pBt, 0);
116964      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
116965        sqlite3OomFault(db);
116966      }
116967      if( rc!=SQLITE_OK ) return;
116968      openedTransaction = 1;
116969    }
116970
116971    /* Read the schema cookie from the database. If it does not match the
116972    ** value stored as part of the in-memory schema representation,
116973    ** set Parse.rc to SQLITE_SCHEMA. */
116974    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
116975    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
116976    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
116977      sqlite3ResetOneSchema(db, iDb);
116978      pParse->rc = SQLITE_SCHEMA;
116979    }
116980
116981    /* Close the transaction, if one was opened. */
116982    if( openedTransaction ){
116983      sqlite3BtreeCommit(pBt);
116984    }
116985  }
116986}
116987
116988/*
116989** Convert a schema pointer into the iDb index that indicates
116990** which database file in db->aDb[] the schema refers to.
116991**
116992** If the same database is attached more than once, the first
116993** attached database is returned.
116994*/
116995SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
116996  int i = -1000000;
116997
116998  /* If pSchema is NULL, then return -1000000. This happens when code in
116999  ** expr.c is trying to resolve a reference to a transient table (i.e. one
117000  ** created by a sub-select). In this case the return value of this
117001  ** function should never be used.
117002  **
117003  ** We return -1000000 instead of the more usual -1 simply because using
117004  ** -1000000 as the incorrect index into db->aDb[] is much
117005  ** more likely to cause a segfault than -1 (of course there are assert()
117006  ** statements too, but it never hurts to play the odds).
117007  */
117008  assert( sqlite3_mutex_held(db->mutex) );
117009  if( pSchema ){
117010    for(i=0; ALWAYS(i<db->nDb); i++){
117011      if( db->aDb[i].pSchema==pSchema ){
117012        break;
117013      }
117014    }
117015    assert( i>=0 && i<db->nDb );
117016  }
117017  return i;
117018}
117019
117020/*
117021** Free all memory allocations in the pParse object
117022*/
117023SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
117024  if( pParse ){
117025    sqlite3 *db = pParse->db;
117026    sqlite3DbFree(db, pParse->aLabel);
117027    sqlite3ExprListDelete(db, pParse->pConstExpr);
117028    if( db ){
117029      assert( db->lookaside.bDisable >= pParse->disableLookaside );
117030      db->lookaside.bDisable -= pParse->disableLookaside;
117031    }
117032    pParse->disableLookaside = 0;
117033  }
117034}
117035
117036/*
117037** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
117038*/
117039static int sqlite3Prepare(
117040  sqlite3 *db,              /* Database handle. */
117041  const char *zSql,         /* UTF-8 encoded SQL statement. */
117042  int nBytes,               /* Length of zSql in bytes. */
117043  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
117044  Vdbe *pReprepare,         /* VM being reprepared */
117045  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117046  const char **pzTail       /* OUT: End of parsed string */
117047){
117048  char *zErrMsg = 0;        /* Error message */
117049  int rc = SQLITE_OK;       /* Result code */
117050  int i;                    /* Loop counter */
117051  Parse sParse;             /* Parsing context */
117052
117053  memset(&sParse, 0, PARSE_HDR_SZ);
117054  memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
117055  sParse.pReprepare = pReprepare;
117056  assert( ppStmt && *ppStmt==0 );
117057  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
117058  assert( sqlite3_mutex_held(db->mutex) );
117059
117060  /* For a long-term use prepared statement avoid the use of
117061  ** lookaside memory.
117062  */
117063  if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
117064    sParse.disableLookaside++;
117065    db->lookaside.bDisable++;
117066  }
117067
117068  /* Check to verify that it is possible to get a read lock on all
117069  ** database schemas.  The inability to get a read lock indicates that
117070  ** some other database connection is holding a write-lock, which in
117071  ** turn means that the other connection has made uncommitted changes
117072  ** to the schema.
117073  **
117074  ** Were we to proceed and prepare the statement against the uncommitted
117075  ** schema changes and if those schema changes are subsequently rolled
117076  ** back and different changes are made in their place, then when this
117077  ** prepared statement goes to run the schema cookie would fail to detect
117078  ** the schema change.  Disaster would follow.
117079  **
117080  ** This thread is currently holding mutexes on all Btrees (because
117081  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
117082  ** is not possible for another thread to start a new schema change
117083  ** while this routine is running.  Hence, we do not need to hold
117084  ** locks on the schema, we just need to make sure nobody else is
117085  ** holding them.
117086  **
117087  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
117088  ** but it does *not* override schema lock detection, so this all still
117089  ** works even if READ_UNCOMMITTED is set.
117090  */
117091  for(i=0; i<db->nDb; i++) {
117092    Btree *pBt = db->aDb[i].pBt;
117093    if( pBt ){
117094      assert( sqlite3BtreeHoldsMutex(pBt) );
117095      rc = sqlite3BtreeSchemaLocked(pBt);
117096      if( rc ){
117097        const char *zDb = db->aDb[i].zDbSName;
117098        sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
117099        testcase( db->flags & SQLITE_ReadUncommit );
117100        goto end_prepare;
117101      }
117102    }
117103  }
117104
117105  sqlite3VtabUnlockList(db);
117106
117107  sParse.db = db;
117108  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
117109    char *zSqlCopy;
117110    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
117111    testcase( nBytes==mxLen );
117112    testcase( nBytes==mxLen+1 );
117113    if( nBytes>mxLen ){
117114      sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
117115      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
117116      goto end_prepare;
117117    }
117118    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
117119    if( zSqlCopy ){
117120      sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
117121      sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
117122      sqlite3DbFree(db, zSqlCopy);
117123    }else{
117124      sParse.zTail = &zSql[nBytes];
117125    }
117126  }else{
117127    sqlite3RunParser(&sParse, zSql, &zErrMsg);
117128  }
117129  assert( 0==sParse.nQueryLoop );
117130
117131  if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
117132  if( sParse.checkSchema ){
117133    schemaIsValid(&sParse);
117134  }
117135  if( db->mallocFailed ){
117136    sParse.rc = SQLITE_NOMEM_BKPT;
117137  }
117138  if( pzTail ){
117139    *pzTail = sParse.zTail;
117140  }
117141  rc = sParse.rc;
117142
117143#ifndef SQLITE_OMIT_EXPLAIN
117144  if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
117145    static const char * const azColName[] = {
117146       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
117147       "selectid", "order", "from", "detail"
117148    };
117149    int iFirst, mx;
117150    if( sParse.explain==2 ){
117151      sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
117152      iFirst = 8;
117153      mx = 12;
117154    }else{
117155      sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
117156      iFirst = 0;
117157      mx = 8;
117158    }
117159    for(i=iFirst; i<mx; i++){
117160      sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
117161                            azColName[i], SQLITE_STATIC);
117162    }
117163  }
117164#endif
117165
117166  if( db->init.busy==0 ){
117167    sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
117168  }
117169  if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
117170    sqlite3VdbeFinalize(sParse.pVdbe);
117171    assert(!(*ppStmt));
117172  }else{
117173    *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
117174  }
117175
117176  if( zErrMsg ){
117177    sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
117178    sqlite3DbFree(db, zErrMsg);
117179  }else{
117180    sqlite3Error(db, rc);
117181  }
117182
117183  /* Delete any TriggerPrg structures allocated while parsing this statement. */
117184  while( sParse.pTriggerPrg ){
117185    TriggerPrg *pT = sParse.pTriggerPrg;
117186    sParse.pTriggerPrg = pT->pNext;
117187    sqlite3DbFree(db, pT);
117188  }
117189
117190end_prepare:
117191
117192  sqlite3ParserReset(&sParse);
117193  rc = sqlite3ApiExit(db, rc);
117194  assert( (rc&db->errMask)==rc );
117195  return rc;
117196}
117197static int sqlite3LockAndPrepare(
117198  sqlite3 *db,              /* Database handle. */
117199  const char *zSql,         /* UTF-8 encoded SQL statement. */
117200  int nBytes,               /* Length of zSql in bytes. */
117201  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
117202  Vdbe *pOld,               /* VM being reprepared */
117203  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117204  const char **pzTail       /* OUT: End of parsed string */
117205){
117206  int rc;
117207
117208#ifdef SQLITE_ENABLE_API_ARMOR
117209  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
117210#endif
117211  *ppStmt = 0;
117212  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
117213    return SQLITE_MISUSE_BKPT;
117214  }
117215  sqlite3_mutex_enter(db->mutex);
117216  sqlite3BtreeEnterAll(db);
117217  rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
117218  if( rc==SQLITE_SCHEMA ){
117219    sqlite3_finalize(*ppStmt);
117220    rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
117221  }
117222  sqlite3BtreeLeaveAll(db);
117223  sqlite3_mutex_leave(db->mutex);
117224  assert( rc==SQLITE_OK || *ppStmt==0 );
117225  return rc;
117226}
117227
117228/*
117229** Rerun the compilation of a statement after a schema change.
117230**
117231** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
117232** if the statement cannot be recompiled because another connection has
117233** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
117234** occurs, return SQLITE_SCHEMA.
117235*/
117236SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
117237  int rc;
117238  sqlite3_stmt *pNew;
117239  const char *zSql;
117240  sqlite3 *db;
117241  u8 prepFlags;
117242
117243  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
117244  zSql = sqlite3_sql((sqlite3_stmt *)p);
117245  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
117246  db = sqlite3VdbeDb(p);
117247  assert( sqlite3_mutex_held(db->mutex) );
117248  prepFlags = sqlite3VdbePrepareFlags(p);
117249  rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
117250  if( rc ){
117251    if( rc==SQLITE_NOMEM ){
117252      sqlite3OomFault(db);
117253    }
117254    assert( pNew==0 );
117255    return rc;
117256  }else{
117257    assert( pNew!=0 );
117258  }
117259  sqlite3VdbeSwap((Vdbe*)pNew, p);
117260  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
117261  sqlite3VdbeResetStepResult((Vdbe*)pNew);
117262  sqlite3VdbeFinalize((Vdbe*)pNew);
117263  return SQLITE_OK;
117264}
117265
117266
117267/*
117268** Two versions of the official API.  Legacy and new use.  In the legacy
117269** version, the original SQL text is not saved in the prepared statement
117270** and so if a schema change occurs, SQLITE_SCHEMA is returned by
117271** sqlite3_step().  In the new version, the original SQL text is retained
117272** and the statement is automatically recompiled if an schema change
117273** occurs.
117274*/
117275SQLITE_API int sqlite3_prepare(
117276  sqlite3 *db,              /* Database handle. */
117277  const char *zSql,         /* UTF-8 encoded SQL statement. */
117278  int nBytes,               /* Length of zSql in bytes. */
117279  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117280  const char **pzTail       /* OUT: End of parsed string */
117281){
117282  int rc;
117283  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
117284  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
117285  return rc;
117286}
117287SQLITE_API int sqlite3_prepare_v2(
117288  sqlite3 *db,              /* Database handle. */
117289  const char *zSql,         /* UTF-8 encoded SQL statement. */
117290  int nBytes,               /* Length of zSql in bytes. */
117291  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117292  const char **pzTail       /* OUT: End of parsed string */
117293){
117294  int rc;
117295  /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
117296  ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
117297  ** parameter.
117298  **
117299  ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
117300  rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
117301                             ppStmt,pzTail);
117302  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
117303  return rc;
117304}
117305SQLITE_API int sqlite3_prepare_v3(
117306  sqlite3 *db,              /* Database handle. */
117307  const char *zSql,         /* UTF-8 encoded SQL statement. */
117308  int nBytes,               /* Length of zSql in bytes. */
117309  unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
117310  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117311  const char **pzTail       /* OUT: End of parsed string */
117312){
117313  int rc;
117314  /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
117315  ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
117316  ** which is a bit array consisting of zero or more of the
117317  ** SQLITE_PREPARE_* flags.
117318  **
117319  ** Proof by comparison to the implementation of sqlite3_prepare_v2()
117320  ** directly above. */
117321  rc = sqlite3LockAndPrepare(db,zSql,nBytes,
117322                 SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
117323                 0,ppStmt,pzTail);
117324  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
117325  return rc;
117326}
117327
117328
117329#ifndef SQLITE_OMIT_UTF16
117330/*
117331** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
117332*/
117333static int sqlite3Prepare16(
117334  sqlite3 *db,              /* Database handle. */
117335  const void *zSql,         /* UTF-16 encoded SQL statement. */
117336  int nBytes,               /* Length of zSql in bytes. */
117337  u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
117338  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117339  const void **pzTail       /* OUT: End of parsed string */
117340){
117341  /* This function currently works by first transforming the UTF-16
117342  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
117343  ** tricky bit is figuring out the pointer to return in *pzTail.
117344  */
117345  char *zSql8;
117346  const char *zTail8 = 0;
117347  int rc = SQLITE_OK;
117348
117349#ifdef SQLITE_ENABLE_API_ARMOR
117350  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
117351#endif
117352  *ppStmt = 0;
117353  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
117354    return SQLITE_MISUSE_BKPT;
117355  }
117356  if( nBytes>=0 ){
117357    int sz;
117358    const char *z = (const char*)zSql;
117359    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
117360    nBytes = sz;
117361  }
117362  sqlite3_mutex_enter(db->mutex);
117363  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
117364  if( zSql8 ){
117365    rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
117366  }
117367
117368  if( zTail8 && pzTail ){
117369    /* If sqlite3_prepare returns a tail pointer, we calculate the
117370    ** equivalent pointer into the UTF-16 string by counting the unicode
117371    ** characters between zSql8 and zTail8, and then returning a pointer
117372    ** the same number of characters into the UTF-16 string.
117373    */
117374    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
117375    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
117376  }
117377  sqlite3DbFree(db, zSql8);
117378  rc = sqlite3ApiExit(db, rc);
117379  sqlite3_mutex_leave(db->mutex);
117380  return rc;
117381}
117382
117383/*
117384** Two versions of the official API.  Legacy and new use.  In the legacy
117385** version, the original SQL text is not saved in the prepared statement
117386** and so if a schema change occurs, SQLITE_SCHEMA is returned by
117387** sqlite3_step().  In the new version, the original SQL text is retained
117388** and the statement is automatically recompiled if an schema change
117389** occurs.
117390*/
117391SQLITE_API int sqlite3_prepare16(
117392  sqlite3 *db,              /* Database handle. */
117393  const void *zSql,         /* UTF-16 encoded SQL statement. */
117394  int nBytes,               /* Length of zSql in bytes. */
117395  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117396  const void **pzTail       /* OUT: End of parsed string */
117397){
117398  int rc;
117399  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
117400  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
117401  return rc;
117402}
117403SQLITE_API int sqlite3_prepare16_v2(
117404  sqlite3 *db,              /* Database handle. */
117405  const void *zSql,         /* UTF-16 encoded SQL statement. */
117406  int nBytes,               /* Length of zSql in bytes. */
117407  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117408  const void **pzTail       /* OUT: End of parsed string */
117409){
117410  int rc;
117411  rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
117412  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
117413  return rc;
117414}
117415SQLITE_API int sqlite3_prepare16_v3(
117416  sqlite3 *db,              /* Database handle. */
117417  const void *zSql,         /* UTF-16 encoded SQL statement. */
117418  int nBytes,               /* Length of zSql in bytes. */
117419  unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
117420  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
117421  const void **pzTail       /* OUT: End of parsed string */
117422){
117423  int rc;
117424  rc = sqlite3Prepare16(db,zSql,nBytes,
117425         SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
117426         ppStmt,pzTail);
117427  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
117428  return rc;
117429}
117430
117431#endif /* SQLITE_OMIT_UTF16 */
117432
117433/************** End of prepare.c *********************************************/
117434/************** Begin file select.c ******************************************/
117435/*
117436** 2001 September 15
117437**
117438** The author disclaims copyright to this source code.  In place of
117439** a legal notice, here is a blessing:
117440**
117441**    May you do good and not evil.
117442**    May you find forgiveness for yourself and forgive others.
117443**    May you share freely, never taking more than you give.
117444**
117445*************************************************************************
117446** This file contains C code routines that are called by the parser
117447** to handle SELECT statements in SQLite.
117448*/
117449/* #include "sqliteInt.h" */
117450
117451/*
117452** Trace output macros
117453*/
117454#if SELECTTRACE_ENABLED
117455/***/ int sqlite3SelectTrace = 0;
117456# define SELECTTRACE(K,P,S,X)  \
117457  if(sqlite3SelectTrace&(K))   \
117458    sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
117459        (S)->zSelName,(S)),\
117460    sqlite3DebugPrintf X
117461#else
117462# define SELECTTRACE(K,P,S,X)
117463#endif
117464
117465
117466/*
117467** An instance of the following object is used to record information about
117468** how to process the DISTINCT keyword, to simplify passing that information
117469** into the selectInnerLoop() routine.
117470*/
117471typedef struct DistinctCtx DistinctCtx;
117472struct DistinctCtx {
117473  u8 isTnct;      /* True if the DISTINCT keyword is present */
117474  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
117475  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
117476  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
117477};
117478
117479/*
117480** An instance of the following object is used to record information about
117481** the ORDER BY (or GROUP BY) clause of query is being coded.
117482*/
117483typedef struct SortCtx SortCtx;
117484struct SortCtx {
117485  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
117486  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
117487  int iECursor;         /* Cursor number for the sorter */
117488  int regReturn;        /* Register holding block-output return address */
117489  int labelBkOut;       /* Start label for the block-output subroutine */
117490  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
117491  int labelDone;        /* Jump here when done, ex: LIMIT reached */
117492  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
117493  u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
117494};
117495#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
117496
117497/*
117498** Delete all the content of a Select structure.  Deallocate the structure
117499** itself only if bFree is true.
117500*/
117501static void clearSelect(sqlite3 *db, Select *p, int bFree){
117502  while( p ){
117503    Select *pPrior = p->pPrior;
117504    sqlite3ExprListDelete(db, p->pEList);
117505    sqlite3SrcListDelete(db, p->pSrc);
117506    sqlite3ExprDelete(db, p->pWhere);
117507    sqlite3ExprListDelete(db, p->pGroupBy);
117508    sqlite3ExprDelete(db, p->pHaving);
117509    sqlite3ExprListDelete(db, p->pOrderBy);
117510    sqlite3ExprDelete(db, p->pLimit);
117511    sqlite3ExprDelete(db, p->pOffset);
117512    if( p->pWith ) sqlite3WithDelete(db, p->pWith);
117513    if( bFree ) sqlite3DbFreeNN(db, p);
117514    p = pPrior;
117515    bFree = 1;
117516  }
117517}
117518
117519/*
117520** Initialize a SelectDest structure.
117521*/
117522SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
117523  pDest->eDest = (u8)eDest;
117524  pDest->iSDParm = iParm;
117525  pDest->zAffSdst = 0;
117526  pDest->iSdst = 0;
117527  pDest->nSdst = 0;
117528}
117529
117530
117531/*
117532** Allocate a new Select structure and return a pointer to that
117533** structure.
117534*/
117535SQLITE_PRIVATE Select *sqlite3SelectNew(
117536  Parse *pParse,        /* Parsing context */
117537  ExprList *pEList,     /* which columns to include in the result */
117538  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
117539  Expr *pWhere,         /* the WHERE clause */
117540  ExprList *pGroupBy,   /* the GROUP BY clause */
117541  Expr *pHaving,        /* the HAVING clause */
117542  ExprList *pOrderBy,   /* the ORDER BY clause */
117543  u32 selFlags,         /* Flag parameters, such as SF_Distinct */
117544  Expr *pLimit,         /* LIMIT value.  NULL means not used */
117545  Expr *pOffset         /* OFFSET value.  NULL means no offset */
117546){
117547  Select *pNew;
117548  Select standin;
117549  pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
117550  if( pNew==0 ){
117551    assert( pParse->db->mallocFailed );
117552    pNew = &standin;
117553  }
117554  if( pEList==0 ){
117555    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(pParse->db,TK_ASTERISK,0));
117556  }
117557  pNew->pEList = pEList;
117558  pNew->op = TK_SELECT;
117559  pNew->selFlags = selFlags;
117560  pNew->iLimit = 0;
117561  pNew->iOffset = 0;
117562#if SELECTTRACE_ENABLED
117563  pNew->zSelName[0] = 0;
117564#endif
117565  pNew->addrOpenEphm[0] = -1;
117566  pNew->addrOpenEphm[1] = -1;
117567  pNew->nSelectRow = 0;
117568  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
117569  pNew->pSrc = pSrc;
117570  pNew->pWhere = pWhere;
117571  pNew->pGroupBy = pGroupBy;
117572  pNew->pHaving = pHaving;
117573  pNew->pOrderBy = pOrderBy;
117574  pNew->pPrior = 0;
117575  pNew->pNext = 0;
117576  pNew->pLimit = pLimit;
117577  pNew->pOffset = pOffset;
117578  pNew->pWith = 0;
117579  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || pParse->db->mallocFailed!=0 );
117580  if( pParse->db->mallocFailed ) {
117581    clearSelect(pParse->db, pNew, pNew!=&standin);
117582    pNew = 0;
117583  }else{
117584    assert( pNew->pSrc!=0 || pParse->nErr>0 );
117585  }
117586  assert( pNew!=&standin );
117587  return pNew;
117588}
117589
117590#if SELECTTRACE_ENABLED
117591/*
117592** Set the name of a Select object
117593*/
117594SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
117595  if( p && zName ){
117596    sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
117597  }
117598}
117599#endif
117600
117601
117602/*
117603** Delete the given Select structure and all of its substructures.
117604*/
117605SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
117606  if( p ) clearSelect(db, p, 1);
117607}
117608
117609/*
117610** Return a pointer to the right-most SELECT statement in a compound.
117611*/
117612static Select *findRightmost(Select *p){
117613  while( p->pNext ) p = p->pNext;
117614  return p;
117615}
117616
117617/*
117618** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
117619** type of join.  Return an integer constant that expresses that type
117620** in terms of the following bit values:
117621**
117622**     JT_INNER
117623**     JT_CROSS
117624**     JT_OUTER
117625**     JT_NATURAL
117626**     JT_LEFT
117627**     JT_RIGHT
117628**
117629** A full outer join is the combination of JT_LEFT and JT_RIGHT.
117630**
117631** If an illegal or unsupported join type is seen, then still return
117632** a join type, but put an error in the pParse structure.
117633*/
117634SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
117635  int jointype = 0;
117636  Token *apAll[3];
117637  Token *p;
117638                             /*   0123456789 123456789 123456789 123 */
117639  static const char zKeyText[] = "naturaleftouterightfullinnercross";
117640  static const struct {
117641    u8 i;        /* Beginning of keyword text in zKeyText[] */
117642    u8 nChar;    /* Length of the keyword in characters */
117643    u8 code;     /* Join type mask */
117644  } aKeyword[] = {
117645    /* natural */ { 0,  7, JT_NATURAL                },
117646    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
117647    /* outer   */ { 10, 5, JT_OUTER                  },
117648    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
117649    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
117650    /* inner   */ { 23, 5, JT_INNER                  },
117651    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
117652  };
117653  int i, j;
117654  apAll[0] = pA;
117655  apAll[1] = pB;
117656  apAll[2] = pC;
117657  for(i=0; i<3 && apAll[i]; i++){
117658    p = apAll[i];
117659    for(j=0; j<ArraySize(aKeyword); j++){
117660      if( p->n==aKeyword[j].nChar
117661          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
117662        jointype |= aKeyword[j].code;
117663        break;
117664      }
117665    }
117666    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
117667    if( j>=ArraySize(aKeyword) ){
117668      jointype |= JT_ERROR;
117669      break;
117670    }
117671  }
117672  if(
117673     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
117674     (jointype & JT_ERROR)!=0
117675  ){
117676    const char *zSp = " ";
117677    assert( pB!=0 );
117678    if( pC==0 ){ zSp++; }
117679    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
117680       "%T %T%s%T", pA, pB, zSp, pC);
117681    jointype = JT_INNER;
117682  }else if( (jointype & JT_OUTER)!=0
117683         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
117684    sqlite3ErrorMsg(pParse,
117685      "RIGHT and FULL OUTER JOINs are not currently supported");
117686    jointype = JT_INNER;
117687  }
117688  return jointype;
117689}
117690
117691/*
117692** Return the index of a column in a table.  Return -1 if the column
117693** is not contained in the table.
117694*/
117695static int columnIndex(Table *pTab, const char *zCol){
117696  int i;
117697  for(i=0; i<pTab->nCol; i++){
117698    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
117699  }
117700  return -1;
117701}
117702
117703/*
117704** Search the first N tables in pSrc, from left to right, looking for a
117705** table that has a column named zCol.
117706**
117707** When found, set *piTab and *piCol to the table index and column index
117708** of the matching column and return TRUE.
117709**
117710** If not found, return FALSE.
117711*/
117712static int tableAndColumnIndex(
117713  SrcList *pSrc,       /* Array of tables to search */
117714  int N,               /* Number of tables in pSrc->a[] to search */
117715  const char *zCol,    /* Name of the column we are looking for */
117716  int *piTab,          /* Write index of pSrc->a[] here */
117717  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
117718){
117719  int i;               /* For looping over tables in pSrc */
117720  int iCol;            /* Index of column matching zCol */
117721
117722  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
117723  for(i=0; i<N; i++){
117724    iCol = columnIndex(pSrc->a[i].pTab, zCol);
117725    if( iCol>=0 ){
117726      if( piTab ){
117727        *piTab = i;
117728        *piCol = iCol;
117729      }
117730      return 1;
117731    }
117732  }
117733  return 0;
117734}
117735
117736/*
117737** This function is used to add terms implied by JOIN syntax to the
117738** WHERE clause expression of a SELECT statement. The new term, which
117739** is ANDed with the existing WHERE clause, is of the form:
117740**
117741**    (tab1.col1 = tab2.col2)
117742**
117743** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
117744** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
117745** column iColRight of tab2.
117746*/
117747static void addWhereTerm(
117748  Parse *pParse,                  /* Parsing context */
117749  SrcList *pSrc,                  /* List of tables in FROM clause */
117750  int iLeft,                      /* Index of first table to join in pSrc */
117751  int iColLeft,                   /* Index of column in first table */
117752  int iRight,                     /* Index of second table in pSrc */
117753  int iColRight,                  /* Index of column in second table */
117754  int isOuterJoin,                /* True if this is an OUTER join */
117755  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
117756){
117757  sqlite3 *db = pParse->db;
117758  Expr *pE1;
117759  Expr *pE2;
117760  Expr *pEq;
117761
117762  assert( iLeft<iRight );
117763  assert( pSrc->nSrc>iRight );
117764  assert( pSrc->a[iLeft].pTab );
117765  assert( pSrc->a[iRight].pTab );
117766
117767  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
117768  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
117769
117770  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
117771  if( pEq && isOuterJoin ){
117772    ExprSetProperty(pEq, EP_FromJoin);
117773    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
117774    ExprSetVVAProperty(pEq, EP_NoReduce);
117775    pEq->iRightJoinTable = (i16)pE2->iTable;
117776  }
117777  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
117778}
117779
117780/*
117781** Set the EP_FromJoin property on all terms of the given expression.
117782** And set the Expr.iRightJoinTable to iTable for every term in the
117783** expression.
117784**
117785** The EP_FromJoin property is used on terms of an expression to tell
117786** the LEFT OUTER JOIN processing logic that this term is part of the
117787** join restriction specified in the ON or USING clause and not a part
117788** of the more general WHERE clause.  These terms are moved over to the
117789** WHERE clause during join processing but we need to remember that they
117790** originated in the ON or USING clause.
117791**
117792** The Expr.iRightJoinTable tells the WHERE clause processing that the
117793** expression depends on table iRightJoinTable even if that table is not
117794** explicitly mentioned in the expression.  That information is needed
117795** for cases like this:
117796**
117797**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
117798**
117799** The where clause needs to defer the handling of the t1.x=5
117800** term until after the t2 loop of the join.  In that way, a
117801** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
117802** defer the handling of t1.x=5, it will be processed immediately
117803** after the t1 loop and rows with t1.x!=5 will never appear in
117804** the output, which is incorrect.
117805*/
117806static void setJoinExpr(Expr *p, int iTable){
117807  while( p ){
117808    ExprSetProperty(p, EP_FromJoin);
117809    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
117810    ExprSetVVAProperty(p, EP_NoReduce);
117811    p->iRightJoinTable = (i16)iTable;
117812    if( p->op==TK_FUNCTION && p->x.pList ){
117813      int i;
117814      for(i=0; i<p->x.pList->nExpr; i++){
117815        setJoinExpr(p->x.pList->a[i].pExpr, iTable);
117816      }
117817    }
117818    setJoinExpr(p->pLeft, iTable);
117819    p = p->pRight;
117820  }
117821}
117822
117823/*
117824** This routine processes the join information for a SELECT statement.
117825** ON and USING clauses are converted into extra terms of the WHERE clause.
117826** NATURAL joins also create extra WHERE clause terms.
117827**
117828** The terms of a FROM clause are contained in the Select.pSrc structure.
117829** The left most table is the first entry in Select.pSrc.  The right-most
117830** table is the last entry.  The join operator is held in the entry to
117831** the left.  Thus entry 0 contains the join operator for the join between
117832** entries 0 and 1.  Any ON or USING clauses associated with the join are
117833** also attached to the left entry.
117834**
117835** This routine returns the number of errors encountered.
117836*/
117837static int sqliteProcessJoin(Parse *pParse, Select *p){
117838  SrcList *pSrc;                  /* All tables in the FROM clause */
117839  int i, j;                       /* Loop counters */
117840  struct SrcList_item *pLeft;     /* Left table being joined */
117841  struct SrcList_item *pRight;    /* Right table being joined */
117842
117843  pSrc = p->pSrc;
117844  pLeft = &pSrc->a[0];
117845  pRight = &pLeft[1];
117846  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
117847    Table *pLeftTab = pLeft->pTab;
117848    Table *pRightTab = pRight->pTab;
117849    int isOuter;
117850
117851    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
117852    isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
117853
117854    /* When the NATURAL keyword is present, add WHERE clause terms for
117855    ** every column that the two tables have in common.
117856    */
117857    if( pRight->fg.jointype & JT_NATURAL ){
117858      if( pRight->pOn || pRight->pUsing ){
117859        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
117860           "an ON or USING clause", 0);
117861        return 1;
117862      }
117863      for(j=0; j<pRightTab->nCol; j++){
117864        char *zName;   /* Name of column in the right table */
117865        int iLeft;     /* Matching left table */
117866        int iLeftCol;  /* Matching column in the left table */
117867
117868        zName = pRightTab->aCol[j].zName;
117869        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
117870          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
117871                       isOuter, &p->pWhere);
117872        }
117873      }
117874    }
117875
117876    /* Disallow both ON and USING clauses in the same join
117877    */
117878    if( pRight->pOn && pRight->pUsing ){
117879      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
117880        "clauses in the same join");
117881      return 1;
117882    }
117883
117884    /* Add the ON clause to the end of the WHERE clause, connected by
117885    ** an AND operator.
117886    */
117887    if( pRight->pOn ){
117888      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
117889      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
117890      pRight->pOn = 0;
117891    }
117892
117893    /* Create extra terms on the WHERE clause for each column named
117894    ** in the USING clause.  Example: If the two tables to be joined are
117895    ** A and B and the USING clause names X, Y, and Z, then add this
117896    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
117897    ** Report an error if any column mentioned in the USING clause is
117898    ** not contained in both tables to be joined.
117899    */
117900    if( pRight->pUsing ){
117901      IdList *pList = pRight->pUsing;
117902      for(j=0; j<pList->nId; j++){
117903        char *zName;     /* Name of the term in the USING clause */
117904        int iLeft;       /* Table on the left with matching column name */
117905        int iLeftCol;    /* Column number of matching column on the left */
117906        int iRightCol;   /* Column number of matching column on the right */
117907
117908        zName = pList->a[j].zName;
117909        iRightCol = columnIndex(pRightTab, zName);
117910        if( iRightCol<0
117911         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
117912        ){
117913          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
117914            "not present in both tables", zName);
117915          return 1;
117916        }
117917        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
117918                     isOuter, &p->pWhere);
117919      }
117920    }
117921  }
117922  return 0;
117923}
117924
117925/* Forward reference */
117926static KeyInfo *keyInfoFromExprList(
117927  Parse *pParse,       /* Parsing context */
117928  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
117929  int iStart,          /* Begin with this column of pList */
117930  int nExtra           /* Add this many extra columns to the end */
117931);
117932
117933/*
117934** Generate code that will push the record in registers regData
117935** through regData+nData-1 onto the sorter.
117936*/
117937static void pushOntoSorter(
117938  Parse *pParse,         /* Parser context */
117939  SortCtx *pSort,        /* Information about the ORDER BY clause */
117940  Select *pSelect,       /* The whole SELECT statement */
117941  int regData,           /* First register holding data to be sorted */
117942  int regOrigData,       /* First register holding data before packing */
117943  int nData,             /* Number of elements in the data array */
117944  int nPrefixReg         /* No. of reg prior to regData available for use */
117945){
117946  Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
117947  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
117948  int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
117949  int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
117950  int regBase;                                     /* Regs for sorter record */
117951  int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
117952  int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
117953  int op;                            /* Opcode to add sorter record to sorter */
117954  int iLimit;                        /* LIMIT counter */
117955
117956  assert( bSeq==0 || bSeq==1 );
117957  assert( nData==1 || regData==regOrigData || regOrigData==0 );
117958  if( nPrefixReg ){
117959    assert( nPrefixReg==nExpr+bSeq );
117960    regBase = regData - nExpr - bSeq;
117961  }else{
117962    regBase = pParse->nMem + 1;
117963    pParse->nMem += nBase;
117964  }
117965  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
117966  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
117967  pSort->labelDone = sqlite3VdbeMakeLabel(v);
117968  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
117969                          SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
117970  if( bSeq ){
117971    sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
117972  }
117973  if( nPrefixReg==0 && nData>0 ){
117974    sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
117975  }
117976  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
117977  if( nOBSat>0 ){
117978    int regPrevKey;   /* The first nOBSat columns of the previous row */
117979    int addrFirst;    /* Address of the OP_IfNot opcode */
117980    int addrJmp;      /* Address of the OP_Jump opcode */
117981    VdbeOp *pOp;      /* Opcode that opens the sorter */
117982    int nKey;         /* Number of sorting key columns, including OP_Sequence */
117983    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
117984
117985    regPrevKey = pParse->nMem+1;
117986    pParse->nMem += pSort->nOBSat;
117987    nKey = nExpr - pSort->nOBSat + bSeq;
117988    if( bSeq ){
117989      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
117990    }else{
117991      addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
117992    }
117993    VdbeCoverage(v);
117994    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
117995    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
117996    if( pParse->db->mallocFailed ) return;
117997    pOp->p2 = nKey + nData;
117998    pKI = pOp->p4.pKeyInfo;
117999    memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
118000    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
118001    testcase( pKI->nXField>2 );
118002    pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
118003                                           pKI->nXField-1);
118004    addrJmp = sqlite3VdbeCurrentAddr(v);
118005    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
118006    pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
118007    pSort->regReturn = ++pParse->nMem;
118008    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
118009    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
118010    if( iLimit ){
118011      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
118012      VdbeCoverage(v);
118013    }
118014    sqlite3VdbeJumpHere(v, addrFirst);
118015    sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
118016    sqlite3VdbeJumpHere(v, addrJmp);
118017  }
118018  if( pSort->sortFlags & SORTFLAG_UseSorter ){
118019    op = OP_SorterInsert;
118020  }else{
118021    op = OP_IdxInsert;
118022  }
118023  sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
118024                       regBase+nOBSat, nBase-nOBSat);
118025  if( iLimit ){
118026    int addr;
118027    int r1 = 0;
118028    /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
118029    ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
118030    ** fills up, delete the least entry in the sorter after each insert.
118031    ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
118032    addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
118033    sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
118034    if( pSort->bOrderedInnerLoop ){
118035      r1 = ++pParse->nMem;
118036      sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
118037      VdbeComment((v, "seq"));
118038    }
118039    sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
118040    if( pSort->bOrderedInnerLoop ){
118041      /* If the inner loop is driven by an index such that values from
118042      ** the same iteration of the inner loop are in sorted order, then
118043      ** immediately jump to the next iteration of an inner loop if the
118044      ** entry from the current iteration does not fit into the top
118045      ** LIMIT+OFFSET entries of the sorter. */
118046      int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
118047      sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
118048      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
118049      VdbeCoverage(v);
118050    }
118051    sqlite3VdbeJumpHere(v, addr);
118052  }
118053}
118054
118055/*
118056** Add code to implement the OFFSET
118057*/
118058static void codeOffset(
118059  Vdbe *v,          /* Generate code into this VM */
118060  int iOffset,      /* Register holding the offset counter */
118061  int iContinue     /* Jump here to skip the current record */
118062){
118063  if( iOffset>0 ){
118064    sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
118065    VdbeComment((v, "OFFSET"));
118066  }
118067}
118068
118069/*
118070** Add code that will check to make sure the N registers starting at iMem
118071** form a distinct entry.  iTab is a sorting index that holds previously
118072** seen combinations of the N values.  A new entry is made in iTab
118073** if the current N values are new.
118074**
118075** A jump to addrRepeat is made and the N+1 values are popped from the
118076** stack if the top N elements are not distinct.
118077*/
118078static void codeDistinct(
118079  Parse *pParse,     /* Parsing and code generating context */
118080  int iTab,          /* A sorting index used to test for distinctness */
118081  int addrRepeat,    /* Jump to here if not distinct */
118082  int N,             /* Number of elements */
118083  int iMem           /* First element */
118084){
118085  Vdbe *v;
118086  int r1;
118087
118088  v = pParse->pVdbe;
118089  r1 = sqlite3GetTempReg(pParse);
118090  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
118091  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
118092  sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
118093  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
118094  sqlite3ReleaseTempReg(pParse, r1);
118095}
118096
118097/*
118098** This routine generates the code for the inside of the inner loop
118099** of a SELECT.
118100**
118101** If srcTab is negative, then the pEList expressions
118102** are evaluated in order to get the data for this row.  If srcTab is
118103** zero or more, then data is pulled from srcTab and pEList is used only
118104** to get the number of columns and the collation sequence for each column.
118105*/
118106static void selectInnerLoop(
118107  Parse *pParse,          /* The parser context */
118108  Select *p,              /* The complete select statement being coded */
118109  ExprList *pEList,       /* List of values being extracted */
118110  int srcTab,             /* Pull data from this table */
118111  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
118112  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
118113  SelectDest *pDest,      /* How to dispose of the results */
118114  int iContinue,          /* Jump here to continue with next row */
118115  int iBreak              /* Jump here to break out of the inner loop */
118116){
118117  Vdbe *v = pParse->pVdbe;
118118  int i;
118119  int hasDistinct;            /* True if the DISTINCT keyword is present */
118120  int eDest = pDest->eDest;   /* How to dispose of results */
118121  int iParm = pDest->iSDParm; /* First argument to disposal method */
118122  int nResultCol;             /* Number of result columns */
118123  int nPrefixReg = 0;         /* Number of extra registers before regResult */
118124
118125  /* Usually, regResult is the first cell in an array of memory cells
118126  ** containing the current result row. In this case regOrig is set to the
118127  ** same value. However, if the results are being sent to the sorter, the
118128  ** values for any expressions that are also part of the sort-key are omitted
118129  ** from this array. In this case regOrig is set to zero.  */
118130  int regResult;              /* Start of memory holding current results */
118131  int regOrig;                /* Start of memory holding full result (or 0) */
118132
118133  assert( v );
118134  assert( pEList!=0 );
118135  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
118136  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
118137  if( pSort==0 && !hasDistinct ){
118138    assert( iContinue!=0 );
118139    codeOffset(v, p->iOffset, iContinue);
118140  }
118141
118142  /* Pull the requested columns.
118143  */
118144  nResultCol = pEList->nExpr;
118145
118146  if( pDest->iSdst==0 ){
118147    if( pSort ){
118148      nPrefixReg = pSort->pOrderBy->nExpr;
118149      if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
118150      pParse->nMem += nPrefixReg;
118151    }
118152    pDest->iSdst = pParse->nMem+1;
118153    pParse->nMem += nResultCol;
118154  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
118155    /* This is an error condition that can result, for example, when a SELECT
118156    ** on the right-hand side of an INSERT contains more result columns than
118157    ** there are columns in the table on the left.  The error will be caught
118158    ** and reported later.  But we need to make sure enough memory is allocated
118159    ** to avoid other spurious errors in the meantime. */
118160    pParse->nMem += nResultCol;
118161  }
118162  pDest->nSdst = nResultCol;
118163  regOrig = regResult = pDest->iSdst;
118164  if( srcTab>=0 ){
118165    for(i=0; i<nResultCol; i++){
118166      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
118167      VdbeComment((v, "%s", pEList->a[i].zName));
118168    }
118169  }else if( eDest!=SRT_Exists ){
118170    /* If the destination is an EXISTS(...) expression, the actual
118171    ** values returned by the SELECT are not required.
118172    */
118173    u8 ecelFlags;
118174    if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
118175      ecelFlags = SQLITE_ECEL_DUP;
118176    }else{
118177      ecelFlags = 0;
118178    }
118179    if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
118180      /* For each expression in pEList that is a copy of an expression in
118181      ** the ORDER BY clause (pSort->pOrderBy), set the associated
118182      ** iOrderByCol value to one more than the index of the ORDER BY
118183      ** expression within the sort-key that pushOntoSorter() will generate.
118184      ** This allows the pEList field to be omitted from the sorted record,
118185      ** saving space and CPU cycles.  */
118186      ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
118187      for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
118188        int j;
118189        if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
118190          pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
118191        }
118192      }
118193      regOrig = 0;
118194      assert( eDest==SRT_Set || eDest==SRT_Mem
118195           || eDest==SRT_Coroutine || eDest==SRT_Output );
118196    }
118197    nResultCol = sqlite3ExprCodeExprList(pParse,pEList,regResult,0,ecelFlags);
118198  }
118199
118200  /* If the DISTINCT keyword was present on the SELECT statement
118201  ** and this row has been seen before, then do not make this row
118202  ** part of the result.
118203  */
118204  if( hasDistinct ){
118205    switch( pDistinct->eTnctType ){
118206      case WHERE_DISTINCT_ORDERED: {
118207        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
118208        int iJump;              /* Jump destination */
118209        int regPrev;            /* Previous row content */
118210
118211        /* Allocate space for the previous row */
118212        regPrev = pParse->nMem+1;
118213        pParse->nMem += nResultCol;
118214
118215        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
118216        ** sets the MEM_Cleared bit on the first register of the
118217        ** previous value.  This will cause the OP_Ne below to always
118218        ** fail on the first iteration of the loop even if the first
118219        ** row is all NULLs.
118220        */
118221        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
118222        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
118223        pOp->opcode = OP_Null;
118224        pOp->p1 = 1;
118225        pOp->p2 = regPrev;
118226
118227        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
118228        for(i=0; i<nResultCol; i++){
118229          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
118230          if( i<nResultCol-1 ){
118231            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
118232            VdbeCoverage(v);
118233          }else{
118234            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
118235            VdbeCoverage(v);
118236           }
118237          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
118238          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
118239        }
118240        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
118241        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
118242        break;
118243      }
118244
118245      case WHERE_DISTINCT_UNIQUE: {
118246        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
118247        break;
118248      }
118249
118250      default: {
118251        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
118252        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
118253                     regResult);
118254        break;
118255      }
118256    }
118257    if( pSort==0 ){
118258      codeOffset(v, p->iOffset, iContinue);
118259    }
118260  }
118261
118262  switch( eDest ){
118263    /* In this mode, write each query result to the key of the temporary
118264    ** table iParm.
118265    */
118266#ifndef SQLITE_OMIT_COMPOUND_SELECT
118267    case SRT_Union: {
118268      int r1;
118269      r1 = sqlite3GetTempReg(pParse);
118270      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
118271      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
118272      sqlite3ReleaseTempReg(pParse, r1);
118273      break;
118274    }
118275
118276    /* Construct a record from the query result, but instead of
118277    ** saving that record, use it as a key to delete elements from
118278    ** the temporary table iParm.
118279    */
118280    case SRT_Except: {
118281      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
118282      break;
118283    }
118284#endif /* SQLITE_OMIT_COMPOUND_SELECT */
118285
118286    /* Store the result as data using a unique key.
118287    */
118288    case SRT_Fifo:
118289    case SRT_DistFifo:
118290    case SRT_Table:
118291    case SRT_EphemTab: {
118292      int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
118293      testcase( eDest==SRT_Table );
118294      testcase( eDest==SRT_EphemTab );
118295      testcase( eDest==SRT_Fifo );
118296      testcase( eDest==SRT_DistFifo );
118297      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
118298#ifndef SQLITE_OMIT_CTE
118299      if( eDest==SRT_DistFifo ){
118300        /* If the destination is DistFifo, then cursor (iParm+1) is open
118301        ** on an ephemeral index. If the current row is already present
118302        ** in the index, do not write it to the output. If not, add the
118303        ** current row to the index and proceed with writing it to the
118304        ** output table as well.  */
118305        int addr = sqlite3VdbeCurrentAddr(v) + 4;
118306        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
118307        VdbeCoverage(v);
118308        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
118309        assert( pSort==0 );
118310      }
118311#endif
118312      if( pSort ){
118313        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
118314      }else{
118315        int r2 = sqlite3GetTempReg(pParse);
118316        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
118317        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
118318        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
118319        sqlite3ReleaseTempReg(pParse, r2);
118320      }
118321      sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
118322      break;
118323    }
118324
118325#ifndef SQLITE_OMIT_SUBQUERY
118326    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
118327    ** then there should be a single item on the stack.  Write this
118328    ** item into the set table with bogus data.
118329    */
118330    case SRT_Set: {
118331      if( pSort ){
118332        /* At first glance you would think we could optimize out the
118333        ** ORDER BY in this case since the order of entries in the set
118334        ** does not matter.  But there might be a LIMIT clause, in which
118335        ** case the order does matter */
118336        pushOntoSorter(
118337            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
118338      }else{
118339        int r1 = sqlite3GetTempReg(pParse);
118340        assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
118341        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
118342            r1, pDest->zAffSdst, nResultCol);
118343        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
118344        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
118345        sqlite3ReleaseTempReg(pParse, r1);
118346      }
118347      break;
118348    }
118349
118350    /* If any row exist in the result set, record that fact and abort.
118351    */
118352    case SRT_Exists: {
118353      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
118354      /* The LIMIT clause will terminate the loop for us */
118355      break;
118356    }
118357
118358    /* If this is a scalar select that is part of an expression, then
118359    ** store the results in the appropriate memory cell or array of
118360    ** memory cells and break out of the scan loop.
118361    */
118362    case SRT_Mem: {
118363      if( pSort ){
118364        assert( nResultCol<=pDest->nSdst );
118365        pushOntoSorter(
118366            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
118367      }else{
118368        assert( nResultCol==pDest->nSdst );
118369        assert( regResult==iParm );
118370        /* The LIMIT clause will jump out of the loop for us */
118371      }
118372      break;
118373    }
118374#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
118375
118376    case SRT_Coroutine:       /* Send data to a co-routine */
118377    case SRT_Output: {        /* Return the results */
118378      testcase( eDest==SRT_Coroutine );
118379      testcase( eDest==SRT_Output );
118380      if( pSort ){
118381        pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
118382                       nPrefixReg);
118383      }else if( eDest==SRT_Coroutine ){
118384        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
118385      }else{
118386        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
118387        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
118388      }
118389      break;
118390    }
118391
118392#ifndef SQLITE_OMIT_CTE
118393    /* Write the results into a priority queue that is order according to
118394    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
118395    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
118396    ** pSO->nExpr columns, then make sure all keys are unique by adding a
118397    ** final OP_Sequence column.  The last column is the record as a blob.
118398    */
118399    case SRT_DistQueue:
118400    case SRT_Queue: {
118401      int nKey;
118402      int r1, r2, r3;
118403      int addrTest = 0;
118404      ExprList *pSO;
118405      pSO = pDest->pOrderBy;
118406      assert( pSO );
118407      nKey = pSO->nExpr;
118408      r1 = sqlite3GetTempReg(pParse);
118409      r2 = sqlite3GetTempRange(pParse, nKey+2);
118410      r3 = r2+nKey+1;
118411      if( eDest==SRT_DistQueue ){
118412        /* If the destination is DistQueue, then cursor (iParm+1) is open
118413        ** on a second ephemeral index that holds all values every previously
118414        ** added to the queue. */
118415        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
118416                                        regResult, nResultCol);
118417        VdbeCoverage(v);
118418      }
118419      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
118420      if( eDest==SRT_DistQueue ){
118421        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
118422        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
118423      }
118424      for(i=0; i<nKey; i++){
118425        sqlite3VdbeAddOp2(v, OP_SCopy,
118426                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
118427                          r2+i);
118428      }
118429      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
118430      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
118431      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
118432      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
118433      sqlite3ReleaseTempReg(pParse, r1);
118434      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
118435      break;
118436    }
118437#endif /* SQLITE_OMIT_CTE */
118438
118439
118440
118441#if !defined(SQLITE_OMIT_TRIGGER)
118442    /* Discard the results.  This is used for SELECT statements inside
118443    ** the body of a TRIGGER.  The purpose of such selects is to call
118444    ** user-defined functions that have side effects.  We do not care
118445    ** about the actual results of the select.
118446    */
118447    default: {
118448      assert( eDest==SRT_Discard );
118449      break;
118450    }
118451#endif
118452  }
118453
118454  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
118455  ** there is a sorter, in which case the sorter has already limited
118456  ** the output for us.
118457  */
118458  if( pSort==0 && p->iLimit ){
118459    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
118460  }
118461}
118462
118463/*
118464** Allocate a KeyInfo object sufficient for an index of N key columns and
118465** X extra columns.
118466*/
118467SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
118468  int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
118469  KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
118470  if( p ){
118471    p->aSortOrder = (u8*)&p->aColl[N+X];
118472    p->nField = (u16)N;
118473    p->nXField = (u16)X;
118474    p->enc = ENC(db);
118475    p->db = db;
118476    p->nRef = 1;
118477    memset(&p[1], 0, nExtra);
118478  }else{
118479    sqlite3OomFault(db);
118480  }
118481  return p;
118482}
118483
118484/*
118485** Deallocate a KeyInfo object
118486*/
118487SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
118488  if( p ){
118489    assert( p->nRef>0 );
118490    p->nRef--;
118491    if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
118492  }
118493}
118494
118495/*
118496** Make a new pointer to a KeyInfo object
118497*/
118498SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
118499  if( p ){
118500    assert( p->nRef>0 );
118501    p->nRef++;
118502  }
118503  return p;
118504}
118505
118506#ifdef SQLITE_DEBUG
118507/*
118508** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
118509** can only be changed if this is just a single reference to the object.
118510**
118511** This routine is used only inside of assert() statements.
118512*/
118513SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
118514#endif /* SQLITE_DEBUG */
118515
118516/*
118517** Given an expression list, generate a KeyInfo structure that records
118518** the collating sequence for each expression in that expression list.
118519**
118520** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
118521** KeyInfo structure is appropriate for initializing a virtual index to
118522** implement that clause.  If the ExprList is the result set of a SELECT
118523** then the KeyInfo structure is appropriate for initializing a virtual
118524** index to implement a DISTINCT test.
118525**
118526** Space to hold the KeyInfo structure is obtained from malloc.  The calling
118527** function is responsible for seeing that this structure is eventually
118528** freed.
118529*/
118530static KeyInfo *keyInfoFromExprList(
118531  Parse *pParse,       /* Parsing context */
118532  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
118533  int iStart,          /* Begin with this column of pList */
118534  int nExtra           /* Add this many extra columns to the end */
118535){
118536  int nExpr;
118537  KeyInfo *pInfo;
118538  struct ExprList_item *pItem;
118539  sqlite3 *db = pParse->db;
118540  int i;
118541
118542  nExpr = pList->nExpr;
118543  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
118544  if( pInfo ){
118545    assert( sqlite3KeyInfoIsWriteable(pInfo) );
118546    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
118547      CollSeq *pColl;
118548      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
118549      if( !pColl ) pColl = db->pDfltColl;
118550      pInfo->aColl[i-iStart] = pColl;
118551      pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
118552    }
118553  }
118554  return pInfo;
118555}
118556
118557/*
118558** Name of the connection operator, used for error messages.
118559*/
118560static const char *selectOpName(int id){
118561  char *z;
118562  switch( id ){
118563    case TK_ALL:       z = "UNION ALL";   break;
118564    case TK_INTERSECT: z = "INTERSECT";   break;
118565    case TK_EXCEPT:    z = "EXCEPT";      break;
118566    default:           z = "UNION";       break;
118567  }
118568  return z;
118569}
118570
118571#ifndef SQLITE_OMIT_EXPLAIN
118572/*
118573** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
118574** is a no-op. Otherwise, it adds a single row of output to the EQP result,
118575** where the caption is of the form:
118576**
118577**   "USE TEMP B-TREE FOR xxx"
118578**
118579** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
118580** is determined by the zUsage argument.
118581*/
118582static void explainTempTable(Parse *pParse, const char *zUsage){
118583  if( pParse->explain==2 ){
118584    Vdbe *v = pParse->pVdbe;
118585    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
118586    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
118587  }
118588}
118589
118590/*
118591** Assign expression b to lvalue a. A second, no-op, version of this macro
118592** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
118593** in sqlite3Select() to assign values to structure member variables that
118594** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
118595** code with #ifndef directives.
118596*/
118597# define explainSetInteger(a, b) a = b
118598
118599#else
118600/* No-op versions of the explainXXX() functions and macros. */
118601# define explainTempTable(y,z)
118602# define explainSetInteger(y,z)
118603#endif
118604
118605#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
118606/*
118607** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
118608** is a no-op. Otherwise, it adds a single row of output to the EQP result,
118609** where the caption is of one of the two forms:
118610**
118611**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
118612**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
118613**
118614** where iSub1 and iSub2 are the integers passed as the corresponding
118615** function parameters, and op is the text representation of the parameter
118616** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
118617** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
118618** false, or the second form if it is true.
118619*/
118620static void explainComposite(
118621  Parse *pParse,                  /* Parse context */
118622  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
118623  int iSub1,                      /* Subquery id 1 */
118624  int iSub2,                      /* Subquery id 2 */
118625  int bUseTmp                     /* True if a temp table was used */
118626){
118627  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
118628  if( pParse->explain==2 ){
118629    Vdbe *v = pParse->pVdbe;
118630    char *zMsg = sqlite3MPrintf(
118631        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
118632        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
118633    );
118634    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
118635  }
118636}
118637#else
118638/* No-op versions of the explainXXX() functions and macros. */
118639# define explainComposite(v,w,x,y,z)
118640#endif
118641
118642/*
118643** If the inner loop was generated using a non-null pOrderBy argument,
118644** then the results were placed in a sorter.  After the loop is terminated
118645** we need to run the sorter and output the results.  The following
118646** routine generates the code needed to do that.
118647*/
118648static void generateSortTail(
118649  Parse *pParse,    /* Parsing context */
118650  Select *p,        /* The SELECT statement */
118651  SortCtx *pSort,   /* Information on the ORDER BY clause */
118652  int nColumn,      /* Number of columns of data */
118653  SelectDest *pDest /* Write the sorted results here */
118654){
118655  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
118656  int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
118657  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
118658  int addr;
118659  int addrOnce = 0;
118660  int iTab;
118661  ExprList *pOrderBy = pSort->pOrderBy;
118662  int eDest = pDest->eDest;
118663  int iParm = pDest->iSDParm;
118664  int regRow;
118665  int regRowid;
118666  int iCol;
118667  int nKey;
118668  int iSortTab;                   /* Sorter cursor to read from */
118669  int nSortData;                  /* Trailing values to read from sorter */
118670  int i;
118671  int bSeq;                       /* True if sorter record includes seq. no. */
118672  struct ExprList_item *aOutEx = p->pEList->a;
118673
118674  assert( addrBreak<0 );
118675  if( pSort->labelBkOut ){
118676    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
118677    sqlite3VdbeGoto(v, addrBreak);
118678    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
118679  }
118680  iTab = pSort->iECursor;
118681  if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
118682    regRowid = 0;
118683    regRow = pDest->iSdst;
118684    nSortData = nColumn;
118685  }else{
118686    regRowid = sqlite3GetTempReg(pParse);
118687    regRow = sqlite3GetTempRange(pParse, nColumn);
118688    nSortData = nColumn;
118689  }
118690  nKey = pOrderBy->nExpr - pSort->nOBSat;
118691  if( pSort->sortFlags & SORTFLAG_UseSorter ){
118692    int regSortOut = ++pParse->nMem;
118693    iSortTab = pParse->nTab++;
118694    if( pSort->labelBkOut ){
118695      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
118696    }
118697    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
118698    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
118699    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
118700    VdbeCoverage(v);
118701    codeOffset(v, p->iOffset, addrContinue);
118702    sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
118703    bSeq = 0;
118704  }else{
118705    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
118706    codeOffset(v, p->iOffset, addrContinue);
118707    iSortTab = iTab;
118708    bSeq = 1;
118709  }
118710  for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
118711    int iRead;
118712    if( aOutEx[i].u.x.iOrderByCol ){
118713      iRead = aOutEx[i].u.x.iOrderByCol-1;
118714    }else{
118715      iRead = iCol++;
118716    }
118717    sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
118718    VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
118719  }
118720  switch( eDest ){
118721    case SRT_Table:
118722    case SRT_EphemTab: {
118723      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
118724      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
118725      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
118726      break;
118727    }
118728#ifndef SQLITE_OMIT_SUBQUERY
118729    case SRT_Set: {
118730      assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
118731      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
118732                        pDest->zAffSdst, nColumn);
118733      sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
118734      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
118735      break;
118736    }
118737    case SRT_Mem: {
118738      /* The LIMIT clause will terminate the loop for us */
118739      break;
118740    }
118741#endif
118742    default: {
118743      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
118744      testcase( eDest==SRT_Output );
118745      testcase( eDest==SRT_Coroutine );
118746      if( eDest==SRT_Output ){
118747        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
118748        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
118749      }else{
118750        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
118751      }
118752      break;
118753    }
118754  }
118755  if( regRowid ){
118756    if( eDest==SRT_Set ){
118757      sqlite3ReleaseTempRange(pParse, regRow, nColumn);
118758    }else{
118759      sqlite3ReleaseTempReg(pParse, regRow);
118760    }
118761    sqlite3ReleaseTempReg(pParse, regRowid);
118762  }
118763  /* The bottom of the loop
118764  */
118765  sqlite3VdbeResolveLabel(v, addrContinue);
118766  if( pSort->sortFlags & SORTFLAG_UseSorter ){
118767    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
118768  }else{
118769    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
118770  }
118771  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
118772  sqlite3VdbeResolveLabel(v, addrBreak);
118773}
118774
118775/*
118776** Return a pointer to a string containing the 'declaration type' of the
118777** expression pExpr. The string may be treated as static by the caller.
118778**
118779** Also try to estimate the size of the returned value and return that
118780** result in *pEstWidth.
118781**
118782** The declaration type is the exact datatype definition extracted from the
118783** original CREATE TABLE statement if the expression is a column. The
118784** declaration type for a ROWID field is INTEGER. Exactly when an expression
118785** is considered a column can be complex in the presence of subqueries. The
118786** result-set expression in all of the following SELECT statements is
118787** considered a column by this function.
118788**
118789**   SELECT col FROM tbl;
118790**   SELECT (SELECT col FROM tbl;
118791**   SELECT (SELECT col FROM tbl);
118792**   SELECT abc FROM (SELECT col AS abc FROM tbl);
118793**
118794** The declaration type for any expression other than a column is NULL.
118795**
118796** This routine has either 3 or 6 parameters depending on whether or not
118797** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
118798*/
118799#ifdef SQLITE_ENABLE_COLUMN_METADATA
118800# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
118801#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
118802# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
118803#endif
118804static const char *columnTypeImpl(
118805  NameContext *pNC,
118806  Expr *pExpr,
118807#ifdef SQLITE_ENABLE_COLUMN_METADATA
118808  const char **pzOrigDb,
118809  const char **pzOrigTab,
118810  const char **pzOrigCol,
118811#endif
118812  u8 *pEstWidth
118813){
118814  char const *zType = 0;
118815  int j;
118816  u8 estWidth = 1;
118817#ifdef SQLITE_ENABLE_COLUMN_METADATA
118818  char const *zOrigDb = 0;
118819  char const *zOrigTab = 0;
118820  char const *zOrigCol = 0;
118821#endif
118822
118823  assert( pExpr!=0 );
118824  assert( pNC->pSrcList!=0 );
118825  switch( pExpr->op ){
118826    case TK_AGG_COLUMN:
118827    case TK_COLUMN: {
118828      /* The expression is a column. Locate the table the column is being
118829      ** extracted from in NameContext.pSrcList. This table may be real
118830      ** database table or a subquery.
118831      */
118832      Table *pTab = 0;            /* Table structure column is extracted from */
118833      Select *pS = 0;             /* Select the column is extracted from */
118834      int iCol = pExpr->iColumn;  /* Index of column in pTab */
118835      testcase( pExpr->op==TK_AGG_COLUMN );
118836      testcase( pExpr->op==TK_COLUMN );
118837      while( pNC && !pTab ){
118838        SrcList *pTabList = pNC->pSrcList;
118839        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
118840        if( j<pTabList->nSrc ){
118841          pTab = pTabList->a[j].pTab;
118842          pS = pTabList->a[j].pSelect;
118843        }else{
118844          pNC = pNC->pNext;
118845        }
118846      }
118847
118848      if( pTab==0 ){
118849        /* At one time, code such as "SELECT new.x" within a trigger would
118850        ** cause this condition to run.  Since then, we have restructured how
118851        ** trigger code is generated and so this condition is no longer
118852        ** possible. However, it can still be true for statements like
118853        ** the following:
118854        **
118855        **   CREATE TABLE t1(col INTEGER);
118856        **   SELECT (SELECT t1.col) FROM FROM t1;
118857        **
118858        ** when columnType() is called on the expression "t1.col" in the
118859        ** sub-select. In this case, set the column type to NULL, even
118860        ** though it should really be "INTEGER".
118861        **
118862        ** This is not a problem, as the column type of "t1.col" is never
118863        ** used. When columnType() is called on the expression
118864        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
118865        ** branch below.  */
118866        break;
118867      }
118868
118869      assert( pTab && pExpr->pTab==pTab );
118870      if( pS ){
118871        /* The "table" is actually a sub-select or a view in the FROM clause
118872        ** of the SELECT statement. Return the declaration type and origin
118873        ** data for the result-set column of the sub-select.
118874        */
118875        if( iCol>=0 && iCol<pS->pEList->nExpr ){
118876          /* If iCol is less than zero, then the expression requests the
118877          ** rowid of the sub-select or view. This expression is legal (see
118878          ** test case misc2.2.2) - it always evaluates to NULL.
118879          */
118880          NameContext sNC;
118881          Expr *p = pS->pEList->a[iCol].pExpr;
118882          sNC.pSrcList = pS->pSrc;
118883          sNC.pNext = pNC;
118884          sNC.pParse = pNC->pParse;
118885          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
118886        }
118887      }else if( pTab->pSchema ){
118888        /* A real table */
118889        assert( !pS );
118890        if( iCol<0 ) iCol = pTab->iPKey;
118891        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
118892#ifdef SQLITE_ENABLE_COLUMN_METADATA
118893        if( iCol<0 ){
118894          zType = "INTEGER";
118895          zOrigCol = "rowid";
118896        }else{
118897          zOrigCol = pTab->aCol[iCol].zName;
118898          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
118899          estWidth = pTab->aCol[iCol].szEst;
118900        }
118901        zOrigTab = pTab->zName;
118902        if( pNC->pParse ){
118903          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
118904          zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
118905        }
118906#else
118907        if( iCol<0 ){
118908          zType = "INTEGER";
118909        }else{
118910          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
118911          estWidth = pTab->aCol[iCol].szEst;
118912        }
118913#endif
118914      }
118915      break;
118916    }
118917#ifndef SQLITE_OMIT_SUBQUERY
118918    case TK_SELECT: {
118919      /* The expression is a sub-select. Return the declaration type and
118920      ** origin info for the single column in the result set of the SELECT
118921      ** statement.
118922      */
118923      NameContext sNC;
118924      Select *pS = pExpr->x.pSelect;
118925      Expr *p = pS->pEList->a[0].pExpr;
118926      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
118927      sNC.pSrcList = pS->pSrc;
118928      sNC.pNext = pNC;
118929      sNC.pParse = pNC->pParse;
118930      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
118931      break;
118932    }
118933#endif
118934  }
118935
118936#ifdef SQLITE_ENABLE_COLUMN_METADATA
118937  if( pzOrigDb ){
118938    assert( pzOrigTab && pzOrigCol );
118939    *pzOrigDb = zOrigDb;
118940    *pzOrigTab = zOrigTab;
118941    *pzOrigCol = zOrigCol;
118942  }
118943#endif
118944  if( pEstWidth ) *pEstWidth = estWidth;
118945  return zType;
118946}
118947
118948/*
118949** Generate code that will tell the VDBE the declaration types of columns
118950** in the result set.
118951*/
118952static void generateColumnTypes(
118953  Parse *pParse,      /* Parser context */
118954  SrcList *pTabList,  /* List of tables */
118955  ExprList *pEList    /* Expressions defining the result set */
118956){
118957#ifndef SQLITE_OMIT_DECLTYPE
118958  Vdbe *v = pParse->pVdbe;
118959  int i;
118960  NameContext sNC;
118961  sNC.pSrcList = pTabList;
118962  sNC.pParse = pParse;
118963  sNC.pNext = 0;
118964  for(i=0; i<pEList->nExpr; i++){
118965    Expr *p = pEList->a[i].pExpr;
118966    const char *zType;
118967#ifdef SQLITE_ENABLE_COLUMN_METADATA
118968    const char *zOrigDb = 0;
118969    const char *zOrigTab = 0;
118970    const char *zOrigCol = 0;
118971    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
118972
118973    /* The vdbe must make its own copy of the column-type and other
118974    ** column specific strings, in case the schema is reset before this
118975    ** virtual machine is deleted.
118976    */
118977    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
118978    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
118979    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
118980#else
118981    zType = columnType(&sNC, p, 0, 0, 0, 0);
118982#endif
118983    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
118984  }
118985#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
118986}
118987
118988
118989/*
118990** Compute the column names for a SELECT statement.
118991**
118992** The only guarantee that SQLite makes about column names is that if the
118993** column has an AS clause assigning it a name, that will be the name used.
118994** That is the only documented guarantee.  However, countless applications
118995** developed over the years have made baseless assumptions about column names
118996** and will break if those assumptions changes.  Hence, use extreme caution
118997** when modifying this routine to avoid breaking legacy.
118998**
118999** See Also: sqlite3ColumnsFromExprList()
119000**
119001** The PRAGMA short_column_names and PRAGMA full_column_names settings are
119002** deprecated.  The default setting is short=ON, full=OFF.  99.9% of all
119003** applications should operate this way.  Nevertheless, we need to support the
119004** other modes for legacy:
119005**
119006**    short=OFF, full=OFF:      Column name is the text of the expression has it
119007**                              originally appears in the SELECT statement.  In
119008**                              other words, the zSpan of the result expression.
119009**
119010**    short=ON, full=OFF:       (This is the default setting).  If the result
119011**                              refers directly to a table column, then the result
119012**                              column name is just the table column name: COLUMN.
119013**                              Otherwise use zSpan.
119014**
119015**    full=ON, short=ANY:       If the result refers directly to a table column,
119016**                              then the result column name with the table name
119017**                              prefix, ex: TABLE.COLUMN.  Otherwise use zSpan.
119018*/
119019static void generateColumnNames(
119020  Parse *pParse,      /* Parser context */
119021  Select *pSelect     /* Generate column names for this SELECT statement */
119022){
119023  Vdbe *v = pParse->pVdbe;
119024  int i;
119025  Table *pTab;
119026  SrcList *pTabList;
119027  ExprList *pEList;
119028  sqlite3 *db = pParse->db;
119029  int fullName;    /* TABLE.COLUMN if no AS clause and is a direct table ref */
119030  int srcName;     /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
119031
119032#ifndef SQLITE_OMIT_EXPLAIN
119033  /* If this is an EXPLAIN, skip this step */
119034  if( pParse->explain ){
119035    return;
119036  }
119037#endif
119038
119039  if( pParse->colNamesSet || db->mallocFailed ) return;
119040  /* Column names are determined by the left-most term of a compound select */
119041  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
119042  pTabList = pSelect->pSrc;
119043  pEList = pSelect->pEList;
119044  assert( v!=0 );
119045  assert( pTabList!=0 );
119046  pParse->colNamesSet = 1;
119047  fullName = (db->flags & SQLITE_FullColNames)!=0;
119048  srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
119049  sqlite3VdbeSetNumCols(v, pEList->nExpr);
119050  for(i=0; i<pEList->nExpr; i++){
119051    Expr *p = pEList->a[i].pExpr;
119052
119053    assert( p!=0 );
119054    if( pEList->a[i].zName ){
119055      /* An AS clause always takes first priority */
119056      char *zName = pEList->a[i].zName;
119057      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
119058    }else if( srcName && p->op==TK_COLUMN ){
119059      char *zCol;
119060      int iCol = p->iColumn;
119061      pTab = p->pTab;
119062      assert( pTab!=0 );
119063      if( iCol<0 ) iCol = pTab->iPKey;
119064      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
119065      if( iCol<0 ){
119066        zCol = "rowid";
119067      }else{
119068        zCol = pTab->aCol[iCol].zName;
119069      }
119070      if( fullName ){
119071        char *zName = 0;
119072        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
119073        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
119074      }else{
119075        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
119076      }
119077    }else{
119078      const char *z = pEList->a[i].zSpan;
119079      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
119080      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
119081    }
119082  }
119083  generateColumnTypes(pParse, pTabList, pEList);
119084}
119085
119086/*
119087** Given an expression list (which is really the list of expressions
119088** that form the result set of a SELECT statement) compute appropriate
119089** column names for a table that would hold the expression list.
119090**
119091** All column names will be unique.
119092**
119093** Only the column names are computed.  Column.zType, Column.zColl,
119094** and other fields of Column are zeroed.
119095**
119096** Return SQLITE_OK on success.  If a memory allocation error occurs,
119097** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
119098**
119099** The only guarantee that SQLite makes about column names is that if the
119100** column has an AS clause assigning it a name, that will be the name used.
119101** That is the only documented guarantee.  However, countless applications
119102** developed over the years have made baseless assumptions about column names
119103** and will break if those assumptions changes.  Hence, use extreme caution
119104** when modifying this routine to avoid breaking legacy.
119105**
119106** See Also: generateColumnNames()
119107*/
119108SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
119109  Parse *pParse,          /* Parsing context */
119110  ExprList *pEList,       /* Expr list from which to derive column names */
119111  i16 *pnCol,             /* Write the number of columns here */
119112  Column **paCol          /* Write the new column list here */
119113){
119114  sqlite3 *db = pParse->db;   /* Database connection */
119115  int i, j;                   /* Loop counters */
119116  u32 cnt;                    /* Index added to make the name unique */
119117  Column *aCol, *pCol;        /* For looping over result columns */
119118  int nCol;                   /* Number of columns in the result set */
119119  char *zName;                /* Column name */
119120  int nName;                  /* Size of name in zName[] */
119121  Hash ht;                    /* Hash table of column names */
119122
119123  sqlite3HashInit(&ht);
119124  if( pEList ){
119125    nCol = pEList->nExpr;
119126    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
119127    testcase( aCol==0 );
119128  }else{
119129    nCol = 0;
119130    aCol = 0;
119131  }
119132  assert( nCol==(i16)nCol );
119133  *pnCol = nCol;
119134  *paCol = aCol;
119135
119136  for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
119137    /* Get an appropriate name for the column
119138    */
119139    if( (zName = pEList->a[i].zName)!=0 ){
119140      /* If the column contains an "AS <name>" phrase, use <name> as the name */
119141    }else{
119142      Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
119143      while( pColExpr->op==TK_DOT ){
119144        pColExpr = pColExpr->pRight;
119145        assert( pColExpr!=0 );
119146      }
119147      if( pColExpr->op==TK_COLUMN && pColExpr->pTab!=0 ){
119148        /* For columns use the column name name */
119149        int iCol = pColExpr->iColumn;
119150        Table *pTab = pColExpr->pTab;
119151        if( iCol<0 ) iCol = pTab->iPKey;
119152        zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
119153      }else if( pColExpr->op==TK_ID ){
119154        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
119155        zName = pColExpr->u.zToken;
119156      }else{
119157        /* Use the original text of the column expression as its name */
119158        zName = pEList->a[i].zSpan;
119159      }
119160    }
119161    if( zName ){
119162      zName = sqlite3DbStrDup(db, zName);
119163    }else{
119164      zName = sqlite3MPrintf(db,"column%d",i+1);
119165    }
119166
119167    /* Make sure the column name is unique.  If the name is not unique,
119168    ** append an integer to the name so that it becomes unique.
119169    */
119170    cnt = 0;
119171    while( zName && sqlite3HashFind(&ht, zName)!=0 ){
119172      nName = sqlite3Strlen30(zName);
119173      if( nName>0 ){
119174        for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
119175        if( zName[j]==':' ) nName = j;
119176      }
119177      zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
119178      if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
119179    }
119180    pCol->zName = zName;
119181    sqlite3ColumnPropertiesFromName(0, pCol);
119182    if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
119183      sqlite3OomFault(db);
119184    }
119185  }
119186  sqlite3HashClear(&ht);
119187  if( db->mallocFailed ){
119188    for(j=0; j<i; j++){
119189      sqlite3DbFree(db, aCol[j].zName);
119190    }
119191    sqlite3DbFree(db, aCol);
119192    *paCol = 0;
119193    *pnCol = 0;
119194    return SQLITE_NOMEM_BKPT;
119195  }
119196  return SQLITE_OK;
119197}
119198
119199/*
119200** Add type and collation information to a column list based on
119201** a SELECT statement.
119202**
119203** The column list presumably came from selectColumnNamesFromExprList().
119204** The column list has only names, not types or collations.  This
119205** routine goes through and adds the types and collations.
119206**
119207** This routine requires that all identifiers in the SELECT
119208** statement be resolved.
119209*/
119210SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
119211  Parse *pParse,        /* Parsing contexts */
119212  Table *pTab,          /* Add column type information to this table */
119213  Select *pSelect       /* SELECT used to determine types and collations */
119214){
119215  sqlite3 *db = pParse->db;
119216  NameContext sNC;
119217  Column *pCol;
119218  CollSeq *pColl;
119219  int i;
119220  Expr *p;
119221  struct ExprList_item *a;
119222  u64 szAll = 0;
119223
119224  assert( pSelect!=0 );
119225  assert( (pSelect->selFlags & SF_Resolved)!=0 );
119226  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
119227  if( db->mallocFailed ) return;
119228  memset(&sNC, 0, sizeof(sNC));
119229  sNC.pSrcList = pSelect->pSrc;
119230  a = pSelect->pEList->a;
119231  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
119232    const char *zType;
119233    int n, m;
119234    p = a[i].pExpr;
119235    zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
119236    szAll += pCol->szEst;
119237    pCol->affinity = sqlite3ExprAffinity(p);
119238    if( zType && (m = sqlite3Strlen30(zType))>0 ){
119239      n = sqlite3Strlen30(pCol->zName);
119240      pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
119241      if( pCol->zName ){
119242        memcpy(&pCol->zName[n+1], zType, m+1);
119243        pCol->colFlags |= COLFLAG_HASTYPE;
119244      }
119245    }
119246    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
119247    pColl = sqlite3ExprCollSeq(pParse, p);
119248    if( pColl && pCol->zColl==0 ){
119249      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
119250    }
119251  }
119252  pTab->szTabRow = sqlite3LogEst(szAll*4);
119253}
119254
119255/*
119256** Given a SELECT statement, generate a Table structure that describes
119257** the result set of that SELECT.
119258*/
119259SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
119260  Table *pTab;
119261  sqlite3 *db = pParse->db;
119262  int savedFlags;
119263
119264  savedFlags = db->flags;
119265  db->flags &= ~SQLITE_FullColNames;
119266  db->flags |= SQLITE_ShortColNames;
119267  sqlite3SelectPrep(pParse, pSelect, 0);
119268  if( pParse->nErr ) return 0;
119269  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
119270  db->flags = savedFlags;
119271  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
119272  if( pTab==0 ){
119273    return 0;
119274  }
119275  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
119276  ** is disabled */
119277  assert( db->lookaside.bDisable );
119278  pTab->nTabRef = 1;
119279  pTab->zName = 0;
119280  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
119281  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
119282  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
119283  pTab->iPKey = -1;
119284  if( db->mallocFailed ){
119285    sqlite3DeleteTable(db, pTab);
119286    return 0;
119287  }
119288  return pTab;
119289}
119290
119291/*
119292** Get a VDBE for the given parser context.  Create a new one if necessary.
119293** If an error occurs, return NULL and leave a message in pParse.
119294*/
119295static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
119296  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
119297  if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1);
119298  if( pParse->pToplevel==0
119299   && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
119300  ){
119301    pParse->okConstFactor = 1;
119302  }
119303  return v;
119304}
119305SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
119306  Vdbe *v = pParse->pVdbe;
119307  return v ? v : allocVdbe(pParse);
119308}
119309
119310
119311/*
119312** Compute the iLimit and iOffset fields of the SELECT based on the
119313** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
119314** that appear in the original SQL statement after the LIMIT and OFFSET
119315** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
119316** are the integer memory register numbers for counters used to compute
119317** the limit and offset.  If there is no limit and/or offset, then
119318** iLimit and iOffset are negative.
119319**
119320** This routine changes the values of iLimit and iOffset only if
119321** a limit or offset is defined by pLimit and pOffset.  iLimit and
119322** iOffset should have been preset to appropriate default values (zero)
119323** prior to calling this routine.
119324**
119325** The iOffset register (if it exists) is initialized to the value
119326** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
119327** iOffset+1 is initialized to LIMIT+OFFSET.
119328**
119329** Only if pLimit!=0 or pOffset!=0 do the limit registers get
119330** redefined.  The UNION ALL operator uses this property to force
119331** the reuse of the same limit and offset registers across multiple
119332** SELECT statements.
119333*/
119334static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
119335  Vdbe *v = 0;
119336  int iLimit = 0;
119337  int iOffset;
119338  int n;
119339  if( p->iLimit ) return;
119340
119341  /*
119342  ** "LIMIT -1" always shows all rows.  There is some
119343  ** controversy about what the correct behavior should be.
119344  ** The current implementation interprets "LIMIT 0" to mean
119345  ** no rows.
119346  */
119347  sqlite3ExprCacheClear(pParse);
119348  assert( p->pOffset==0 || p->pLimit!=0 );
119349  if( p->pLimit ){
119350    p->iLimit = iLimit = ++pParse->nMem;
119351    v = sqlite3GetVdbe(pParse);
119352    assert( v!=0 );
119353    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
119354      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
119355      VdbeComment((v, "LIMIT counter"));
119356      if( n==0 ){
119357        sqlite3VdbeGoto(v, iBreak);
119358      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
119359        p->nSelectRow = sqlite3LogEst((u64)n);
119360        p->selFlags |= SF_FixedLimit;
119361      }
119362    }else{
119363      sqlite3ExprCode(pParse, p->pLimit, iLimit);
119364      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
119365      VdbeComment((v, "LIMIT counter"));
119366      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
119367    }
119368    if( p->pOffset ){
119369      p->iOffset = iOffset = ++pParse->nMem;
119370      pParse->nMem++;   /* Allocate an extra register for limit+offset */
119371      sqlite3ExprCode(pParse, p->pOffset, iOffset);
119372      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
119373      VdbeComment((v, "OFFSET counter"));
119374      sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
119375      VdbeComment((v, "LIMIT+OFFSET"));
119376    }
119377  }
119378}
119379
119380#ifndef SQLITE_OMIT_COMPOUND_SELECT
119381/*
119382** Return the appropriate collating sequence for the iCol-th column of
119383** the result set for the compound-select statement "p".  Return NULL if
119384** the column has no default collating sequence.
119385**
119386** The collating sequence for the compound select is taken from the
119387** left-most term of the select that has a collating sequence.
119388*/
119389static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
119390  CollSeq *pRet;
119391  if( p->pPrior ){
119392    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
119393  }else{
119394    pRet = 0;
119395  }
119396  assert( iCol>=0 );
119397  /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
119398  ** have been thrown during name resolution and we would not have gotten
119399  ** this far */
119400  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
119401    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
119402  }
119403  return pRet;
119404}
119405
119406/*
119407** The select statement passed as the second parameter is a compound SELECT
119408** with an ORDER BY clause. This function allocates and returns a KeyInfo
119409** structure suitable for implementing the ORDER BY.
119410**
119411** Space to hold the KeyInfo structure is obtained from malloc. The calling
119412** function is responsible for ensuring that this structure is eventually
119413** freed.
119414*/
119415static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
119416  ExprList *pOrderBy = p->pOrderBy;
119417  int nOrderBy = p->pOrderBy->nExpr;
119418  sqlite3 *db = pParse->db;
119419  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
119420  if( pRet ){
119421    int i;
119422    for(i=0; i<nOrderBy; i++){
119423      struct ExprList_item *pItem = &pOrderBy->a[i];
119424      Expr *pTerm = pItem->pExpr;
119425      CollSeq *pColl;
119426
119427      if( pTerm->flags & EP_Collate ){
119428        pColl = sqlite3ExprCollSeq(pParse, pTerm);
119429      }else{
119430        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
119431        if( pColl==0 ) pColl = db->pDfltColl;
119432        pOrderBy->a[i].pExpr =
119433          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
119434      }
119435      assert( sqlite3KeyInfoIsWriteable(pRet) );
119436      pRet->aColl[i] = pColl;
119437      pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
119438    }
119439  }
119440
119441  return pRet;
119442}
119443
119444#ifndef SQLITE_OMIT_CTE
119445/*
119446** This routine generates VDBE code to compute the content of a WITH RECURSIVE
119447** query of the form:
119448**
119449**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
119450**                         \___________/             \_______________/
119451**                           p->pPrior                      p
119452**
119453**
119454** There is exactly one reference to the recursive-table in the FROM clause
119455** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
119456**
119457** The setup-query runs once to generate an initial set of rows that go
119458** into a Queue table.  Rows are extracted from the Queue table one by
119459** one.  Each row extracted from Queue is output to pDest.  Then the single
119460** extracted row (now in the iCurrent table) becomes the content of the
119461** recursive-table for a recursive-query run.  The output of the recursive-query
119462** is added back into the Queue table.  Then another row is extracted from Queue
119463** and the iteration continues until the Queue table is empty.
119464**
119465** If the compound query operator is UNION then no duplicate rows are ever
119466** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
119467** that have ever been inserted into Queue and causes duplicates to be
119468** discarded.  If the operator is UNION ALL, then duplicates are allowed.
119469**
119470** If the query has an ORDER BY, then entries in the Queue table are kept in
119471** ORDER BY order and the first entry is extracted for each cycle.  Without
119472** an ORDER BY, the Queue table is just a FIFO.
119473**
119474** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
119475** have been output to pDest.  A LIMIT of zero means to output no rows and a
119476** negative LIMIT means to output all rows.  If there is also an OFFSET clause
119477** with a positive value, then the first OFFSET outputs are discarded rather
119478** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
119479** rows have been skipped.
119480*/
119481static void generateWithRecursiveQuery(
119482  Parse *pParse,        /* Parsing context */
119483  Select *p,            /* The recursive SELECT to be coded */
119484  SelectDest *pDest     /* What to do with query results */
119485){
119486  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
119487  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
119488  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
119489  Select *pSetup = p->pPrior;   /* The setup query */
119490  int addrTop;                  /* Top of the loop */
119491  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
119492  int iCurrent = 0;             /* The Current table */
119493  int regCurrent;               /* Register holding Current table */
119494  int iQueue;                   /* The Queue table */
119495  int iDistinct = 0;            /* To ensure unique results if UNION */
119496  int eDest = SRT_Fifo;         /* How to write to Queue */
119497  SelectDest destQueue;         /* SelectDest targetting the Queue table */
119498  int i;                        /* Loop counter */
119499  int rc;                       /* Result code */
119500  ExprList *pOrderBy;           /* The ORDER BY clause */
119501  Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
119502  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
119503
119504  /* Obtain authorization to do a recursive query */
119505  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
119506
119507  /* Process the LIMIT and OFFSET clauses, if they exist */
119508  addrBreak = sqlite3VdbeMakeLabel(v);
119509  p->nSelectRow = 320;  /* 4 billion rows */
119510  computeLimitRegisters(pParse, p, addrBreak);
119511  pLimit = p->pLimit;
119512  pOffset = p->pOffset;
119513  regLimit = p->iLimit;
119514  regOffset = p->iOffset;
119515  p->pLimit = p->pOffset = 0;
119516  p->iLimit = p->iOffset = 0;
119517  pOrderBy = p->pOrderBy;
119518
119519  /* Locate the cursor number of the Current table */
119520  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
119521    if( pSrc->a[i].fg.isRecursive ){
119522      iCurrent = pSrc->a[i].iCursor;
119523      break;
119524    }
119525  }
119526
119527  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
119528  ** the Distinct table must be exactly one greater than Queue in order
119529  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
119530  iQueue = pParse->nTab++;
119531  if( p->op==TK_UNION ){
119532    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
119533    iDistinct = pParse->nTab++;
119534  }else{
119535    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
119536  }
119537  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
119538
119539  /* Allocate cursors for Current, Queue, and Distinct. */
119540  regCurrent = ++pParse->nMem;
119541  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
119542  if( pOrderBy ){
119543    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
119544    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
119545                      (char*)pKeyInfo, P4_KEYINFO);
119546    destQueue.pOrderBy = pOrderBy;
119547  }else{
119548    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
119549  }
119550  VdbeComment((v, "Queue table"));
119551  if( iDistinct ){
119552    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
119553    p->selFlags |= SF_UsesEphemeral;
119554  }
119555
119556  /* Detach the ORDER BY clause from the compound SELECT */
119557  p->pOrderBy = 0;
119558
119559  /* Store the results of the setup-query in Queue. */
119560  pSetup->pNext = 0;
119561  rc = sqlite3Select(pParse, pSetup, &destQueue);
119562  pSetup->pNext = p;
119563  if( rc ) goto end_of_recursive_query;
119564
119565  /* Find the next row in the Queue and output that row */
119566  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
119567
119568  /* Transfer the next row in Queue over to Current */
119569  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
119570  if( pOrderBy ){
119571    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
119572  }else{
119573    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
119574  }
119575  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
119576
119577  /* Output the single row in Current */
119578  addrCont = sqlite3VdbeMakeLabel(v);
119579  codeOffset(v, regOffset, addrCont);
119580  selectInnerLoop(pParse, p, p->pEList, iCurrent,
119581      0, 0, pDest, addrCont, addrBreak);
119582  if( regLimit ){
119583    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
119584    VdbeCoverage(v);
119585  }
119586  sqlite3VdbeResolveLabel(v, addrCont);
119587
119588  /* Execute the recursive SELECT taking the single row in Current as
119589  ** the value for the recursive-table. Store the results in the Queue.
119590  */
119591  if( p->selFlags & SF_Aggregate ){
119592    sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
119593  }else{
119594    p->pPrior = 0;
119595    sqlite3Select(pParse, p, &destQueue);
119596    assert( p->pPrior==0 );
119597    p->pPrior = pSetup;
119598  }
119599
119600  /* Keep running the loop until the Queue is empty */
119601  sqlite3VdbeGoto(v, addrTop);
119602  sqlite3VdbeResolveLabel(v, addrBreak);
119603
119604end_of_recursive_query:
119605  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
119606  p->pOrderBy = pOrderBy;
119607  p->pLimit = pLimit;
119608  p->pOffset = pOffset;
119609  return;
119610}
119611#endif /* SQLITE_OMIT_CTE */
119612
119613/* Forward references */
119614static int multiSelectOrderBy(
119615  Parse *pParse,        /* Parsing context */
119616  Select *p,            /* The right-most of SELECTs to be coded */
119617  SelectDest *pDest     /* What to do with query results */
119618);
119619
119620/*
119621** Handle the special case of a compound-select that originates from a
119622** VALUES clause.  By handling this as a special case, we avoid deep
119623** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
119624** on a VALUES clause.
119625**
119626** Because the Select object originates from a VALUES clause:
119627**   (1) It has no LIMIT or OFFSET
119628**   (2) All terms are UNION ALL
119629**   (3) There is no ORDER BY clause
119630*/
119631static int multiSelectValues(
119632  Parse *pParse,        /* Parsing context */
119633  Select *p,            /* The right-most of SELECTs to be coded */
119634  SelectDest *pDest     /* What to do with query results */
119635){
119636  Select *pPrior;
119637  int nRow = 1;
119638  int rc = 0;
119639  assert( p->selFlags & SF_MultiValue );
119640  do{
119641    assert( p->selFlags & SF_Values );
119642    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
119643    assert( p->pLimit==0 );
119644    assert( p->pOffset==0 );
119645    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
119646    if( p->pPrior==0 ) break;
119647    assert( p->pPrior->pNext==p );
119648    p = p->pPrior;
119649    nRow++;
119650  }while(1);
119651  while( p ){
119652    pPrior = p->pPrior;
119653    p->pPrior = 0;
119654    rc = sqlite3Select(pParse, p, pDest);
119655    p->pPrior = pPrior;
119656    if( rc ) break;
119657    p->nSelectRow = nRow;
119658    p = p->pNext;
119659  }
119660  return rc;
119661}
119662
119663/*
119664** This routine is called to process a compound query form from
119665** two or more separate queries using UNION, UNION ALL, EXCEPT, or
119666** INTERSECT
119667**
119668** "p" points to the right-most of the two queries.  the query on the
119669** left is p->pPrior.  The left query could also be a compound query
119670** in which case this routine will be called recursively.
119671**
119672** The results of the total query are to be written into a destination
119673** of type eDest with parameter iParm.
119674**
119675** Example 1:  Consider a three-way compound SQL statement.
119676**
119677**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
119678**
119679** This statement is parsed up as follows:
119680**
119681**     SELECT c FROM t3
119682**      |
119683**      `----->  SELECT b FROM t2
119684**                |
119685**                `------>  SELECT a FROM t1
119686**
119687** The arrows in the diagram above represent the Select.pPrior pointer.
119688** So if this routine is called with p equal to the t3 query, then
119689** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
119690**
119691** Notice that because of the way SQLite parses compound SELECTs, the
119692** individual selects always group from left to right.
119693*/
119694static int multiSelect(
119695  Parse *pParse,        /* Parsing context */
119696  Select *p,            /* The right-most of SELECTs to be coded */
119697  SelectDest *pDest     /* What to do with query results */
119698){
119699  int rc = SQLITE_OK;   /* Success code from a subroutine */
119700  Select *pPrior;       /* Another SELECT immediately to our left */
119701  Vdbe *v;              /* Generate code to this VDBE */
119702  SelectDest dest;      /* Alternative data destination */
119703  Select *pDelete = 0;  /* Chain of simple selects to delete */
119704  sqlite3 *db;          /* Database connection */
119705#ifndef SQLITE_OMIT_EXPLAIN
119706  int iSub1 = 0;        /* EQP id of left-hand query */
119707  int iSub2 = 0;        /* EQP id of right-hand query */
119708#endif
119709
119710  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
119711  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
119712  */
119713  assert( p && p->pPrior );  /* Calling function guarantees this much */
119714  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
119715  db = pParse->db;
119716  pPrior = p->pPrior;
119717  dest = *pDest;
119718  if( pPrior->pOrderBy ){
119719    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
119720      selectOpName(p->op));
119721    rc = 1;
119722    goto multi_select_end;
119723  }
119724  if( pPrior->pLimit ){
119725    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
119726      selectOpName(p->op));
119727    rc = 1;
119728    goto multi_select_end;
119729  }
119730
119731  v = sqlite3GetVdbe(pParse);
119732  assert( v!=0 );  /* The VDBE already created by calling function */
119733
119734  /* Create the destination temporary table if necessary
119735  */
119736  if( dest.eDest==SRT_EphemTab ){
119737    assert( p->pEList );
119738    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
119739    dest.eDest = SRT_Table;
119740  }
119741
119742  /* Special handling for a compound-select that originates as a VALUES clause.
119743  */
119744  if( p->selFlags & SF_MultiValue ){
119745    rc = multiSelectValues(pParse, p, &dest);
119746    goto multi_select_end;
119747  }
119748
119749  /* Make sure all SELECTs in the statement have the same number of elements
119750  ** in their result sets.
119751  */
119752  assert( p->pEList && pPrior->pEList );
119753  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
119754
119755#ifndef SQLITE_OMIT_CTE
119756  if( p->selFlags & SF_Recursive ){
119757    generateWithRecursiveQuery(pParse, p, &dest);
119758  }else
119759#endif
119760
119761  /* Compound SELECTs that have an ORDER BY clause are handled separately.
119762  */
119763  if( p->pOrderBy ){
119764    return multiSelectOrderBy(pParse, p, pDest);
119765  }else
119766
119767  /* Generate code for the left and right SELECT statements.
119768  */
119769  switch( p->op ){
119770    case TK_ALL: {
119771      int addr = 0;
119772      int nLimit;
119773      assert( !pPrior->pLimit );
119774      pPrior->iLimit = p->iLimit;
119775      pPrior->iOffset = p->iOffset;
119776      pPrior->pLimit = p->pLimit;
119777      pPrior->pOffset = p->pOffset;
119778      explainSetInteger(iSub1, pParse->iNextSelectId);
119779      rc = sqlite3Select(pParse, pPrior, &dest);
119780      p->pLimit = 0;
119781      p->pOffset = 0;
119782      if( rc ){
119783        goto multi_select_end;
119784      }
119785      p->pPrior = 0;
119786      p->iLimit = pPrior->iLimit;
119787      p->iOffset = pPrior->iOffset;
119788      if( p->iLimit ){
119789        addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
119790        VdbeComment((v, "Jump ahead if LIMIT reached"));
119791        if( p->iOffset ){
119792          sqlite3VdbeAddOp3(v, OP_OffsetLimit,
119793                            p->iLimit, p->iOffset+1, p->iOffset);
119794        }
119795      }
119796      explainSetInteger(iSub2, pParse->iNextSelectId);
119797      rc = sqlite3Select(pParse, p, &dest);
119798      testcase( rc!=SQLITE_OK );
119799      pDelete = p->pPrior;
119800      p->pPrior = pPrior;
119801      p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
119802      if( pPrior->pLimit
119803       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
119804       && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
119805      ){
119806        p->nSelectRow = sqlite3LogEst((u64)nLimit);
119807      }
119808      if( addr ){
119809        sqlite3VdbeJumpHere(v, addr);
119810      }
119811      break;
119812    }
119813    case TK_EXCEPT:
119814    case TK_UNION: {
119815      int unionTab;    /* Cursor number of the temporary table holding result */
119816      u8 op = 0;       /* One of the SRT_ operations to apply to self */
119817      int priorOp;     /* The SRT_ operation to apply to prior selects */
119818      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
119819      int addr;
119820      SelectDest uniondest;
119821
119822      testcase( p->op==TK_EXCEPT );
119823      testcase( p->op==TK_UNION );
119824      priorOp = SRT_Union;
119825      if( dest.eDest==priorOp ){
119826        /* We can reuse a temporary table generated by a SELECT to our
119827        ** right.
119828        */
119829        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
119830        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
119831        unionTab = dest.iSDParm;
119832      }else{
119833        /* We will need to create our own temporary table to hold the
119834        ** intermediate results.
119835        */
119836        unionTab = pParse->nTab++;
119837        assert( p->pOrderBy==0 );
119838        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
119839        assert( p->addrOpenEphm[0] == -1 );
119840        p->addrOpenEphm[0] = addr;
119841        findRightmost(p)->selFlags |= SF_UsesEphemeral;
119842        assert( p->pEList );
119843      }
119844
119845      /* Code the SELECT statements to our left
119846      */
119847      assert( !pPrior->pOrderBy );
119848      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
119849      explainSetInteger(iSub1, pParse->iNextSelectId);
119850      rc = sqlite3Select(pParse, pPrior, &uniondest);
119851      if( rc ){
119852        goto multi_select_end;
119853      }
119854
119855      /* Code the current SELECT statement
119856      */
119857      if( p->op==TK_EXCEPT ){
119858        op = SRT_Except;
119859      }else{
119860        assert( p->op==TK_UNION );
119861        op = SRT_Union;
119862      }
119863      p->pPrior = 0;
119864      pLimit = p->pLimit;
119865      p->pLimit = 0;
119866      pOffset = p->pOffset;
119867      p->pOffset = 0;
119868      uniondest.eDest = op;
119869      explainSetInteger(iSub2, pParse->iNextSelectId);
119870      rc = sqlite3Select(pParse, p, &uniondest);
119871      testcase( rc!=SQLITE_OK );
119872      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
119873      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
119874      sqlite3ExprListDelete(db, p->pOrderBy);
119875      pDelete = p->pPrior;
119876      p->pPrior = pPrior;
119877      p->pOrderBy = 0;
119878      if( p->op==TK_UNION ){
119879        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
119880      }
119881      sqlite3ExprDelete(db, p->pLimit);
119882      p->pLimit = pLimit;
119883      p->pOffset = pOffset;
119884      p->iLimit = 0;
119885      p->iOffset = 0;
119886
119887      /* Convert the data in the temporary table into whatever form
119888      ** it is that we currently need.
119889      */
119890      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
119891      if( dest.eDest!=priorOp ){
119892        int iCont, iBreak, iStart;
119893        assert( p->pEList );
119894        iBreak = sqlite3VdbeMakeLabel(v);
119895        iCont = sqlite3VdbeMakeLabel(v);
119896        computeLimitRegisters(pParse, p, iBreak);
119897        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
119898        iStart = sqlite3VdbeCurrentAddr(v);
119899        selectInnerLoop(pParse, p, p->pEList, unionTab,
119900                        0, 0, &dest, iCont, iBreak);
119901        sqlite3VdbeResolveLabel(v, iCont);
119902        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
119903        sqlite3VdbeResolveLabel(v, iBreak);
119904        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
119905      }
119906      break;
119907    }
119908    default: assert( p->op==TK_INTERSECT ); {
119909      int tab1, tab2;
119910      int iCont, iBreak, iStart;
119911      Expr *pLimit, *pOffset;
119912      int addr;
119913      SelectDest intersectdest;
119914      int r1;
119915
119916      /* INTERSECT is different from the others since it requires
119917      ** two temporary tables.  Hence it has its own case.  Begin
119918      ** by allocating the tables we will need.
119919      */
119920      tab1 = pParse->nTab++;
119921      tab2 = pParse->nTab++;
119922      assert( p->pOrderBy==0 );
119923
119924      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
119925      assert( p->addrOpenEphm[0] == -1 );
119926      p->addrOpenEphm[0] = addr;
119927      findRightmost(p)->selFlags |= SF_UsesEphemeral;
119928      assert( p->pEList );
119929
119930      /* Code the SELECTs to our left into temporary table "tab1".
119931      */
119932      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
119933      explainSetInteger(iSub1, pParse->iNextSelectId);
119934      rc = sqlite3Select(pParse, pPrior, &intersectdest);
119935      if( rc ){
119936        goto multi_select_end;
119937      }
119938
119939      /* Code the current SELECT into temporary table "tab2"
119940      */
119941      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
119942      assert( p->addrOpenEphm[1] == -1 );
119943      p->addrOpenEphm[1] = addr;
119944      p->pPrior = 0;
119945      pLimit = p->pLimit;
119946      p->pLimit = 0;
119947      pOffset = p->pOffset;
119948      p->pOffset = 0;
119949      intersectdest.iSDParm = tab2;
119950      explainSetInteger(iSub2, pParse->iNextSelectId);
119951      rc = sqlite3Select(pParse, p, &intersectdest);
119952      testcase( rc!=SQLITE_OK );
119953      pDelete = p->pPrior;
119954      p->pPrior = pPrior;
119955      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
119956      sqlite3ExprDelete(db, p->pLimit);
119957      p->pLimit = pLimit;
119958      p->pOffset = pOffset;
119959
119960      /* Generate code to take the intersection of the two temporary
119961      ** tables.
119962      */
119963      assert( p->pEList );
119964      iBreak = sqlite3VdbeMakeLabel(v);
119965      iCont = sqlite3VdbeMakeLabel(v);
119966      computeLimitRegisters(pParse, p, iBreak);
119967      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
119968      r1 = sqlite3GetTempReg(pParse);
119969      iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
119970      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
119971      sqlite3ReleaseTempReg(pParse, r1);
119972      selectInnerLoop(pParse, p, p->pEList, tab1,
119973                      0, 0, &dest, iCont, iBreak);
119974      sqlite3VdbeResolveLabel(v, iCont);
119975      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
119976      sqlite3VdbeResolveLabel(v, iBreak);
119977      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
119978      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
119979      break;
119980    }
119981  }
119982
119983  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
119984
119985  /* Compute collating sequences used by
119986  ** temporary tables needed to implement the compound select.
119987  ** Attach the KeyInfo structure to all temporary tables.
119988  **
119989  ** This section is run by the right-most SELECT statement only.
119990  ** SELECT statements to the left always skip this part.  The right-most
119991  ** SELECT might also skip this part if it has no ORDER BY clause and
119992  ** no temp tables are required.
119993  */
119994  if( p->selFlags & SF_UsesEphemeral ){
119995    int i;                        /* Loop counter */
119996    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
119997    Select *pLoop;                /* For looping through SELECT statements */
119998    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
119999    int nCol;                     /* Number of columns in result set */
120000
120001    assert( p->pNext==0 );
120002    nCol = p->pEList->nExpr;
120003    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
120004    if( !pKeyInfo ){
120005      rc = SQLITE_NOMEM_BKPT;
120006      goto multi_select_end;
120007    }
120008    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
120009      *apColl = multiSelectCollSeq(pParse, p, i);
120010      if( 0==*apColl ){
120011        *apColl = db->pDfltColl;
120012      }
120013    }
120014
120015    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
120016      for(i=0; i<2; i++){
120017        int addr = pLoop->addrOpenEphm[i];
120018        if( addr<0 ){
120019          /* If [0] is unused then [1] is also unused.  So we can
120020          ** always safely abort as soon as the first unused slot is found */
120021          assert( pLoop->addrOpenEphm[1]<0 );
120022          break;
120023        }
120024        sqlite3VdbeChangeP2(v, addr, nCol);
120025        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
120026                            P4_KEYINFO);
120027        pLoop->addrOpenEphm[i] = -1;
120028      }
120029    }
120030    sqlite3KeyInfoUnref(pKeyInfo);
120031  }
120032
120033multi_select_end:
120034  pDest->iSdst = dest.iSdst;
120035  pDest->nSdst = dest.nSdst;
120036  sqlite3SelectDelete(db, pDelete);
120037  return rc;
120038}
120039#endif /* SQLITE_OMIT_COMPOUND_SELECT */
120040
120041/*
120042** Error message for when two or more terms of a compound select have different
120043** size result sets.
120044*/
120045SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
120046  if( p->selFlags & SF_Values ){
120047    sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
120048  }else{
120049    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
120050      " do not have the same number of result columns", selectOpName(p->op));
120051  }
120052}
120053
120054/*
120055** Code an output subroutine for a coroutine implementation of a
120056** SELECT statment.
120057**
120058** The data to be output is contained in pIn->iSdst.  There are
120059** pIn->nSdst columns to be output.  pDest is where the output should
120060** be sent.
120061**
120062** regReturn is the number of the register holding the subroutine
120063** return address.
120064**
120065** If regPrev>0 then it is the first register in a vector that
120066** records the previous output.  mem[regPrev] is a flag that is false
120067** if there has been no previous output.  If regPrev>0 then code is
120068** generated to suppress duplicates.  pKeyInfo is used for comparing
120069** keys.
120070**
120071** If the LIMIT found in p->iLimit is reached, jump immediately to
120072** iBreak.
120073*/
120074static int generateOutputSubroutine(
120075  Parse *pParse,          /* Parsing context */
120076  Select *p,              /* The SELECT statement */
120077  SelectDest *pIn,        /* Coroutine supplying data */
120078  SelectDest *pDest,      /* Where to send the data */
120079  int regReturn,          /* The return address register */
120080  int regPrev,            /* Previous result register.  No uniqueness if 0 */
120081  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
120082  int iBreak              /* Jump here if we hit the LIMIT */
120083){
120084  Vdbe *v = pParse->pVdbe;
120085  int iContinue;
120086  int addr;
120087
120088  addr = sqlite3VdbeCurrentAddr(v);
120089  iContinue = sqlite3VdbeMakeLabel(v);
120090
120091  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
120092  */
120093  if( regPrev ){
120094    int addr1, addr2;
120095    addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
120096    addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
120097                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
120098    sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
120099    sqlite3VdbeJumpHere(v, addr1);
120100    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
120101    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
120102  }
120103  if( pParse->db->mallocFailed ) return 0;
120104
120105  /* Suppress the first OFFSET entries if there is an OFFSET clause
120106  */
120107  codeOffset(v, p->iOffset, iContinue);
120108
120109  assert( pDest->eDest!=SRT_Exists );
120110  assert( pDest->eDest!=SRT_Table );
120111  switch( pDest->eDest ){
120112    /* Store the result as data using a unique key.
120113    */
120114    case SRT_EphemTab: {
120115      int r1 = sqlite3GetTempReg(pParse);
120116      int r2 = sqlite3GetTempReg(pParse);
120117      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
120118      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
120119      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
120120      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
120121      sqlite3ReleaseTempReg(pParse, r2);
120122      sqlite3ReleaseTempReg(pParse, r1);
120123      break;
120124    }
120125
120126#ifndef SQLITE_OMIT_SUBQUERY
120127    /* If we are creating a set for an "expr IN (SELECT ...)".
120128    */
120129    case SRT_Set: {
120130      int r1;
120131      testcase( pIn->nSdst>1 );
120132      r1 = sqlite3GetTempReg(pParse);
120133      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
120134          r1, pDest->zAffSdst, pIn->nSdst);
120135      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
120136      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
120137                           pIn->iSdst, pIn->nSdst);
120138      sqlite3ReleaseTempReg(pParse, r1);
120139      break;
120140    }
120141
120142    /* If this is a scalar select that is part of an expression, then
120143    ** store the results in the appropriate memory cell and break out
120144    ** of the scan loop.
120145    */
120146    case SRT_Mem: {
120147      assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
120148      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
120149      /* The LIMIT clause will jump out of the loop for us */
120150      break;
120151    }
120152#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
120153
120154    /* The results are stored in a sequence of registers
120155    ** starting at pDest->iSdst.  Then the co-routine yields.
120156    */
120157    case SRT_Coroutine: {
120158      if( pDest->iSdst==0 ){
120159        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
120160        pDest->nSdst = pIn->nSdst;
120161      }
120162      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
120163      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
120164      break;
120165    }
120166
120167    /* If none of the above, then the result destination must be
120168    ** SRT_Output.  This routine is never called with any other
120169    ** destination other than the ones handled above or SRT_Output.
120170    **
120171    ** For SRT_Output, results are stored in a sequence of registers.
120172    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
120173    ** return the next row of result.
120174    */
120175    default: {
120176      assert( pDest->eDest==SRT_Output );
120177      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
120178      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
120179      break;
120180    }
120181  }
120182
120183  /* Jump to the end of the loop if the LIMIT is reached.
120184  */
120185  if( p->iLimit ){
120186    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
120187  }
120188
120189  /* Generate the subroutine return
120190  */
120191  sqlite3VdbeResolveLabel(v, iContinue);
120192  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
120193
120194  return addr;
120195}
120196
120197/*
120198** Alternative compound select code generator for cases when there
120199** is an ORDER BY clause.
120200**
120201** We assume a query of the following form:
120202**
120203**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
120204**
120205** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
120206** is to code both <selectA> and <selectB> with the ORDER BY clause as
120207** co-routines.  Then run the co-routines in parallel and merge the results
120208** into the output.  In addition to the two coroutines (called selectA and
120209** selectB) there are 7 subroutines:
120210**
120211**    outA:    Move the output of the selectA coroutine into the output
120212**             of the compound query.
120213**
120214**    outB:    Move the output of the selectB coroutine into the output
120215**             of the compound query.  (Only generated for UNION and
120216**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
120217**             appears only in B.)
120218**
120219**    AltB:    Called when there is data from both coroutines and A<B.
120220**
120221**    AeqB:    Called when there is data from both coroutines and A==B.
120222**
120223**    AgtB:    Called when there is data from both coroutines and A>B.
120224**
120225**    EofA:    Called when data is exhausted from selectA.
120226**
120227**    EofB:    Called when data is exhausted from selectB.
120228**
120229** The implementation of the latter five subroutines depend on which
120230** <operator> is used:
120231**
120232**
120233**             UNION ALL         UNION            EXCEPT          INTERSECT
120234**          -------------  -----------------  --------------  -----------------
120235**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
120236**
120237**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
120238**
120239**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
120240**
120241**   EofA:   outB, nextB      outB, nextB          halt             halt
120242**
120243**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
120244**
120245** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
120246** causes an immediate jump to EofA and an EOF on B following nextB causes
120247** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
120248** following nextX causes a jump to the end of the select processing.
120249**
120250** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
120251** within the output subroutine.  The regPrev register set holds the previously
120252** output value.  A comparison is made against this value and the output
120253** is skipped if the next results would be the same as the previous.
120254**
120255** The implementation plan is to implement the two coroutines and seven
120256** subroutines first, then put the control logic at the bottom.  Like this:
120257**
120258**          goto Init
120259**     coA: coroutine for left query (A)
120260**     coB: coroutine for right query (B)
120261**    outA: output one row of A
120262**    outB: output one row of B (UNION and UNION ALL only)
120263**    EofA: ...
120264**    EofB: ...
120265**    AltB: ...
120266**    AeqB: ...
120267**    AgtB: ...
120268**    Init: initialize coroutine registers
120269**          yield coA
120270**          if eof(A) goto EofA
120271**          yield coB
120272**          if eof(B) goto EofB
120273**    Cmpr: Compare A, B
120274**          Jump AltB, AeqB, AgtB
120275**     End: ...
120276**
120277** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
120278** actually called using Gosub and they do not Return.  EofA and EofB loop
120279** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
120280** and AgtB jump to either L2 or to one of EofA or EofB.
120281*/
120282#ifndef SQLITE_OMIT_COMPOUND_SELECT
120283static int multiSelectOrderBy(
120284  Parse *pParse,        /* Parsing context */
120285  Select *p,            /* The right-most of SELECTs to be coded */
120286  SelectDest *pDest     /* What to do with query results */
120287){
120288  int i, j;             /* Loop counters */
120289  Select *pPrior;       /* Another SELECT immediately to our left */
120290  Vdbe *v;              /* Generate code to this VDBE */
120291  SelectDest destA;     /* Destination for coroutine A */
120292  SelectDest destB;     /* Destination for coroutine B */
120293  int regAddrA;         /* Address register for select-A coroutine */
120294  int regAddrB;         /* Address register for select-B coroutine */
120295  int addrSelectA;      /* Address of the select-A coroutine */
120296  int addrSelectB;      /* Address of the select-B coroutine */
120297  int regOutA;          /* Address register for the output-A subroutine */
120298  int regOutB;          /* Address register for the output-B subroutine */
120299  int addrOutA;         /* Address of the output-A subroutine */
120300  int addrOutB = 0;     /* Address of the output-B subroutine */
120301  int addrEofA;         /* Address of the select-A-exhausted subroutine */
120302  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
120303  int addrEofB;         /* Address of the select-B-exhausted subroutine */
120304  int addrAltB;         /* Address of the A<B subroutine */
120305  int addrAeqB;         /* Address of the A==B subroutine */
120306  int addrAgtB;         /* Address of the A>B subroutine */
120307  int regLimitA;        /* Limit register for select-A */
120308  int regLimitB;        /* Limit register for select-A */
120309  int regPrev;          /* A range of registers to hold previous output */
120310  int savedLimit;       /* Saved value of p->iLimit */
120311  int savedOffset;      /* Saved value of p->iOffset */
120312  int labelCmpr;        /* Label for the start of the merge algorithm */
120313  int labelEnd;         /* Label for the end of the overall SELECT stmt */
120314  int addr1;            /* Jump instructions that get retargetted */
120315  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
120316  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
120317  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
120318  sqlite3 *db;          /* Database connection */
120319  ExprList *pOrderBy;   /* The ORDER BY clause */
120320  int nOrderBy;         /* Number of terms in the ORDER BY clause */
120321  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
120322#ifndef SQLITE_OMIT_EXPLAIN
120323  int iSub1;            /* EQP id of left-hand query */
120324  int iSub2;            /* EQP id of right-hand query */
120325#endif
120326
120327  assert( p->pOrderBy!=0 );
120328  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
120329  db = pParse->db;
120330  v = pParse->pVdbe;
120331  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
120332  labelEnd = sqlite3VdbeMakeLabel(v);
120333  labelCmpr = sqlite3VdbeMakeLabel(v);
120334
120335
120336  /* Patch up the ORDER BY clause
120337  */
120338  op = p->op;
120339  pPrior = p->pPrior;
120340  assert( pPrior->pOrderBy==0 );
120341  pOrderBy = p->pOrderBy;
120342  assert( pOrderBy );
120343  nOrderBy = pOrderBy->nExpr;
120344
120345  /* For operators other than UNION ALL we have to make sure that
120346  ** the ORDER BY clause covers every term of the result set.  Add
120347  ** terms to the ORDER BY clause as necessary.
120348  */
120349  if( op!=TK_ALL ){
120350    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
120351      struct ExprList_item *pItem;
120352      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
120353        assert( pItem->u.x.iOrderByCol>0 );
120354        if( pItem->u.x.iOrderByCol==i ) break;
120355      }
120356      if( j==nOrderBy ){
120357        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
120358        if( pNew==0 ) return SQLITE_NOMEM_BKPT;
120359        pNew->flags |= EP_IntValue;
120360        pNew->u.iValue = i;
120361        p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
120362        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
120363      }
120364    }
120365  }
120366
120367  /* Compute the comparison permutation and keyinfo that is used with
120368  ** the permutation used to determine if the next
120369  ** row of results comes from selectA or selectB.  Also add explicit
120370  ** collations to the ORDER BY clause terms so that when the subqueries
120371  ** to the right and the left are evaluated, they use the correct
120372  ** collation.
120373  */
120374  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
120375  if( aPermute ){
120376    struct ExprList_item *pItem;
120377    aPermute[0] = nOrderBy;
120378    for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
120379      assert( pItem->u.x.iOrderByCol>0 );
120380      assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
120381      aPermute[i] = pItem->u.x.iOrderByCol - 1;
120382    }
120383    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
120384  }else{
120385    pKeyMerge = 0;
120386  }
120387
120388  /* Reattach the ORDER BY clause to the query.
120389  */
120390  p->pOrderBy = pOrderBy;
120391  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
120392
120393  /* Allocate a range of temporary registers and the KeyInfo needed
120394  ** for the logic that removes duplicate result rows when the
120395  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
120396  */
120397  if( op==TK_ALL ){
120398    regPrev = 0;
120399  }else{
120400    int nExpr = p->pEList->nExpr;
120401    assert( nOrderBy>=nExpr || db->mallocFailed );
120402    regPrev = pParse->nMem+1;
120403    pParse->nMem += nExpr+1;
120404    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
120405    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
120406    if( pKeyDup ){
120407      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
120408      for(i=0; i<nExpr; i++){
120409        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
120410        pKeyDup->aSortOrder[i] = 0;
120411      }
120412    }
120413  }
120414
120415  /* Separate the left and the right query from one another
120416  */
120417  p->pPrior = 0;
120418  pPrior->pNext = 0;
120419  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
120420  if( pPrior->pPrior==0 ){
120421    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
120422  }
120423
120424  /* Compute the limit registers */
120425  computeLimitRegisters(pParse, p, labelEnd);
120426  if( p->iLimit && op==TK_ALL ){
120427    regLimitA = ++pParse->nMem;
120428    regLimitB = ++pParse->nMem;
120429    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
120430                                  regLimitA);
120431    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
120432  }else{
120433    regLimitA = regLimitB = 0;
120434  }
120435  sqlite3ExprDelete(db, p->pLimit);
120436  p->pLimit = 0;
120437  sqlite3ExprDelete(db, p->pOffset);
120438  p->pOffset = 0;
120439
120440  regAddrA = ++pParse->nMem;
120441  regAddrB = ++pParse->nMem;
120442  regOutA = ++pParse->nMem;
120443  regOutB = ++pParse->nMem;
120444  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
120445  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
120446
120447  /* Generate a coroutine to evaluate the SELECT statement to the
120448  ** left of the compound operator - the "A" select.
120449  */
120450  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
120451  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
120452  VdbeComment((v, "left SELECT"));
120453  pPrior->iLimit = regLimitA;
120454  explainSetInteger(iSub1, pParse->iNextSelectId);
120455  sqlite3Select(pParse, pPrior, &destA);
120456  sqlite3VdbeEndCoroutine(v, regAddrA);
120457  sqlite3VdbeJumpHere(v, addr1);
120458
120459  /* Generate a coroutine to evaluate the SELECT statement on
120460  ** the right - the "B" select
120461  */
120462  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
120463  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
120464  VdbeComment((v, "right SELECT"));
120465  savedLimit = p->iLimit;
120466  savedOffset = p->iOffset;
120467  p->iLimit = regLimitB;
120468  p->iOffset = 0;
120469  explainSetInteger(iSub2, pParse->iNextSelectId);
120470  sqlite3Select(pParse, p, &destB);
120471  p->iLimit = savedLimit;
120472  p->iOffset = savedOffset;
120473  sqlite3VdbeEndCoroutine(v, regAddrB);
120474
120475  /* Generate a subroutine that outputs the current row of the A
120476  ** select as the next output row of the compound select.
120477  */
120478  VdbeNoopComment((v, "Output routine for A"));
120479  addrOutA = generateOutputSubroutine(pParse,
120480                 p, &destA, pDest, regOutA,
120481                 regPrev, pKeyDup, labelEnd);
120482
120483  /* Generate a subroutine that outputs the current row of the B
120484  ** select as the next output row of the compound select.
120485  */
120486  if( op==TK_ALL || op==TK_UNION ){
120487    VdbeNoopComment((v, "Output routine for B"));
120488    addrOutB = generateOutputSubroutine(pParse,
120489                 p, &destB, pDest, regOutB,
120490                 regPrev, pKeyDup, labelEnd);
120491  }
120492  sqlite3KeyInfoUnref(pKeyDup);
120493
120494  /* Generate a subroutine to run when the results from select A
120495  ** are exhausted and only data in select B remains.
120496  */
120497  if( op==TK_EXCEPT || op==TK_INTERSECT ){
120498    addrEofA_noB = addrEofA = labelEnd;
120499  }else{
120500    VdbeNoopComment((v, "eof-A subroutine"));
120501    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
120502    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
120503                                     VdbeCoverage(v);
120504    sqlite3VdbeGoto(v, addrEofA);
120505    p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
120506  }
120507
120508  /* Generate a subroutine to run when the results from select B
120509  ** are exhausted and only data in select A remains.
120510  */
120511  if( op==TK_INTERSECT ){
120512    addrEofB = addrEofA;
120513    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
120514  }else{
120515    VdbeNoopComment((v, "eof-B subroutine"));
120516    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
120517    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
120518    sqlite3VdbeGoto(v, addrEofB);
120519  }
120520
120521  /* Generate code to handle the case of A<B
120522  */
120523  VdbeNoopComment((v, "A-lt-B subroutine"));
120524  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
120525  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
120526  sqlite3VdbeGoto(v, labelCmpr);
120527
120528  /* Generate code to handle the case of A==B
120529  */
120530  if( op==TK_ALL ){
120531    addrAeqB = addrAltB;
120532  }else if( op==TK_INTERSECT ){
120533    addrAeqB = addrAltB;
120534    addrAltB++;
120535  }else{
120536    VdbeNoopComment((v, "A-eq-B subroutine"));
120537    addrAeqB =
120538    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
120539    sqlite3VdbeGoto(v, labelCmpr);
120540  }
120541
120542  /* Generate code to handle the case of A>B
120543  */
120544  VdbeNoopComment((v, "A-gt-B subroutine"));
120545  addrAgtB = sqlite3VdbeCurrentAddr(v);
120546  if( op==TK_ALL || op==TK_UNION ){
120547    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
120548  }
120549  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
120550  sqlite3VdbeGoto(v, labelCmpr);
120551
120552  /* This code runs once to initialize everything.
120553  */
120554  sqlite3VdbeJumpHere(v, addr1);
120555  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
120556  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
120557
120558  /* Implement the main merge loop
120559  */
120560  sqlite3VdbeResolveLabel(v, labelCmpr);
120561  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
120562  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
120563                         (char*)pKeyMerge, P4_KEYINFO);
120564  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
120565  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
120566
120567  /* Jump to the this point in order to terminate the query.
120568  */
120569  sqlite3VdbeResolveLabel(v, labelEnd);
120570
120571  /* Reassembly the compound query so that it will be freed correctly
120572  ** by the calling function */
120573  if( p->pPrior ){
120574    sqlite3SelectDelete(db, p->pPrior);
120575  }
120576  p->pPrior = pPrior;
120577  pPrior->pNext = p;
120578
120579  /*** TBD:  Insert subroutine calls to close cursors on incomplete
120580  **** subqueries ****/
120581  explainComposite(pParse, p->op, iSub1, iSub2, 0);
120582  return pParse->nErr!=0;
120583}
120584#endif
120585
120586#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
120587
120588/* An instance of the SubstContext object describes an substitution edit
120589** to be performed on a parse tree.
120590**
120591** All references to columns in table iTable are to be replaced by corresponding
120592** expressions in pEList.
120593*/
120594typedef struct SubstContext {
120595  Parse *pParse;            /* The parsing context */
120596  int iTable;               /* Replace references to this table */
120597  int iNewTable;            /* New table number */
120598  int isLeftJoin;           /* Add TK_IF_NULL_ROW opcodes on each replacement */
120599  ExprList *pEList;         /* Replacement expressions */
120600} SubstContext;
120601
120602/* Forward Declarations */
120603static void substExprList(SubstContext*, ExprList*);
120604static void substSelect(SubstContext*, Select*, int);
120605
120606/*
120607** Scan through the expression pExpr.  Replace every reference to
120608** a column in table number iTable with a copy of the iColumn-th
120609** entry in pEList.  (But leave references to the ROWID column
120610** unchanged.)
120611**
120612** This routine is part of the flattening procedure.  A subquery
120613** whose result set is defined by pEList appears as entry in the
120614** FROM clause of a SELECT such that the VDBE cursor assigned to that
120615** FORM clause entry is iTable.  This routine makes the necessary
120616** changes to pExpr so that it refers directly to the source table
120617** of the subquery rather the result set of the subquery.
120618*/
120619static Expr *substExpr(
120620  SubstContext *pSubst,  /* Description of the substitution */
120621  Expr *pExpr            /* Expr in which substitution occurs */
120622){
120623  if( pExpr==0 ) return 0;
120624  if( ExprHasProperty(pExpr, EP_FromJoin) && pExpr->iRightJoinTable==pSubst->iTable ){
120625    pExpr->iRightJoinTable = pSubst->iNewTable;
120626  }
120627  if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
120628    if( pExpr->iColumn<0 ){
120629      pExpr->op = TK_NULL;
120630    }else{
120631      Expr *pNew;
120632      Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
120633      Expr ifNullRow;
120634      assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
120635      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
120636      if( sqlite3ExprIsVector(pCopy) ){
120637        sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
120638      }else{
120639        sqlite3 *db = pSubst->pParse->db;
120640        if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
120641          memset(&ifNullRow, 0, sizeof(ifNullRow));
120642          ifNullRow.op = TK_IF_NULL_ROW;
120643          ifNullRow.pLeft = pCopy;
120644          ifNullRow.iTable = pSubst->iNewTable;
120645          pCopy = &ifNullRow;
120646        }
120647        pNew = sqlite3ExprDup(db, pCopy, 0);
120648        if( pNew && pSubst->isLeftJoin ){
120649          ExprSetProperty(pNew, EP_CanBeNull);
120650        }
120651        if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
120652          pNew->iRightJoinTable = pExpr->iRightJoinTable;
120653          ExprSetProperty(pNew, EP_FromJoin);
120654        }
120655        sqlite3ExprDelete(db, pExpr);
120656        pExpr = pNew;
120657      }
120658    }
120659  }else{
120660    if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
120661      pExpr->iTable = pSubst->iNewTable;
120662    }
120663    pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
120664    pExpr->pRight = substExpr(pSubst, pExpr->pRight);
120665    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
120666      substSelect(pSubst, pExpr->x.pSelect, 1);
120667    }else{
120668      substExprList(pSubst, pExpr->x.pList);
120669    }
120670  }
120671  return pExpr;
120672}
120673static void substExprList(
120674  SubstContext *pSubst, /* Description of the substitution */
120675  ExprList *pList       /* List to scan and in which to make substitutes */
120676){
120677  int i;
120678  if( pList==0 ) return;
120679  for(i=0; i<pList->nExpr; i++){
120680    pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
120681  }
120682}
120683static void substSelect(
120684  SubstContext *pSubst, /* Description of the substitution */
120685  Select *p,            /* SELECT statement in which to make substitutions */
120686  int doPrior           /* Do substitutes on p->pPrior too */
120687){
120688  SrcList *pSrc;
120689  struct SrcList_item *pItem;
120690  int i;
120691  if( !p ) return;
120692  do{
120693    substExprList(pSubst, p->pEList);
120694    substExprList(pSubst, p->pGroupBy);
120695    substExprList(pSubst, p->pOrderBy);
120696    p->pHaving = substExpr(pSubst, p->pHaving);
120697    p->pWhere = substExpr(pSubst, p->pWhere);
120698    pSrc = p->pSrc;
120699    assert( pSrc!=0 );
120700    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
120701      substSelect(pSubst, pItem->pSelect, 1);
120702      if( pItem->fg.isTabFunc ){
120703        substExprList(pSubst, pItem->u1.pFuncArg);
120704      }
120705    }
120706  }while( doPrior && (p = p->pPrior)!=0 );
120707}
120708#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
120709
120710#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
120711/*
120712** This routine attempts to flatten subqueries as a performance optimization.
120713** This routine returns 1 if it makes changes and 0 if no flattening occurs.
120714**
120715** To understand the concept of flattening, consider the following
120716** query:
120717**
120718**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
120719**
120720** The default way of implementing this query is to execute the
120721** subquery first and store the results in a temporary table, then
120722** run the outer query on that temporary table.  This requires two
120723** passes over the data.  Furthermore, because the temporary table
120724** has no indices, the WHERE clause on the outer query cannot be
120725** optimized.
120726**
120727** This routine attempts to rewrite queries such as the above into
120728** a single flat select, like this:
120729**
120730**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
120731**
120732** The code generated for this simplification gives the same result
120733** but only has to scan the data once.  And because indices might
120734** exist on the table t1, a complete scan of the data might be
120735** avoided.
120736**
120737** Flattening is only attempted if all of the following are true:
120738**
120739**   (1)  The subquery and the outer query do not both use aggregates.
120740**
120741**   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
120742**        and (2b) the outer query does not use subqueries other than the one
120743**        FROM-clause subquery that is a candidate for flattening.  (2b is
120744**        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
120745**
120746**   (3)  The subquery is not the right operand of a LEFT JOIN
120747**        or (a) the subquery is not itself a join and (b) the FROM clause
120748**        of the subquery does not contain a virtual table and (c) the
120749**        outer query is not an aggregate.
120750**
120751**   (4)  The subquery is not DISTINCT.
120752**
120753**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
120754**        sub-queries that were excluded from this optimization. Restriction
120755**        (4) has since been expanded to exclude all DISTINCT subqueries.
120756**
120757**   (6)  The subquery does not use aggregates or the outer query is not
120758**        DISTINCT.
120759**
120760**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
120761**        A FROM clause, consider adding a FROM clause with the special
120762**        table sqlite_once that consists of a single row containing a
120763**        single NULL.
120764**
120765**   (8)  The subquery does not use LIMIT or the outer query is not a join.
120766**
120767**   (9)  The subquery does not use LIMIT or the outer query does not use
120768**        aggregates.
120769**
120770**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
120771**        accidently carried the comment forward until 2014-09-15.  Original
120772**        text: "The subquery does not use aggregates or the outer query
120773**        does not use LIMIT."
120774**
120775**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
120776**
120777**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
120778**        a separate restriction deriving from ticket #350.
120779**
120780**  (13)  The subquery and outer query do not both use LIMIT.
120781**
120782**  (14)  The subquery does not use OFFSET.
120783**
120784**  (15)  The outer query is not part of a compound select or the
120785**        subquery does not have a LIMIT clause.
120786**        (See ticket #2339 and ticket [02a8e81d44]).
120787**
120788**  (16)  The outer query is not an aggregate or the subquery does
120789**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
120790**        until we introduced the group_concat() function.
120791**
120792**  (17)  The sub-query is not a compound select, or it is a UNION ALL
120793**        compound clause made up entirely of non-aggregate queries, and
120794**        the parent query:
120795**
120796**          * is not itself part of a compound select,
120797**          * is not an aggregate or DISTINCT query, and
120798**          * is not a join
120799**
120800**        The parent and sub-query may contain WHERE clauses. Subject to
120801**        rules (11), (13) and (14), they may also contain ORDER BY,
120802**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
120803**        operator other than UNION ALL because all the other compound
120804**        operators have an implied DISTINCT which is disallowed by
120805**        restriction (4).
120806**
120807**        Also, each component of the sub-query must return the same number
120808**        of result columns. This is actually a requirement for any compound
120809**        SELECT statement, but all the code here does is make sure that no
120810**        such (illegal) sub-query is flattened. The caller will detect the
120811**        syntax error and return a detailed message.
120812**
120813**  (18)  If the sub-query is a compound select, then all terms of the
120814**        ORDER by clause of the parent must be simple references to
120815**        columns of the sub-query.
120816**
120817**  (19)  The subquery does not use LIMIT or the outer query does not
120818**        have a WHERE clause.
120819**
120820**  (20)  If the sub-query is a compound select, then it must not use
120821**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
120822**        somewhat by saying that the terms of the ORDER BY clause must
120823**        appear as unmodified result columns in the outer query.  But we
120824**        have other optimizations in mind to deal with that case.
120825**
120826**  (21)  The subquery does not use LIMIT or the outer query is not
120827**        DISTINCT.  (See ticket [752e1646fc]).
120828**
120829**  (22)  The subquery is not a recursive CTE.
120830**
120831**  (23)  The parent is not a recursive CTE, or the sub-query is not a
120832**        compound query. This restriction is because transforming the
120833**        parent to a compound query confuses the code that handles
120834**        recursive queries in multiSelect().
120835**
120836**  (24)  The subquery is not an aggregate that uses the built-in min() or
120837**        or max() functions.  (Without this restriction, a query like:
120838**        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
120839**        return the value X for which Y was maximal.)
120840**
120841**
120842** In this routine, the "p" parameter is a pointer to the outer query.
120843** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
120844** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
120845**
120846** If flattening is not attempted, this routine is a no-op and returns 0.
120847** If flattening is attempted this routine returns 1.
120848**
120849** All of the expression analysis must occur on both the outer query and
120850** the subquery before this routine runs.
120851*/
120852static int flattenSubquery(
120853  Parse *pParse,       /* Parsing context */
120854  Select *p,           /* The parent or outer SELECT statement */
120855  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
120856  int isAgg,           /* True if outer SELECT uses aggregate functions */
120857  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
120858){
120859  const char *zSavedAuthContext = pParse->zAuthContext;
120860  Select *pParent;    /* Current UNION ALL term of the other query */
120861  Select *pSub;       /* The inner query or "subquery" */
120862  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
120863  SrcList *pSrc;      /* The FROM clause of the outer query */
120864  SrcList *pSubSrc;   /* The FROM clause of the subquery */
120865  int iParent;        /* VDBE cursor number of the pSub result set temp table */
120866  int iNewParent = -1;/* Replacement table for iParent */
120867  int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
120868  int i;              /* Loop counter */
120869  Expr *pWhere;                    /* The WHERE clause */
120870  struct SrcList_item *pSubitem;   /* The subquery */
120871  sqlite3 *db = pParse->db;
120872
120873  /* Check to see if flattening is permitted.  Return 0 if not.
120874  */
120875  assert( p!=0 );
120876  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
120877  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
120878  pSrc = p->pSrc;
120879  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
120880  pSubitem = &pSrc->a[iFrom];
120881  iParent = pSubitem->iCursor;
120882  pSub = pSubitem->pSelect;
120883  assert( pSub!=0 );
120884  if( subqueryIsAgg ){
120885    if( isAgg ) return 0;                                /* Restriction (1)   */
120886    if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
120887    if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
120888     || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
120889     || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
120890    ){
120891      return 0;                                          /* Restriction (2b)  */
120892    }
120893  }
120894
120895  pSubSrc = pSub->pSrc;
120896  assert( pSubSrc );
120897  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
120898  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
120899  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
120900  ** became arbitrary expressions, we were forced to add restrictions (13)
120901  ** and (14). */
120902  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
120903  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
120904  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
120905    return 0;                                            /* Restriction (15) */
120906  }
120907  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
120908  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
120909  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
120910     return 0;         /* Restrictions (8)(9) */
120911  }
120912  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
120913     return 0;         /* Restriction (6)  */
120914  }
120915  if( p->pOrderBy && pSub->pOrderBy ){
120916     return 0;                                           /* Restriction (11) */
120917  }
120918  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
120919  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
120920  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
120921     return 0;         /* Restriction (21) */
120922  }
120923  testcase( pSub->selFlags & SF_Recursive );
120924  testcase( pSub->selFlags & SF_MinMaxAgg );
120925  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
120926    return 0; /* Restrictions (22) and (24) */
120927  }
120928  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
120929    return 0; /* Restriction (23) */
120930  }
120931
120932  /*
120933  ** If the subquery is the right operand of a LEFT JOIN, then the
120934  ** subquery may not be a join itself.  Example of why this is not allowed:
120935  **
120936  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
120937  **
120938  ** If we flatten the above, we would get
120939  **
120940  **         (t1 LEFT OUTER JOIN t2) JOIN t3
120941  **
120942  ** which is not at all the same thing.
120943  **
120944  ** If the subquery is the right operand of a LEFT JOIN, then the outer
120945  ** query cannot be an aggregate.  This is an artifact of the way aggregates
120946  ** are processed - there is no mechanism to determine if the LEFT JOIN
120947  ** table should be all-NULL.
120948  **
120949  ** See also tickets #306, #350, and #3300.
120950  */
120951  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
120952    isLeftJoin = 1;
120953    if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
120954      return 0; /* Restriction (3) */
120955    }
120956  }
120957#ifdef SQLITE_EXTRA_IFNULLROW
120958  else if( iFrom>0 && !isAgg ){
120959    /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
120960    ** every reference to any result column from subquery in a join, even though
120961    ** they are not necessary.  This will stress-test the OP_IfNullRow opcode. */
120962    isLeftJoin = -1;
120963  }
120964#endif
120965
120966  /* Restriction 17: If the sub-query is a compound SELECT, then it must
120967  ** use only the UNION ALL operator. And none of the simple select queries
120968  ** that make up the compound SELECT are allowed to be aggregate or distinct
120969  ** queries.
120970  */
120971  if( pSub->pPrior ){
120972    if( pSub->pOrderBy ){
120973      return 0;  /* Restriction 20 */
120974    }
120975    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
120976      return 0;
120977    }
120978    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
120979      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
120980      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
120981      assert( pSub->pSrc!=0 );
120982      assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
120983      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
120984       || (pSub1->pPrior && pSub1->op!=TK_ALL)
120985       || pSub1->pSrc->nSrc<1
120986      ){
120987        return 0;
120988      }
120989      testcase( pSub1->pSrc->nSrc>1 );
120990    }
120991
120992    /* Restriction 18. */
120993    if( p->pOrderBy ){
120994      int ii;
120995      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
120996        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
120997      }
120998    }
120999  }
121000
121001  /***** If we reach this point, flattening is permitted. *****/
121002  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
121003                   pSub->zSelName, pSub, iFrom));
121004
121005  /* Authorize the subquery */
121006  pParse->zAuthContext = pSubitem->zName;
121007  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
121008  testcase( i==SQLITE_DENY );
121009  pParse->zAuthContext = zSavedAuthContext;
121010
121011  /* If the sub-query is a compound SELECT statement, then (by restrictions
121012  ** 17 and 18 above) it must be a UNION ALL and the parent query must
121013  ** be of the form:
121014  **
121015  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
121016  **
121017  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
121018  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
121019  ** OFFSET clauses and joins them to the left-hand-side of the original
121020  ** using UNION ALL operators. In this case N is the number of simple
121021  ** select statements in the compound sub-query.
121022  **
121023  ** Example:
121024  **
121025  **     SELECT a+1 FROM (
121026  **        SELECT x FROM tab
121027  **        UNION ALL
121028  **        SELECT y FROM tab
121029  **        UNION ALL
121030  **        SELECT abs(z*2) FROM tab2
121031  **     ) WHERE a!=5 ORDER BY 1
121032  **
121033  ** Transformed into:
121034  **
121035  **     SELECT x+1 FROM tab WHERE x+1!=5
121036  **     UNION ALL
121037  **     SELECT y+1 FROM tab WHERE y+1!=5
121038  **     UNION ALL
121039  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
121040  **     ORDER BY 1
121041  **
121042  ** We call this the "compound-subquery flattening".
121043  */
121044  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
121045    Select *pNew;
121046    ExprList *pOrderBy = p->pOrderBy;
121047    Expr *pLimit = p->pLimit;
121048    Expr *pOffset = p->pOffset;
121049    Select *pPrior = p->pPrior;
121050    p->pOrderBy = 0;
121051    p->pSrc = 0;
121052    p->pPrior = 0;
121053    p->pLimit = 0;
121054    p->pOffset = 0;
121055    pNew = sqlite3SelectDup(db, p, 0);
121056    sqlite3SelectSetName(pNew, pSub->zSelName);
121057    p->pOffset = pOffset;
121058    p->pLimit = pLimit;
121059    p->pOrderBy = pOrderBy;
121060    p->pSrc = pSrc;
121061    p->op = TK_ALL;
121062    if( pNew==0 ){
121063      p->pPrior = pPrior;
121064    }else{
121065      pNew->pPrior = pPrior;
121066      if( pPrior ) pPrior->pNext = pNew;
121067      pNew->pNext = p;
121068      p->pPrior = pNew;
121069      SELECTTRACE(2,pParse,p,
121070         ("compound-subquery flattener creates %s.%p as peer\n",
121071         pNew->zSelName, pNew));
121072    }
121073    if( db->mallocFailed ) return 1;
121074  }
121075
121076  /* Begin flattening the iFrom-th entry of the FROM clause
121077  ** in the outer query.
121078  */
121079  pSub = pSub1 = pSubitem->pSelect;
121080
121081  /* Delete the transient table structure associated with the
121082  ** subquery
121083  */
121084  sqlite3DbFree(db, pSubitem->zDatabase);
121085  sqlite3DbFree(db, pSubitem->zName);
121086  sqlite3DbFree(db, pSubitem->zAlias);
121087  pSubitem->zDatabase = 0;
121088  pSubitem->zName = 0;
121089  pSubitem->zAlias = 0;
121090  pSubitem->pSelect = 0;
121091
121092  /* Defer deleting the Table object associated with the
121093  ** subquery until code generation is
121094  ** complete, since there may still exist Expr.pTab entries that
121095  ** refer to the subquery even after flattening.  Ticket #3346.
121096  **
121097  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
121098  */
121099  if( ALWAYS(pSubitem->pTab!=0) ){
121100    Table *pTabToDel = pSubitem->pTab;
121101    if( pTabToDel->nTabRef==1 ){
121102      Parse *pToplevel = sqlite3ParseToplevel(pParse);
121103      pTabToDel->pNextZombie = pToplevel->pZombieTab;
121104      pToplevel->pZombieTab = pTabToDel;
121105    }else{
121106      pTabToDel->nTabRef--;
121107    }
121108    pSubitem->pTab = 0;
121109  }
121110
121111  /* The following loop runs once for each term in a compound-subquery
121112  ** flattening (as described above).  If we are doing a different kind
121113  ** of flattening - a flattening other than a compound-subquery flattening -
121114  ** then this loop only runs once.
121115  **
121116  ** This loop moves all of the FROM elements of the subquery into the
121117  ** the FROM clause of the outer query.  Before doing this, remember
121118  ** the cursor number for the original outer query FROM element in
121119  ** iParent.  The iParent cursor will never be used.  Subsequent code
121120  ** will scan expressions looking for iParent references and replace
121121  ** those references with expressions that resolve to the subquery FROM
121122  ** elements we are now copying in.
121123  */
121124  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
121125    int nSubSrc;
121126    u8 jointype = 0;
121127    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
121128    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
121129    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
121130
121131    if( pSrc ){
121132      assert( pParent==p );  /* First time through the loop */
121133      jointype = pSubitem->fg.jointype;
121134    }else{
121135      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
121136      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
121137      if( pSrc==0 ){
121138        assert( db->mallocFailed );
121139        break;
121140      }
121141    }
121142
121143    /* The subquery uses a single slot of the FROM clause of the outer
121144    ** query.  If the subquery has more than one element in its FROM clause,
121145    ** then expand the outer query to make space for it to hold all elements
121146    ** of the subquery.
121147    **
121148    ** Example:
121149    **
121150    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
121151    **
121152    ** The outer query has 3 slots in its FROM clause.  One slot of the
121153    ** outer query (the middle slot) is used by the subquery.  The next
121154    ** block of code will expand the outer query FROM clause to 4 slots.
121155    ** The middle slot is expanded to two slots in order to make space
121156    ** for the two elements in the FROM clause of the subquery.
121157    */
121158    if( nSubSrc>1 ){
121159      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
121160      if( db->mallocFailed ){
121161        break;
121162      }
121163    }
121164
121165    /* Transfer the FROM clause terms from the subquery into the
121166    ** outer query.
121167    */
121168    for(i=0; i<nSubSrc; i++){
121169      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
121170      assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
121171      pSrc->a[i+iFrom] = pSubSrc->a[i];
121172      iNewParent = pSubSrc->a[i].iCursor;
121173      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
121174    }
121175    pSrc->a[iFrom].fg.jointype = jointype;
121176
121177    /* Now begin substituting subquery result set expressions for
121178    ** references to the iParent in the outer query.
121179    **
121180    ** Example:
121181    **
121182    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
121183    **   \                     \_____________ subquery __________/          /
121184    **    \_____________________ outer query ______________________________/
121185    **
121186    ** We look at every expression in the outer query and every place we see
121187    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
121188    */
121189    if( pSub->pOrderBy ){
121190      /* At this point, any non-zero iOrderByCol values indicate that the
121191      ** ORDER BY column expression is identical to the iOrderByCol'th
121192      ** expression returned by SELECT statement pSub. Since these values
121193      ** do not necessarily correspond to columns in SELECT statement pParent,
121194      ** zero them before transfering the ORDER BY clause.
121195      **
121196      ** Not doing this may cause an error if a subsequent call to this
121197      ** function attempts to flatten a compound sub-query into pParent
121198      ** (the only way this can happen is if the compound sub-query is
121199      ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
121200      ExprList *pOrderBy = pSub->pOrderBy;
121201      for(i=0; i<pOrderBy->nExpr; i++){
121202        pOrderBy->a[i].u.x.iOrderByCol = 0;
121203      }
121204      assert( pParent->pOrderBy==0 );
121205      assert( pSub->pPrior==0 );
121206      pParent->pOrderBy = pOrderBy;
121207      pSub->pOrderBy = 0;
121208    }
121209    pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
121210    if( isLeftJoin>0 ){
121211      setJoinExpr(pWhere, iNewParent);
121212    }
121213    if( subqueryIsAgg ){
121214      assert( pParent->pHaving==0 );
121215      pParent->pHaving = pParent->pWhere;
121216      pParent->pWhere = pWhere;
121217      pParent->pHaving = sqlite3ExprAnd(db,
121218          sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving
121219      );
121220      assert( pParent->pGroupBy==0 );
121221      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
121222    }else{
121223      pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
121224    }
121225    if( db->mallocFailed==0 ){
121226      SubstContext x;
121227      x.pParse = pParse;
121228      x.iTable = iParent;
121229      x.iNewTable = iNewParent;
121230      x.isLeftJoin = isLeftJoin;
121231      x.pEList = pSub->pEList;
121232      substSelect(&x, pParent, 0);
121233    }
121234
121235    /* The flattened query is distinct if either the inner or the
121236    ** outer query is distinct.
121237    */
121238    pParent->selFlags |= pSub->selFlags & SF_Distinct;
121239
121240    /*
121241    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
121242    **
121243    ** One is tempted to try to add a and b to combine the limits.  But this
121244    ** does not work if either limit is negative.
121245    */
121246    if( pSub->pLimit ){
121247      pParent->pLimit = pSub->pLimit;
121248      pSub->pLimit = 0;
121249    }
121250  }
121251
121252  /* Finially, delete what is left of the subquery and return
121253  ** success.
121254  */
121255  sqlite3SelectDelete(db, pSub1);
121256
121257#if SELECTTRACE_ENABLED
121258  if( sqlite3SelectTrace & 0x100 ){
121259    SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
121260    sqlite3TreeViewSelect(0, p, 0);
121261  }
121262#endif
121263
121264  return 1;
121265}
121266#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
121267
121268
121269
121270#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
121271/*
121272** Make copies of relevant WHERE clause terms of the outer query into
121273** the WHERE clause of subquery.  Example:
121274**
121275**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
121276**
121277** Transformed into:
121278**
121279**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
121280**     WHERE x=5 AND y=10;
121281**
121282** The hope is that the terms added to the inner query will make it more
121283** efficient.
121284**
121285** Do not attempt this optimization if:
121286**
121287**   (1) The inner query is an aggregate.  (In that case, we'd really want
121288**       to copy the outer WHERE-clause terms onto the HAVING clause of the
121289**       inner query.  But they probably won't help there so do not bother.)
121290**
121291**   (2) The inner query is the recursive part of a common table expression.
121292**
121293**   (3) The inner query has a LIMIT clause (since the changes to the WHERE
121294**       close would change the meaning of the LIMIT).
121295**
121296**   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
121297**       enforces this restriction since this routine does not have enough
121298**       information to know.)
121299**
121300**   (5) The WHERE clause expression originates in the ON or USING clause
121301**       of a LEFT JOIN.
121302**
121303** Return 0 if no changes are made and non-zero if one or more WHERE clause
121304** terms are duplicated into the subquery.
121305*/
121306static int pushDownWhereTerms(
121307  Parse *pParse,        /* Parse context (for malloc() and error reporting) */
121308  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
121309  Expr *pWhere,         /* The WHERE clause of the outer query */
121310  int iCursor           /* Cursor number of the subquery */
121311){
121312  Expr *pNew;
121313  int nChng = 0;
121314  Select *pX;           /* For looping over compound SELECTs in pSubq */
121315  if( pWhere==0 ) return 0;
121316  for(pX=pSubq; pX; pX=pX->pPrior){
121317    if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
121318      testcase( pX->selFlags & SF_Aggregate );
121319      testcase( pX->selFlags & SF_Recursive );
121320      testcase( pX!=pSubq );
121321      return 0; /* restrictions (1) and (2) */
121322    }
121323  }
121324  if( pSubq->pLimit!=0 ){
121325    return 0; /* restriction (3) */
121326  }
121327  while( pWhere->op==TK_AND ){
121328    nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
121329    pWhere = pWhere->pLeft;
121330  }
121331  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
121332  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
121333    nChng++;
121334    while( pSubq ){
121335      SubstContext x;
121336      pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
121337      x.pParse = pParse;
121338      x.iTable = iCursor;
121339      x.iNewTable = iCursor;
121340      x.isLeftJoin = 0;
121341      x.pEList = pSubq->pEList;
121342      pNew = substExpr(&x, pNew);
121343      pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
121344      pSubq = pSubq->pPrior;
121345    }
121346  }
121347  return nChng;
121348}
121349#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
121350
121351/*
121352** Based on the contents of the AggInfo structure indicated by the first
121353** argument, this function checks if the following are true:
121354**
121355**    * the query contains just a single aggregate function,
121356**    * the aggregate function is either min() or max(), and
121357**    * the argument to the aggregate function is a column value.
121358**
121359** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
121360** is returned as appropriate. Also, *ppMinMax is set to point to the
121361** list of arguments passed to the aggregate before returning.
121362**
121363** Or, if the conditions above are not met, *ppMinMax is set to 0 and
121364** WHERE_ORDERBY_NORMAL is returned.
121365*/
121366static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
121367  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
121368
121369  *ppMinMax = 0;
121370  if( pAggInfo->nFunc==1 ){
121371    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
121372    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
121373
121374    assert( pExpr->op==TK_AGG_FUNCTION );
121375    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
121376      const char *zFunc = pExpr->u.zToken;
121377      if( sqlite3StrICmp(zFunc, "min")==0 ){
121378        eRet = WHERE_ORDERBY_MIN;
121379        *ppMinMax = pEList;
121380      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
121381        eRet = WHERE_ORDERBY_MAX;
121382        *ppMinMax = pEList;
121383      }
121384    }
121385  }
121386
121387  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
121388  return eRet;
121389}
121390
121391/*
121392** The select statement passed as the first argument is an aggregate query.
121393** The second argument is the associated aggregate-info object. This
121394** function tests if the SELECT is of the form:
121395**
121396**   SELECT count(*) FROM <tbl>
121397**
121398** where table is a database table, not a sub-select or view. If the query
121399** does match this pattern, then a pointer to the Table object representing
121400** <tbl> is returned. Otherwise, 0 is returned.
121401*/
121402static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
121403  Table *pTab;
121404  Expr *pExpr;
121405
121406  assert( !p->pGroupBy );
121407
121408  if( p->pWhere || p->pEList->nExpr!=1
121409   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
121410  ){
121411    return 0;
121412  }
121413  pTab = p->pSrc->a[0].pTab;
121414  pExpr = p->pEList->a[0].pExpr;
121415  assert( pTab && !pTab->pSelect && pExpr );
121416
121417  if( IsVirtual(pTab) ) return 0;
121418  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
121419  if( NEVER(pAggInfo->nFunc==0) ) return 0;
121420  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
121421  if( pExpr->flags&EP_Distinct ) return 0;
121422
121423  return pTab;
121424}
121425
121426/*
121427** If the source-list item passed as an argument was augmented with an
121428** INDEXED BY clause, then try to locate the specified index. If there
121429** was such a clause and the named index cannot be found, return
121430** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
121431** pFrom->pIndex and return SQLITE_OK.
121432*/
121433SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
121434  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
121435    Table *pTab = pFrom->pTab;
121436    char *zIndexedBy = pFrom->u1.zIndexedBy;
121437    Index *pIdx;
121438    for(pIdx=pTab->pIndex;
121439        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
121440        pIdx=pIdx->pNext
121441    );
121442    if( !pIdx ){
121443      sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
121444      pParse->checkSchema = 1;
121445      return SQLITE_ERROR;
121446    }
121447    pFrom->pIBIndex = pIdx;
121448  }
121449  return SQLITE_OK;
121450}
121451/*
121452** Detect compound SELECT statements that use an ORDER BY clause with
121453** an alternative collating sequence.
121454**
121455**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
121456**
121457** These are rewritten as a subquery:
121458**
121459**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
121460**     ORDER BY ... COLLATE ...
121461**
121462** This transformation is necessary because the multiSelectOrderBy() routine
121463** above that generates the code for a compound SELECT with an ORDER BY clause
121464** uses a merge algorithm that requires the same collating sequence on the
121465** result columns as on the ORDER BY clause.  See ticket
121466** http://www.sqlite.org/src/info/6709574d2a
121467**
121468** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
121469** The UNION ALL operator works fine with multiSelectOrderBy() even when
121470** there are COLLATE terms in the ORDER BY.
121471*/
121472static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
121473  int i;
121474  Select *pNew;
121475  Select *pX;
121476  sqlite3 *db;
121477  struct ExprList_item *a;
121478  SrcList *pNewSrc;
121479  Parse *pParse;
121480  Token dummy;
121481
121482  if( p->pPrior==0 ) return WRC_Continue;
121483  if( p->pOrderBy==0 ) return WRC_Continue;
121484  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
121485  if( pX==0 ) return WRC_Continue;
121486  a = p->pOrderBy->a;
121487  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
121488    if( a[i].pExpr->flags & EP_Collate ) break;
121489  }
121490  if( i<0 ) return WRC_Continue;
121491
121492  /* If we reach this point, that means the transformation is required. */
121493
121494  pParse = pWalker->pParse;
121495  db = pParse->db;
121496  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
121497  if( pNew==0 ) return WRC_Abort;
121498  memset(&dummy, 0, sizeof(dummy));
121499  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
121500  if( pNewSrc==0 ) return WRC_Abort;
121501  *pNew = *p;
121502  p->pSrc = pNewSrc;
121503  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
121504  p->op = TK_SELECT;
121505  p->pWhere = 0;
121506  pNew->pGroupBy = 0;
121507  pNew->pHaving = 0;
121508  pNew->pOrderBy = 0;
121509  p->pPrior = 0;
121510  p->pNext = 0;
121511  p->pWith = 0;
121512  p->selFlags &= ~SF_Compound;
121513  assert( (p->selFlags & SF_Converted)==0 );
121514  p->selFlags |= SF_Converted;
121515  assert( pNew->pPrior!=0 );
121516  pNew->pPrior->pNext = pNew;
121517  pNew->pLimit = 0;
121518  pNew->pOffset = 0;
121519  return WRC_Continue;
121520}
121521
121522/*
121523** Check to see if the FROM clause term pFrom has table-valued function
121524** arguments.  If it does, leave an error message in pParse and return
121525** non-zero, since pFrom is not allowed to be a table-valued function.
121526*/
121527static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
121528  if( pFrom->fg.isTabFunc ){
121529    sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
121530    return 1;
121531  }
121532  return 0;
121533}
121534
121535#ifndef SQLITE_OMIT_CTE
121536/*
121537** Argument pWith (which may be NULL) points to a linked list of nested
121538** WITH contexts, from inner to outermost. If the table identified by
121539** FROM clause element pItem is really a common-table-expression (CTE)
121540** then return a pointer to the CTE definition for that table. Otherwise
121541** return NULL.
121542**
121543** If a non-NULL value is returned, set *ppContext to point to the With
121544** object that the returned CTE belongs to.
121545*/
121546static struct Cte *searchWith(
121547  With *pWith,                    /* Current innermost WITH clause */
121548  struct SrcList_item *pItem,     /* FROM clause element to resolve */
121549  With **ppContext                /* OUT: WITH clause return value belongs to */
121550){
121551  const char *zName;
121552  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
121553    With *p;
121554    for(p=pWith; p; p=p->pOuter){
121555      int i;
121556      for(i=0; i<p->nCte; i++){
121557        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
121558          *ppContext = p;
121559          return &p->a[i];
121560        }
121561      }
121562    }
121563  }
121564  return 0;
121565}
121566
121567/* The code generator maintains a stack of active WITH clauses
121568** with the inner-most WITH clause being at the top of the stack.
121569**
121570** This routine pushes the WITH clause passed as the second argument
121571** onto the top of the stack. If argument bFree is true, then this
121572** WITH clause will never be popped from the stack. In this case it
121573** should be freed along with the Parse object. In other cases, when
121574** bFree==0, the With object will be freed along with the SELECT
121575** statement with which it is associated.
121576*/
121577SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
121578  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
121579  if( pWith ){
121580    assert( pParse->pWith!=pWith );
121581    pWith->pOuter = pParse->pWith;
121582    pParse->pWith = pWith;
121583    if( bFree ) pParse->pWithToFree = pWith;
121584  }
121585}
121586
121587/*
121588** This function checks if argument pFrom refers to a CTE declared by
121589** a WITH clause on the stack currently maintained by the parser. And,
121590** if currently processing a CTE expression, if it is a recursive
121591** reference to the current CTE.
121592**
121593** If pFrom falls into either of the two categories above, pFrom->pTab
121594** and other fields are populated accordingly. The caller should check
121595** (pFrom->pTab!=0) to determine whether or not a successful match
121596** was found.
121597**
121598** Whether or not a match is found, SQLITE_OK is returned if no error
121599** occurs. If an error does occur, an error message is stored in the
121600** parser and some error code other than SQLITE_OK returned.
121601*/
121602static int withExpand(
121603  Walker *pWalker,
121604  struct SrcList_item *pFrom
121605){
121606  Parse *pParse = pWalker->pParse;
121607  sqlite3 *db = pParse->db;
121608  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
121609  With *pWith;                    /* WITH clause that pCte belongs to */
121610
121611  assert( pFrom->pTab==0 );
121612
121613  pCte = searchWith(pParse->pWith, pFrom, &pWith);
121614  if( pCte ){
121615    Table *pTab;
121616    ExprList *pEList;
121617    Select *pSel;
121618    Select *pLeft;                /* Left-most SELECT statement */
121619    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
121620    With *pSavedWith;             /* Initial value of pParse->pWith */
121621
121622    /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
121623    ** recursive reference to CTE pCte. Leave an error in pParse and return
121624    ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
121625    ** In this case, proceed.  */
121626    if( pCte->zCteErr ){
121627      sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
121628      return SQLITE_ERROR;
121629    }
121630    if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
121631
121632    assert( pFrom->pTab==0 );
121633    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
121634    if( pTab==0 ) return WRC_Abort;
121635    pTab->nTabRef = 1;
121636    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
121637    pTab->iPKey = -1;
121638    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
121639    pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
121640    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
121641    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
121642    assert( pFrom->pSelect );
121643
121644    /* Check if this is a recursive CTE. */
121645    pSel = pFrom->pSelect;
121646    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
121647    if( bMayRecursive ){
121648      int i;
121649      SrcList *pSrc = pFrom->pSelect->pSrc;
121650      for(i=0; i<pSrc->nSrc; i++){
121651        struct SrcList_item *pItem = &pSrc->a[i];
121652        if( pItem->zDatabase==0
121653         && pItem->zName!=0
121654         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
121655          ){
121656          pItem->pTab = pTab;
121657          pItem->fg.isRecursive = 1;
121658          pTab->nTabRef++;
121659          pSel->selFlags |= SF_Recursive;
121660        }
121661      }
121662    }
121663
121664    /* Only one recursive reference is permitted. */
121665    if( pTab->nTabRef>2 ){
121666      sqlite3ErrorMsg(
121667          pParse, "multiple references to recursive table: %s", pCte->zName
121668      );
121669      return SQLITE_ERROR;
121670    }
121671    assert( pTab->nTabRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
121672
121673    pCte->zCteErr = "circular reference: %s";
121674    pSavedWith = pParse->pWith;
121675    pParse->pWith = pWith;
121676    if( bMayRecursive ){
121677      Select *pPrior = pSel->pPrior;
121678      assert( pPrior->pWith==0 );
121679      pPrior->pWith = pSel->pWith;
121680      sqlite3WalkSelect(pWalker, pPrior);
121681      pPrior->pWith = 0;
121682    }else{
121683      sqlite3WalkSelect(pWalker, pSel);
121684    }
121685    pParse->pWith = pWith;
121686
121687    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
121688    pEList = pLeft->pEList;
121689    if( pCte->pCols ){
121690      if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
121691        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
121692            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
121693        );
121694        pParse->pWith = pSavedWith;
121695        return SQLITE_ERROR;
121696      }
121697      pEList = pCte->pCols;
121698    }
121699
121700    sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
121701    if( bMayRecursive ){
121702      if( pSel->selFlags & SF_Recursive ){
121703        pCte->zCteErr = "multiple recursive references: %s";
121704      }else{
121705        pCte->zCteErr = "recursive reference in a subquery: %s";
121706      }
121707      sqlite3WalkSelect(pWalker, pSel);
121708    }
121709    pCte->zCteErr = 0;
121710    pParse->pWith = pSavedWith;
121711  }
121712
121713  return SQLITE_OK;
121714}
121715#endif
121716
121717#ifndef SQLITE_OMIT_CTE
121718/*
121719** If the SELECT passed as the second argument has an associated WITH
121720** clause, pop it from the stack stored as part of the Parse object.
121721**
121722** This function is used as the xSelectCallback2() callback by
121723** sqlite3SelectExpand() when walking a SELECT tree to resolve table
121724** names and other FROM clause elements.
121725*/
121726static void selectPopWith(Walker *pWalker, Select *p){
121727  Parse *pParse = pWalker->pParse;
121728  if( pParse->pWith && p->pPrior==0 ){
121729    With *pWith = findRightmost(p)->pWith;
121730    if( pWith!=0 ){
121731      assert( pParse->pWith==pWith );
121732      pParse->pWith = pWith->pOuter;
121733    }
121734  }
121735}
121736#else
121737#define selectPopWith 0
121738#endif
121739
121740/*
121741** This routine is a Walker callback for "expanding" a SELECT statement.
121742** "Expanding" means to do the following:
121743**
121744**    (1)  Make sure VDBE cursor numbers have been assigned to every
121745**         element of the FROM clause.
121746**
121747**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
121748**         defines FROM clause.  When views appear in the FROM clause,
121749**         fill pTabList->a[].pSelect with a copy of the SELECT statement
121750**         that implements the view.  A copy is made of the view's SELECT
121751**         statement so that we can freely modify or delete that statement
121752**         without worrying about messing up the persistent representation
121753**         of the view.
121754**
121755**    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
121756**         on joins and the ON and USING clause of joins.
121757**
121758**    (4)  Scan the list of columns in the result set (pEList) looking
121759**         for instances of the "*" operator or the TABLE.* operator.
121760**         If found, expand each "*" to be every column in every table
121761**         and TABLE.* to be every column in TABLE.
121762**
121763*/
121764static int selectExpander(Walker *pWalker, Select *p){
121765  Parse *pParse = pWalker->pParse;
121766  int i, j, k;
121767  SrcList *pTabList;
121768  ExprList *pEList;
121769  struct SrcList_item *pFrom;
121770  sqlite3 *db = pParse->db;
121771  Expr *pE, *pRight, *pExpr;
121772  u16 selFlags = p->selFlags;
121773
121774  p->selFlags |= SF_Expanded;
121775  if( db->mallocFailed  ){
121776    return WRC_Abort;
121777  }
121778  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
121779    return WRC_Prune;
121780  }
121781  pTabList = p->pSrc;
121782  pEList = p->pEList;
121783  if( p->pWith ){
121784    sqlite3WithPush(pParse, p->pWith, 0);
121785  }
121786
121787  /* Make sure cursor numbers have been assigned to all entries in
121788  ** the FROM clause of the SELECT statement.
121789  */
121790  sqlite3SrcListAssignCursors(pParse, pTabList);
121791
121792  /* Look up every table named in the FROM clause of the select.  If
121793  ** an entry of the FROM clause is a subquery instead of a table or view,
121794  ** then create a transient table structure to describe the subquery.
121795  */
121796  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
121797    Table *pTab;
121798    assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
121799    if( pFrom->fg.isRecursive ) continue;
121800    assert( pFrom->pTab==0 );
121801#ifndef SQLITE_OMIT_CTE
121802    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
121803    if( pFrom->pTab ) {} else
121804#endif
121805    if( pFrom->zName==0 ){
121806#ifndef SQLITE_OMIT_SUBQUERY
121807      Select *pSel = pFrom->pSelect;
121808      /* A sub-query in the FROM clause of a SELECT */
121809      assert( pSel!=0 );
121810      assert( pFrom->pTab==0 );
121811      if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
121812      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
121813      if( pTab==0 ) return WRC_Abort;
121814      pTab->nTabRef = 1;
121815      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
121816      while( pSel->pPrior ){ pSel = pSel->pPrior; }
121817      sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
121818      pTab->iPKey = -1;
121819      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
121820      pTab->tabFlags |= TF_Ephemeral;
121821#endif
121822    }else{
121823      /* An ordinary table or view name in the FROM clause */
121824      assert( pFrom->pTab==0 );
121825      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
121826      if( pTab==0 ) return WRC_Abort;
121827      if( pTab->nTabRef>=0xffff ){
121828        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
121829           pTab->zName);
121830        pFrom->pTab = 0;
121831        return WRC_Abort;
121832      }
121833      pTab->nTabRef++;
121834      if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
121835        return WRC_Abort;
121836      }
121837#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
121838      if( IsVirtual(pTab) || pTab->pSelect ){
121839        i16 nCol;
121840        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
121841        assert( pFrom->pSelect==0 );
121842        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
121843        sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
121844        nCol = pTab->nCol;
121845        pTab->nCol = -1;
121846        sqlite3WalkSelect(pWalker, pFrom->pSelect);
121847        pTab->nCol = nCol;
121848      }
121849#endif
121850    }
121851
121852    /* Locate the index named by the INDEXED BY clause, if any. */
121853    if( sqlite3IndexedByLookup(pParse, pFrom) ){
121854      return WRC_Abort;
121855    }
121856  }
121857
121858  /* Process NATURAL keywords, and ON and USING clauses of joins.
121859  */
121860  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
121861    return WRC_Abort;
121862  }
121863
121864  /* For every "*" that occurs in the column list, insert the names of
121865  ** all columns in all tables.  And for every TABLE.* insert the names
121866  ** of all columns in TABLE.  The parser inserted a special expression
121867  ** with the TK_ASTERISK operator for each "*" that it found in the column
121868  ** list.  The following code just has to locate the TK_ASTERISK
121869  ** expressions and expand each one to the list of all columns in
121870  ** all tables.
121871  **
121872  ** The first loop just checks to see if there are any "*" operators
121873  ** that need expanding.
121874  */
121875  for(k=0; k<pEList->nExpr; k++){
121876    pE = pEList->a[k].pExpr;
121877    if( pE->op==TK_ASTERISK ) break;
121878    assert( pE->op!=TK_DOT || pE->pRight!=0 );
121879    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
121880    if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
121881  }
121882  if( k<pEList->nExpr ){
121883    /*
121884    ** If we get here it means the result set contains one or more "*"
121885    ** operators that need to be expanded.  Loop through each expression
121886    ** in the result set and expand them one by one.
121887    */
121888    struct ExprList_item *a = pEList->a;
121889    ExprList *pNew = 0;
121890    int flags = pParse->db->flags;
121891    int longNames = (flags & SQLITE_FullColNames)!=0
121892                      && (flags & SQLITE_ShortColNames)==0;
121893
121894    for(k=0; k<pEList->nExpr; k++){
121895      pE = a[k].pExpr;
121896      pRight = pE->pRight;
121897      assert( pE->op!=TK_DOT || pRight!=0 );
121898      if( pE->op!=TK_ASTERISK
121899       && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
121900      ){
121901        /* This particular expression does not need to be expanded.
121902        */
121903        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
121904        if( pNew ){
121905          pNew->a[pNew->nExpr-1].zName = a[k].zName;
121906          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
121907          a[k].zName = 0;
121908          a[k].zSpan = 0;
121909        }
121910        a[k].pExpr = 0;
121911      }else{
121912        /* This expression is a "*" or a "TABLE.*" and needs to be
121913        ** expanded. */
121914        int tableSeen = 0;      /* Set to 1 when TABLE matches */
121915        char *zTName = 0;       /* text of name of TABLE */
121916        if( pE->op==TK_DOT ){
121917          assert( pE->pLeft!=0 );
121918          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
121919          zTName = pE->pLeft->u.zToken;
121920        }
121921        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
121922          Table *pTab = pFrom->pTab;
121923          Select *pSub = pFrom->pSelect;
121924          char *zTabName = pFrom->zAlias;
121925          const char *zSchemaName = 0;
121926          int iDb;
121927          if( zTabName==0 ){
121928            zTabName = pTab->zName;
121929          }
121930          if( db->mallocFailed ) break;
121931          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
121932            pSub = 0;
121933            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
121934              continue;
121935            }
121936            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121937            zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
121938          }
121939          for(j=0; j<pTab->nCol; j++){
121940            char *zName = pTab->aCol[j].zName;
121941            char *zColname;  /* The computed column name */
121942            char *zToFree;   /* Malloced string that needs to be freed */
121943            Token sColname;  /* Computed column name as a token */
121944
121945            assert( zName );
121946            if( zTName && pSub
121947             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
121948            ){
121949              continue;
121950            }
121951
121952            /* If a column is marked as 'hidden', omit it from the expanded
121953            ** result-set list unless the SELECT has the SF_IncludeHidden
121954            ** bit set.
121955            */
121956            if( (p->selFlags & SF_IncludeHidden)==0
121957             && IsHiddenColumn(&pTab->aCol[j])
121958            ){
121959              continue;
121960            }
121961            tableSeen = 1;
121962
121963            if( i>0 && zTName==0 ){
121964              if( (pFrom->fg.jointype & JT_NATURAL)!=0
121965                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
121966              ){
121967                /* In a NATURAL join, omit the join columns from the
121968                ** table to the right of the join */
121969                continue;
121970              }
121971              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
121972                /* In a join with a USING clause, omit columns in the
121973                ** using clause from the table on the right. */
121974                continue;
121975              }
121976            }
121977            pRight = sqlite3Expr(db, TK_ID, zName);
121978            zColname = zName;
121979            zToFree = 0;
121980            if( longNames || pTabList->nSrc>1 ){
121981              Expr *pLeft;
121982              pLeft = sqlite3Expr(db, TK_ID, zTabName);
121983              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
121984              if( zSchemaName ){
121985                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
121986                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
121987              }
121988              if( longNames ){
121989                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
121990                zToFree = zColname;
121991              }
121992            }else{
121993              pExpr = pRight;
121994            }
121995            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
121996            sqlite3TokenInit(&sColname, zColname);
121997            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
121998            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
121999              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
122000              if( pSub ){
122001                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
122002                testcase( pX->zSpan==0 );
122003              }else{
122004                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
122005                                           zSchemaName, zTabName, zColname);
122006                testcase( pX->zSpan==0 );
122007              }
122008              pX->bSpanIsTab = 1;
122009            }
122010            sqlite3DbFree(db, zToFree);
122011          }
122012        }
122013        if( !tableSeen ){
122014          if( zTName ){
122015            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
122016          }else{
122017            sqlite3ErrorMsg(pParse, "no tables specified");
122018          }
122019        }
122020      }
122021    }
122022    sqlite3ExprListDelete(db, pEList);
122023    p->pEList = pNew;
122024  }
122025#if SQLITE_MAX_COLUMN
122026  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
122027    sqlite3ErrorMsg(pParse, "too many columns in result set");
122028    return WRC_Abort;
122029  }
122030#endif
122031  return WRC_Continue;
122032}
122033
122034/*
122035** No-op routine for the parse-tree walker.
122036**
122037** When this routine is the Walker.xExprCallback then expression trees
122038** are walked without any actions being taken at each node.  Presumably,
122039** when this routine is used for Walker.xExprCallback then
122040** Walker.xSelectCallback is set to do something useful for every
122041** subquery in the parser tree.
122042*/
122043SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
122044  UNUSED_PARAMETER2(NotUsed, NotUsed2);
122045  return WRC_Continue;
122046}
122047
122048/*
122049** No-op routine for the parse-tree walker for SELECT statements.
122050** subquery in the parser tree.
122051*/
122052SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
122053  UNUSED_PARAMETER2(NotUsed, NotUsed2);
122054  return WRC_Continue;
122055}
122056
122057#if SQLITE_DEBUG
122058/*
122059** Always assert.  This xSelectCallback2 implementation proves that the
122060** xSelectCallback2 is never invoked.
122061*/
122062SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
122063  UNUSED_PARAMETER2(NotUsed, NotUsed2);
122064  assert( 0 );
122065}
122066#endif
122067/*
122068** This routine "expands" a SELECT statement and all of its subqueries.
122069** For additional information on what it means to "expand" a SELECT
122070** statement, see the comment on the selectExpand worker callback above.
122071**
122072** Expanding a SELECT statement is the first step in processing a
122073** SELECT statement.  The SELECT statement must be expanded before
122074** name resolution is performed.
122075**
122076** If anything goes wrong, an error message is written into pParse.
122077** The calling function can detect the problem by looking at pParse->nErr
122078** and/or pParse->db->mallocFailed.
122079*/
122080static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
122081  Walker w;
122082  w.xExprCallback = sqlite3ExprWalkNoop;
122083  w.pParse = pParse;
122084  if( pParse->hasCompound ){
122085    w.xSelectCallback = convertCompoundSelectToSubquery;
122086    w.xSelectCallback2 = 0;
122087    sqlite3WalkSelect(&w, pSelect);
122088  }
122089  w.xSelectCallback = selectExpander;
122090  w.xSelectCallback2 = selectPopWith;
122091  sqlite3WalkSelect(&w, pSelect);
122092}
122093
122094
122095#ifndef SQLITE_OMIT_SUBQUERY
122096/*
122097** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
122098** interface.
122099**
122100** For each FROM-clause subquery, add Column.zType and Column.zColl
122101** information to the Table structure that represents the result set
122102** of that subquery.
122103**
122104** The Table structure that represents the result set was constructed
122105** by selectExpander() but the type and collation information was omitted
122106** at that point because identifiers had not yet been resolved.  This
122107** routine is called after identifier resolution.
122108*/
122109static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
122110  Parse *pParse;
122111  int i;
122112  SrcList *pTabList;
122113  struct SrcList_item *pFrom;
122114
122115  assert( p->selFlags & SF_Resolved );
122116  assert( (p->selFlags & SF_HasTypeInfo)==0 );
122117  p->selFlags |= SF_HasTypeInfo;
122118  pParse = pWalker->pParse;
122119  pTabList = p->pSrc;
122120  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
122121    Table *pTab = pFrom->pTab;
122122    assert( pTab!=0 );
122123    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
122124      /* A sub-query in the FROM clause of a SELECT */
122125      Select *pSel = pFrom->pSelect;
122126      if( pSel ){
122127        while( pSel->pPrior ) pSel = pSel->pPrior;
122128        sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
122129      }
122130    }
122131  }
122132}
122133#endif
122134
122135
122136/*
122137** This routine adds datatype and collating sequence information to
122138** the Table structures of all FROM-clause subqueries in a
122139** SELECT statement.
122140**
122141** Use this routine after name resolution.
122142*/
122143static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
122144#ifndef SQLITE_OMIT_SUBQUERY
122145  Walker w;
122146  w.xSelectCallback = sqlite3SelectWalkNoop;
122147  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
122148  w.xExprCallback = sqlite3ExprWalkNoop;
122149  w.pParse = pParse;
122150  sqlite3WalkSelect(&w, pSelect);
122151#endif
122152}
122153
122154
122155/*
122156** This routine sets up a SELECT statement for processing.  The
122157** following is accomplished:
122158**
122159**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
122160**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
122161**     *  ON and USING clauses are shifted into WHERE statements
122162**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
122163**     *  Identifiers in expression are matched to tables.
122164**
122165** This routine acts recursively on all subqueries within the SELECT.
122166*/
122167SQLITE_PRIVATE void sqlite3SelectPrep(
122168  Parse *pParse,         /* The parser context */
122169  Select *p,             /* The SELECT statement being coded. */
122170  NameContext *pOuterNC  /* Name context for container */
122171){
122172  sqlite3 *db;
122173  if( NEVER(p==0) ) return;
122174  db = pParse->db;
122175  if( db->mallocFailed ) return;
122176  if( p->selFlags & SF_HasTypeInfo ) return;
122177  sqlite3SelectExpand(pParse, p);
122178  if( pParse->nErr || db->mallocFailed ) return;
122179  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
122180  if( pParse->nErr || db->mallocFailed ) return;
122181  sqlite3SelectAddTypeInfo(pParse, p);
122182}
122183
122184/*
122185** Reset the aggregate accumulator.
122186**
122187** The aggregate accumulator is a set of memory cells that hold
122188** intermediate results while calculating an aggregate.  This
122189** routine generates code that stores NULLs in all of those memory
122190** cells.
122191*/
122192static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
122193  Vdbe *v = pParse->pVdbe;
122194  int i;
122195  struct AggInfo_func *pFunc;
122196  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
122197  if( nReg==0 ) return;
122198#ifdef SQLITE_DEBUG
122199  /* Verify that all AggInfo registers are within the range specified by
122200  ** AggInfo.mnReg..AggInfo.mxReg */
122201  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
122202  for(i=0; i<pAggInfo->nColumn; i++){
122203    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
122204         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
122205  }
122206  for(i=0; i<pAggInfo->nFunc; i++){
122207    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
122208         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
122209  }
122210#endif
122211  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
122212  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
122213    if( pFunc->iDistinct>=0 ){
122214      Expr *pE = pFunc->pExpr;
122215      assert( !ExprHasProperty(pE, EP_xIsSelect) );
122216      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
122217        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
122218           "argument");
122219        pFunc->iDistinct = -1;
122220      }else{
122221        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
122222        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
122223                          (char*)pKeyInfo, P4_KEYINFO);
122224      }
122225    }
122226  }
122227}
122228
122229/*
122230** Invoke the OP_AggFinalize opcode for every aggregate function
122231** in the AggInfo structure.
122232*/
122233static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
122234  Vdbe *v = pParse->pVdbe;
122235  int i;
122236  struct AggInfo_func *pF;
122237  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
122238    ExprList *pList = pF->pExpr->x.pList;
122239    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
122240    sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
122241    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
122242  }
122243}
122244
122245/*
122246** Update the accumulator memory cells for an aggregate based on
122247** the current cursor position.
122248*/
122249static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
122250  Vdbe *v = pParse->pVdbe;
122251  int i;
122252  int regHit = 0;
122253  int addrHitTest = 0;
122254  struct AggInfo_func *pF;
122255  struct AggInfo_col *pC;
122256
122257  pAggInfo->directMode = 1;
122258  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
122259    int nArg;
122260    int addrNext = 0;
122261    int regAgg;
122262    ExprList *pList = pF->pExpr->x.pList;
122263    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
122264    if( pList ){
122265      nArg = pList->nExpr;
122266      regAgg = sqlite3GetTempRange(pParse, nArg);
122267      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
122268    }else{
122269      nArg = 0;
122270      regAgg = 0;
122271    }
122272    if( pF->iDistinct>=0 ){
122273      addrNext = sqlite3VdbeMakeLabel(v);
122274      testcase( nArg==0 );  /* Error condition */
122275      testcase( nArg>1 );   /* Also an error */
122276      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
122277    }
122278    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
122279      CollSeq *pColl = 0;
122280      struct ExprList_item *pItem;
122281      int j;
122282      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
122283      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
122284        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
122285      }
122286      if( !pColl ){
122287        pColl = pParse->db->pDfltColl;
122288      }
122289      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
122290      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
122291    }
122292    sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
122293    sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
122294    sqlite3VdbeChangeP5(v, (u8)nArg);
122295    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
122296    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
122297    if( addrNext ){
122298      sqlite3VdbeResolveLabel(v, addrNext);
122299      sqlite3ExprCacheClear(pParse);
122300    }
122301  }
122302
122303  /* Before populating the accumulator registers, clear the column cache.
122304  ** Otherwise, if any of the required column values are already present
122305  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
122306  ** to pC->iMem. But by the time the value is used, the original register
122307  ** may have been used, invalidating the underlying buffer holding the
122308  ** text or blob value. See ticket [883034dcb5].
122309  **
122310  ** Another solution would be to change the OP_SCopy used to copy cached
122311  ** values to an OP_Copy.
122312  */
122313  if( regHit ){
122314    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
122315  }
122316  sqlite3ExprCacheClear(pParse);
122317  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
122318    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
122319  }
122320  pAggInfo->directMode = 0;
122321  sqlite3ExprCacheClear(pParse);
122322  if( addrHitTest ){
122323    sqlite3VdbeJumpHere(v, addrHitTest);
122324  }
122325}
122326
122327/*
122328** Add a single OP_Explain instruction to the VDBE to explain a simple
122329** count(*) query ("SELECT count(*) FROM pTab").
122330*/
122331#ifndef SQLITE_OMIT_EXPLAIN
122332static void explainSimpleCount(
122333  Parse *pParse,                  /* Parse context */
122334  Table *pTab,                    /* Table being queried */
122335  Index *pIdx                     /* Index used to optimize scan, or NULL */
122336){
122337  if( pParse->explain==2 ){
122338    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
122339    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
122340        pTab->zName,
122341        bCover ? " USING COVERING INDEX " : "",
122342        bCover ? pIdx->zName : ""
122343    );
122344    sqlite3VdbeAddOp4(
122345        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
122346    );
122347  }
122348}
122349#else
122350# define explainSimpleCount(a,b,c)
122351#endif
122352
122353/*
122354** Context object for havingToWhereExprCb().
122355*/
122356struct HavingToWhereCtx {
122357  Expr **ppWhere;
122358  ExprList *pGroupBy;
122359};
122360
122361/*
122362** sqlite3WalkExpr() callback used by havingToWhere().
122363**
122364** If the node passed to the callback is a TK_AND node, return
122365** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
122366**
122367** Otherwise, return WRC_Prune. In this case, also check if the
122368** sub-expression matches the criteria for being moved to the WHERE
122369** clause. If so, add it to the WHERE clause and replace the sub-expression
122370** within the HAVING expression with a constant "1".
122371*/
122372static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
122373  if( pExpr->op!=TK_AND ){
122374    struct HavingToWhereCtx *p = pWalker->u.pHavingCtx;
122375    if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){
122376      sqlite3 *db = pWalker->pParse->db;
122377      Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
122378      if( pNew ){
122379        Expr *pWhere = *(p->ppWhere);
122380        SWAP(Expr, *pNew, *pExpr);
122381        pNew = sqlite3ExprAnd(db, pWhere, pNew);
122382        *(p->ppWhere) = pNew;
122383      }
122384    }
122385    return WRC_Prune;
122386  }
122387  return WRC_Continue;
122388}
122389
122390/*
122391** Transfer eligible terms from the HAVING clause of a query, which is
122392** processed after grouping, to the WHERE clause, which is processed before
122393** grouping. For example, the query:
122394**
122395**   SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
122396**
122397** can be rewritten as:
122398**
122399**   SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
122400**
122401** A term of the HAVING expression is eligible for transfer if it consists
122402** entirely of constants and expressions that are also GROUP BY terms that
122403** use the "BINARY" collation sequence.
122404*/
122405static void havingToWhere(
122406  Parse *pParse,
122407  ExprList *pGroupBy,
122408  Expr *pHaving,
122409  Expr **ppWhere
122410){
122411  struct HavingToWhereCtx sCtx;
122412  Walker sWalker;
122413
122414  sCtx.ppWhere = ppWhere;
122415  sCtx.pGroupBy = pGroupBy;
122416
122417  memset(&sWalker, 0, sizeof(sWalker));
122418  sWalker.pParse = pParse;
122419  sWalker.xExprCallback = havingToWhereExprCb;
122420  sWalker.u.pHavingCtx = &sCtx;
122421  sqlite3WalkExpr(&sWalker, pHaving);
122422}
122423
122424/*
122425** Check to see if the pThis entry of pTabList is a self-join of a prior view.
122426** If it is, then return the SrcList_item for the prior view.  If it is not,
122427** then return 0.
122428*/
122429static struct SrcList_item *isSelfJoinView(
122430  SrcList *pTabList,           /* Search for self-joins in this FROM clause */
122431  struct SrcList_item *pThis   /* Search for prior reference to this subquery */
122432){
122433  struct SrcList_item *pItem;
122434  for(pItem = pTabList->a; pItem<pThis; pItem++){
122435    if( pItem->pSelect==0 ) continue;
122436    if( pItem->fg.viaCoroutine ) continue;
122437    if( pItem->zName==0 ) continue;
122438    if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
122439    if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
122440    if( sqlite3ExprCompare(0,
122441          pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1)
122442    ){
122443      /* The view was modified by some other optimization such as
122444      ** pushDownWhereTerms() */
122445      continue;
122446    }
122447    return pItem;
122448  }
122449  return 0;
122450}
122451
122452#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
122453/*
122454** Attempt to transform a query of the form
122455**
122456**    SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
122457**
122458** Into this:
122459**
122460**    SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
122461**
122462** The transformation only works if all of the following are true:
122463**
122464**   *  The subquery is a UNION ALL of two or more terms
122465**   *  There is no WHERE or GROUP BY or HAVING clauses on the subqueries
122466**   *  The outer query is a simple count(*)
122467**
122468** Return TRUE if the optimization is undertaken.
122469*/
122470static int countOfViewOptimization(Parse *pParse, Select *p){
122471  Select *pSub, *pPrior;
122472  Expr *pExpr;
122473  Expr *pCount;
122474  sqlite3 *db;
122475  if( (p->selFlags & SF_Aggregate)==0 ) return 0;   /* This is an aggregate query */
122476  if( p->pEList->nExpr!=1 ) return 0;               /* Single result column */
122477  pExpr = p->pEList->a[0].pExpr;
122478  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;        /* Result is an aggregate */
122479  if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0;  /* Must be count() */
122480  if( pExpr->x.pList!=0 ) return 0;                 /* Must be count(*) */
122481  if( p->pSrc->nSrc!=1 ) return 0;                  /* One table in the FROM clause */
122482  pSub = p->pSrc->a[0].pSelect;
122483  if( pSub==0 ) return 0;                           /* The FROM is a subquery */
122484  if( pSub->pPrior==0 ) return 0;                   /* Must be a compound subquery */
122485  do{
122486    if( pSub->op!=TK_ALL && pSub->pPrior ) return 0;  /* Must be UNION ALL */
122487    if( pSub->pWhere ) return 0;                      /* No WHERE clause */
122488    if( pSub->selFlags & SF_Aggregate ) return 0;     /* Not an aggregate */
122489    pSub = pSub->pPrior;                              /* Repeat over compound terms */
122490  }while( pSub );
122491
122492  /* If we reach this point, that means it is OK to perform the transformation */
122493
122494  db = pParse->db;
122495  pCount = pExpr;
122496  pExpr = 0;
122497  pSub = p->pSrc->a[0].pSelect;
122498  p->pSrc->a[0].pSelect = 0;
122499  sqlite3SrcListDelete(db, p->pSrc);
122500  p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
122501  while( pSub ){
122502    Expr *pTerm;
122503    pPrior = pSub->pPrior;
122504    pSub->pPrior = 0;
122505    pSub->pNext = 0;
122506    pSub->selFlags |= SF_Aggregate;
122507    pSub->selFlags &= ~SF_Compound;
122508    pSub->nSelectRow = 0;
122509    sqlite3ExprListDelete(db, pSub->pEList);
122510    pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
122511    pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
122512    pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
122513    sqlite3PExprAddSelect(pParse, pTerm, pSub);
122514    if( pExpr==0 ){
122515      pExpr = pTerm;
122516    }else{
122517      pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
122518    }
122519    pSub = pPrior;
122520  }
122521  p->pEList->a[0].pExpr = pExpr;
122522  p->selFlags &= ~SF_Aggregate;
122523
122524#if SELECTTRACE_ENABLED
122525  if( sqlite3SelectTrace & 0x400 ){
122526    SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
122527    sqlite3TreeViewSelect(0, p, 0);
122528  }
122529#endif
122530  return 1;
122531}
122532#endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
122533
122534/*
122535** Generate code for the SELECT statement given in the p argument.
122536**
122537** The results are returned according to the SelectDest structure.
122538** See comments in sqliteInt.h for further information.
122539**
122540** This routine returns the number of errors.  If any errors are
122541** encountered, then an appropriate error message is left in
122542** pParse->zErrMsg.
122543**
122544** This routine does NOT free the Select structure passed in.  The
122545** calling function needs to do that.
122546*/
122547SQLITE_PRIVATE int sqlite3Select(
122548  Parse *pParse,         /* The parser context */
122549  Select *p,             /* The SELECT statement being coded. */
122550  SelectDest *pDest      /* What to do with the query results */
122551){
122552  int i, j;              /* Loop counters */
122553  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
122554  Vdbe *v;               /* The virtual machine under construction */
122555  int isAgg;             /* True for select lists like "count(*)" */
122556  ExprList *pEList = 0;  /* List of columns to extract. */
122557  SrcList *pTabList;     /* List of tables to select from */
122558  Expr *pWhere;          /* The WHERE clause.  May be NULL */
122559  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
122560  Expr *pHaving;         /* The HAVING clause.  May be NULL */
122561  int rc = 1;            /* Value to return from this function */
122562  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
122563  SortCtx sSort;         /* Info on how to code the ORDER BY clause */
122564  AggInfo sAggInfo;      /* Information used by aggregate queries */
122565  int iEnd;              /* Address of the end of the query */
122566  sqlite3 *db;           /* The database connection */
122567
122568#ifndef SQLITE_OMIT_EXPLAIN
122569  int iRestoreSelectId = pParse->iSelectId;
122570  pParse->iSelectId = pParse->iNextSelectId++;
122571#endif
122572
122573  db = pParse->db;
122574  if( p==0 || db->mallocFailed || pParse->nErr ){
122575    return 1;
122576  }
122577  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
122578  memset(&sAggInfo, 0, sizeof(sAggInfo));
122579#if SELECTTRACE_ENABLED
122580  pParse->nSelectIndent++;
122581  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
122582  if( sqlite3SelectTrace & 0x100 ){
122583    sqlite3TreeViewSelect(0, p, 0);
122584  }
122585#endif
122586
122587  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
122588  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
122589  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
122590  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
122591  if( IgnorableOrderby(pDest) ){
122592    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
122593           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
122594           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
122595           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
122596    /* If ORDER BY makes no difference in the output then neither does
122597    ** DISTINCT so it can be removed too. */
122598    sqlite3ExprListDelete(db, p->pOrderBy);
122599    p->pOrderBy = 0;
122600    p->selFlags &= ~SF_Distinct;
122601  }
122602  sqlite3SelectPrep(pParse, p, 0);
122603  memset(&sSort, 0, sizeof(sSort));
122604  sSort.pOrderBy = p->pOrderBy;
122605  pTabList = p->pSrc;
122606  if( pParse->nErr || db->mallocFailed ){
122607    goto select_end;
122608  }
122609  assert( p->pEList!=0 );
122610  isAgg = (p->selFlags & SF_Aggregate)!=0;
122611#if SELECTTRACE_ENABLED
122612  if( sqlite3SelectTrace & 0x100 ){
122613    SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
122614    sqlite3TreeViewSelect(0, p, 0);
122615  }
122616#endif
122617
122618  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
122619  ** does not already exist */
122620  v = sqlite3GetVdbe(pParse);
122621  if( v==0 ) goto select_end;
122622  if( pDest->eDest==SRT_Output ){
122623    generateColumnNames(pParse, p);
122624  }
122625
122626  /* Try to flatten subqueries in the FROM clause up into the main query
122627  */
122628#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
122629  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
122630    struct SrcList_item *pItem = &pTabList->a[i];
122631    Select *pSub = pItem->pSelect;
122632    int isAggSub;
122633    Table *pTab = pItem->pTab;
122634    if( pSub==0 ) continue;
122635
122636    /* Catch mismatch in the declared columns of a view and the number of
122637    ** columns in the SELECT on the RHS */
122638    if( pTab->nCol!=pSub->pEList->nExpr ){
122639      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
122640                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);
122641      goto select_end;
122642    }
122643
122644    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
122645    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
122646      /* This subquery can be absorbed into its parent. */
122647      if( isAggSub ){
122648        isAgg = 1;
122649        p->selFlags |= SF_Aggregate;
122650      }
122651      i = -1;
122652    }
122653    pTabList = p->pSrc;
122654    if( db->mallocFailed ) goto select_end;
122655    if( !IgnorableOrderby(pDest) ){
122656      sSort.pOrderBy = p->pOrderBy;
122657    }
122658  }
122659#endif
122660
122661#ifndef SQLITE_OMIT_COMPOUND_SELECT
122662  /* Handle compound SELECT statements using the separate multiSelect()
122663  ** procedure.
122664  */
122665  if( p->pPrior ){
122666    rc = multiSelect(pParse, p, pDest);
122667    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
122668#if SELECTTRACE_ENABLED
122669    SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
122670    pParse->nSelectIndent--;
122671#endif
122672    return rc;
122673  }
122674#endif
122675
122676  /* For each term in the FROM clause, do two things:
122677  ** (1) Authorized unreferenced tables
122678  ** (2) Generate code for all sub-queries
122679  */
122680  for(i=0; i<pTabList->nSrc; i++){
122681    struct SrcList_item *pItem = &pTabList->a[i];
122682    SelectDest dest;
122683    Select *pSub;
122684
122685    /* Issue SQLITE_READ authorizations with a fake column name for any tables that
122686    ** are referenced but from which no values are extracted. Examples of where these
122687    ** kinds of null SQLITE_READ authorizations would occur:
122688    **
122689    **     SELECT count(*) FROM t1;   -- SQLITE_READ t1.""
122690    **     SELECT t1.* FROM t1, t2;   -- SQLITE_READ t2.""
122691    **
122692    ** The fake column name is an empty string.  It is possible for a table to
122693    ** have a column named by the empty string, in which case there is no way to
122694    ** distinguish between an unreferenced table and an actual reference to the
122695    ** "" column.  The original design was for the fake column name to be a NULL,
122696    ** which would be unambiguous.  But legacy authorization callbacks might
122697    ** assume the column name is non-NULL and segfault.  The use of an empty string
122698    ** for the fake column name seems safer.
122699    */
122700    if( pItem->colUsed==0 ){
122701      sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
122702    }
122703
122704#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
122705    /* Generate code for all sub-queries in the FROM clause
122706    */
122707    pSub = pItem->pSelect;
122708    if( pSub==0 ) continue;
122709
122710    /* Sometimes the code for a subquery will be generated more than
122711    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
122712    ** for example.  In that case, do not regenerate the code to manifest
122713    ** a view or the co-routine to implement a view.  The first instance
122714    ** is sufficient, though the subroutine to manifest the view does need
122715    ** to be invoked again. */
122716    if( pItem->addrFillSub ){
122717      if( pItem->fg.viaCoroutine==0 ){
122718        /* The subroutine that manifests the view might be a one-time routine,
122719        ** or it might need to be rerun on each iteration because it
122720        ** encodes a correlated subquery. */
122721        testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
122722        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
122723      }
122724      continue;
122725    }
122726
122727    /* Increment Parse.nHeight by the height of the largest expression
122728    ** tree referred to by this, the parent select. The child select
122729    ** may contain expression trees of at most
122730    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
122731    ** more conservative than necessary, but much easier than enforcing
122732    ** an exact limit.
122733    */
122734    pParse->nHeight += sqlite3SelectExprHeight(p);
122735
122736    /* Make copies of constant WHERE-clause terms in the outer query down
122737    ** inside the subquery.  This can help the subquery to run more efficiently.
122738    */
122739    if( (pItem->fg.jointype & JT_OUTER)==0
122740     && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
122741    ){
122742#if SELECTTRACE_ENABLED
122743      if( sqlite3SelectTrace & 0x100 ){
122744        SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
122745        sqlite3TreeViewSelect(0, p, 0);
122746      }
122747#endif
122748    }
122749
122750    /* Generate code to implement the subquery
122751    **
122752    ** The subquery is implemented as a co-routine if all of these are true:
122753    **   (1)  The subquery is guaranteed to be the outer loop (so that it
122754    **        does not need to be computed more than once)
122755    **   (2)  The ALL keyword after SELECT is omitted.  (Applications are
122756    **        allowed to say "SELECT ALL" instead of just "SELECT" to disable
122757    **        the use of co-routines.)
122758    **   (3)  Co-routines are not disabled using sqlite3_test_control()
122759    **        with SQLITE_TESTCTRL_OPTIMIZATIONS.
122760    **
122761    ** TODO: Are there other reasons beside (1) to use a co-routine
122762    ** implementation?
122763    */
122764    if( i==0
122765     && (pTabList->nSrc==1
122766            || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
122767     && (p->selFlags & SF_All)==0                                   /* (2) */
122768     && OptimizationEnabled(db, SQLITE_SubqCoroutine)               /* (3) */
122769    ){
122770      /* Implement a co-routine that will return a single row of the result
122771      ** set on each invocation.
122772      */
122773      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
122774      pItem->regReturn = ++pParse->nMem;
122775      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
122776      VdbeComment((v, "%s", pItem->pTab->zName));
122777      pItem->addrFillSub = addrTop;
122778      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
122779      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
122780      sqlite3Select(pParse, pSub, &dest);
122781      pItem->pTab->nRowLogEst = pSub->nSelectRow;
122782      pItem->fg.viaCoroutine = 1;
122783      pItem->regResult = dest.iSdst;
122784      sqlite3VdbeEndCoroutine(v, pItem->regReturn);
122785      sqlite3VdbeJumpHere(v, addrTop-1);
122786      sqlite3ClearTempRegCache(pParse);
122787    }else{
122788      /* Generate a subroutine that will fill an ephemeral table with
122789      ** the content of this subquery.  pItem->addrFillSub will point
122790      ** to the address of the generated subroutine.  pItem->regReturn
122791      ** is a register allocated to hold the subroutine return address
122792      */
122793      int topAddr;
122794      int onceAddr = 0;
122795      int retAddr;
122796      struct SrcList_item *pPrior;
122797
122798      assert( pItem->addrFillSub==0 );
122799      pItem->regReturn = ++pParse->nMem;
122800      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
122801      pItem->addrFillSub = topAddr+1;
122802      if( pItem->fg.isCorrelated==0 ){
122803        /* If the subquery is not correlated and if we are not inside of
122804        ** a trigger, then we only need to compute the value of the subquery
122805        ** once. */
122806        onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
122807        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
122808      }else{
122809        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
122810      }
122811      pPrior = isSelfJoinView(pTabList, pItem);
122812      if( pPrior ){
122813        sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
122814        explainSetInteger(pItem->iSelectId, pPrior->iSelectId);
122815        assert( pPrior->pSelect!=0 );
122816        pSub->nSelectRow = pPrior->pSelect->nSelectRow;
122817      }else{
122818        sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
122819        explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
122820        sqlite3Select(pParse, pSub, &dest);
122821      }
122822      pItem->pTab->nRowLogEst = pSub->nSelectRow;
122823      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
122824      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
122825      VdbeComment((v, "end %s", pItem->pTab->zName));
122826      sqlite3VdbeChangeP1(v, topAddr, retAddr);
122827      sqlite3ClearTempRegCache(pParse);
122828    }
122829    if( db->mallocFailed ) goto select_end;
122830    pParse->nHeight -= sqlite3SelectExprHeight(p);
122831#endif
122832  }
122833
122834  /* Various elements of the SELECT copied into local variables for
122835  ** convenience */
122836  pEList = p->pEList;
122837  pWhere = p->pWhere;
122838  pGroupBy = p->pGroupBy;
122839  pHaving = p->pHaving;
122840  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
122841
122842#if SELECTTRACE_ENABLED
122843  if( sqlite3SelectTrace & 0x400 ){
122844    SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
122845    sqlite3TreeViewSelect(0, p, 0);
122846  }
122847#endif
122848
122849#ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
122850  if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
122851   && countOfViewOptimization(pParse, p)
122852  ){
122853    if( db->mallocFailed ) goto select_end;
122854    pEList = p->pEList;
122855    pTabList = p->pSrc;
122856  }
122857#endif
122858
122859  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
122860  ** if the select-list is the same as the ORDER BY list, then this query
122861  ** can be rewritten as a GROUP BY. In other words, this:
122862  **
122863  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
122864  **
122865  ** is transformed to:
122866  **
122867  **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
122868  **
122869  ** The second form is preferred as a single index (or temp-table) may be
122870  ** used for both the ORDER BY and DISTINCT processing. As originally
122871  ** written the query must use a temp-table for at least one of the ORDER
122872  ** BY and DISTINCT, and an index or separate temp-table for the other.
122873  */
122874  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
122875   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
122876  ){
122877    p->selFlags &= ~SF_Distinct;
122878    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
122879    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
122880    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
122881    ** original setting of the SF_Distinct flag, not the current setting */
122882    assert( sDistinct.isTnct );
122883
122884#if SELECTTRACE_ENABLED
122885    if( sqlite3SelectTrace & 0x400 ){
122886      SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
122887      sqlite3TreeViewSelect(0, p, 0);
122888    }
122889#endif
122890  }
122891
122892  /* If there is an ORDER BY clause, then create an ephemeral index to
122893  ** do the sorting.  But this sorting ephemeral index might end up
122894  ** being unused if the data can be extracted in pre-sorted order.
122895  ** If that is the case, then the OP_OpenEphemeral instruction will be
122896  ** changed to an OP_Noop once we figure out that the sorting index is
122897  ** not needed.  The sSort.addrSortIndex variable is used to facilitate
122898  ** that change.
122899  */
122900  if( sSort.pOrderBy ){
122901    KeyInfo *pKeyInfo;
122902    pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
122903    sSort.iECursor = pParse->nTab++;
122904    sSort.addrSortIndex =
122905      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
122906          sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
122907          (char*)pKeyInfo, P4_KEYINFO
122908      );
122909  }else{
122910    sSort.addrSortIndex = -1;
122911  }
122912
122913  /* If the output is destined for a temporary table, open that table.
122914  */
122915  if( pDest->eDest==SRT_EphemTab ){
122916    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
122917  }
122918
122919  /* Set the limiter.
122920  */
122921  iEnd = sqlite3VdbeMakeLabel(v);
122922  if( (p->selFlags & SF_FixedLimit)==0 ){
122923    p->nSelectRow = 320;  /* 4 billion rows */
122924  }
122925  computeLimitRegisters(pParse, p, iEnd);
122926  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
122927    sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
122928    sSort.sortFlags |= SORTFLAG_UseSorter;
122929  }
122930
122931  /* Open an ephemeral index to use for the distinct set.
122932  */
122933  if( p->selFlags & SF_Distinct ){
122934    sDistinct.tabTnct = pParse->nTab++;
122935    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
122936                             sDistinct.tabTnct, 0, 0,
122937                             (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
122938                             P4_KEYINFO);
122939    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
122940    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
122941  }else{
122942    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
122943  }
122944
122945  if( !isAgg && pGroupBy==0 ){
122946    /* No aggregate functions and no GROUP BY clause */
122947    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
122948    assert( WHERE_USE_LIMIT==SF_FixedLimit );
122949    wctrlFlags |= p->selFlags & SF_FixedLimit;
122950
122951    /* Begin the database scan. */
122952    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
122953                               p->pEList, wctrlFlags, p->nSelectRow);
122954    if( pWInfo==0 ) goto select_end;
122955    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
122956      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
122957    }
122958    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
122959      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
122960    }
122961    if( sSort.pOrderBy ){
122962      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
122963      sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
122964      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
122965        sSort.pOrderBy = 0;
122966      }
122967    }
122968
122969    /* If sorting index that was created by a prior OP_OpenEphemeral
122970    ** instruction ended up not being needed, then change the OP_OpenEphemeral
122971    ** into an OP_Noop.
122972    */
122973    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
122974      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
122975    }
122976
122977    /* Use the standard inner loop. */
122978    selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
122979                    sqlite3WhereContinueLabel(pWInfo),
122980                    sqlite3WhereBreakLabel(pWInfo));
122981
122982    /* End the database scan loop.
122983    */
122984    sqlite3WhereEnd(pWInfo);
122985  }else{
122986    /* This case when there exist aggregate functions or a GROUP BY clause
122987    ** or both */
122988    NameContext sNC;    /* Name context for processing aggregate information */
122989    int iAMem;          /* First Mem address for storing current GROUP BY */
122990    int iBMem;          /* First Mem address for previous GROUP BY */
122991    int iUseFlag;       /* Mem address holding flag indicating that at least
122992                        ** one row of the input to the aggregator has been
122993                        ** processed */
122994    int iAbortFlag;     /* Mem address which causes query abort if positive */
122995    int groupBySort;    /* Rows come from source in GROUP BY order */
122996    int addrEnd;        /* End of processing for this SELECT */
122997    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
122998    int sortOut = 0;    /* Output register from the sorter */
122999    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
123000
123001    /* Remove any and all aliases between the result set and the
123002    ** GROUP BY clause.
123003    */
123004    if( pGroupBy ){
123005      int k;                        /* Loop counter */
123006      struct ExprList_item *pItem;  /* For looping over expression in a list */
123007
123008      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
123009        pItem->u.x.iAlias = 0;
123010      }
123011      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
123012        pItem->u.x.iAlias = 0;
123013      }
123014      assert( 66==sqlite3LogEst(100) );
123015      if( p->nSelectRow>66 ) p->nSelectRow = 66;
123016    }else{
123017      assert( 0==sqlite3LogEst(1) );
123018      p->nSelectRow = 0;
123019    }
123020
123021    /* If there is both a GROUP BY and an ORDER BY clause and they are
123022    ** identical, then it may be possible to disable the ORDER BY clause
123023    ** on the grounds that the GROUP BY will cause elements to come out
123024    ** in the correct order. It also may not - the GROUP BY might use a
123025    ** database index that causes rows to be grouped together as required
123026    ** but not actually sorted. Either way, record the fact that the
123027    ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
123028    ** variable.  */
123029    if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
123030      orderByGrp = 1;
123031    }
123032
123033    /* Create a label to jump to when we want to abort the query */
123034    addrEnd = sqlite3VdbeMakeLabel(v);
123035
123036    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
123037    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
123038    ** SELECT statement.
123039    */
123040    memset(&sNC, 0, sizeof(sNC));
123041    sNC.pParse = pParse;
123042    sNC.pSrcList = pTabList;
123043    sNC.pAggInfo = &sAggInfo;
123044    sAggInfo.mnReg = pParse->nMem+1;
123045    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
123046    sAggInfo.pGroupBy = pGroupBy;
123047    sqlite3ExprAnalyzeAggList(&sNC, pEList);
123048    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
123049    if( pHaving ){
123050      if( pGroupBy ){
123051        assert( pWhere==p->pWhere );
123052        havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere);
123053        pWhere = p->pWhere;
123054      }
123055      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
123056    }
123057    sAggInfo.nAccumulator = sAggInfo.nColumn;
123058    for(i=0; i<sAggInfo.nFunc; i++){
123059      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
123060      sNC.ncFlags |= NC_InAggFunc;
123061      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
123062      sNC.ncFlags &= ~NC_InAggFunc;
123063    }
123064    sAggInfo.mxReg = pParse->nMem;
123065    if( db->mallocFailed ) goto select_end;
123066
123067    /* Processing for aggregates with GROUP BY is very different and
123068    ** much more complex than aggregates without a GROUP BY.
123069    */
123070    if( pGroupBy ){
123071      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
123072      int addr1;          /* A-vs-B comparision jump */
123073      int addrOutputRow;  /* Start of subroutine that outputs a result row */
123074      int regOutputRow;   /* Return address register for output subroutine */
123075      int addrSetAbort;   /* Set the abort flag and return */
123076      int addrTopOfLoop;  /* Top of the input loop */
123077      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
123078      int addrReset;      /* Subroutine for resetting the accumulator */
123079      int regReset;       /* Return address register for reset subroutine */
123080
123081      /* If there is a GROUP BY clause we might need a sorting index to
123082      ** implement it.  Allocate that sorting index now.  If it turns out
123083      ** that we do not need it after all, the OP_SorterOpen instruction
123084      ** will be converted into a Noop.
123085      */
123086      sAggInfo.sortingIdx = pParse->nTab++;
123087      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
123088      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
123089          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
123090          0, (char*)pKeyInfo, P4_KEYINFO);
123091
123092      /* Initialize memory locations used by GROUP BY aggregate processing
123093      */
123094      iUseFlag = ++pParse->nMem;
123095      iAbortFlag = ++pParse->nMem;
123096      regOutputRow = ++pParse->nMem;
123097      addrOutputRow = sqlite3VdbeMakeLabel(v);
123098      regReset = ++pParse->nMem;
123099      addrReset = sqlite3VdbeMakeLabel(v);
123100      iAMem = pParse->nMem + 1;
123101      pParse->nMem += pGroupBy->nExpr;
123102      iBMem = pParse->nMem + 1;
123103      pParse->nMem += pGroupBy->nExpr;
123104      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
123105      VdbeComment((v, "clear abort flag"));
123106      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
123107      VdbeComment((v, "indicate accumulator empty"));
123108      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
123109
123110      /* Begin a loop that will extract all source rows in GROUP BY order.
123111      ** This might involve two separate loops with an OP_Sort in between, or
123112      ** it might be a single loop that uses an index to extract information
123113      ** in the right order to begin with.
123114      */
123115      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
123116      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
123117          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
123118      );
123119      if( pWInfo==0 ) goto select_end;
123120      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
123121        /* The optimizer is able to deliver rows in group by order so
123122        ** we do not have to sort.  The OP_OpenEphemeral table will be
123123        ** cancelled later because we still need to use the pKeyInfo
123124        */
123125        groupBySort = 0;
123126      }else{
123127        /* Rows are coming out in undetermined order.  We have to push
123128        ** each row into a sorting index, terminate the first loop,
123129        ** then loop over the sorting index in order to get the output
123130        ** in sorted order
123131        */
123132        int regBase;
123133        int regRecord;
123134        int nCol;
123135        int nGroupBy;
123136
123137        explainTempTable(pParse,
123138            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
123139                    "DISTINCT" : "GROUP BY");
123140
123141        groupBySort = 1;
123142        nGroupBy = pGroupBy->nExpr;
123143        nCol = nGroupBy;
123144        j = nGroupBy;
123145        for(i=0; i<sAggInfo.nColumn; i++){
123146          if( sAggInfo.aCol[i].iSorterColumn>=j ){
123147            nCol++;
123148            j++;
123149          }
123150        }
123151        regBase = sqlite3GetTempRange(pParse, nCol);
123152        sqlite3ExprCacheClear(pParse);
123153        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
123154        j = nGroupBy;
123155        for(i=0; i<sAggInfo.nColumn; i++){
123156          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
123157          if( pCol->iSorterColumn>=j ){
123158            int r1 = j + regBase;
123159            sqlite3ExprCodeGetColumnToReg(pParse,
123160                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
123161            j++;
123162          }
123163        }
123164        regRecord = sqlite3GetTempReg(pParse);
123165        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
123166        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
123167        sqlite3ReleaseTempReg(pParse, regRecord);
123168        sqlite3ReleaseTempRange(pParse, regBase, nCol);
123169        sqlite3WhereEnd(pWInfo);
123170        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
123171        sortOut = sqlite3GetTempReg(pParse);
123172        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
123173        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
123174        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
123175        sAggInfo.useSortingIdx = 1;
123176        sqlite3ExprCacheClear(pParse);
123177
123178      }
123179
123180      /* If the index or temporary table used by the GROUP BY sort
123181      ** will naturally deliver rows in the order required by the ORDER BY
123182      ** clause, cancel the ephemeral table open coded earlier.
123183      **
123184      ** This is an optimization - the correct answer should result regardless.
123185      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
123186      ** disable this optimization for testing purposes.  */
123187      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
123188       && (groupBySort || sqlite3WhereIsSorted(pWInfo))
123189      ){
123190        sSort.pOrderBy = 0;
123191        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
123192      }
123193
123194      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
123195      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
123196      ** Then compare the current GROUP BY terms against the GROUP BY terms
123197      ** from the previous row currently stored in a0, a1, a2...
123198      */
123199      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
123200      sqlite3ExprCacheClear(pParse);
123201      if( groupBySort ){
123202        sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
123203                          sortOut, sortPTab);
123204      }
123205      for(j=0; j<pGroupBy->nExpr; j++){
123206        if( groupBySort ){
123207          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
123208        }else{
123209          sAggInfo.directMode = 1;
123210          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
123211        }
123212      }
123213      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
123214                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
123215      addr1 = sqlite3VdbeCurrentAddr(v);
123216      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
123217
123218      /* Generate code that runs whenever the GROUP BY changes.
123219      ** Changes in the GROUP BY are detected by the previous code
123220      ** block.  If there were no changes, this block is skipped.
123221      **
123222      ** This code copies current group by terms in b0,b1,b2,...
123223      ** over to a0,a1,a2.  It then calls the output subroutine
123224      ** and resets the aggregate accumulator registers in preparation
123225      ** for the next GROUP BY batch.
123226      */
123227      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
123228      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
123229      VdbeComment((v, "output one row"));
123230      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
123231      VdbeComment((v, "check abort flag"));
123232      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
123233      VdbeComment((v, "reset accumulator"));
123234
123235      /* Update the aggregate accumulators based on the content of
123236      ** the current row
123237      */
123238      sqlite3VdbeJumpHere(v, addr1);
123239      updateAccumulator(pParse, &sAggInfo);
123240      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
123241      VdbeComment((v, "indicate data in accumulator"));
123242
123243      /* End of the loop
123244      */
123245      if( groupBySort ){
123246        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
123247        VdbeCoverage(v);
123248      }else{
123249        sqlite3WhereEnd(pWInfo);
123250        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
123251      }
123252
123253      /* Output the final row of result
123254      */
123255      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
123256      VdbeComment((v, "output final row"));
123257
123258      /* Jump over the subroutines
123259      */
123260      sqlite3VdbeGoto(v, addrEnd);
123261
123262      /* Generate a subroutine that outputs a single row of the result
123263      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
123264      ** is less than or equal to zero, the subroutine is a no-op.  If
123265      ** the processing calls for the query to abort, this subroutine
123266      ** increments the iAbortFlag memory location before returning in
123267      ** order to signal the caller to abort.
123268      */
123269      addrSetAbort = sqlite3VdbeCurrentAddr(v);
123270      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
123271      VdbeComment((v, "set abort flag"));
123272      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123273      sqlite3VdbeResolveLabel(v, addrOutputRow);
123274      addrOutputRow = sqlite3VdbeCurrentAddr(v);
123275      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
123276      VdbeCoverage(v);
123277      VdbeComment((v, "Groupby result generator entry point"));
123278      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123279      finalizeAggFunctions(pParse, &sAggInfo);
123280      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
123281      selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
123282                      &sDistinct, pDest,
123283                      addrOutputRow+1, addrSetAbort);
123284      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
123285      VdbeComment((v, "end groupby result generator"));
123286
123287      /* Generate a subroutine that will reset the group-by accumulator
123288      */
123289      sqlite3VdbeResolveLabel(v, addrReset);
123290      resetAccumulator(pParse, &sAggInfo);
123291      sqlite3VdbeAddOp1(v, OP_Return, regReset);
123292
123293    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
123294    else {
123295      ExprList *pDel = 0;
123296#ifndef SQLITE_OMIT_BTREECOUNT
123297      Table *pTab;
123298      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
123299        /* If isSimpleCount() returns a pointer to a Table structure, then
123300        ** the SQL statement is of the form:
123301        **
123302        **   SELECT count(*) FROM <tbl>
123303        **
123304        ** where the Table structure returned represents table <tbl>.
123305        **
123306        ** This statement is so common that it is optimized specially. The
123307        ** OP_Count instruction is executed either on the intkey table that
123308        ** contains the data for table <tbl> or on one of its indexes. It
123309        ** is better to execute the op on an index, as indexes are almost
123310        ** always spread across less pages than their corresponding tables.
123311        */
123312        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
123313        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
123314        Index *pIdx;                         /* Iterator variable */
123315        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
123316        Index *pBest = 0;                    /* Best index found so far */
123317        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
123318
123319        sqlite3CodeVerifySchema(pParse, iDb);
123320        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
123321
123322        /* Search for the index that has the lowest scan cost.
123323        **
123324        ** (2011-04-15) Do not do a full scan of an unordered index.
123325        **
123326        ** (2013-10-03) Do not count the entries in a partial index.
123327        **
123328        ** In practice the KeyInfo structure will not be used. It is only
123329        ** passed to keep OP_OpenRead happy.
123330        */
123331        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
123332        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
123333          if( pIdx->bUnordered==0
123334           && pIdx->szIdxRow<pTab->szTabRow
123335           && pIdx->pPartIdxWhere==0
123336           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
123337          ){
123338            pBest = pIdx;
123339          }
123340        }
123341        if( pBest ){
123342          iRoot = pBest->tnum;
123343          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
123344        }
123345
123346        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
123347        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
123348        if( pKeyInfo ){
123349          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
123350        }
123351        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
123352        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
123353        explainSimpleCount(pParse, pTab, pBest);
123354      }else
123355#endif /* SQLITE_OMIT_BTREECOUNT */
123356      {
123357        /* Check if the query is of one of the following forms:
123358        **
123359        **   SELECT min(x) FROM ...
123360        **   SELECT max(x) FROM ...
123361        **
123362        ** If it is, then ask the code in where.c to attempt to sort results
123363        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
123364        ** If where.c is able to produce results sorted in this order, then
123365        ** add vdbe code to break out of the processing loop after the
123366        ** first iteration (since the first iteration of the loop is
123367        ** guaranteed to operate on the row with the minimum or maximum
123368        ** value of x, the only row required).
123369        **
123370        ** A special flag must be passed to sqlite3WhereBegin() to slightly
123371        ** modify behavior as follows:
123372        **
123373        **   + If the query is a "SELECT min(x)", then the loop coded by
123374        **     where.c should not iterate over any values with a NULL value
123375        **     for x.
123376        **
123377        **   + The optimizer code in where.c (the thing that decides which
123378        **     index or indices to use) should place a different priority on
123379        **     satisfying the 'ORDER BY' clause than it does in other cases.
123380        **     Refer to code and comments in where.c for details.
123381        */
123382        ExprList *pMinMax = 0;
123383        u8 flag = WHERE_ORDERBY_NORMAL;
123384
123385        assert( p->pGroupBy==0 );
123386        assert( flag==0 );
123387        if( p->pHaving==0 ){
123388          flag = minMaxQuery(&sAggInfo, &pMinMax);
123389        }
123390        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
123391
123392        if( flag ){
123393          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
123394          pDel = pMinMax;
123395          assert( db->mallocFailed || pMinMax!=0 );
123396          if( !db->mallocFailed ){
123397            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
123398            pMinMax->a[0].pExpr->op = TK_COLUMN;
123399          }
123400        }
123401
123402        /* This case runs if the aggregate has no GROUP BY clause.  The
123403        ** processing is much simpler since there is only a single row
123404        ** of output.
123405        */
123406        resetAccumulator(pParse, &sAggInfo);
123407        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0);
123408        if( pWInfo==0 ){
123409          sqlite3ExprListDelete(db, pDel);
123410          goto select_end;
123411        }
123412        updateAccumulator(pParse, &sAggInfo);
123413        assert( pMinMax==0 || pMinMax->nExpr==1 );
123414        if( sqlite3WhereIsOrdered(pWInfo)>0 ){
123415          sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
123416          VdbeComment((v, "%s() by index",
123417                (flag==WHERE_ORDERBY_MIN?"min":"max")));
123418        }
123419        sqlite3WhereEnd(pWInfo);
123420        finalizeAggFunctions(pParse, &sAggInfo);
123421      }
123422
123423      sSort.pOrderBy = 0;
123424      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
123425      selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
123426                      pDest, addrEnd, addrEnd);
123427      sqlite3ExprListDelete(db, pDel);
123428    }
123429    sqlite3VdbeResolveLabel(v, addrEnd);
123430
123431  } /* endif aggregate query */
123432
123433  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
123434    explainTempTable(pParse, "DISTINCT");
123435  }
123436
123437  /* If there is an ORDER BY clause, then we need to sort the results
123438  ** and send them to the callback one by one.
123439  */
123440  if( sSort.pOrderBy ){
123441    explainTempTable(pParse,
123442                     sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
123443    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
123444  }
123445
123446  /* Jump here to skip this query
123447  */
123448  sqlite3VdbeResolveLabel(v, iEnd);
123449
123450  /* The SELECT has been coded. If there is an error in the Parse structure,
123451  ** set the return code to 1. Otherwise 0. */
123452  rc = (pParse->nErr>0);
123453
123454  /* Control jumps to here if an error is encountered above, or upon
123455  ** successful coding of the SELECT.
123456  */
123457select_end:
123458  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
123459
123460  sqlite3DbFree(db, sAggInfo.aCol);
123461  sqlite3DbFree(db, sAggInfo.aFunc);
123462#if SELECTTRACE_ENABLED
123463  SELECTTRACE(1,pParse,p,("end processing\n"));
123464  pParse->nSelectIndent--;
123465#endif
123466  return rc;
123467}
123468
123469/************** End of select.c **********************************************/
123470/************** Begin file table.c *******************************************/
123471/*
123472** 2001 September 15
123473**
123474** The author disclaims copyright to this source code.  In place of
123475** a legal notice, here is a blessing:
123476**
123477**    May you do good and not evil.
123478**    May you find forgiveness for yourself and forgive others.
123479**    May you share freely, never taking more than you give.
123480**
123481*************************************************************************
123482** This file contains the sqlite3_get_table() and sqlite3_free_table()
123483** interface routines.  These are just wrappers around the main
123484** interface routine of sqlite3_exec().
123485**
123486** These routines are in a separate files so that they will not be linked
123487** if they are not used.
123488*/
123489/* #include "sqliteInt.h" */
123490
123491#ifndef SQLITE_OMIT_GET_TABLE
123492
123493/*
123494** This structure is used to pass data from sqlite3_get_table() through
123495** to the callback function is uses to build the result.
123496*/
123497typedef struct TabResult {
123498  char **azResult;   /* Accumulated output */
123499  char *zErrMsg;     /* Error message text, if an error occurs */
123500  u32 nAlloc;        /* Slots allocated for azResult[] */
123501  u32 nRow;          /* Number of rows in the result */
123502  u32 nColumn;       /* Number of columns in the result */
123503  u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
123504  int rc;            /* Return code from sqlite3_exec() */
123505} TabResult;
123506
123507/*
123508** This routine is called once for each row in the result table.  Its job
123509** is to fill in the TabResult structure appropriately, allocating new
123510** memory as necessary.
123511*/
123512static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
123513  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
123514  int need;                         /* Slots needed in p->azResult[] */
123515  int i;                            /* Loop counter */
123516  char *z;                          /* A single column of result */
123517
123518  /* Make sure there is enough space in p->azResult to hold everything
123519  ** we need to remember from this invocation of the callback.
123520  */
123521  if( p->nRow==0 && argv!=0 ){
123522    need = nCol*2;
123523  }else{
123524    need = nCol;
123525  }
123526  if( p->nData + need > p->nAlloc ){
123527    char **azNew;
123528    p->nAlloc = p->nAlloc*2 + need;
123529    azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
123530    if( azNew==0 ) goto malloc_failed;
123531    p->azResult = azNew;
123532  }
123533
123534  /* If this is the first row, then generate an extra row containing
123535  ** the names of all columns.
123536  */
123537  if( p->nRow==0 ){
123538    p->nColumn = nCol;
123539    for(i=0; i<nCol; i++){
123540      z = sqlite3_mprintf("%s", colv[i]);
123541      if( z==0 ) goto malloc_failed;
123542      p->azResult[p->nData++] = z;
123543    }
123544  }else if( (int)p->nColumn!=nCol ){
123545    sqlite3_free(p->zErrMsg);
123546    p->zErrMsg = sqlite3_mprintf(
123547       "sqlite3_get_table() called with two or more incompatible queries"
123548    );
123549    p->rc = SQLITE_ERROR;
123550    return 1;
123551  }
123552
123553  /* Copy over the row data
123554  */
123555  if( argv!=0 ){
123556    for(i=0; i<nCol; i++){
123557      if( argv[i]==0 ){
123558        z = 0;
123559      }else{
123560        int n = sqlite3Strlen30(argv[i])+1;
123561        z = sqlite3_malloc64( n );
123562        if( z==0 ) goto malloc_failed;
123563        memcpy(z, argv[i], n);
123564      }
123565      p->azResult[p->nData++] = z;
123566    }
123567    p->nRow++;
123568  }
123569  return 0;
123570
123571malloc_failed:
123572  p->rc = SQLITE_NOMEM_BKPT;
123573  return 1;
123574}
123575
123576/*
123577** Query the database.  But instead of invoking a callback for each row,
123578** malloc() for space to hold the result and return the entire results
123579** at the conclusion of the call.
123580**
123581** The result that is written to ***pazResult is held in memory obtained
123582** from malloc().  But the caller cannot free this memory directly.
123583** Instead, the entire table should be passed to sqlite3_free_table() when
123584** the calling procedure is finished using it.
123585*/
123586SQLITE_API int sqlite3_get_table(
123587  sqlite3 *db,                /* The database on which the SQL executes */
123588  const char *zSql,           /* The SQL to be executed */
123589  char ***pazResult,          /* Write the result table here */
123590  int *pnRow,                 /* Write the number of rows in the result here */
123591  int *pnColumn,              /* Write the number of columns of result here */
123592  char **pzErrMsg             /* Write error messages here */
123593){
123594  int rc;
123595  TabResult res;
123596
123597#ifdef SQLITE_ENABLE_API_ARMOR
123598  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
123599#endif
123600  *pazResult = 0;
123601  if( pnColumn ) *pnColumn = 0;
123602  if( pnRow ) *pnRow = 0;
123603  if( pzErrMsg ) *pzErrMsg = 0;
123604  res.zErrMsg = 0;
123605  res.nRow = 0;
123606  res.nColumn = 0;
123607  res.nData = 1;
123608  res.nAlloc = 20;
123609  res.rc = SQLITE_OK;
123610  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
123611  if( res.azResult==0 ){
123612     db->errCode = SQLITE_NOMEM;
123613     return SQLITE_NOMEM_BKPT;
123614  }
123615  res.azResult[0] = 0;
123616  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
123617  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
123618  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
123619  if( (rc&0xff)==SQLITE_ABORT ){
123620    sqlite3_free_table(&res.azResult[1]);
123621    if( res.zErrMsg ){
123622      if( pzErrMsg ){
123623        sqlite3_free(*pzErrMsg);
123624        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
123625      }
123626      sqlite3_free(res.zErrMsg);
123627    }
123628    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
123629    return res.rc;
123630  }
123631  sqlite3_free(res.zErrMsg);
123632  if( rc!=SQLITE_OK ){
123633    sqlite3_free_table(&res.azResult[1]);
123634    return rc;
123635  }
123636  if( res.nAlloc>res.nData ){
123637    char **azNew;
123638    azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
123639    if( azNew==0 ){
123640      sqlite3_free_table(&res.azResult[1]);
123641      db->errCode = SQLITE_NOMEM;
123642      return SQLITE_NOMEM_BKPT;
123643    }
123644    res.azResult = azNew;
123645  }
123646  *pazResult = &res.azResult[1];
123647  if( pnColumn ) *pnColumn = res.nColumn;
123648  if( pnRow ) *pnRow = res.nRow;
123649  return rc;
123650}
123651
123652/*
123653** This routine frees the space the sqlite3_get_table() malloced.
123654*/
123655SQLITE_API void sqlite3_free_table(
123656  char **azResult            /* Result returned from sqlite3_get_table() */
123657){
123658  if( azResult ){
123659    int i, n;
123660    azResult--;
123661    assert( azResult!=0 );
123662    n = SQLITE_PTR_TO_INT(azResult[0]);
123663    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
123664    sqlite3_free(azResult);
123665  }
123666}
123667
123668#endif /* SQLITE_OMIT_GET_TABLE */
123669
123670/************** End of table.c ***********************************************/
123671/************** Begin file trigger.c *****************************************/
123672/*
123673**
123674** The author disclaims copyright to this source code.  In place of
123675** a legal notice, here is a blessing:
123676**
123677**    May you do good and not evil.
123678**    May you find forgiveness for yourself and forgive others.
123679**    May you share freely, never taking more than you give.
123680**
123681*************************************************************************
123682** This file contains the implementation for TRIGGERs
123683*/
123684/* #include "sqliteInt.h" */
123685
123686#ifndef SQLITE_OMIT_TRIGGER
123687/*
123688** Delete a linked list of TriggerStep structures.
123689*/
123690SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
123691  while( pTriggerStep ){
123692    TriggerStep * pTmp = pTriggerStep;
123693    pTriggerStep = pTriggerStep->pNext;
123694
123695    sqlite3ExprDelete(db, pTmp->pWhere);
123696    sqlite3ExprListDelete(db, pTmp->pExprList);
123697    sqlite3SelectDelete(db, pTmp->pSelect);
123698    sqlite3IdListDelete(db, pTmp->pIdList);
123699
123700    sqlite3DbFree(db, pTmp);
123701  }
123702}
123703
123704/*
123705** Given table pTab, return a list of all the triggers attached to
123706** the table. The list is connected by Trigger.pNext pointers.
123707**
123708** All of the triggers on pTab that are in the same database as pTab
123709** are already attached to pTab->pTrigger.  But there might be additional
123710** triggers on pTab in the TEMP schema.  This routine prepends all
123711** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
123712** and returns the combined list.
123713**
123714** To state it another way:  This routine returns a list of all triggers
123715** that fire off of pTab.  The list will include any TEMP triggers on
123716** pTab as well as the triggers lised in pTab->pTrigger.
123717*/
123718SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
123719  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
123720  Trigger *pList = 0;                  /* List of triggers to return */
123721
123722  if( pParse->disableTriggers ){
123723    return 0;
123724  }
123725
123726  if( pTmpSchema!=pTab->pSchema ){
123727    HashElem *p;
123728    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
123729    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
123730      Trigger *pTrig = (Trigger *)sqliteHashData(p);
123731      if( pTrig->pTabSchema==pTab->pSchema
123732       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
123733      ){
123734        pTrig->pNext = (pList ? pList : pTab->pTrigger);
123735        pList = pTrig;
123736      }
123737    }
123738  }
123739
123740  return (pList ? pList : pTab->pTrigger);
123741}
123742
123743/*
123744** This is called by the parser when it sees a CREATE TRIGGER statement
123745** up to the point of the BEGIN before the trigger actions.  A Trigger
123746** structure is generated based on the information available and stored
123747** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
123748** sqlite3FinishTrigger() function is called to complete the trigger
123749** construction process.
123750*/
123751SQLITE_PRIVATE void sqlite3BeginTrigger(
123752  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
123753  Token *pName1,      /* The name of the trigger */
123754  Token *pName2,      /* The name of the trigger */
123755  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
123756  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
123757  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
123758  SrcList *pTableName,/* The name of the table/view the trigger applies to */
123759  Expr *pWhen,        /* WHEN clause */
123760  int isTemp,         /* True if the TEMPORARY keyword is present */
123761  int noErr           /* Suppress errors if the trigger already exists */
123762){
123763  Trigger *pTrigger = 0;  /* The new trigger */
123764  Table *pTab;            /* Table that the trigger fires off of */
123765  char *zName = 0;        /* Name of the trigger */
123766  sqlite3 *db = pParse->db;  /* The database connection */
123767  int iDb;                /* The database to store the trigger in */
123768  Token *pName;           /* The unqualified db name */
123769  DbFixer sFix;           /* State vector for the DB fixer */
123770
123771  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
123772  assert( pName2!=0 );
123773  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
123774  assert( op>0 && op<0xff );
123775  if( isTemp ){
123776    /* If TEMP was specified, then the trigger name may not be qualified. */
123777    if( pName2->n>0 ){
123778      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
123779      goto trigger_cleanup;
123780    }
123781    iDb = 1;
123782    pName = pName1;
123783  }else{
123784    /* Figure out the db that the trigger will be created in */
123785    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
123786    if( iDb<0 ){
123787      goto trigger_cleanup;
123788    }
123789  }
123790  if( !pTableName || db->mallocFailed ){
123791    goto trigger_cleanup;
123792  }
123793
123794  /* A long-standing parser bug is that this syntax was allowed:
123795  **
123796  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
123797  **                                                 ^^^^^^^^
123798  **
123799  ** To maintain backwards compatibility, ignore the database
123800  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
123801  */
123802  if( db->init.busy && iDb!=1 ){
123803    sqlite3DbFree(db, pTableName->a[0].zDatabase);
123804    pTableName->a[0].zDatabase = 0;
123805  }
123806
123807  /* If the trigger name was unqualified, and the table is a temp table,
123808  ** then set iDb to 1 to create the trigger in the temporary database.
123809  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
123810  ** exist, the error is caught by the block below.
123811  */
123812  pTab = sqlite3SrcListLookup(pParse, pTableName);
123813  if( db->init.busy==0 && pName2->n==0 && pTab
123814        && pTab->pSchema==db->aDb[1].pSchema ){
123815    iDb = 1;
123816  }
123817
123818  /* Ensure the table name matches database name and that the table exists */
123819  if( db->mallocFailed ) goto trigger_cleanup;
123820  assert( pTableName->nSrc==1 );
123821  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
123822  if( sqlite3FixSrcList(&sFix, pTableName) ){
123823    goto trigger_cleanup;
123824  }
123825  pTab = sqlite3SrcListLookup(pParse, pTableName);
123826  if( !pTab ){
123827    /* The table does not exist. */
123828    if( db->init.iDb==1 ){
123829      /* Ticket #3810.
123830      ** Normally, whenever a table is dropped, all associated triggers are
123831      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
123832      ** and the table is dropped by a different database connection, the
123833      ** trigger is not visible to the database connection that does the
123834      ** drop so the trigger cannot be dropped.  This results in an
123835      ** "orphaned trigger" - a trigger whose associated table is missing.
123836      */
123837      db->init.orphanTrigger = 1;
123838    }
123839    goto trigger_cleanup;
123840  }
123841  if( IsVirtual(pTab) ){
123842    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
123843    goto trigger_cleanup;
123844  }
123845
123846  /* Check that the trigger name is not reserved and that no trigger of the
123847  ** specified name exists */
123848  zName = sqlite3NameFromToken(db, pName);
123849  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
123850    goto trigger_cleanup;
123851  }
123852  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
123853  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
123854    if( !noErr ){
123855      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
123856    }else{
123857      assert( !db->init.busy );
123858      sqlite3CodeVerifySchema(pParse, iDb);
123859    }
123860    goto trigger_cleanup;
123861  }
123862
123863  /* Do not create a trigger on a system table */
123864  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
123865    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
123866    goto trigger_cleanup;
123867  }
123868
123869  /* INSTEAD of triggers are only for views and views only support INSTEAD
123870  ** of triggers.
123871  */
123872  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
123873    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
123874        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
123875    goto trigger_cleanup;
123876  }
123877  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
123878    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
123879        " trigger on table: %S", pTableName, 0);
123880    goto trigger_cleanup;
123881  }
123882
123883#ifndef SQLITE_OMIT_AUTHORIZATION
123884  {
123885    int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
123886    int code = SQLITE_CREATE_TRIGGER;
123887    const char *zDb = db->aDb[iTabDb].zDbSName;
123888    const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
123889    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
123890    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
123891      goto trigger_cleanup;
123892    }
123893    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
123894      goto trigger_cleanup;
123895    }
123896  }
123897#endif
123898
123899  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
123900  ** cannot appear on views.  So we might as well translate every
123901  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
123902  ** elsewhere.
123903  */
123904  if (tr_tm == TK_INSTEAD){
123905    tr_tm = TK_BEFORE;
123906  }
123907
123908  /* Build the Trigger object */
123909  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
123910  if( pTrigger==0 ) goto trigger_cleanup;
123911  pTrigger->zName = zName;
123912  zName = 0;
123913  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
123914  pTrigger->pSchema = db->aDb[iDb].pSchema;
123915  pTrigger->pTabSchema = pTab->pSchema;
123916  pTrigger->op = (u8)op;
123917  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
123918  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
123919  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
123920  assert( pParse->pNewTrigger==0 );
123921  pParse->pNewTrigger = pTrigger;
123922
123923trigger_cleanup:
123924  sqlite3DbFree(db, zName);
123925  sqlite3SrcListDelete(db, pTableName);
123926  sqlite3IdListDelete(db, pColumns);
123927  sqlite3ExprDelete(db, pWhen);
123928  if( !pParse->pNewTrigger ){
123929    sqlite3DeleteTrigger(db, pTrigger);
123930  }else{
123931    assert( pParse->pNewTrigger==pTrigger );
123932  }
123933}
123934
123935/*
123936** This routine is called after all of the trigger actions have been parsed
123937** in order to complete the process of building the trigger.
123938*/
123939SQLITE_PRIVATE void sqlite3FinishTrigger(
123940  Parse *pParse,          /* Parser context */
123941  TriggerStep *pStepList, /* The triggered program */
123942  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
123943){
123944  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
123945  char *zName;                            /* Name of trigger */
123946  sqlite3 *db = pParse->db;               /* The database */
123947  DbFixer sFix;                           /* Fixer object */
123948  int iDb;                                /* Database containing the trigger */
123949  Token nameToken;                        /* Trigger name for error reporting */
123950
123951  pParse->pNewTrigger = 0;
123952  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
123953  zName = pTrig->zName;
123954  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
123955  pTrig->step_list = pStepList;
123956  while( pStepList ){
123957    pStepList->pTrig = pTrig;
123958    pStepList = pStepList->pNext;
123959  }
123960  sqlite3TokenInit(&nameToken, pTrig->zName);
123961  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
123962  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
123963   || sqlite3FixExpr(&sFix, pTrig->pWhen)
123964  ){
123965    goto triggerfinish_cleanup;
123966  }
123967
123968  /* if we are not initializing,
123969  ** build the sqlite_master entry
123970  */
123971  if( !db->init.busy ){
123972    Vdbe *v;
123973    char *z;
123974
123975    /* Make an entry in the sqlite_master table */
123976    v = sqlite3GetVdbe(pParse);
123977    if( v==0 ) goto triggerfinish_cleanup;
123978    sqlite3BeginWriteOperation(pParse, 0, iDb);
123979    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
123980    testcase( z==0 );
123981    sqlite3NestedParse(pParse,
123982       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
123983       db->aDb[iDb].zDbSName, MASTER_NAME, zName,
123984       pTrig->table, z);
123985    sqlite3DbFree(db, z);
123986    sqlite3ChangeCookie(pParse, iDb);
123987    sqlite3VdbeAddParseSchemaOp(v, iDb,
123988        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
123989  }
123990
123991  if( db->init.busy ){
123992    Trigger *pLink = pTrig;
123993    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
123994    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
123995    pTrig = sqlite3HashInsert(pHash, zName, pTrig);
123996    if( pTrig ){
123997      sqlite3OomFault(db);
123998    }else if( pLink->pSchema==pLink->pTabSchema ){
123999      Table *pTab;
124000      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
124001      assert( pTab!=0 );
124002      pLink->pNext = pTab->pTrigger;
124003      pTab->pTrigger = pLink;
124004    }
124005  }
124006
124007triggerfinish_cleanup:
124008  sqlite3DeleteTrigger(db, pTrig);
124009  assert( !pParse->pNewTrigger );
124010  sqlite3DeleteTriggerStep(db, pStepList);
124011}
124012
124013/*
124014** Turn a SELECT statement (that the pSelect parameter points to) into
124015** a trigger step.  Return a pointer to a TriggerStep structure.
124016**
124017** The parser calls this routine when it finds a SELECT statement in
124018** body of a TRIGGER.
124019*/
124020SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
124021  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
124022  if( pTriggerStep==0 ) {
124023    sqlite3SelectDelete(db, pSelect);
124024    return 0;
124025  }
124026  pTriggerStep->op = TK_SELECT;
124027  pTriggerStep->pSelect = pSelect;
124028  pTriggerStep->orconf = OE_Default;
124029  return pTriggerStep;
124030}
124031
124032/*
124033** Allocate space to hold a new trigger step.  The allocated space
124034** holds both the TriggerStep object and the TriggerStep.target.z string.
124035**
124036** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
124037*/
124038static TriggerStep *triggerStepAllocate(
124039  sqlite3 *db,                /* Database connection */
124040  u8 op,                      /* Trigger opcode */
124041  Token *pName                /* The target name */
124042){
124043  TriggerStep *pTriggerStep;
124044
124045  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
124046  if( pTriggerStep ){
124047    char *z = (char*)&pTriggerStep[1];
124048    memcpy(z, pName->z, pName->n);
124049    sqlite3Dequote(z);
124050    pTriggerStep->zTarget = z;
124051    pTriggerStep->op = op;
124052  }
124053  return pTriggerStep;
124054}
124055
124056/*
124057** Build a trigger step out of an INSERT statement.  Return a pointer
124058** to the new trigger step.
124059**
124060** The parser calls this routine when it sees an INSERT inside the
124061** body of a trigger.
124062*/
124063SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
124064  sqlite3 *db,        /* The database connection */
124065  Token *pTableName,  /* Name of the table into which we insert */
124066  IdList *pColumn,    /* List of columns in pTableName to insert into */
124067  Select *pSelect,    /* A SELECT statement that supplies values */
124068  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
124069){
124070  TriggerStep *pTriggerStep;
124071
124072  assert(pSelect != 0 || db->mallocFailed);
124073
124074  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
124075  if( pTriggerStep ){
124076    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
124077    pTriggerStep->pIdList = pColumn;
124078    pTriggerStep->orconf = orconf;
124079  }else{
124080    sqlite3IdListDelete(db, pColumn);
124081  }
124082  sqlite3SelectDelete(db, pSelect);
124083
124084  return pTriggerStep;
124085}
124086
124087/*
124088** Construct a trigger step that implements an UPDATE statement and return
124089** a pointer to that trigger step.  The parser calls this routine when it
124090** sees an UPDATE statement inside the body of a CREATE TRIGGER.
124091*/
124092SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
124093  sqlite3 *db,         /* The database connection */
124094  Token *pTableName,   /* Name of the table to be updated */
124095  ExprList *pEList,    /* The SET clause: list of column and new values */
124096  Expr *pWhere,        /* The WHERE clause */
124097  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
124098){
124099  TriggerStep *pTriggerStep;
124100
124101  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
124102  if( pTriggerStep ){
124103    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
124104    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
124105    pTriggerStep->orconf = orconf;
124106  }
124107  sqlite3ExprListDelete(db, pEList);
124108  sqlite3ExprDelete(db, pWhere);
124109  return pTriggerStep;
124110}
124111
124112/*
124113** Construct a trigger step that implements a DELETE statement and return
124114** a pointer to that trigger step.  The parser calls this routine when it
124115** sees a DELETE statement inside the body of a CREATE TRIGGER.
124116*/
124117SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
124118  sqlite3 *db,            /* Database connection */
124119  Token *pTableName,      /* The table from which rows are deleted */
124120  Expr *pWhere            /* The WHERE clause */
124121){
124122  TriggerStep *pTriggerStep;
124123
124124  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
124125  if( pTriggerStep ){
124126    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
124127    pTriggerStep->orconf = OE_Default;
124128  }
124129  sqlite3ExprDelete(db, pWhere);
124130  return pTriggerStep;
124131}
124132
124133/*
124134** Recursively delete a Trigger structure
124135*/
124136SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
124137  if( pTrigger==0 ) return;
124138  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
124139  sqlite3DbFree(db, pTrigger->zName);
124140  sqlite3DbFree(db, pTrigger->table);
124141  sqlite3ExprDelete(db, pTrigger->pWhen);
124142  sqlite3IdListDelete(db, pTrigger->pColumns);
124143  sqlite3DbFree(db, pTrigger);
124144}
124145
124146/*
124147** This function is called to drop a trigger from the database schema.
124148**
124149** This may be called directly from the parser and therefore identifies
124150** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
124151** same job as this routine except it takes a pointer to the trigger
124152** instead of the trigger name.
124153**/
124154SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
124155  Trigger *pTrigger = 0;
124156  int i;
124157  const char *zDb;
124158  const char *zName;
124159  sqlite3 *db = pParse->db;
124160
124161  if( db->mallocFailed ) goto drop_trigger_cleanup;
124162  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
124163    goto drop_trigger_cleanup;
124164  }
124165
124166  assert( pName->nSrc==1 );
124167  zDb = pName->a[0].zDatabase;
124168  zName = pName->a[0].zName;
124169  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
124170  for(i=OMIT_TEMPDB; i<db->nDb; i++){
124171    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
124172    if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
124173    assert( sqlite3SchemaMutexHeld(db, j, 0) );
124174    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
124175    if( pTrigger ) break;
124176  }
124177  if( !pTrigger ){
124178    if( !noErr ){
124179      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
124180    }else{
124181      sqlite3CodeVerifyNamedSchema(pParse, zDb);
124182    }
124183    pParse->checkSchema = 1;
124184    goto drop_trigger_cleanup;
124185  }
124186  sqlite3DropTriggerPtr(pParse, pTrigger);
124187
124188drop_trigger_cleanup:
124189  sqlite3SrcListDelete(db, pName);
124190}
124191
124192/*
124193** Return a pointer to the Table structure for the table that a trigger
124194** is set on.
124195*/
124196static Table *tableOfTrigger(Trigger *pTrigger){
124197  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
124198}
124199
124200
124201/*
124202** Drop a trigger given a pointer to that trigger.
124203*/
124204SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
124205  Table   *pTable;
124206  Vdbe *v;
124207  sqlite3 *db = pParse->db;
124208  int iDb;
124209
124210  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
124211  assert( iDb>=0 && iDb<db->nDb );
124212  pTable = tableOfTrigger(pTrigger);
124213  assert( pTable );
124214  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
124215#ifndef SQLITE_OMIT_AUTHORIZATION
124216  {
124217    int code = SQLITE_DROP_TRIGGER;
124218    const char *zDb = db->aDb[iDb].zDbSName;
124219    const char *zTab = SCHEMA_TABLE(iDb);
124220    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
124221    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
124222      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
124223      return;
124224    }
124225  }
124226#endif
124227
124228  /* Generate code to destroy the database record of the trigger.
124229  */
124230  assert( pTable!=0 );
124231  if( (v = sqlite3GetVdbe(pParse))!=0 ){
124232    sqlite3NestedParse(pParse,
124233       "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
124234       db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
124235    );
124236    sqlite3ChangeCookie(pParse, iDb);
124237    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
124238  }
124239}
124240
124241/*
124242** Remove a trigger from the hash tables of the sqlite* pointer.
124243*/
124244SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
124245  Trigger *pTrigger;
124246  Hash *pHash;
124247
124248  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
124249  pHash = &(db->aDb[iDb].pSchema->trigHash);
124250  pTrigger = sqlite3HashInsert(pHash, zName, 0);
124251  if( ALWAYS(pTrigger) ){
124252    if( pTrigger->pSchema==pTrigger->pTabSchema ){
124253      Table *pTab = tableOfTrigger(pTrigger);
124254      Trigger **pp;
124255      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
124256      *pp = (*pp)->pNext;
124257    }
124258    sqlite3DeleteTrigger(db, pTrigger);
124259    db->flags |= SQLITE_InternChanges;
124260  }
124261}
124262
124263/*
124264** pEList is the SET clause of an UPDATE statement.  Each entry
124265** in pEList is of the format <id>=<expr>.  If any of the entries
124266** in pEList have an <id> which matches an identifier in pIdList,
124267** then return TRUE.  If pIdList==NULL, then it is considered a
124268** wildcard that matches anything.  Likewise if pEList==NULL then
124269** it matches anything so always return true.  Return false only
124270** if there is no match.
124271*/
124272static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
124273  int e;
124274  if( pIdList==0 || NEVER(pEList==0) ) return 1;
124275  for(e=0; e<pEList->nExpr; e++){
124276    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
124277  }
124278  return 0;
124279}
124280
124281/*
124282** Return a list of all triggers on table pTab if there exists at least
124283** one trigger that must be fired when an operation of type 'op' is
124284** performed on the table, and, if that operation is an UPDATE, if at
124285** least one of the columns in pChanges is being modified.
124286*/
124287SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
124288  Parse *pParse,          /* Parse context */
124289  Table *pTab,            /* The table the contains the triggers */
124290  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
124291  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
124292  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
124293){
124294  int mask = 0;
124295  Trigger *pList = 0;
124296  Trigger *p;
124297
124298  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
124299    pList = sqlite3TriggerList(pParse, pTab);
124300  }
124301  assert( pList==0 || IsVirtual(pTab)==0 );
124302  for(p=pList; p; p=p->pNext){
124303    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
124304      mask |= p->tr_tm;
124305    }
124306  }
124307  if( pMask ){
124308    *pMask = mask;
124309  }
124310  return (mask ? pList : 0);
124311}
124312
124313/*
124314** Convert the pStep->zTarget string into a SrcList and return a pointer
124315** to that SrcList.
124316**
124317** This routine adds a specific database name, if needed, to the target when
124318** forming the SrcList.  This prevents a trigger in one database from
124319** referring to a target in another database.  An exception is when the
124320** trigger is in TEMP in which case it can refer to any other database it
124321** wants.
124322*/
124323static SrcList *targetSrcList(
124324  Parse *pParse,       /* The parsing context */
124325  TriggerStep *pStep   /* The trigger containing the target token */
124326){
124327  sqlite3 *db = pParse->db;
124328  int iDb;             /* Index of the database to use */
124329  SrcList *pSrc;       /* SrcList to be returned */
124330
124331  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
124332  if( pSrc ){
124333    assert( pSrc->nSrc>0 );
124334    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
124335    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
124336    if( iDb==0 || iDb>=2 ){
124337      const char *zDb;
124338      assert( iDb<db->nDb );
124339      zDb = db->aDb[iDb].zDbSName;
124340      pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);
124341    }
124342  }
124343  return pSrc;
124344}
124345
124346/*
124347** Generate VDBE code for the statements inside the body of a single
124348** trigger.
124349*/
124350static int codeTriggerProgram(
124351  Parse *pParse,            /* The parser context */
124352  TriggerStep *pStepList,   /* List of statements inside the trigger body */
124353  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
124354){
124355  TriggerStep *pStep;
124356  Vdbe *v = pParse->pVdbe;
124357  sqlite3 *db = pParse->db;
124358
124359  assert( pParse->pTriggerTab && pParse->pToplevel );
124360  assert( pStepList );
124361  assert( v!=0 );
124362  for(pStep=pStepList; pStep; pStep=pStep->pNext){
124363    /* Figure out the ON CONFLICT policy that will be used for this step
124364    ** of the trigger program. If the statement that caused this trigger
124365    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
124366    ** the ON CONFLICT policy that was specified as part of the trigger
124367    ** step statement. Example:
124368    **
124369    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
124370    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
124371    **   END;
124372    **
124373    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
124374    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
124375    */
124376    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
124377    assert( pParse->okConstFactor==0 );
124378
124379    switch( pStep->op ){
124380      case TK_UPDATE: {
124381        sqlite3Update(pParse,
124382          targetSrcList(pParse, pStep),
124383          sqlite3ExprListDup(db, pStep->pExprList, 0),
124384          sqlite3ExprDup(db, pStep->pWhere, 0),
124385          pParse->eOrconf
124386        );
124387        break;
124388      }
124389      case TK_INSERT: {
124390        sqlite3Insert(pParse,
124391          targetSrcList(pParse, pStep),
124392          sqlite3SelectDup(db, pStep->pSelect, 0),
124393          sqlite3IdListDup(db, pStep->pIdList),
124394          pParse->eOrconf
124395        );
124396        break;
124397      }
124398      case TK_DELETE: {
124399        sqlite3DeleteFrom(pParse,
124400          targetSrcList(pParse, pStep),
124401          sqlite3ExprDup(db, pStep->pWhere, 0)
124402        );
124403        break;
124404      }
124405      default: assert( pStep->op==TK_SELECT ); {
124406        SelectDest sDest;
124407        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
124408        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
124409        sqlite3Select(pParse, pSelect, &sDest);
124410        sqlite3SelectDelete(db, pSelect);
124411        break;
124412      }
124413    }
124414    if( pStep->op!=TK_SELECT ){
124415      sqlite3VdbeAddOp0(v, OP_ResetCount);
124416    }
124417  }
124418
124419  return 0;
124420}
124421
124422#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
124423/*
124424** This function is used to add VdbeComment() annotations to a VDBE
124425** program. It is not used in production code, only for debugging.
124426*/
124427static const char *onErrorText(int onError){
124428  switch( onError ){
124429    case OE_Abort:    return "abort";
124430    case OE_Rollback: return "rollback";
124431    case OE_Fail:     return "fail";
124432    case OE_Replace:  return "replace";
124433    case OE_Ignore:   return "ignore";
124434    case OE_Default:  return "default";
124435  }
124436  return "n/a";
124437}
124438#endif
124439
124440/*
124441** Parse context structure pFrom has just been used to create a sub-vdbe
124442** (trigger program). If an error has occurred, transfer error information
124443** from pFrom to pTo.
124444*/
124445static void transferParseError(Parse *pTo, Parse *pFrom){
124446  assert( pFrom->zErrMsg==0 || pFrom->nErr );
124447  assert( pTo->zErrMsg==0 || pTo->nErr );
124448  if( pTo->nErr==0 ){
124449    pTo->zErrMsg = pFrom->zErrMsg;
124450    pTo->nErr = pFrom->nErr;
124451    pTo->rc = pFrom->rc;
124452  }else{
124453    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
124454  }
124455}
124456
124457/*
124458** Create and populate a new TriggerPrg object with a sub-program
124459** implementing trigger pTrigger with ON CONFLICT policy orconf.
124460*/
124461static TriggerPrg *codeRowTrigger(
124462  Parse *pParse,       /* Current parse context */
124463  Trigger *pTrigger,   /* Trigger to code */
124464  Table *pTab,         /* The table pTrigger is attached to */
124465  int orconf           /* ON CONFLICT policy to code trigger program with */
124466){
124467  Parse *pTop = sqlite3ParseToplevel(pParse);
124468  sqlite3 *db = pParse->db;   /* Database handle */
124469  TriggerPrg *pPrg;           /* Value to return */
124470  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
124471  Vdbe *v;                    /* Temporary VM */
124472  NameContext sNC;            /* Name context for sub-vdbe */
124473  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
124474  Parse *pSubParse;           /* Parse context for sub-vdbe */
124475  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
124476
124477  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
124478  assert( pTop->pVdbe );
124479
124480  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
124481  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
124482  ** list of the top-level Parse object sooner rather than later.  */
124483  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
124484  if( !pPrg ) return 0;
124485  pPrg->pNext = pTop->pTriggerPrg;
124486  pTop->pTriggerPrg = pPrg;
124487  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
124488  if( !pProgram ) return 0;
124489  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
124490  pPrg->pTrigger = pTrigger;
124491  pPrg->orconf = orconf;
124492  pPrg->aColmask[0] = 0xffffffff;
124493  pPrg->aColmask[1] = 0xffffffff;
124494
124495  /* Allocate and populate a new Parse context to use for coding the
124496  ** trigger sub-program.  */
124497  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
124498  if( !pSubParse ) return 0;
124499  memset(&sNC, 0, sizeof(sNC));
124500  sNC.pParse = pSubParse;
124501  pSubParse->db = db;
124502  pSubParse->pTriggerTab = pTab;
124503  pSubParse->pToplevel = pTop;
124504  pSubParse->zAuthContext = pTrigger->zName;
124505  pSubParse->eTriggerOp = pTrigger->op;
124506  pSubParse->nQueryLoop = pParse->nQueryLoop;
124507
124508  v = sqlite3GetVdbe(pSubParse);
124509  if( v ){
124510    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
124511      pTrigger->zName, onErrorText(orconf),
124512      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
124513        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
124514        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
124515        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
124516      pTab->zName
124517    ));
124518#ifndef SQLITE_OMIT_TRACE
124519    sqlite3VdbeChangeP4(v, -1,
124520      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
124521    );
124522#endif
124523
124524    /* If one was specified, code the WHEN clause. If it evaluates to false
124525    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
124526    ** OP_Halt inserted at the end of the program.  */
124527    if( pTrigger->pWhen ){
124528      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
124529      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
124530       && db->mallocFailed==0
124531      ){
124532        iEndTrigger = sqlite3VdbeMakeLabel(v);
124533        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
124534      }
124535      sqlite3ExprDelete(db, pWhen);
124536    }
124537
124538    /* Code the trigger program into the sub-vdbe. */
124539    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
124540
124541    /* Insert an OP_Halt at the end of the sub-program. */
124542    if( iEndTrigger ){
124543      sqlite3VdbeResolveLabel(v, iEndTrigger);
124544    }
124545    sqlite3VdbeAddOp0(v, OP_Halt);
124546    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
124547
124548    transferParseError(pParse, pSubParse);
124549    if( db->mallocFailed==0 ){
124550      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
124551    }
124552    pProgram->nMem = pSubParse->nMem;
124553    pProgram->nCsr = pSubParse->nTab;
124554    pProgram->token = (void *)pTrigger;
124555    pPrg->aColmask[0] = pSubParse->oldmask;
124556    pPrg->aColmask[1] = pSubParse->newmask;
124557    sqlite3VdbeDelete(v);
124558  }
124559
124560  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
124561  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
124562  sqlite3ParserReset(pSubParse);
124563  sqlite3StackFree(db, pSubParse);
124564
124565  return pPrg;
124566}
124567
124568/*
124569** Return a pointer to a TriggerPrg object containing the sub-program for
124570** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
124571** TriggerPrg object exists, a new object is allocated and populated before
124572** being returned.
124573*/
124574static TriggerPrg *getRowTrigger(
124575  Parse *pParse,       /* Current parse context */
124576  Trigger *pTrigger,   /* Trigger to code */
124577  Table *pTab,         /* The table trigger pTrigger is attached to */
124578  int orconf           /* ON CONFLICT algorithm. */
124579){
124580  Parse *pRoot = sqlite3ParseToplevel(pParse);
124581  TriggerPrg *pPrg;
124582
124583  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
124584
124585  /* It may be that this trigger has already been coded (or is in the
124586  ** process of being coded). If this is the case, then an entry with
124587  ** a matching TriggerPrg.pTrigger field will be present somewhere
124588  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
124589  for(pPrg=pRoot->pTriggerPrg;
124590      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
124591      pPrg=pPrg->pNext
124592  );
124593
124594  /* If an existing TriggerPrg could not be located, create a new one. */
124595  if( !pPrg ){
124596    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
124597  }
124598
124599  return pPrg;
124600}
124601
124602/*
124603** Generate code for the trigger program associated with trigger p on
124604** table pTab. The reg, orconf and ignoreJump parameters passed to this
124605** function are the same as those described in the header function for
124606** sqlite3CodeRowTrigger()
124607*/
124608SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
124609  Parse *pParse,       /* Parse context */
124610  Trigger *p,          /* Trigger to code */
124611  Table *pTab,         /* The table to code triggers from */
124612  int reg,             /* Reg array containing OLD.* and NEW.* values */
124613  int orconf,          /* ON CONFLICT policy */
124614  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
124615){
124616  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
124617  TriggerPrg *pPrg;
124618  pPrg = getRowTrigger(pParse, p, pTab, orconf);
124619  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
124620
124621  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
124622  ** is a pointer to the sub-vdbe containing the trigger program.  */
124623  if( pPrg ){
124624    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
124625
124626    sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
124627                      (const char *)pPrg->pProgram, P4_SUBPROGRAM);
124628    VdbeComment(
124629        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
124630
124631    /* Set the P5 operand of the OP_Program instruction to non-zero if
124632    ** recursive invocation of this trigger program is disallowed. Recursive
124633    ** invocation is disallowed if (a) the sub-program is really a trigger,
124634    ** not a foreign key action, and (b) the flag to enable recursive triggers
124635    ** is clear.  */
124636    sqlite3VdbeChangeP5(v, (u8)bRecursive);
124637  }
124638}
124639
124640/*
124641** This is called to code the required FOR EACH ROW triggers for an operation
124642** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
124643** is given by the op parameter. The tr_tm parameter determines whether the
124644** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
124645** parameter pChanges is passed the list of columns being modified.
124646**
124647** If there are no triggers that fire at the specified time for the specified
124648** operation on pTab, this function is a no-op.
124649**
124650** The reg argument is the address of the first in an array of registers
124651** that contain the values substituted for the new.* and old.* references
124652** in the trigger program. If N is the number of columns in table pTab
124653** (a copy of pTab->nCol), then registers are populated as follows:
124654**
124655**   Register       Contains
124656**   ------------------------------------------------------
124657**   reg+0          OLD.rowid
124658**   reg+1          OLD.* value of left-most column of pTab
124659**   ...            ...
124660**   reg+N          OLD.* value of right-most column of pTab
124661**   reg+N+1        NEW.rowid
124662**   reg+N+2        OLD.* value of left-most column of pTab
124663**   ...            ...
124664**   reg+N+N+1      NEW.* value of right-most column of pTab
124665**
124666** For ON DELETE triggers, the registers containing the NEW.* values will
124667** never be accessed by the trigger program, so they are not allocated or
124668** populated by the caller (there is no data to populate them with anyway).
124669** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
124670** are never accessed, and so are not allocated by the caller. So, for an
124671** ON INSERT trigger, the value passed to this function as parameter reg
124672** is not a readable register, although registers (reg+N) through
124673** (reg+N+N+1) are.
124674**
124675** Parameter orconf is the default conflict resolution algorithm for the
124676** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
124677** is the instruction that control should jump to if a trigger program
124678** raises an IGNORE exception.
124679*/
124680SQLITE_PRIVATE void sqlite3CodeRowTrigger(
124681  Parse *pParse,       /* Parse context */
124682  Trigger *pTrigger,   /* List of triggers on table pTab */
124683  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
124684  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
124685  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
124686  Table *pTab,         /* The table to code triggers from */
124687  int reg,             /* The first in an array of registers (see above) */
124688  int orconf,          /* ON CONFLICT policy */
124689  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
124690){
124691  Trigger *p;          /* Used to iterate through pTrigger list */
124692
124693  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
124694  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
124695  assert( (op==TK_UPDATE)==(pChanges!=0) );
124696
124697  for(p=pTrigger; p; p=p->pNext){
124698
124699    /* Sanity checking:  The schema for the trigger and for the table are
124700    ** always defined.  The trigger must be in the same schema as the table
124701    ** or else it must be a TEMP trigger. */
124702    assert( p->pSchema!=0 );
124703    assert( p->pTabSchema!=0 );
124704    assert( p->pSchema==p->pTabSchema
124705         || p->pSchema==pParse->db->aDb[1].pSchema );
124706
124707    /* Determine whether we should code this trigger */
124708    if( p->op==op
124709     && p->tr_tm==tr_tm
124710     && checkColumnOverlap(p->pColumns, pChanges)
124711    ){
124712      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
124713    }
124714  }
124715}
124716
124717/*
124718** Triggers may access values stored in the old.* or new.* pseudo-table.
124719** This function returns a 32-bit bitmask indicating which columns of the
124720** old.* or new.* tables actually are used by triggers. This information
124721** may be used by the caller, for example, to avoid having to load the entire
124722** old.* record into memory when executing an UPDATE or DELETE command.
124723**
124724** Bit 0 of the returned mask is set if the left-most column of the
124725** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
124726** the second leftmost column value is required, and so on. If there
124727** are more than 32 columns in the table, and at least one of the columns
124728** with an index greater than 32 may be accessed, 0xffffffff is returned.
124729**
124730** It is not possible to determine if the old.rowid or new.rowid column is
124731** accessed by triggers. The caller must always assume that it is.
124732**
124733** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
124734** applies to the old.* table. If 1, the new.* table.
124735**
124736** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
124737** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
124738** included in the returned mask if the TRIGGER_BEFORE bit is set in the
124739** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
124740** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
124741*/
124742SQLITE_PRIVATE u32 sqlite3TriggerColmask(
124743  Parse *pParse,       /* Parse context */
124744  Trigger *pTrigger,   /* List of triggers on table pTab */
124745  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
124746  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
124747  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
124748  Table *pTab,         /* The table to code triggers from */
124749  int orconf           /* Default ON CONFLICT policy for trigger steps */
124750){
124751  const int op = pChanges ? TK_UPDATE : TK_DELETE;
124752  u32 mask = 0;
124753  Trigger *p;
124754
124755  assert( isNew==1 || isNew==0 );
124756  for(p=pTrigger; p; p=p->pNext){
124757    if( p->op==op && (tr_tm&p->tr_tm)
124758     && checkColumnOverlap(p->pColumns,pChanges)
124759    ){
124760      TriggerPrg *pPrg;
124761      pPrg = getRowTrigger(pParse, p, pTab, orconf);
124762      if( pPrg ){
124763        mask |= pPrg->aColmask[isNew];
124764      }
124765    }
124766  }
124767
124768  return mask;
124769}
124770
124771#endif /* !defined(SQLITE_OMIT_TRIGGER) */
124772
124773/************** End of trigger.c *********************************************/
124774/************** Begin file update.c ******************************************/
124775/*
124776** 2001 September 15
124777**
124778** The author disclaims copyright to this source code.  In place of
124779** a legal notice, here is a blessing:
124780**
124781**    May you do good and not evil.
124782**    May you find forgiveness for yourself and forgive others.
124783**    May you share freely, never taking more than you give.
124784**
124785*************************************************************************
124786** This file contains C code routines that are called by the parser
124787** to handle UPDATE statements.
124788*/
124789/* #include "sqliteInt.h" */
124790
124791#ifndef SQLITE_OMIT_VIRTUALTABLE
124792/* Forward declaration */
124793static void updateVirtualTable(
124794  Parse *pParse,       /* The parsing context */
124795  SrcList *pSrc,       /* The virtual table to be modified */
124796  Table *pTab,         /* The virtual table */
124797  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
124798  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
124799  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
124800  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
124801  int onError          /* ON CONFLICT strategy */
124802);
124803#endif /* SQLITE_OMIT_VIRTUALTABLE */
124804
124805/*
124806** The most recently coded instruction was an OP_Column to retrieve the
124807** i-th column of table pTab. This routine sets the P4 parameter of the
124808** OP_Column to the default value, if any.
124809**
124810** The default value of a column is specified by a DEFAULT clause in the
124811** column definition. This was either supplied by the user when the table
124812** was created, or added later to the table definition by an ALTER TABLE
124813** command. If the latter, then the row-records in the table btree on disk
124814** may not contain a value for the column and the default value, taken
124815** from the P4 parameter of the OP_Column instruction, is returned instead.
124816** If the former, then all row-records are guaranteed to include a value
124817** for the column and the P4 value is not required.
124818**
124819** Column definitions created by an ALTER TABLE command may only have
124820** literal default values specified: a number, null or a string. (If a more
124821** complicated default expression value was provided, it is evaluated
124822** when the ALTER TABLE is executed and one of the literal values written
124823** into the sqlite_master table.)
124824**
124825** Therefore, the P4 parameter is only required if the default value for
124826** the column is a literal number, string or null. The sqlite3ValueFromExpr()
124827** function is capable of transforming these types of expressions into
124828** sqlite3_value objects.
124829**
124830** If parameter iReg is not negative, code an OP_RealAffinity instruction
124831** on register iReg. This is used when an equivalent integer value is
124832** stored in place of an 8-byte floating point value in order to save
124833** space.
124834*/
124835SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
124836  assert( pTab!=0 );
124837  if( !pTab->pSelect ){
124838    sqlite3_value *pValue = 0;
124839    u8 enc = ENC(sqlite3VdbeDb(v));
124840    Column *pCol = &pTab->aCol[i];
124841    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
124842    assert( i<pTab->nCol );
124843    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
124844                         pCol->affinity, &pValue);
124845    if( pValue ){
124846      sqlite3VdbeAppendP4(v, pValue, P4_MEM);
124847    }
124848  }
124849#ifndef SQLITE_OMIT_FLOATING_POINT
124850  if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
124851    sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
124852  }
124853#endif
124854}
124855
124856/*
124857** Process an UPDATE statement.
124858**
124859**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
124860**          \_______/ \________/     \______/       \________________/
124861*            onError   pTabList      pChanges             pWhere
124862*/
124863SQLITE_PRIVATE void sqlite3Update(
124864  Parse *pParse,         /* The parser context */
124865  SrcList *pTabList,     /* The table in which we should change things */
124866  ExprList *pChanges,    /* Things to be changed */
124867  Expr *pWhere,          /* The WHERE clause.  May be null */
124868  int onError            /* How to handle constraint errors */
124869){
124870  int i, j;              /* Loop counters */
124871  Table *pTab;           /* The table to be updated */
124872  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
124873  WhereInfo *pWInfo;     /* Information about the WHERE clause */
124874  Vdbe *v;               /* The virtual database engine */
124875  Index *pIdx;           /* For looping over indices */
124876  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
124877  int nIdx;              /* Number of indices that need updating */
124878  int iBaseCur;          /* Base cursor number */
124879  int iDataCur;          /* Cursor for the canonical data btree */
124880  int iIdxCur;           /* Cursor for the first index */
124881  sqlite3 *db;           /* The database structure */
124882  int *aRegIdx = 0;      /* First register in array assigned to each index */
124883  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
124884                         ** an expression for the i-th column of the table.
124885                         ** aXRef[i]==-1 if the i-th column is not changed. */
124886  u8 *aToOpen;           /* 1 for tables and indices to be opened */
124887  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
124888  u8 chngRowid;          /* Rowid changed in a normal table */
124889  u8 chngKey;            /* Either chngPk or chngRowid */
124890  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
124891  AuthContext sContext;  /* The authorization context */
124892  NameContext sNC;       /* The name-context to resolve expressions in */
124893  int iDb;               /* Database containing the table being updated */
124894  int eOnePass;          /* ONEPASS_XXX value from where.c */
124895  int hasFK;             /* True if foreign key processing is required */
124896  int labelBreak;        /* Jump here to break out of UPDATE loop */
124897  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
124898  int flags;             /* Flags for sqlite3WhereBegin() */
124899
124900#ifndef SQLITE_OMIT_TRIGGER
124901  int isView;            /* True when updating a view (INSTEAD OF trigger) */
124902  Trigger *pTrigger;     /* List of triggers on pTab, if required */
124903  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
124904#endif
124905  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
124906  int iEph = 0;          /* Ephemeral table holding all primary key values */
124907  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
124908  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
124909  int addrOpen = 0;      /* Address of OP_OpenEphemeral */
124910  int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
124911  i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
124912  int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
124913
124914  /* Register Allocations */
124915  int regRowCount = 0;   /* A count of rows changed */
124916  int regOldRowid = 0;   /* The old rowid */
124917  int regNewRowid = 0;   /* The new rowid */
124918  int regNew = 0;        /* Content of the NEW.* table in triggers */
124919  int regOld = 0;        /* Content of OLD.* table in triggers */
124920  int regRowSet = 0;     /* Rowset of rows to be updated */
124921  int regKey = 0;        /* composite PRIMARY KEY value */
124922
124923  memset(&sContext, 0, sizeof(sContext));
124924  db = pParse->db;
124925  if( pParse->nErr || db->mallocFailed ){
124926    goto update_cleanup;
124927  }
124928  assert( pTabList->nSrc==1 );
124929
124930  /* Locate the table which we want to update.
124931  */
124932  pTab = sqlite3SrcListLookup(pParse, pTabList);
124933  if( pTab==0 ) goto update_cleanup;
124934  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
124935
124936  /* Figure out if we have any triggers and if the table being
124937  ** updated is a view.
124938  */
124939#ifndef SQLITE_OMIT_TRIGGER
124940  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
124941  isView = pTab->pSelect!=0;
124942  assert( pTrigger || tmask==0 );
124943#else
124944# define pTrigger 0
124945# define isView 0
124946# define tmask 0
124947#endif
124948#ifdef SQLITE_OMIT_VIEW
124949# undef isView
124950# define isView 0
124951#endif
124952
124953  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
124954    goto update_cleanup;
124955  }
124956  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
124957    goto update_cleanup;
124958  }
124959
124960  /* Allocate a cursors for the main database table and for all indices.
124961  ** The index cursors might not be used, but if they are used they
124962  ** need to occur right after the database cursor.  So go ahead and
124963  ** allocate enough space, just in case.
124964  */
124965  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
124966  iIdxCur = iDataCur+1;
124967  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
124968  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
124969    if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
124970      iDataCur = pParse->nTab;
124971      pTabList->a[0].iCursor = iDataCur;
124972    }
124973    pParse->nTab++;
124974  }
124975
124976  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
124977  ** Initialize aXRef[] and aToOpen[] to their default values.
124978  */
124979  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
124980  if( aXRef==0 ) goto update_cleanup;
124981  aRegIdx = aXRef+pTab->nCol;
124982  aToOpen = (u8*)(aRegIdx+nIdx);
124983  memset(aToOpen, 1, nIdx+1);
124984  aToOpen[nIdx+1] = 0;
124985  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
124986
124987  /* Initialize the name-context */
124988  memset(&sNC, 0, sizeof(sNC));
124989  sNC.pParse = pParse;
124990  sNC.pSrcList = pTabList;
124991
124992  /* Resolve the column names in all the expressions of the
124993  ** of the UPDATE statement.  Also find the column index
124994  ** for each column to be updated in the pChanges array.  For each
124995  ** column to be updated, make sure we have authorization to change
124996  ** that column.
124997  */
124998  chngRowid = chngPk = 0;
124999  for(i=0; i<pChanges->nExpr; i++){
125000    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
125001      goto update_cleanup;
125002    }
125003    for(j=0; j<pTab->nCol; j++){
125004      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
125005        if( j==pTab->iPKey ){
125006          chngRowid = 1;
125007          pRowidExpr = pChanges->a[i].pExpr;
125008        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
125009          chngPk = 1;
125010        }
125011        aXRef[j] = i;
125012        break;
125013      }
125014    }
125015    if( j>=pTab->nCol ){
125016      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
125017        j = -1;
125018        chngRowid = 1;
125019        pRowidExpr = pChanges->a[i].pExpr;
125020      }else{
125021        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
125022        pParse->checkSchema = 1;
125023        goto update_cleanup;
125024      }
125025    }
125026#ifndef SQLITE_OMIT_AUTHORIZATION
125027    {
125028      int rc;
125029      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
125030                            j<0 ? "ROWID" : pTab->aCol[j].zName,
125031                            db->aDb[iDb].zDbSName);
125032      if( rc==SQLITE_DENY ){
125033        goto update_cleanup;
125034      }else if( rc==SQLITE_IGNORE ){
125035        aXRef[j] = -1;
125036      }
125037    }
125038#endif
125039  }
125040  assert( (chngRowid & chngPk)==0 );
125041  assert( chngRowid==0 || chngRowid==1 );
125042  assert( chngPk==0 || chngPk==1 );
125043  chngKey = chngRowid + chngPk;
125044
125045  /* The SET expressions are not actually used inside the WHERE loop.
125046  ** So reset the colUsed mask. Unless this is a virtual table. In that
125047  ** case, set all bits of the colUsed mask (to ensure that the virtual
125048  ** table implementation makes all columns available).
125049  */
125050  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
125051
125052  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
125053
125054  /* There is one entry in the aRegIdx[] array for each index on the table
125055  ** being updated.  Fill in aRegIdx[] with a register number that will hold
125056  ** the key for accessing each index.
125057  **
125058  ** FIXME:  Be smarter about omitting indexes that use expressions.
125059  */
125060  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
125061    int reg;
125062    if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
125063      reg = ++pParse->nMem;
125064      pParse->nMem += pIdx->nColumn;
125065    }else{
125066      reg = 0;
125067      for(i=0; i<pIdx->nKeyCol; i++){
125068        i16 iIdxCol = pIdx->aiColumn[i];
125069        if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
125070          reg = ++pParse->nMem;
125071          pParse->nMem += pIdx->nColumn;
125072          if( (onError==OE_Replace)
125073           || (onError==OE_Default && pIdx->onError==OE_Replace)
125074          ){
125075            bReplace = 1;
125076          }
125077          break;
125078        }
125079      }
125080    }
125081    if( reg==0 ) aToOpen[j+1] = 0;
125082    aRegIdx[j] = reg;
125083  }
125084  if( bReplace ){
125085    /* If REPLACE conflict resolution might be invoked, open cursors on all
125086    ** indexes in case they are needed to delete records.  */
125087    memset(aToOpen, 1, nIdx+1);
125088  }
125089
125090  /* Begin generating code. */
125091  v = sqlite3GetVdbe(pParse);
125092  if( v==0 ) goto update_cleanup;
125093  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
125094  sqlite3BeginWriteOperation(pParse, 1, iDb);
125095
125096  /* Allocate required registers. */
125097  if( !IsVirtual(pTab) ){
125098    regRowSet = ++pParse->nMem;
125099    regOldRowid = regNewRowid = ++pParse->nMem;
125100    if( chngPk || pTrigger || hasFK ){
125101      regOld = pParse->nMem + 1;
125102      pParse->nMem += pTab->nCol;
125103    }
125104    if( chngKey || pTrigger || hasFK ){
125105      regNewRowid = ++pParse->nMem;
125106    }
125107    regNew = pParse->nMem + 1;
125108    pParse->nMem += pTab->nCol;
125109  }
125110
125111  /* Start the view context. */
125112  if( isView ){
125113    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
125114  }
125115
125116  /* If we are trying to update a view, realize that view into
125117  ** an ephemeral table.
125118  */
125119#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
125120  if( isView ){
125121    sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
125122  }
125123#endif
125124
125125  /* Resolve the column names in all the expressions in the
125126  ** WHERE clause.
125127  */
125128  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
125129    goto update_cleanup;
125130  }
125131
125132#ifndef SQLITE_OMIT_VIRTUALTABLE
125133  /* Virtual tables must be handled separately */
125134  if( IsVirtual(pTab) ){
125135    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
125136                       pWhere, onError);
125137    goto update_cleanup;
125138  }
125139#endif
125140
125141  /* Initialize the count of updated rows */
125142  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
125143    regRowCount = ++pParse->nMem;
125144    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
125145  }
125146
125147  if( HasRowid(pTab) ){
125148    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
125149  }else{
125150    assert( pPk!=0 );
125151    nPk = pPk->nKeyCol;
125152    iPk = pParse->nMem+1;
125153    pParse->nMem += nPk;
125154    regKey = ++pParse->nMem;
125155    iEph = pParse->nTab++;
125156
125157    sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
125158    addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
125159    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
125160  }
125161
125162  /* Begin the database scan.
125163  **
125164  ** Do not consider a single-pass strategy for a multi-row update if
125165  ** there are any triggers or foreign keys to process, or rows may
125166  ** be deleted as a result of REPLACE conflict handling. Any of these
125167  ** things might disturb a cursor being used to scan through the table
125168  ** or index, causing a single-pass approach to malfunction.  */
125169  flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
125170  if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
125171    flags |= WHERE_ONEPASS_MULTIROW;
125172  }
125173  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
125174  if( pWInfo==0 ) goto update_cleanup;
125175
125176  /* A one-pass strategy that might update more than one row may not
125177  ** be used if any column of the index used for the scan is being
125178  ** updated. Otherwise, if there is an index on "b", statements like
125179  ** the following could create an infinite loop:
125180  **
125181  **   UPDATE t1 SET b=b+1 WHERE b>?
125182  **
125183  ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
125184  ** strategy that uses an index for which one or more columns are being
125185  ** updated.  */
125186  eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
125187  if( eOnePass==ONEPASS_MULTI ){
125188    int iCur = aiCurOnePass[1];
125189    if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
125190      eOnePass = ONEPASS_OFF;
125191    }
125192    assert( iCur!=iDataCur || !HasRowid(pTab) );
125193  }
125194
125195  if( HasRowid(pTab) ){
125196    /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
125197    ** mode, write the rowid into the FIFO. In either of the one-pass modes,
125198    ** leave it in register regOldRowid.  */
125199    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
125200    if( eOnePass==ONEPASS_OFF ){
125201      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
125202    }
125203  }else{
125204    /* Read the PK of the current row into an array of registers. In
125205    ** ONEPASS_OFF mode, serialize the array into a record and store it in
125206    ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
125207    ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
125208    ** is not required) and leave the PK fields in the array of registers.  */
125209    for(i=0; i<nPk; i++){
125210      assert( pPk->aiColumn[i]>=0 );
125211      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
125212    }
125213    if( eOnePass ){
125214      sqlite3VdbeChangeToNoop(v, addrOpen);
125215      nKey = nPk;
125216      regKey = iPk;
125217    }else{
125218      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
125219                        sqlite3IndexAffinityStr(db, pPk), nPk);
125220      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
125221    }
125222  }
125223
125224  if( eOnePass!=ONEPASS_MULTI ){
125225    sqlite3WhereEnd(pWInfo);
125226  }
125227
125228  labelBreak = sqlite3VdbeMakeLabel(v);
125229  if( !isView ){
125230    int addrOnce = 0;
125231
125232    /* Open every index that needs updating. */
125233    if( eOnePass!=ONEPASS_OFF ){
125234      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
125235      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
125236    }
125237
125238    if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
125239      addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
125240    }
125241    sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
125242                               0, 0);
125243    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
125244  }
125245
125246  /* Top of the update loop */
125247  if( eOnePass!=ONEPASS_OFF ){
125248    if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
125249      assert( pPk );
125250      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
125251      VdbeCoverageNeverTaken(v);
125252    }
125253    if( eOnePass==ONEPASS_SINGLE ){
125254      labelContinue = labelBreak;
125255    }else{
125256      labelContinue = sqlite3VdbeMakeLabel(v);
125257    }
125258    sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
125259    VdbeCoverageIf(v, pPk==0);
125260    VdbeCoverageIf(v, pPk!=0);
125261  }else if( pPk ){
125262    labelContinue = sqlite3VdbeMakeLabel(v);
125263    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
125264    addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
125265    sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
125266    VdbeCoverage(v);
125267  }else{
125268    labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
125269                             regOldRowid);
125270    VdbeCoverage(v);
125271    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
125272    VdbeCoverage(v);
125273  }
125274
125275  /* If the record number will change, set register regNewRowid to
125276  ** contain the new value. If the record number is not being modified,
125277  ** then regNewRowid is the same register as regOldRowid, which is
125278  ** already populated.  */
125279  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
125280  if( chngRowid ){
125281    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
125282    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
125283  }
125284
125285  /* Compute the old pre-UPDATE content of the row being changed, if that
125286  ** information is needed */
125287  if( chngPk || hasFK || pTrigger ){
125288    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
125289    oldmask |= sqlite3TriggerColmask(pParse,
125290        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
125291    );
125292    for(i=0; i<pTab->nCol; i++){
125293      if( oldmask==0xffffffff
125294       || (i<32 && (oldmask & MASKBIT32(i))!=0)
125295       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
125296      ){
125297        testcase(  oldmask!=0xffffffff && i==31 );
125298        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
125299      }else{
125300        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
125301      }
125302    }
125303    if( chngRowid==0 && pPk==0 ){
125304      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
125305    }
125306  }
125307
125308  /* Populate the array of registers beginning at regNew with the new
125309  ** row data. This array is used to check constants, create the new
125310  ** table and index records, and as the values for any new.* references
125311  ** made by triggers.
125312  **
125313  ** If there are one or more BEFORE triggers, then do not populate the
125314  ** registers associated with columns that are (a) not modified by
125315  ** this UPDATE statement and (b) not accessed by new.* references. The
125316  ** values for registers not modified by the UPDATE must be reloaded from
125317  ** the database after the BEFORE triggers are fired anyway (as the trigger
125318  ** may have modified them). So not loading those that are not going to
125319  ** be used eliminates some redundant opcodes.
125320  */
125321  newmask = sqlite3TriggerColmask(
125322      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
125323  );
125324  for(i=0; i<pTab->nCol; i++){
125325    if( i==pTab->iPKey ){
125326      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
125327    }else{
125328      j = aXRef[i];
125329      if( j>=0 ){
125330        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
125331      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
125332        /* This branch loads the value of a column that will not be changed
125333        ** into a register. This is done if there are no BEFORE triggers, or
125334        ** if there are one or more BEFORE triggers that use this value via
125335        ** a new.* reference in a trigger program.
125336        */
125337        testcase( i==31 );
125338        testcase( i==32 );
125339        sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
125340      }else{
125341        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
125342      }
125343    }
125344  }
125345
125346  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
125347  ** verified. One could argue that this is wrong.
125348  */
125349  if( tmask&TRIGGER_BEFORE ){
125350    sqlite3TableAffinity(v, pTab, regNew);
125351    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
125352        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
125353
125354    /* The row-trigger may have deleted the row being updated. In this
125355    ** case, jump to the next row. No updates or AFTER triggers are
125356    ** required. This behavior - what happens when the row being updated
125357    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
125358    ** documentation.
125359    */
125360    if( pPk ){
125361      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
125362      VdbeCoverage(v);
125363    }else{
125364      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
125365      VdbeCoverage(v);
125366    }
125367
125368    /* If it did not delete it, the row-trigger may still have modified
125369    ** some of the columns of the row being updated. Load the values for
125370    ** all columns not modified by the update statement into their
125371    ** registers in case this has happened.
125372    */
125373    for(i=0; i<pTab->nCol; i++){
125374      if( aXRef[i]<0 && i!=pTab->iPKey ){
125375        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
125376      }
125377    }
125378  }
125379
125380  if( !isView ){
125381    int addr1 = 0;        /* Address of jump instruction */
125382
125383    /* Do constraint checks. */
125384    assert( regOldRowid>0 );
125385    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
125386        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
125387        aXRef);
125388
125389    /* Do FK constraint checks. */
125390    if( hasFK ){
125391      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
125392    }
125393
125394    /* Delete the index entries associated with the current record.  */
125395    if( bReplace || chngKey ){
125396      if( pPk ){
125397        addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
125398      }else{
125399        addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
125400      }
125401      VdbeCoverageNeverTaken(v);
125402    }
125403    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
125404
125405    /* If changing the rowid value, or if there are foreign key constraints
125406    ** to process, delete the old record. Otherwise, add a noop OP_Delete
125407    ** to invoke the pre-update hook.
125408    **
125409    ** That (regNew==regnewRowid+1) is true is also important for the
125410    ** pre-update hook. If the caller invokes preupdate_new(), the returned
125411    ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
125412    ** is the column index supplied by the user.
125413    */
125414    assert( regNew==regNewRowid+1 );
125415#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
125416    sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
125417        OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
125418        regNewRowid
125419    );
125420    if( eOnePass==ONEPASS_MULTI ){
125421      assert( hasFK==0 && chngKey==0 );
125422      sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
125423    }
125424    if( !pParse->nested ){
125425      sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
125426    }
125427#else
125428    if( hasFK>1 || chngKey ){
125429      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
125430    }
125431#endif
125432    if( bReplace || chngKey ){
125433      sqlite3VdbeJumpHere(v, addr1);
125434    }
125435
125436    if( hasFK ){
125437      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
125438    }
125439
125440    /* Insert the new index entries and the new record. */
125441    sqlite3CompleteInsertion(
125442        pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
125443        OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
125444        0, 0
125445    );
125446
125447    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
125448    ** handle rows (possibly in other tables) that refer via a foreign key
125449    ** to the row just updated. */
125450    if( hasFK ){
125451      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
125452    }
125453  }
125454
125455  /* Increment the row counter
125456  */
125457  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
125458    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
125459  }
125460
125461  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
125462      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
125463
125464  /* Repeat the above with the next record to be updated, until
125465  ** all record selected by the WHERE clause have been updated.
125466  */
125467  if( eOnePass==ONEPASS_SINGLE ){
125468    /* Nothing to do at end-of-loop for a single-pass */
125469  }else if( eOnePass==ONEPASS_MULTI ){
125470    sqlite3VdbeResolveLabel(v, labelContinue);
125471    sqlite3WhereEnd(pWInfo);
125472  }else if( pPk ){
125473    sqlite3VdbeResolveLabel(v, labelContinue);
125474    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
125475  }else{
125476    sqlite3VdbeGoto(v, labelContinue);
125477  }
125478  sqlite3VdbeResolveLabel(v, labelBreak);
125479
125480  /* Update the sqlite_sequence table by storing the content of the
125481  ** maximum rowid counter values recorded while inserting into
125482  ** autoincrement tables.
125483  */
125484  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
125485    sqlite3AutoincrementEnd(pParse);
125486  }
125487
125488  /*
125489  ** Return the number of rows that were changed. If this routine is
125490  ** generating code because of a call to sqlite3NestedParse(), do not
125491  ** invoke the callback function.
125492  */
125493  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
125494    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
125495    sqlite3VdbeSetNumCols(v, 1);
125496    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
125497  }
125498
125499update_cleanup:
125500  sqlite3AuthContextPop(&sContext);
125501  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
125502  sqlite3SrcListDelete(db, pTabList);
125503  sqlite3ExprListDelete(db, pChanges);
125504  sqlite3ExprDelete(db, pWhere);
125505  return;
125506}
125507/* Make sure "isView" and other macros defined above are undefined. Otherwise
125508** they may interfere with compilation of other functions in this file
125509** (or in another file, if this file becomes part of the amalgamation).  */
125510#ifdef isView
125511 #undef isView
125512#endif
125513#ifdef pTrigger
125514 #undef pTrigger
125515#endif
125516
125517#ifndef SQLITE_OMIT_VIRTUALTABLE
125518/*
125519** Generate code for an UPDATE of a virtual table.
125520**
125521** There are two possible strategies - the default and the special
125522** "onepass" strategy. Onepass is only used if the virtual table
125523** implementation indicates that pWhere may match at most one row.
125524**
125525** The default strategy is to create an ephemeral table that contains
125526** for each row to be changed:
125527**
125528**   (A)  The original rowid of that row.
125529**   (B)  The revised rowid for the row.
125530**   (C)  The content of every column in the row.
125531**
125532** Then loop through the contents of this ephemeral table executing a
125533** VUpdate for each row. When finished, drop the ephemeral table.
125534**
125535** The "onepass" strategy does not use an ephemeral table. Instead, it
125536** stores the same values (A, B and C above) in a register array and
125537** makes a single invocation of VUpdate.
125538*/
125539static void updateVirtualTable(
125540  Parse *pParse,       /* The parsing context */
125541  SrcList *pSrc,       /* The virtual table to be modified */
125542  Table *pTab,         /* The virtual table */
125543  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
125544  Expr *pRowid,        /* Expression used to recompute the rowid */
125545  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
125546  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
125547  int onError          /* ON CONFLICT strategy */
125548){
125549  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
125550  int ephemTab;             /* Table holding the result of the SELECT */
125551  int i;                    /* Loop counter */
125552  sqlite3 *db = pParse->db; /* Database connection */
125553  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
125554  WhereInfo *pWInfo;
125555  int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
125556  int regArg;                     /* First register in VUpdate arg array */
125557  int regRec;                     /* Register in which to assemble record */
125558  int regRowid;                   /* Register for ephem table rowid */
125559  int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
125560  int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
125561  int bOnePass;                   /* True to use onepass strategy */
125562  int addr;                       /* Address of OP_OpenEphemeral */
125563
125564  /* Allocate nArg registers to martial the arguments to VUpdate. Then
125565  ** create and open the ephemeral table in which the records created from
125566  ** these arguments will be temporarily stored. */
125567  assert( v );
125568  ephemTab = pParse->nTab++;
125569  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
125570  regArg = pParse->nMem + 1;
125571  pParse->nMem += nArg;
125572  regRec = ++pParse->nMem;
125573  regRowid = ++pParse->nMem;
125574
125575  /* Start scanning the virtual table */
125576  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
125577  if( pWInfo==0 ) return;
125578
125579  /* Populate the argument registers. */
125580  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
125581  if( pRowid ){
125582    sqlite3ExprCode(pParse, pRowid, regArg+1);
125583  }else{
125584    sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
125585  }
125586  for(i=0; i<pTab->nCol; i++){
125587    if( aXRef[i]>=0 ){
125588      sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
125589    }else{
125590      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
125591    }
125592  }
125593
125594  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
125595
125596  if( bOnePass ){
125597    /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
125598    ** above. Also, if this is a top-level parse (not a trigger), clear the
125599    ** multi-write flag so that the VM does not open a statement journal */
125600    sqlite3VdbeChangeToNoop(v, addr);
125601    if( sqlite3IsToplevel(pParse) ){
125602      pParse->isMultiWrite = 0;
125603    }
125604  }else{
125605    /* Create a record from the argument register contents and insert it into
125606    ** the ephemeral table. */
125607    sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
125608    sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
125609    sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
125610  }
125611
125612
125613  if( bOnePass==0 ){
125614    /* End the virtual table scan */
125615    sqlite3WhereEnd(pWInfo);
125616
125617    /* Begin scannning through the ephemeral table. */
125618    addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
125619
125620    /* Extract arguments from the current row of the ephemeral table and
125621    ** invoke the VUpdate method.  */
125622    for(i=0; i<nArg; i++){
125623      sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
125624    }
125625  }
125626  sqlite3VtabMakeWritable(pParse, pTab);
125627  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
125628  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
125629  sqlite3MayAbort(pParse);
125630
125631  /* End of the ephemeral table scan. Or, if using the onepass strategy,
125632  ** jump to here if the scan visited zero rows. */
125633  if( bOnePass==0 ){
125634    sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
125635    sqlite3VdbeJumpHere(v, addr);
125636    sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
125637  }else{
125638    sqlite3WhereEnd(pWInfo);
125639  }
125640}
125641#endif /* SQLITE_OMIT_VIRTUALTABLE */
125642
125643/************** End of update.c **********************************************/
125644/************** Begin file vacuum.c ******************************************/
125645/*
125646** 2003 April 6
125647**
125648** The author disclaims copyright to this source code.  In place of
125649** a legal notice, here is a blessing:
125650**
125651**    May you do good and not evil.
125652**    May you find forgiveness for yourself and forgive others.
125653**    May you share freely, never taking more than you give.
125654**
125655*************************************************************************
125656** This file contains code used to implement the VACUUM command.
125657**
125658** Most of the code in this file may be omitted by defining the
125659** SQLITE_OMIT_VACUUM macro.
125660*/
125661/* #include "sqliteInt.h" */
125662/* #include "vdbeInt.h" */
125663
125664#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
125665
125666/*
125667** Execute zSql on database db.
125668**
125669** If zSql returns rows, then each row will have exactly one
125670** column.  (This will only happen if zSql begins with "SELECT".)
125671** Take each row of result and call execSql() again recursively.
125672**
125673** The execSqlF() routine does the same thing, except it accepts
125674** a format string as its third argument
125675*/
125676static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
125677  sqlite3_stmt *pStmt;
125678  int rc;
125679
125680  /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
125681  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
125682  if( rc!=SQLITE_OK ) return rc;
125683  while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
125684    const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
125685    assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
125686    if( zSubSql ){
125687      assert( zSubSql[0]!='S' );
125688      rc = execSql(db, pzErrMsg, zSubSql);
125689      if( rc!=SQLITE_OK ) break;
125690    }
125691  }
125692  assert( rc!=SQLITE_ROW );
125693  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
125694  if( rc ){
125695    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
125696  }
125697  (void)sqlite3_finalize(pStmt);
125698  return rc;
125699}
125700static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
125701  char *z;
125702  va_list ap;
125703  int rc;
125704  va_start(ap, zSql);
125705  z = sqlite3VMPrintf(db, zSql, ap);
125706  va_end(ap);
125707  if( z==0 ) return SQLITE_NOMEM;
125708  rc = execSql(db, pzErrMsg, z);
125709  sqlite3DbFree(db, z);
125710  return rc;
125711}
125712
125713/*
125714** The VACUUM command is used to clean up the database,
125715** collapse free space, etc.  It is modelled after the VACUUM command
125716** in PostgreSQL.  The VACUUM command works as follows:
125717**
125718**   (1)  Create a new transient database file
125719**   (2)  Copy all content from the database being vacuumed into
125720**        the new transient database file
125721**   (3)  Copy content from the transient database back into the
125722**        original database.
125723**
125724** The transient database requires temporary disk space approximately
125725** equal to the size of the original database.  The copy operation of
125726** step (3) requires additional temporary disk space approximately equal
125727** to the size of the original database for the rollback journal.
125728** Hence, temporary disk space that is approximately 2x the size of the
125729** original database is required.  Every page of the database is written
125730** approximately 3 times:  Once for step (2) and twice for step (3).
125731** Two writes per page are required in step (3) because the original
125732** database content must be written into the rollback journal prior to
125733** overwriting the database with the vacuumed content.
125734**
125735** Only 1x temporary space and only 1x writes would be required if
125736** the copy of step (3) were replaced by deleting the original database
125737** and renaming the transient database as the original.  But that will
125738** not work if other processes are attached to the original database.
125739** And a power loss in between deleting the original and renaming the
125740** transient would cause the database file to appear to be deleted
125741** following reboot.
125742*/
125743SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
125744  Vdbe *v = sqlite3GetVdbe(pParse);
125745  int iDb = 0;
125746  if( v==0 ) return;
125747  if( pNm ){
125748#ifndef SQLITE_BUG_COMPATIBLE_20160819
125749    /* Default behavior:  Report an error if the argument to VACUUM is
125750    ** not recognized */
125751    iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
125752    if( iDb<0 ) return;
125753#else
125754    /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
125755    ** to VACUUM are silently ignored.  This is a back-out of a bug fix that
125756    ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
125757    ** The buggy behavior is required for binary compatibility with some
125758    ** legacy applications. */
125759    iDb = sqlite3FindDb(pParse->db, pNm);
125760    if( iDb<0 ) iDb = 0;
125761#endif
125762  }
125763  if( iDb!=1 ){
125764    sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
125765    sqlite3VdbeUsesBtree(v, iDb);
125766  }
125767  return;
125768}
125769
125770/*
125771** This routine implements the OP_Vacuum opcode of the VDBE.
125772*/
125773SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
125774  int rc = SQLITE_OK;     /* Return code from service routines */
125775  Btree *pMain;           /* The database being vacuumed */
125776  Btree *pTemp;           /* The temporary database we vacuum into */
125777  int saved_flags;        /* Saved value of the db->flags */
125778  int saved_nChange;      /* Saved value of db->nChange */
125779  int saved_nTotalChange; /* Saved value of db->nTotalChange */
125780  u8 saved_mTrace;        /* Saved trace settings */
125781  Db *pDb = 0;            /* Database to detach at end of vacuum */
125782  int isMemDb;            /* True if vacuuming a :memory: database */
125783  int nRes;               /* Bytes of reserved space at the end of each page */
125784  int nDb;                /* Number of attached databases */
125785  const char *zDbMain;    /* Schema name of database to vacuum */
125786
125787  if( !db->autoCommit ){
125788    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
125789    return SQLITE_ERROR;
125790  }
125791  if( db->nVdbeActive>1 ){
125792    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
125793    return SQLITE_ERROR;
125794  }
125795
125796  /* Save the current value of the database flags so that it can be
125797  ** restored before returning. Then set the writable-schema flag, and
125798  ** disable CHECK and foreign key constraints.  */
125799  saved_flags = db->flags;
125800  saved_nChange = db->nChange;
125801  saved_nTotalChange = db->nTotalChange;
125802  saved_mTrace = db->mTrace;
125803  db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks
125804                 | SQLITE_PreferBuiltin | SQLITE_Vacuum);
125805  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
125806  db->mTrace = 0;
125807
125808  zDbMain = db->aDb[iDb].zDbSName;
125809  pMain = db->aDb[iDb].pBt;
125810  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
125811
125812  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
125813  ** can be set to 'off' for this file, as it is not recovered if a crash
125814  ** occurs anyway. The integrity of the database is maintained by a
125815  ** (possibly synchronous) transaction opened on the main database before
125816  ** sqlite3BtreeCopyFile() is called.
125817  **
125818  ** An optimisation would be to use a non-journaled pager.
125819  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
125820  ** that actually made the VACUUM run slower.  Very little journalling
125821  ** actually occurs when doing a vacuum since the vacuum_db is initially
125822  ** empty.  Only the journal header is written.  Apparently it takes more
125823  ** time to parse and run the PRAGMA to turn journalling off than it does
125824  ** to write the journal header file.
125825  */
125826  nDb = db->nDb;
125827  rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
125828  if( rc!=SQLITE_OK ) goto end_of_vacuum;
125829  assert( (db->nDb-1)==nDb );
125830  pDb = &db->aDb[nDb];
125831  assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
125832  pTemp = pDb->pBt;
125833
125834  /* The call to execSql() to attach the temp database has left the file
125835  ** locked (as there was more than one active statement when the transaction
125836  ** to read the schema was concluded. Unlock it here so that this doesn't
125837  ** cause problems for the call to BtreeSetPageSize() below.  */
125838  sqlite3BtreeCommit(pTemp);
125839
125840  nRes = sqlite3BtreeGetOptimalReserve(pMain);
125841
125842  /* A VACUUM cannot change the pagesize of an encrypted database. */
125843#ifdef SQLITE_HAS_CODEC
125844  if( db->nextPagesize ){
125845    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
125846    int nKey;
125847    char *zKey;
125848    sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
125849    if( nKey ) db->nextPagesize = 0;
125850  }
125851#endif
125852
125853  sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
125854  sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
125855  sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
125856
125857  /* Begin a transaction and take an exclusive lock on the main database
125858  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
125859  ** to ensure that we do not try to change the page-size on a WAL database.
125860  */
125861  rc = execSql(db, pzErrMsg, "BEGIN");
125862  if( rc!=SQLITE_OK ) goto end_of_vacuum;
125863  rc = sqlite3BtreeBeginTrans(pMain, 2);
125864  if( rc!=SQLITE_OK ) goto end_of_vacuum;
125865
125866  /* Do not attempt to change the page size for a WAL database */
125867  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
125868                                               ==PAGER_JOURNALMODE_WAL ){
125869    db->nextPagesize = 0;
125870  }
125871
125872  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
125873   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
125874   || NEVER(db->mallocFailed)
125875  ){
125876    rc = SQLITE_NOMEM_BKPT;
125877    goto end_of_vacuum;
125878  }
125879
125880#ifndef SQLITE_OMIT_AUTOVACUUM
125881  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
125882                                           sqlite3BtreeGetAutoVacuum(pMain));
125883#endif
125884
125885  /* Query the schema of the main database. Create a mirror schema
125886  ** in the temporary database.
125887  */
125888  db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
125889  rc = execSqlF(db, pzErrMsg,
125890      "SELECT sql FROM \"%w\".sqlite_master"
125891      " WHERE type='table'AND name<>'sqlite_sequence'"
125892      " AND coalesce(rootpage,1)>0",
125893      zDbMain
125894  );
125895  if( rc!=SQLITE_OK ) goto end_of_vacuum;
125896  rc = execSqlF(db, pzErrMsg,
125897      "SELECT sql FROM \"%w\".sqlite_master"
125898      " WHERE type='index' AND length(sql)>10",
125899      zDbMain
125900  );
125901  if( rc!=SQLITE_OK ) goto end_of_vacuum;
125902  db->init.iDb = 0;
125903
125904  /* Loop through the tables in the main database. For each, do
125905  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
125906  ** the contents to the temporary database.
125907  */
125908  rc = execSqlF(db, pzErrMsg,
125909      "SELECT'INSERT INTO vacuum_db.'||quote(name)"
125910      "||' SELECT*FROM\"%w\".'||quote(name)"
125911      "FROM vacuum_db.sqlite_master "
125912      "WHERE type='table'AND coalesce(rootpage,1)>0",
125913      zDbMain
125914  );
125915  assert( (db->flags & SQLITE_Vacuum)!=0 );
125916  db->flags &= ~SQLITE_Vacuum;
125917  if( rc!=SQLITE_OK ) goto end_of_vacuum;
125918
125919  /* Copy the triggers, views, and virtual tables from the main database
125920  ** over to the temporary database.  None of these objects has any
125921  ** associated storage, so all we have to do is copy their entries
125922  ** from the SQLITE_MASTER table.
125923  */
125924  rc = execSqlF(db, pzErrMsg,
125925      "INSERT INTO vacuum_db.sqlite_master"
125926      " SELECT*FROM \"%w\".sqlite_master"
125927      " WHERE type IN('view','trigger')"
125928      " OR(type='table'AND rootpage=0)",
125929      zDbMain
125930  );
125931  if( rc ) goto end_of_vacuum;
125932
125933  /* At this point, there is a write transaction open on both the
125934  ** vacuum database and the main database. Assuming no error occurs,
125935  ** both transactions are closed by this block - the main database
125936  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
125937  ** call to sqlite3BtreeCommit().
125938  */
125939  {
125940    u32 meta;
125941    int i;
125942
125943    /* This array determines which meta meta values are preserved in the
125944    ** vacuum.  Even entries are the meta value number and odd entries
125945    ** are an increment to apply to the meta value after the vacuum.
125946    ** The increment is used to increase the schema cookie so that other
125947    ** connections to the same database will know to reread the schema.
125948    */
125949    static const unsigned char aCopy[] = {
125950       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
125951       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
125952       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
125953       BTREE_USER_VERSION,       0,  /* Preserve the user version */
125954       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
125955    };
125956
125957    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
125958    assert( 1==sqlite3BtreeIsInTrans(pMain) );
125959
125960    /* Copy Btree meta values */
125961    for(i=0; i<ArraySize(aCopy); i+=2){
125962      /* GetMeta() and UpdateMeta() cannot fail in this context because
125963      ** we already have page 1 loaded into cache and marked dirty. */
125964      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
125965      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
125966      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
125967    }
125968
125969    rc = sqlite3BtreeCopyFile(pMain, pTemp);
125970    if( rc!=SQLITE_OK ) goto end_of_vacuum;
125971    rc = sqlite3BtreeCommit(pTemp);
125972    if( rc!=SQLITE_OK ) goto end_of_vacuum;
125973#ifndef SQLITE_OMIT_AUTOVACUUM
125974    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
125975#endif
125976  }
125977
125978  assert( rc==SQLITE_OK );
125979  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
125980
125981end_of_vacuum:
125982  /* Restore the original value of db->flags */
125983  db->init.iDb = 0;
125984  db->flags = saved_flags;
125985  db->nChange = saved_nChange;
125986  db->nTotalChange = saved_nTotalChange;
125987  db->mTrace = saved_mTrace;
125988  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
125989
125990  /* Currently there is an SQL level transaction open on the vacuum
125991  ** database. No locks are held on any other files (since the main file
125992  ** was committed at the btree level). So it safe to end the transaction
125993  ** by manually setting the autoCommit flag to true and detaching the
125994  ** vacuum database. The vacuum_db journal file is deleted when the pager
125995  ** is closed by the DETACH.
125996  */
125997  db->autoCommit = 1;
125998
125999  if( pDb ){
126000    sqlite3BtreeClose(pDb->pBt);
126001    pDb->pBt = 0;
126002    pDb->pSchema = 0;
126003  }
126004
126005  /* This both clears the schemas and reduces the size of the db->aDb[]
126006  ** array. */
126007  sqlite3ResetAllSchemasOfConnection(db);
126008
126009  return rc;
126010}
126011
126012#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
126013
126014/************** End of vacuum.c **********************************************/
126015/************** Begin file vtab.c ********************************************/
126016/*
126017** 2006 June 10
126018**
126019** The author disclaims copyright to this source code.  In place of
126020** a legal notice, here is a blessing:
126021**
126022**    May you do good and not evil.
126023**    May you find forgiveness for yourself and forgive others.
126024**    May you share freely, never taking more than you give.
126025**
126026*************************************************************************
126027** This file contains code used to help implement virtual tables.
126028*/
126029#ifndef SQLITE_OMIT_VIRTUALTABLE
126030/* #include "sqliteInt.h" */
126031
126032/*
126033** Before a virtual table xCreate() or xConnect() method is invoked, the
126034** sqlite3.pVtabCtx member variable is set to point to an instance of
126035** this struct allocated on the stack. It is used by the implementation of
126036** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
126037** are invoked only from within xCreate and xConnect methods.
126038*/
126039struct VtabCtx {
126040  VTable *pVTable;    /* The virtual table being constructed */
126041  Table *pTab;        /* The Table object to which the virtual table belongs */
126042  VtabCtx *pPrior;    /* Parent context (if any) */
126043  int bDeclared;      /* True after sqlite3_declare_vtab() is called */
126044};
126045
126046/*
126047** Construct and install a Module object for a virtual table.  When this
126048** routine is called, it is guaranteed that all appropriate locks are held
126049** and the module is not already part of the connection.
126050*/
126051SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
126052  sqlite3 *db,                    /* Database in which module is registered */
126053  const char *zName,              /* Name assigned to this module */
126054  const sqlite3_module *pModule,  /* The definition of the module */
126055  void *pAux,                     /* Context pointer for xCreate/xConnect */
126056  void (*xDestroy)(void *)        /* Module destructor function */
126057){
126058  Module *pMod;
126059  int nName = sqlite3Strlen30(zName);
126060  pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
126061  if( pMod ){
126062    Module *pDel;
126063    char *zCopy = (char *)(&pMod[1]);
126064    memcpy(zCopy, zName, nName+1);
126065    pMod->zName = zCopy;
126066    pMod->pModule = pModule;
126067    pMod->pAux = pAux;
126068    pMod->xDestroy = xDestroy;
126069    pMod->pEpoTab = 0;
126070    pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
126071    assert( pDel==0 || pDel==pMod );
126072    if( pDel ){
126073      sqlite3OomFault(db);
126074      sqlite3DbFree(db, pDel);
126075      pMod = 0;
126076    }
126077  }
126078  return pMod;
126079}
126080
126081/*
126082** The actual function that does the work of creating a new module.
126083** This function implements the sqlite3_create_module() and
126084** sqlite3_create_module_v2() interfaces.
126085*/
126086static int createModule(
126087  sqlite3 *db,                    /* Database in which module is registered */
126088  const char *zName,              /* Name assigned to this module */
126089  const sqlite3_module *pModule,  /* The definition of the module */
126090  void *pAux,                     /* Context pointer for xCreate/xConnect */
126091  void (*xDestroy)(void *)        /* Module destructor function */
126092){
126093  int rc = SQLITE_OK;
126094
126095  sqlite3_mutex_enter(db->mutex);
126096  if( sqlite3HashFind(&db->aModule, zName) ){
126097    rc = SQLITE_MISUSE_BKPT;
126098  }else{
126099    (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
126100  }
126101  rc = sqlite3ApiExit(db, rc);
126102  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
126103  sqlite3_mutex_leave(db->mutex);
126104  return rc;
126105}
126106
126107
126108/*
126109** External API function used to create a new virtual-table module.
126110*/
126111SQLITE_API int sqlite3_create_module(
126112  sqlite3 *db,                    /* Database in which module is registered */
126113  const char *zName,              /* Name assigned to this module */
126114  const sqlite3_module *pModule,  /* The definition of the module */
126115  void *pAux                      /* Context pointer for xCreate/xConnect */
126116){
126117#ifdef SQLITE_ENABLE_API_ARMOR
126118  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
126119#endif
126120  return createModule(db, zName, pModule, pAux, 0);
126121}
126122
126123/*
126124** External API function used to create a new virtual-table module.
126125*/
126126SQLITE_API int sqlite3_create_module_v2(
126127  sqlite3 *db,                    /* Database in which module is registered */
126128  const char *zName,              /* Name assigned to this module */
126129  const sqlite3_module *pModule,  /* The definition of the module */
126130  void *pAux,                     /* Context pointer for xCreate/xConnect */
126131  void (*xDestroy)(void *)        /* Module destructor function */
126132){
126133#ifdef SQLITE_ENABLE_API_ARMOR
126134  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
126135#endif
126136  return createModule(db, zName, pModule, pAux, xDestroy);
126137}
126138
126139/*
126140** Lock the virtual table so that it cannot be disconnected.
126141** Locks nest.  Every lock should have a corresponding unlock.
126142** If an unlock is omitted, resources leaks will occur.
126143**
126144** If a disconnect is attempted while a virtual table is locked,
126145** the disconnect is deferred until all locks have been removed.
126146*/
126147SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
126148  pVTab->nRef++;
126149}
126150
126151
126152/*
126153** pTab is a pointer to a Table structure representing a virtual-table.
126154** Return a pointer to the VTable object used by connection db to access
126155** this virtual-table, if one has been created, or NULL otherwise.
126156*/
126157SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
126158  VTable *pVtab;
126159  assert( IsVirtual(pTab) );
126160  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
126161  return pVtab;
126162}
126163
126164/*
126165** Decrement the ref-count on a virtual table object. When the ref-count
126166** reaches zero, call the xDisconnect() method to delete the object.
126167*/
126168SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
126169  sqlite3 *db = pVTab->db;
126170
126171  assert( db );
126172  assert( pVTab->nRef>0 );
126173  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
126174
126175  pVTab->nRef--;
126176  if( pVTab->nRef==0 ){
126177    sqlite3_vtab *p = pVTab->pVtab;
126178    if( p ){
126179      p->pModule->xDisconnect(p);
126180    }
126181    sqlite3DbFree(db, pVTab);
126182  }
126183}
126184
126185/*
126186** Table p is a virtual table. This function moves all elements in the
126187** p->pVTable list to the sqlite3.pDisconnect lists of their associated
126188** database connections to be disconnected at the next opportunity.
126189** Except, if argument db is not NULL, then the entry associated with
126190** connection db is left in the p->pVTable list.
126191*/
126192static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
126193  VTable *pRet = 0;
126194  VTable *pVTable = p->pVTable;
126195  p->pVTable = 0;
126196
126197  /* Assert that the mutex (if any) associated with the BtShared database
126198  ** that contains table p is held by the caller. See header comments
126199  ** above function sqlite3VtabUnlockList() for an explanation of why
126200  ** this makes it safe to access the sqlite3.pDisconnect list of any
126201  ** database connection that may have an entry in the p->pVTable list.
126202  */
126203  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
126204
126205  while( pVTable ){
126206    sqlite3 *db2 = pVTable->db;
126207    VTable *pNext = pVTable->pNext;
126208    assert( db2 );
126209    if( db2==db ){
126210      pRet = pVTable;
126211      p->pVTable = pRet;
126212      pRet->pNext = 0;
126213    }else{
126214      pVTable->pNext = db2->pDisconnect;
126215      db2->pDisconnect = pVTable;
126216    }
126217    pVTable = pNext;
126218  }
126219
126220  assert( !db || pRet );
126221  return pRet;
126222}
126223
126224/*
126225** Table *p is a virtual table. This function removes the VTable object
126226** for table *p associated with database connection db from the linked
126227** list in p->pVTab. It also decrements the VTable ref count. This is
126228** used when closing database connection db to free all of its VTable
126229** objects without disturbing the rest of the Schema object (which may
126230** be being used by other shared-cache connections).
126231*/
126232SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
126233  VTable **ppVTab;
126234
126235  assert( IsVirtual(p) );
126236  assert( sqlite3BtreeHoldsAllMutexes(db) );
126237  assert( sqlite3_mutex_held(db->mutex) );
126238
126239  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
126240    if( (*ppVTab)->db==db  ){
126241      VTable *pVTab = *ppVTab;
126242      *ppVTab = pVTab->pNext;
126243      sqlite3VtabUnlock(pVTab);
126244      break;
126245    }
126246  }
126247}
126248
126249
126250/*
126251** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
126252**
126253** This function may only be called when the mutexes associated with all
126254** shared b-tree databases opened using connection db are held by the
126255** caller. This is done to protect the sqlite3.pDisconnect list. The
126256** sqlite3.pDisconnect list is accessed only as follows:
126257**
126258**   1) By this function. In this case, all BtShared mutexes and the mutex
126259**      associated with the database handle itself must be held.
126260**
126261**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
126262**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
126263**      associated with the database the virtual table is stored in is held
126264**      or, if the virtual table is stored in a non-sharable database, then
126265**      the database handle mutex is held.
126266**
126267** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
126268** by multiple threads. It is thread-safe.
126269*/
126270SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
126271  VTable *p = db->pDisconnect;
126272  db->pDisconnect = 0;
126273
126274  assert( sqlite3BtreeHoldsAllMutexes(db) );
126275  assert( sqlite3_mutex_held(db->mutex) );
126276
126277  if( p ){
126278    sqlite3ExpirePreparedStatements(db);
126279    do {
126280      VTable *pNext = p->pNext;
126281      sqlite3VtabUnlock(p);
126282      p = pNext;
126283    }while( p );
126284  }
126285}
126286
126287/*
126288** Clear any and all virtual-table information from the Table record.
126289** This routine is called, for example, just before deleting the Table
126290** record.
126291**
126292** Since it is a virtual-table, the Table structure contains a pointer
126293** to the head of a linked list of VTable structures. Each VTable
126294** structure is associated with a single sqlite3* user of the schema.
126295** The reference count of the VTable structure associated with database
126296** connection db is decremented immediately (which may lead to the
126297** structure being xDisconnected and free). Any other VTable structures
126298** in the list are moved to the sqlite3.pDisconnect list of the associated
126299** database connection.
126300*/
126301SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
126302  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
126303  if( p->azModuleArg ){
126304    int i;
126305    for(i=0; i<p->nModuleArg; i++){
126306      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
126307    }
126308    sqlite3DbFree(db, p->azModuleArg);
126309  }
126310}
126311
126312/*
126313** Add a new module argument to pTable->azModuleArg[].
126314** The string is not copied - the pointer is stored.  The
126315** string will be freed automatically when the table is
126316** deleted.
126317*/
126318static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
126319  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
126320  char **azModuleArg;
126321  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
126322  if( azModuleArg==0 ){
126323    sqlite3DbFree(db, zArg);
126324  }else{
126325    int i = pTable->nModuleArg++;
126326    azModuleArg[i] = zArg;
126327    azModuleArg[i+1] = 0;
126328    pTable->azModuleArg = azModuleArg;
126329  }
126330}
126331
126332/*
126333** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
126334** statement.  The module name has been parsed, but the optional list
126335** of parameters that follow the module name are still pending.
126336*/
126337SQLITE_PRIVATE void sqlite3VtabBeginParse(
126338  Parse *pParse,        /* Parsing context */
126339  Token *pName1,        /* Name of new table, or database name */
126340  Token *pName2,        /* Name of new table or NULL */
126341  Token *pModuleName,   /* Name of the module for the virtual table */
126342  int ifNotExists       /* No error if the table already exists */
126343){
126344  int iDb;              /* The database the table is being created in */
126345  Table *pTable;        /* The new virtual table */
126346  sqlite3 *db;          /* Database connection */
126347
126348  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
126349  pTable = pParse->pNewTable;
126350  if( pTable==0 ) return;
126351  assert( 0==pTable->pIndex );
126352
126353  db = pParse->db;
126354  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
126355  assert( iDb>=0 );
126356
126357  assert( pTable->nModuleArg==0 );
126358  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
126359  addModuleArgument(db, pTable, 0);
126360  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
126361  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
126362       || (pParse->sNameToken.z==pName1->z && pName2->z==0)
126363  );
126364  pParse->sNameToken.n = (int)(
126365      &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
126366  );
126367
126368#ifndef SQLITE_OMIT_AUTHORIZATION
126369  /* Creating a virtual table invokes the authorization callback twice.
126370  ** The first invocation, to obtain permission to INSERT a row into the
126371  ** sqlite_master table, has already been made by sqlite3StartTable().
126372  ** The second call, to obtain permission to create the table, is made now.
126373  */
126374  if( pTable->azModuleArg ){
126375    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
126376            pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
126377  }
126378#endif
126379}
126380
126381/*
126382** This routine takes the module argument that has been accumulating
126383** in pParse->zArg[] and appends it to the list of arguments on the
126384** virtual table currently under construction in pParse->pTable.
126385*/
126386static void addArgumentToVtab(Parse *pParse){
126387  if( pParse->sArg.z && pParse->pNewTable ){
126388    const char *z = (const char*)pParse->sArg.z;
126389    int n = pParse->sArg.n;
126390    sqlite3 *db = pParse->db;
126391    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
126392  }
126393}
126394
126395/*
126396** The parser calls this routine after the CREATE VIRTUAL TABLE statement
126397** has been completely parsed.
126398*/
126399SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
126400  Table *pTab = pParse->pNewTable;  /* The table being constructed */
126401  sqlite3 *db = pParse->db;         /* The database connection */
126402
126403  if( pTab==0 ) return;
126404  addArgumentToVtab(pParse);
126405  pParse->sArg.z = 0;
126406  if( pTab->nModuleArg<1 ) return;
126407
126408  /* If the CREATE VIRTUAL TABLE statement is being entered for the
126409  ** first time (in other words if the virtual table is actually being
126410  ** created now instead of just being read out of sqlite_master) then
126411  ** do additional initialization work and store the statement text
126412  ** in the sqlite_master table.
126413  */
126414  if( !db->init.busy ){
126415    char *zStmt;
126416    char *zWhere;
126417    int iDb;
126418    int iReg;
126419    Vdbe *v;
126420
126421    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
126422    if( pEnd ){
126423      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
126424    }
126425    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
126426
126427    /* A slot for the record has already been allocated in the
126428    ** SQLITE_MASTER table.  We just need to update that slot with all
126429    ** the information we've collected.
126430    **
126431    ** The VM register number pParse->regRowid holds the rowid of an
126432    ** entry in the sqlite_master table tht was created for this vtab
126433    ** by sqlite3StartTable().
126434    */
126435    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
126436    sqlite3NestedParse(pParse,
126437      "UPDATE %Q.%s "
126438         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
126439       "WHERE rowid=#%d",
126440      db->aDb[iDb].zDbSName, MASTER_NAME,
126441      pTab->zName,
126442      pTab->zName,
126443      zStmt,
126444      pParse->regRowid
126445    );
126446    sqlite3DbFree(db, zStmt);
126447    v = sqlite3GetVdbe(pParse);
126448    sqlite3ChangeCookie(pParse, iDb);
126449
126450    sqlite3VdbeAddOp0(v, OP_Expire);
126451    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
126452    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
126453
126454    iReg = ++pParse->nMem;
126455    sqlite3VdbeLoadString(v, iReg, pTab->zName);
126456    sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
126457  }
126458
126459  /* If we are rereading the sqlite_master table create the in-memory
126460  ** record of the table. The xConnect() method is not called until
126461  ** the first time the virtual table is used in an SQL statement. This
126462  ** allows a schema that contains virtual tables to be loaded before
126463  ** the required virtual table implementations are registered.  */
126464  else {
126465    Table *pOld;
126466    Schema *pSchema = pTab->pSchema;
126467    const char *zName = pTab->zName;
126468    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
126469    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
126470    if( pOld ){
126471      sqlite3OomFault(db);
126472      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
126473      return;
126474    }
126475    pParse->pNewTable = 0;
126476  }
126477}
126478
126479/*
126480** The parser calls this routine when it sees the first token
126481** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
126482*/
126483SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
126484  addArgumentToVtab(pParse);
126485  pParse->sArg.z = 0;
126486  pParse->sArg.n = 0;
126487}
126488
126489/*
126490** The parser calls this routine for each token after the first token
126491** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
126492*/
126493SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
126494  Token *pArg = &pParse->sArg;
126495  if( pArg->z==0 ){
126496    pArg->z = p->z;
126497    pArg->n = p->n;
126498  }else{
126499    assert(pArg->z <= p->z);
126500    pArg->n = (int)(&p->z[p->n] - pArg->z);
126501  }
126502}
126503
126504/*
126505** Invoke a virtual table constructor (either xCreate or xConnect). The
126506** pointer to the function to invoke is passed as the fourth parameter
126507** to this procedure.
126508*/
126509static int vtabCallConstructor(
126510  sqlite3 *db,
126511  Table *pTab,
126512  Module *pMod,
126513  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
126514  char **pzErr
126515){
126516  VtabCtx sCtx;
126517  VTable *pVTable;
126518  int rc;
126519  const char *const*azArg = (const char *const*)pTab->azModuleArg;
126520  int nArg = pTab->nModuleArg;
126521  char *zErr = 0;
126522  char *zModuleName;
126523  int iDb;
126524  VtabCtx *pCtx;
126525
126526  /* Check that the virtual-table is not already being initialized */
126527  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
126528    if( pCtx->pTab==pTab ){
126529      *pzErr = sqlite3MPrintf(db,
126530          "vtable constructor called recursively: %s", pTab->zName
126531      );
126532      return SQLITE_LOCKED;
126533    }
126534  }
126535
126536  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
126537  if( !zModuleName ){
126538    return SQLITE_NOMEM_BKPT;
126539  }
126540
126541  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
126542  if( !pVTable ){
126543    sqlite3DbFree(db, zModuleName);
126544    return SQLITE_NOMEM_BKPT;
126545  }
126546  pVTable->db = db;
126547  pVTable->pMod = pMod;
126548
126549  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
126550  pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
126551
126552  /* Invoke the virtual table constructor */
126553  assert( &db->pVtabCtx );
126554  assert( xConstruct );
126555  sCtx.pTab = pTab;
126556  sCtx.pVTable = pVTable;
126557  sCtx.pPrior = db->pVtabCtx;
126558  sCtx.bDeclared = 0;
126559  db->pVtabCtx = &sCtx;
126560  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
126561  db->pVtabCtx = sCtx.pPrior;
126562  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
126563  assert( sCtx.pTab==pTab );
126564
126565  if( SQLITE_OK!=rc ){
126566    if( zErr==0 ){
126567      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
126568    }else {
126569      *pzErr = sqlite3MPrintf(db, "%s", zErr);
126570      sqlite3_free(zErr);
126571    }
126572    sqlite3DbFree(db, pVTable);
126573  }else if( ALWAYS(pVTable->pVtab) ){
126574    /* Justification of ALWAYS():  A correct vtab constructor must allocate
126575    ** the sqlite3_vtab object if successful.  */
126576    memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
126577    pVTable->pVtab->pModule = pMod->pModule;
126578    pVTable->nRef = 1;
126579    if( sCtx.bDeclared==0 ){
126580      const char *zFormat = "vtable constructor did not declare schema: %s";
126581      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
126582      sqlite3VtabUnlock(pVTable);
126583      rc = SQLITE_ERROR;
126584    }else{
126585      int iCol;
126586      u8 oooHidden = 0;
126587      /* If everything went according to plan, link the new VTable structure
126588      ** into the linked list headed by pTab->pVTable. Then loop through the
126589      ** columns of the table to see if any of them contain the token "hidden".
126590      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
126591      ** the type string.  */
126592      pVTable->pNext = pTab->pVTable;
126593      pTab->pVTable = pVTable;
126594
126595      for(iCol=0; iCol<pTab->nCol; iCol++){
126596        char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
126597        int nType;
126598        int i = 0;
126599        nType = sqlite3Strlen30(zType);
126600        for(i=0; i<nType; i++){
126601          if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
126602           && (i==0 || zType[i-1]==' ')
126603           && (zType[i+6]=='\0' || zType[i+6]==' ')
126604          ){
126605            break;
126606          }
126607        }
126608        if( i<nType ){
126609          int j;
126610          int nDel = 6 + (zType[i+6] ? 1 : 0);
126611          for(j=i; (j+nDel)<=nType; j++){
126612            zType[j] = zType[j+nDel];
126613          }
126614          if( zType[i]=='\0' && i>0 ){
126615            assert(zType[i-1]==' ');
126616            zType[i-1] = '\0';
126617          }
126618          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
126619          oooHidden = TF_OOOHidden;
126620        }else{
126621          pTab->tabFlags |= oooHidden;
126622        }
126623      }
126624    }
126625  }
126626
126627  sqlite3DbFree(db, zModuleName);
126628  return rc;
126629}
126630
126631/*
126632** This function is invoked by the parser to call the xConnect() method
126633** of the virtual table pTab. If an error occurs, an error code is returned
126634** and an error left in pParse.
126635**
126636** This call is a no-op if table pTab is not a virtual table.
126637*/
126638SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
126639  sqlite3 *db = pParse->db;
126640  const char *zMod;
126641  Module *pMod;
126642  int rc;
126643
126644  assert( pTab );
126645  if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
126646    return SQLITE_OK;
126647  }
126648
126649  /* Locate the required virtual table module */
126650  zMod = pTab->azModuleArg[0];
126651  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
126652
126653  if( !pMod ){
126654    const char *zModule = pTab->azModuleArg[0];
126655    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
126656    rc = SQLITE_ERROR;
126657  }else{
126658    char *zErr = 0;
126659    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
126660    if( rc!=SQLITE_OK ){
126661      sqlite3ErrorMsg(pParse, "%s", zErr);
126662    }
126663    sqlite3DbFree(db, zErr);
126664  }
126665
126666  return rc;
126667}
126668/*
126669** Grow the db->aVTrans[] array so that there is room for at least one
126670** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
126671*/
126672static int growVTrans(sqlite3 *db){
126673  const int ARRAY_INCR = 5;
126674
126675  /* Grow the sqlite3.aVTrans array if required */
126676  if( (db->nVTrans%ARRAY_INCR)==0 ){
126677    VTable **aVTrans;
126678    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
126679    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
126680    if( !aVTrans ){
126681      return SQLITE_NOMEM_BKPT;
126682    }
126683    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
126684    db->aVTrans = aVTrans;
126685  }
126686
126687  return SQLITE_OK;
126688}
126689
126690/*
126691** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
126692** have already been reserved using growVTrans().
126693*/
126694static void addToVTrans(sqlite3 *db, VTable *pVTab){
126695  /* Add pVtab to the end of sqlite3.aVTrans */
126696  db->aVTrans[db->nVTrans++] = pVTab;
126697  sqlite3VtabLock(pVTab);
126698}
126699
126700/*
126701** This function is invoked by the vdbe to call the xCreate method
126702** of the virtual table named zTab in database iDb.
126703**
126704** If an error occurs, *pzErr is set to point to an English language
126705** description of the error and an SQLITE_XXX error code is returned.
126706** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
126707*/
126708SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
126709  int rc = SQLITE_OK;
126710  Table *pTab;
126711  Module *pMod;
126712  const char *zMod;
126713
126714  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
126715  assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
126716
126717  /* Locate the required virtual table module */
126718  zMod = pTab->azModuleArg[0];
126719  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
126720
126721  /* If the module has been registered and includes a Create method,
126722  ** invoke it now. If the module has not been registered, return an
126723  ** error. Otherwise, do nothing.
126724  */
126725  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
126726    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
126727    rc = SQLITE_ERROR;
126728  }else{
126729    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
126730  }
126731
126732  /* Justification of ALWAYS():  The xConstructor method is required to
126733  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
126734  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
126735    rc = growVTrans(db);
126736    if( rc==SQLITE_OK ){
126737      addToVTrans(db, sqlite3GetVTable(db, pTab));
126738    }
126739  }
126740
126741  return rc;
126742}
126743
126744/*
126745** This function is used to set the schema of a virtual table.  It is only
126746** valid to call this function from within the xCreate() or xConnect() of a
126747** virtual table module.
126748*/
126749SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
126750  VtabCtx *pCtx;
126751  Parse *pParse;
126752  int rc = SQLITE_OK;
126753  Table *pTab;
126754  char *zErr = 0;
126755
126756#ifdef SQLITE_ENABLE_API_ARMOR
126757  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
126758    return SQLITE_MISUSE_BKPT;
126759  }
126760#endif
126761  sqlite3_mutex_enter(db->mutex);
126762  pCtx = db->pVtabCtx;
126763  if( !pCtx || pCtx->bDeclared ){
126764    sqlite3Error(db, SQLITE_MISUSE);
126765    sqlite3_mutex_leave(db->mutex);
126766    return SQLITE_MISUSE_BKPT;
126767  }
126768  pTab = pCtx->pTab;
126769  assert( IsVirtual(pTab) );
126770
126771  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
126772  if( pParse==0 ){
126773    rc = SQLITE_NOMEM_BKPT;
126774  }else{
126775    pParse->declareVtab = 1;
126776    pParse->db = db;
126777    pParse->nQueryLoop = 1;
126778
126779    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
126780     && pParse->pNewTable
126781     && !db->mallocFailed
126782     && !pParse->pNewTable->pSelect
126783     && !IsVirtual(pParse->pNewTable)
126784    ){
126785      if( !pTab->aCol ){
126786        Table *pNew = pParse->pNewTable;
126787        Index *pIdx;
126788        pTab->aCol = pNew->aCol;
126789        pTab->nCol = pNew->nCol;
126790        pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
126791        pNew->nCol = 0;
126792        pNew->aCol = 0;
126793        assert( pTab->pIndex==0 );
126794        if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
126795          rc = SQLITE_ERROR;
126796        }
126797        pIdx = pNew->pIndex;
126798        if( pIdx ){
126799          assert( pIdx->pNext==0 );
126800          pTab->pIndex = pIdx;
126801          pNew->pIndex = 0;
126802          pIdx->pTable = pTab;
126803        }
126804      }
126805      pCtx->bDeclared = 1;
126806    }else{
126807      sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
126808      sqlite3DbFree(db, zErr);
126809      rc = SQLITE_ERROR;
126810    }
126811    pParse->declareVtab = 0;
126812
126813    if( pParse->pVdbe ){
126814      sqlite3VdbeFinalize(pParse->pVdbe);
126815    }
126816    sqlite3DeleteTable(db, pParse->pNewTable);
126817    sqlite3ParserReset(pParse);
126818    sqlite3StackFree(db, pParse);
126819  }
126820
126821  assert( (rc&0xff)==rc );
126822  rc = sqlite3ApiExit(db, rc);
126823  sqlite3_mutex_leave(db->mutex);
126824  return rc;
126825}
126826
126827/*
126828** This function is invoked by the vdbe to call the xDestroy method
126829** of the virtual table named zTab in database iDb. This occurs
126830** when a DROP TABLE is mentioned.
126831**
126832** This call is a no-op if zTab is not a virtual table.
126833*/
126834SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
126835  int rc = SQLITE_OK;
126836  Table *pTab;
126837
126838  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
126839  if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
126840    VTable *p;
126841    int (*xDestroy)(sqlite3_vtab *);
126842    for(p=pTab->pVTable; p; p=p->pNext){
126843      assert( p->pVtab );
126844      if( p->pVtab->nRef>0 ){
126845        return SQLITE_LOCKED;
126846      }
126847    }
126848    p = vtabDisconnectAll(db, pTab);
126849    xDestroy = p->pMod->pModule->xDestroy;
126850    assert( xDestroy!=0 );  /* Checked before the virtual table is created */
126851    rc = xDestroy(p->pVtab);
126852    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
126853    if( rc==SQLITE_OK ){
126854      assert( pTab->pVTable==p && p->pNext==0 );
126855      p->pVtab = 0;
126856      pTab->pVTable = 0;
126857      sqlite3VtabUnlock(p);
126858    }
126859  }
126860
126861  return rc;
126862}
126863
126864/*
126865** This function invokes either the xRollback or xCommit method
126866** of each of the virtual tables in the sqlite3.aVTrans array. The method
126867** called is identified by the second argument, "offset", which is
126868** the offset of the method to call in the sqlite3_module structure.
126869**
126870** The array is cleared after invoking the callbacks.
126871*/
126872static void callFinaliser(sqlite3 *db, int offset){
126873  int i;
126874  if( db->aVTrans ){
126875    VTable **aVTrans = db->aVTrans;
126876    db->aVTrans = 0;
126877    for(i=0; i<db->nVTrans; i++){
126878      VTable *pVTab = aVTrans[i];
126879      sqlite3_vtab *p = pVTab->pVtab;
126880      if( p ){
126881        int (*x)(sqlite3_vtab *);
126882        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
126883        if( x ) x(p);
126884      }
126885      pVTab->iSavepoint = 0;
126886      sqlite3VtabUnlock(pVTab);
126887    }
126888    sqlite3DbFree(db, aVTrans);
126889    db->nVTrans = 0;
126890  }
126891}
126892
126893/*
126894** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
126895** array. Return the error code for the first error that occurs, or
126896** SQLITE_OK if all xSync operations are successful.
126897**
126898** If an error message is available, leave it in p->zErrMsg.
126899*/
126900SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
126901  int i;
126902  int rc = SQLITE_OK;
126903  VTable **aVTrans = db->aVTrans;
126904
126905  db->aVTrans = 0;
126906  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
126907    int (*x)(sqlite3_vtab *);
126908    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
126909    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
126910      rc = x(pVtab);
126911      sqlite3VtabImportErrmsg(p, pVtab);
126912    }
126913  }
126914  db->aVTrans = aVTrans;
126915  return rc;
126916}
126917
126918/*
126919** Invoke the xRollback method of all virtual tables in the
126920** sqlite3.aVTrans array. Then clear the array itself.
126921*/
126922SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
126923  callFinaliser(db, offsetof(sqlite3_module,xRollback));
126924  return SQLITE_OK;
126925}
126926
126927/*
126928** Invoke the xCommit method of all virtual tables in the
126929** sqlite3.aVTrans array. Then clear the array itself.
126930*/
126931SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
126932  callFinaliser(db, offsetof(sqlite3_module,xCommit));
126933  return SQLITE_OK;
126934}
126935
126936/*
126937** If the virtual table pVtab supports the transaction interface
126938** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
126939** not currently open, invoke the xBegin method now.
126940**
126941** If the xBegin call is successful, place the sqlite3_vtab pointer
126942** in the sqlite3.aVTrans array.
126943*/
126944SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
126945  int rc = SQLITE_OK;
126946  const sqlite3_module *pModule;
126947
126948  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
126949  ** than zero, then this function is being called from within a
126950  ** virtual module xSync() callback. It is illegal to write to
126951  ** virtual module tables in this case, so return SQLITE_LOCKED.
126952  */
126953  if( sqlite3VtabInSync(db) ){
126954    return SQLITE_LOCKED;
126955  }
126956  if( !pVTab ){
126957    return SQLITE_OK;
126958  }
126959  pModule = pVTab->pVtab->pModule;
126960
126961  if( pModule->xBegin ){
126962    int i;
126963
126964    /* If pVtab is already in the aVTrans array, return early */
126965    for(i=0; i<db->nVTrans; i++){
126966      if( db->aVTrans[i]==pVTab ){
126967        return SQLITE_OK;
126968      }
126969    }
126970
126971    /* Invoke the xBegin method. If successful, add the vtab to the
126972    ** sqlite3.aVTrans[] array. */
126973    rc = growVTrans(db);
126974    if( rc==SQLITE_OK ){
126975      rc = pModule->xBegin(pVTab->pVtab);
126976      if( rc==SQLITE_OK ){
126977        int iSvpt = db->nStatement + db->nSavepoint;
126978        addToVTrans(db, pVTab);
126979        if( iSvpt && pModule->xSavepoint ){
126980          pVTab->iSavepoint = iSvpt;
126981          rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
126982        }
126983      }
126984    }
126985  }
126986  return rc;
126987}
126988
126989/*
126990** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
126991** virtual tables that currently have an open transaction. Pass iSavepoint
126992** as the second argument to the virtual table method invoked.
126993**
126994** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
126995** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
126996** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
126997** an open transaction is invoked.
126998**
126999** If any virtual table method returns an error code other than SQLITE_OK,
127000** processing is abandoned and the error returned to the caller of this
127001** function immediately. If all calls to virtual table methods are successful,
127002** SQLITE_OK is returned.
127003*/
127004SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
127005  int rc = SQLITE_OK;
127006
127007  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
127008  assert( iSavepoint>=-1 );
127009  if( db->aVTrans ){
127010    int i;
127011    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
127012      VTable *pVTab = db->aVTrans[i];
127013      const sqlite3_module *pMod = pVTab->pMod->pModule;
127014      if( pVTab->pVtab && pMod->iVersion>=2 ){
127015        int (*xMethod)(sqlite3_vtab *, int);
127016        switch( op ){
127017          case SAVEPOINT_BEGIN:
127018            xMethod = pMod->xSavepoint;
127019            pVTab->iSavepoint = iSavepoint+1;
127020            break;
127021          case SAVEPOINT_ROLLBACK:
127022            xMethod = pMod->xRollbackTo;
127023            break;
127024          default:
127025            xMethod = pMod->xRelease;
127026            break;
127027        }
127028        if( xMethod && pVTab->iSavepoint>iSavepoint ){
127029          rc = xMethod(pVTab->pVtab, iSavepoint);
127030        }
127031      }
127032    }
127033  }
127034  return rc;
127035}
127036
127037/*
127038** The first parameter (pDef) is a function implementation.  The
127039** second parameter (pExpr) is the first argument to this function.
127040** If pExpr is a column in a virtual table, then let the virtual
127041** table implementation have an opportunity to overload the function.
127042**
127043** This routine is used to allow virtual table implementations to
127044** overload MATCH, LIKE, GLOB, and REGEXP operators.
127045**
127046** Return either the pDef argument (indicating no change) or a
127047** new FuncDef structure that is marked as ephemeral using the
127048** SQLITE_FUNC_EPHEM flag.
127049*/
127050SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
127051  sqlite3 *db,    /* Database connection for reporting malloc problems */
127052  FuncDef *pDef,  /* Function to possibly overload */
127053  int nArg,       /* Number of arguments to the function */
127054  Expr *pExpr     /* First argument to the function */
127055){
127056  Table *pTab;
127057  sqlite3_vtab *pVtab;
127058  sqlite3_module *pMod;
127059  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
127060  void *pArg = 0;
127061  FuncDef *pNew;
127062  int rc = 0;
127063  char *zLowerName;
127064  unsigned char *z;
127065
127066
127067  /* Check to see the left operand is a column in a virtual table */
127068  if( NEVER(pExpr==0) ) return pDef;
127069  if( pExpr->op!=TK_COLUMN ) return pDef;
127070  pTab = pExpr->pTab;
127071  if( pTab==0 ) return pDef;
127072  if( !IsVirtual(pTab) ) return pDef;
127073  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
127074  assert( pVtab!=0 );
127075  assert( pVtab->pModule!=0 );
127076  pMod = (sqlite3_module *)pVtab->pModule;
127077  if( pMod->xFindFunction==0 ) return pDef;
127078
127079  /* Call the xFindFunction method on the virtual table implementation
127080  ** to see if the implementation wants to overload this function
127081  */
127082  zLowerName = sqlite3DbStrDup(db, pDef->zName);
127083  if( zLowerName ){
127084    for(z=(unsigned char*)zLowerName; *z; z++){
127085      *z = sqlite3UpperToLower[*z];
127086    }
127087    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
127088    sqlite3DbFree(db, zLowerName);
127089  }
127090  if( rc==0 ){
127091    return pDef;
127092  }
127093
127094  /* Create a new ephemeral function definition for the overloaded
127095  ** function */
127096  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
127097                             + sqlite3Strlen30(pDef->zName) + 1);
127098  if( pNew==0 ){
127099    return pDef;
127100  }
127101  *pNew = *pDef;
127102  pNew->zName = (const char*)&pNew[1];
127103  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
127104  pNew->xSFunc = xSFunc;
127105  pNew->pUserData = pArg;
127106  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
127107  return pNew;
127108}
127109
127110/*
127111** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
127112** array so that an OP_VBegin will get generated for it.  Add pTab to the
127113** array if it is missing.  If pTab is already in the array, this routine
127114** is a no-op.
127115*/
127116SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
127117  Parse *pToplevel = sqlite3ParseToplevel(pParse);
127118  int i, n;
127119  Table **apVtabLock;
127120
127121  assert( IsVirtual(pTab) );
127122  for(i=0; i<pToplevel->nVtabLock; i++){
127123    if( pTab==pToplevel->apVtabLock[i] ) return;
127124  }
127125  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
127126  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
127127  if( apVtabLock ){
127128    pToplevel->apVtabLock = apVtabLock;
127129    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
127130  }else{
127131    sqlite3OomFault(pToplevel->db);
127132  }
127133}
127134
127135/*
127136** Check to see if virtual table module pMod can be have an eponymous
127137** virtual table instance.  If it can, create one if one does not already
127138** exist. Return non-zero if the eponymous virtual table instance exists
127139** when this routine returns, and return zero if it does not exist.
127140**
127141** An eponymous virtual table instance is one that is named after its
127142** module, and more importantly, does not require a CREATE VIRTUAL TABLE
127143** statement in order to come into existance.  Eponymous virtual table
127144** instances always exist.  They cannot be DROP-ed.
127145**
127146** Any virtual table module for which xConnect and xCreate are the same
127147** method can have an eponymous virtual table instance.
127148*/
127149SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
127150  const sqlite3_module *pModule = pMod->pModule;
127151  Table *pTab;
127152  char *zErr = 0;
127153  int rc;
127154  sqlite3 *db = pParse->db;
127155  if( pMod->pEpoTab ) return 1;
127156  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
127157  pTab = sqlite3DbMallocZero(db, sizeof(Table));
127158  if( pTab==0 ) return 0;
127159  pTab->zName = sqlite3DbStrDup(db, pMod->zName);
127160  if( pTab->zName==0 ){
127161    sqlite3DbFree(db, pTab);
127162    return 0;
127163  }
127164  pMod->pEpoTab = pTab;
127165  pTab->nTabRef = 1;
127166  pTab->pSchema = db->aDb[0].pSchema;
127167  assert( pTab->nModuleArg==0 );
127168  pTab->iPKey = -1;
127169  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
127170  addModuleArgument(db, pTab, 0);
127171  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
127172  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
127173  if( rc ){
127174    sqlite3ErrorMsg(pParse, "%s", zErr);
127175    sqlite3DbFree(db, zErr);
127176    sqlite3VtabEponymousTableClear(db, pMod);
127177    return 0;
127178  }
127179  return 1;
127180}
127181
127182/*
127183** Erase the eponymous virtual table instance associated with
127184** virtual table module pMod, if it exists.
127185*/
127186SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
127187  Table *pTab = pMod->pEpoTab;
127188  if( pTab!=0 ){
127189    /* Mark the table as Ephemeral prior to deleting it, so that the
127190    ** sqlite3DeleteTable() routine will know that it is not stored in
127191    ** the schema. */
127192    pTab->tabFlags |= TF_Ephemeral;
127193    sqlite3DeleteTable(db, pTab);
127194    pMod->pEpoTab = 0;
127195  }
127196}
127197
127198/*
127199** Return the ON CONFLICT resolution mode in effect for the virtual
127200** table update operation currently in progress.
127201**
127202** The results of this routine are undefined unless it is called from
127203** within an xUpdate method.
127204*/
127205SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
127206  static const unsigned char aMap[] = {
127207    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
127208  };
127209#ifdef SQLITE_ENABLE_API_ARMOR
127210  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
127211#endif
127212  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
127213  assert( OE_Ignore==4 && OE_Replace==5 );
127214  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
127215  return (int)aMap[db->vtabOnConflict-1];
127216}
127217
127218/*
127219** Call from within the xCreate() or xConnect() methods to provide
127220** the SQLite core with additional information about the behavior
127221** of the virtual table being implemented.
127222*/
127223SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
127224  va_list ap;
127225  int rc = SQLITE_OK;
127226
127227#ifdef SQLITE_ENABLE_API_ARMOR
127228  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
127229#endif
127230  sqlite3_mutex_enter(db->mutex);
127231  va_start(ap, op);
127232  switch( op ){
127233    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
127234      VtabCtx *p = db->pVtabCtx;
127235      if( !p ){
127236        rc = SQLITE_MISUSE_BKPT;
127237      }else{
127238        assert( p->pTab==0 || IsVirtual(p->pTab) );
127239        p->pVTable->bConstraint = (u8)va_arg(ap, int);
127240      }
127241      break;
127242    }
127243    default:
127244      rc = SQLITE_MISUSE_BKPT;
127245      break;
127246  }
127247  va_end(ap);
127248
127249  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
127250  sqlite3_mutex_leave(db->mutex);
127251  return rc;
127252}
127253
127254#endif /* SQLITE_OMIT_VIRTUALTABLE */
127255
127256/************** End of vtab.c ************************************************/
127257/************** Begin file wherecode.c ***************************************/
127258/*
127259** 2015-06-06
127260**
127261** The author disclaims copyright to this source code.  In place of
127262** a legal notice, here is a blessing:
127263**
127264**    May you do good and not evil.
127265**    May you find forgiveness for yourself and forgive others.
127266**    May you share freely, never taking more than you give.
127267**
127268*************************************************************************
127269** This module contains C code that generates VDBE code used to process
127270** the WHERE clause of SQL statements.
127271**
127272** This file was split off from where.c on 2015-06-06 in order to reduce the
127273** size of where.c and make it easier to edit.  This file contains the routines
127274** that actually generate the bulk of the WHERE loop code.  The original where.c
127275** file retains the code that does query planning and analysis.
127276*/
127277/* #include "sqliteInt.h" */
127278/************** Include whereInt.h in the middle of wherecode.c **************/
127279/************** Begin file whereInt.h ****************************************/
127280/*
127281** 2013-11-12
127282**
127283** The author disclaims copyright to this source code.  In place of
127284** a legal notice, here is a blessing:
127285**
127286**    May you do good and not evil.
127287**    May you find forgiveness for yourself and forgive others.
127288**    May you share freely, never taking more than you give.
127289**
127290*************************************************************************
127291**
127292** This file contains structure and macro definitions for the query
127293** planner logic in "where.c".  These definitions are broken out into
127294** a separate source file for easier editing.
127295*/
127296
127297/*
127298** Trace output macros
127299*/
127300#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
127301/***/ int sqlite3WhereTrace;
127302#endif
127303#if defined(SQLITE_DEBUG) \
127304    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
127305# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
127306# define WHERETRACE_ENABLED 1
127307#else
127308# define WHERETRACE(K,X)
127309#endif
127310
127311/* Forward references
127312*/
127313typedef struct WhereClause WhereClause;
127314typedef struct WhereMaskSet WhereMaskSet;
127315typedef struct WhereOrInfo WhereOrInfo;
127316typedef struct WhereAndInfo WhereAndInfo;
127317typedef struct WhereLevel WhereLevel;
127318typedef struct WhereLoop WhereLoop;
127319typedef struct WherePath WherePath;
127320typedef struct WhereTerm WhereTerm;
127321typedef struct WhereLoopBuilder WhereLoopBuilder;
127322typedef struct WhereScan WhereScan;
127323typedef struct WhereOrCost WhereOrCost;
127324typedef struct WhereOrSet WhereOrSet;
127325
127326/*
127327** This object contains information needed to implement a single nested
127328** loop in WHERE clause.
127329**
127330** Contrast this object with WhereLoop.  This object describes the
127331** implementation of the loop.  WhereLoop describes the algorithm.
127332** This object contains a pointer to the WhereLoop algorithm as one of
127333** its elements.
127334**
127335** The WhereInfo object contains a single instance of this object for
127336** each term in the FROM clause (which is to say, for each of the
127337** nested loops as implemented).  The order of WhereLevel objects determines
127338** the loop nested order, with WhereInfo.a[0] being the outer loop and
127339** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
127340*/
127341struct WhereLevel {
127342  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
127343  int iTabCur;          /* The VDBE cursor used to access the table */
127344  int iIdxCur;          /* The VDBE cursor used to access pIdx */
127345  int addrBrk;          /* Jump here to break out of the loop */
127346  int addrNxt;          /* Jump here to start the next IN combination */
127347  int addrSkip;         /* Jump here for next iteration of skip-scan */
127348  int addrCont;         /* Jump here to continue with the next loop cycle */
127349  int addrFirst;        /* First instruction of interior of the loop */
127350  int addrBody;         /* Beginning of the body of this loop */
127351#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
127352  u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
127353  int addrLikeRep;      /* LIKE range processing address */
127354#endif
127355  u8 iFrom;             /* Which entry in the FROM clause */
127356  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
127357  int p1, p2;           /* Operands of the opcode used to ends the loop */
127358  union {               /* Information that depends on pWLoop->wsFlags */
127359    struct {
127360      int nIn;              /* Number of entries in aInLoop[] */
127361      struct InLoop {
127362        int iCur;              /* The VDBE cursor used by this IN operator */
127363        int addrInTop;         /* Top of the IN loop */
127364        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
127365      } *aInLoop;           /* Information about each nested IN operator */
127366    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
127367    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
127368  } u;
127369  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
127370  Bitmask notReady;          /* FROM entries not usable at this level */
127371#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
127372  int addrVisit;        /* Address at which row is visited */
127373#endif
127374};
127375
127376/*
127377** Each instance of this object represents an algorithm for evaluating one
127378** term of a join.  Every term of the FROM clause will have at least
127379** one corresponding WhereLoop object (unless INDEXED BY constraints
127380** prevent a query solution - which is an error) and many terms of the
127381** FROM clause will have multiple WhereLoop objects, each describing a
127382** potential way of implementing that FROM-clause term, together with
127383** dependencies and cost estimates for using the chosen algorithm.
127384**
127385** Query planning consists of building up a collection of these WhereLoop
127386** objects, then computing a particular sequence of WhereLoop objects, with
127387** one WhereLoop object per FROM clause term, that satisfy all dependencies
127388** and that minimize the overall cost.
127389*/
127390struct WhereLoop {
127391  Bitmask prereq;       /* Bitmask of other loops that must run first */
127392  Bitmask maskSelf;     /* Bitmask identifying table iTab */
127393#ifdef SQLITE_DEBUG
127394  char cId;             /* Symbolic ID of this loop for debugging use */
127395#endif
127396  u8 iTab;              /* Position in FROM clause of table for this loop */
127397  u8 iSortIdx;          /* Sorting index number.  0==None */
127398  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
127399  LogEst rRun;          /* Cost of running each loop */
127400  LogEst nOut;          /* Estimated number of output rows */
127401  union {
127402    struct {               /* Information for internal btree tables */
127403      u16 nEq;               /* Number of equality constraints */
127404      u16 nBtm;              /* Size of BTM vector */
127405      u16 nTop;              /* Size of TOP vector */
127406      u16 nIdxCol;           /* Index column used for ORDER BY */
127407      Index *pIndex;         /* Index used, or NULL */
127408    } btree;
127409    struct {               /* Information for virtual tables */
127410      int idxNum;            /* Index number */
127411      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
127412      i8 isOrdered;          /* True if satisfies ORDER BY */
127413      u16 omitMask;          /* Terms that may be omitted */
127414      char *idxStr;          /* Index identifier string */
127415    } vtab;
127416  } u;
127417  u32 wsFlags;          /* WHERE_* flags describing the plan */
127418  u16 nLTerm;           /* Number of entries in aLTerm[] */
127419  u16 nSkip;            /* Number of NULL aLTerm[] entries */
127420  /**** whereLoopXfer() copies fields above ***********************/
127421# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
127422  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
127423  WhereTerm **aLTerm;   /* WhereTerms used */
127424  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
127425  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
127426};
127427
127428/* This object holds the prerequisites and the cost of running a
127429** subquery on one operand of an OR operator in the WHERE clause.
127430** See WhereOrSet for additional information
127431*/
127432struct WhereOrCost {
127433  Bitmask prereq;     /* Prerequisites */
127434  LogEst rRun;        /* Cost of running this subquery */
127435  LogEst nOut;        /* Number of outputs for this subquery */
127436};
127437
127438/* The WhereOrSet object holds a set of possible WhereOrCosts that
127439** correspond to the subquery(s) of OR-clause processing.  Only the
127440** best N_OR_COST elements are retained.
127441*/
127442#define N_OR_COST 3
127443struct WhereOrSet {
127444  u16 n;                      /* Number of valid a[] entries */
127445  WhereOrCost a[N_OR_COST];   /* Set of best costs */
127446};
127447
127448/*
127449** Each instance of this object holds a sequence of WhereLoop objects
127450** that implement some or all of a query plan.
127451**
127452** Think of each WhereLoop object as a node in a graph with arcs
127453** showing dependencies and costs for travelling between nodes.  (That is
127454** not a completely accurate description because WhereLoop costs are a
127455** vector, not a scalar, and because dependencies are many-to-one, not
127456** one-to-one as are graph nodes.  But it is a useful visualization aid.)
127457** Then a WherePath object is a path through the graph that visits some
127458** or all of the WhereLoop objects once.
127459**
127460** The "solver" works by creating the N best WherePath objects of length
127461** 1.  Then using those as a basis to compute the N best WherePath objects
127462** of length 2.  And so forth until the length of WherePaths equals the
127463** number of nodes in the FROM clause.  The best (lowest cost) WherePath
127464** at the end is the chosen query plan.
127465*/
127466struct WherePath {
127467  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
127468  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
127469  LogEst nRow;          /* Estimated number of rows generated by this path */
127470  LogEst rCost;         /* Total cost of this path */
127471  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
127472  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
127473  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
127474};
127475
127476/*
127477** The query generator uses an array of instances of this structure to
127478** help it analyze the subexpressions of the WHERE clause.  Each WHERE
127479** clause subexpression is separated from the others by AND operators,
127480** usually, or sometimes subexpressions separated by OR.
127481**
127482** All WhereTerms are collected into a single WhereClause structure.
127483** The following identity holds:
127484**
127485**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
127486**
127487** When a term is of the form:
127488**
127489**              X <op> <expr>
127490**
127491** where X is a column name and <op> is one of certain operators,
127492** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
127493** cursor number and column number for X.  WhereTerm.eOperator records
127494** the <op> using a bitmask encoding defined by WO_xxx below.  The
127495** use of a bitmask encoding for the operator allows us to search
127496** quickly for terms that match any of several different operators.
127497**
127498** A WhereTerm might also be two or more subterms connected by OR:
127499**
127500**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
127501**
127502** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
127503** and the WhereTerm.u.pOrInfo field points to auxiliary information that
127504** is collected about the OR clause.
127505**
127506** If a term in the WHERE clause does not match either of the two previous
127507** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
127508** to the original subexpression content and wtFlags is set up appropriately
127509** but no other fields in the WhereTerm object are meaningful.
127510**
127511** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
127512** but they do so indirectly.  A single WhereMaskSet structure translates
127513** cursor number into bits and the translated bit is stored in the prereq
127514** fields.  The translation is used in order to maximize the number of
127515** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
127516** spread out over the non-negative integers.  For example, the cursor
127517** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
127518** translates these sparse cursor numbers into consecutive integers
127519** beginning with 0 in order to make the best possible use of the available
127520** bits in the Bitmask.  So, in the example above, the cursor numbers
127521** would be mapped into integers 0 through 7.
127522**
127523** The number of terms in a join is limited by the number of bits
127524** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
127525** is only able to process joins with 64 or fewer tables.
127526*/
127527struct WhereTerm {
127528  Expr *pExpr;            /* Pointer to the subexpression that is this term */
127529  WhereClause *pWC;       /* The clause this term is part of */
127530  LogEst truthProb;       /* Probability of truth for this expression */
127531  u16 wtFlags;            /* TERM_xxx bit flags.  See below */
127532  u16 eOperator;          /* A WO_xx value describing <op> */
127533  u8 nChild;              /* Number of children that must disable us */
127534  u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
127535  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
127536  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
127537  int iField;             /* Field in (?,?,?) IN (SELECT...) vector */
127538  union {
127539    int leftColumn;         /* Column number of X in "X <op> <expr>" */
127540    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
127541    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
127542  } u;
127543  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
127544  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
127545};
127546
127547/*
127548** Allowed values of WhereTerm.wtFlags
127549*/
127550#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
127551#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
127552#define TERM_CODED      0x04   /* This term is already coded */
127553#define TERM_COPIED     0x08   /* Has a child */
127554#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
127555#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
127556#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
127557#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127558#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
127559#else
127560#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
127561#endif
127562#define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
127563#define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
127564#define TERM_LIKE       0x400  /* The original LIKE operator */
127565#define TERM_IS         0x800  /* Term.pExpr is an IS operator */
127566#define TERM_VARSELECT  0x1000 /* Term.pExpr contains a correlated sub-query */
127567
127568/*
127569** An instance of the WhereScan object is used as an iterator for locating
127570** terms in the WHERE clause that are useful to the query planner.
127571*/
127572struct WhereScan {
127573  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
127574  WhereClause *pWC;          /* WhereClause currently being scanned */
127575  const char *zCollName;     /* Required collating sequence, if not NULL */
127576  Expr *pIdxExpr;            /* Search for this index expression */
127577  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
127578  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
127579  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
127580  u32 opMask;                /* Acceptable operators */
127581  int k;                     /* Resume scanning at this->pWC->a[this->k] */
127582  int aiCur[11];             /* Cursors in the equivalence class */
127583  i16 aiColumn[11];          /* Corresponding column number in the eq-class */
127584};
127585
127586/*
127587** An instance of the following structure holds all information about a
127588** WHERE clause.  Mostly this is a container for one or more WhereTerms.
127589**
127590** Explanation of pOuter:  For a WHERE clause of the form
127591**
127592**           a AND ((b AND c) OR (d AND e)) AND f
127593**
127594** There are separate WhereClause objects for the whole clause and for
127595** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
127596** subclauses points to the WhereClause object for the whole clause.
127597*/
127598struct WhereClause {
127599  WhereInfo *pWInfo;       /* WHERE clause processing context */
127600  WhereClause *pOuter;     /* Outer conjunction */
127601  u8 op;                   /* Split operator.  TK_AND or TK_OR */
127602  int nTerm;               /* Number of terms */
127603  int nSlot;               /* Number of entries in a[] */
127604  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
127605#if defined(SQLITE_SMALL_STACK)
127606  WhereTerm aStatic[1];    /* Initial static space for a[] */
127607#else
127608  WhereTerm aStatic[8];    /* Initial static space for a[] */
127609#endif
127610};
127611
127612/*
127613** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
127614** a dynamically allocated instance of the following structure.
127615*/
127616struct WhereOrInfo {
127617  WhereClause wc;          /* Decomposition into subterms */
127618  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
127619};
127620
127621/*
127622** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
127623** a dynamically allocated instance of the following structure.
127624*/
127625struct WhereAndInfo {
127626  WhereClause wc;          /* The subexpression broken out */
127627};
127628
127629/*
127630** An instance of the following structure keeps track of a mapping
127631** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
127632**
127633** The VDBE cursor numbers are small integers contained in
127634** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
127635** clause, the cursor numbers might not begin with 0 and they might
127636** contain gaps in the numbering sequence.  But we want to make maximum
127637** use of the bits in our bitmasks.  This structure provides a mapping
127638** from the sparse cursor numbers into consecutive integers beginning
127639** with 0.
127640**
127641** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
127642** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
127643**
127644** For example, if the WHERE clause expression used these VDBE
127645** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
127646** would map those cursor numbers into bits 0 through 5.
127647**
127648** Note that the mapping is not necessarily ordered.  In the example
127649** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
127650** 57->5, 73->4.  Or one of 719 other combinations might be used. It
127651** does not really matter.  What is important is that sparse cursor
127652** numbers all get mapped into bit numbers that begin with 0 and contain
127653** no gaps.
127654*/
127655struct WhereMaskSet {
127656  int bVarSelect;               /* Used by sqlite3WhereExprUsage() */
127657  int n;                        /* Number of assigned cursor values */
127658  int ix[BMS];                  /* Cursor assigned to each bit */
127659};
127660
127661/*
127662** Initialize a WhereMaskSet object
127663*/
127664#define initMaskSet(P)  (P)->n=0
127665
127666/*
127667** This object is a convenience wrapper holding all information needed
127668** to construct WhereLoop objects for a particular query.
127669*/
127670struct WhereLoopBuilder {
127671  WhereInfo *pWInfo;        /* Information about this WHERE */
127672  WhereClause *pWC;         /* WHERE clause terms */
127673  ExprList *pOrderBy;       /* ORDER BY clause */
127674  WhereLoop *pNew;          /* Template WhereLoop */
127675  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
127676#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127677  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
127678  int nRecValid;            /* Number of valid fields currently in pRec */
127679#endif
127680  unsigned int bldFlags;    /* SQLITE_BLDF_* flags */
127681};
127682
127683/* Allowed values for WhereLoopBuider.bldFlags */
127684#define SQLITE_BLDF_INDEXED  0x0001   /* An index is used */
127685#define SQLITE_BLDF_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
127686
127687/*
127688** The WHERE clause processing routine has two halves.  The
127689** first part does the start of the WHERE loop and the second
127690** half does the tail of the WHERE loop.  An instance of
127691** this structure is returned by the first half and passed
127692** into the second half to give some continuity.
127693**
127694** An instance of this object holds the complete state of the query
127695** planner.
127696*/
127697struct WhereInfo {
127698  Parse *pParse;            /* Parsing and code generating context */
127699  SrcList *pTabList;        /* List of tables in the join */
127700  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
127701  ExprList *pResultSet;     /* Result set of the query */
127702  Expr *pWhere;             /* The complete WHERE clause */
127703  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
127704  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
127705  int iContinue;            /* Jump here to continue with next record */
127706  int iBreak;               /* Jump here to break out of the loop */
127707  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
127708  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
127709  u8 nLevel;                /* Number of nested loop */
127710  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
127711  u8 sorted;                /* True if really sorted (not just grouped) */
127712  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
127713  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
127714  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
127715  u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
127716  int iTop;                 /* The very beginning of the WHERE loop */
127717  WhereLoop *pLoops;        /* List of all WhereLoop objects */
127718  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
127719  LogEst nRowOut;           /* Estimated number of output rows */
127720  WhereClause sWC;          /* Decomposition of the WHERE clause */
127721  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
127722  WhereLevel a[1];          /* Information about each nest loop in WHERE */
127723};
127724
127725/*
127726** Private interfaces - callable only by other where.c routines.
127727**
127728** where.c:
127729*/
127730SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
127731#ifdef WHERETRACE_ENABLED
127732SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
127733#endif
127734SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
127735  WhereClause *pWC,     /* The WHERE clause to be searched */
127736  int iCur,             /* Cursor number of LHS */
127737  int iColumn,          /* Column number of LHS */
127738  Bitmask notReady,     /* RHS must not overlap with this mask */
127739  u32 op,               /* Mask of WO_xx values describing operator */
127740  Index *pIdx           /* Must be compatible with this index, if not NULL */
127741);
127742
127743/* wherecode.c: */
127744#ifndef SQLITE_OMIT_EXPLAIN
127745SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
127746  Parse *pParse,                  /* Parse context */
127747  SrcList *pTabList,              /* Table list this loop refers to */
127748  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
127749  int iLevel,                     /* Value for "level" column of output */
127750  int iFrom,                      /* Value for "from" column of output */
127751  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
127752);
127753#else
127754# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
127755#endif /* SQLITE_OMIT_EXPLAIN */
127756#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
127757SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
127758  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
127759  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
127760  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
127761  int addrExplain                 /* Address of OP_Explain (or 0) */
127762);
127763#else
127764# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
127765#endif
127766SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
127767  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
127768  int iLevel,          /* Which level of pWInfo->a[] should be coded */
127769  Bitmask notReady     /* Which tables are currently available */
127770);
127771
127772/* whereexpr.c: */
127773SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
127774SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
127775SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
127776SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
127777SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
127778SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
127779SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
127780
127781
127782
127783
127784
127785/*
127786** Bitmasks for the operators on WhereTerm objects.  These are all
127787** operators that are of interest to the query planner.  An
127788** OR-ed combination of these values can be used when searching for
127789** particular WhereTerms within a WhereClause.
127790**
127791** Value constraints:
127792**     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
127793**     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
127794**     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
127795**     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
127796**     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
127797**     WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
127798*/
127799#define WO_IN     0x0001
127800#define WO_EQ     0x0002
127801#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
127802#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
127803#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
127804#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
127805#define WO_MATCH  0x0040
127806#define WO_IS     0x0080
127807#define WO_ISNULL 0x0100
127808#define WO_OR     0x0200       /* Two or more OR-connected terms */
127809#define WO_AND    0x0400       /* Two or more AND-connected terms */
127810#define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
127811#define WO_NOOP   0x1000       /* This term does not restrict search space */
127812
127813#define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
127814#define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
127815
127816/*
127817** These are definitions of bits in the WhereLoop.wsFlags field.
127818** The particular combination of bits in each WhereLoop help to
127819** determine the algorithm that WhereLoop represents.
127820*/
127821#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
127822#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
127823#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
127824#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
127825#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
127826#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
127827#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
127828#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
127829#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
127830#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
127831#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
127832#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
127833#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
127834#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
127835#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
127836#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
127837#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
127838#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
127839#define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
127840
127841/************** End of whereInt.h ********************************************/
127842/************** Continuing where we left off in wherecode.c ******************/
127843
127844#ifndef SQLITE_OMIT_EXPLAIN
127845
127846/*
127847** Return the name of the i-th column of the pIdx index.
127848*/
127849static const char *explainIndexColumnName(Index *pIdx, int i){
127850  i = pIdx->aiColumn[i];
127851  if( i==XN_EXPR ) return "<expr>";
127852  if( i==XN_ROWID ) return "rowid";
127853  return pIdx->pTable->aCol[i].zName;
127854}
127855
127856/*
127857** This routine is a helper for explainIndexRange() below
127858**
127859** pStr holds the text of an expression that we are building up one term
127860** at a time.  This routine adds a new term to the end of the expression.
127861** Terms are separated by AND so add the "AND" text for second and subsequent
127862** terms only.
127863*/
127864static void explainAppendTerm(
127865  StrAccum *pStr,             /* The text expression being built */
127866  Index *pIdx,                /* Index to read column names from */
127867  int nTerm,                  /* Number of terms */
127868  int iTerm,                  /* Zero-based index of first term. */
127869  int bAnd,                   /* Non-zero to append " AND " */
127870  const char *zOp             /* Name of the operator */
127871){
127872  int i;
127873
127874  assert( nTerm>=1 );
127875  if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
127876
127877  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
127878  for(i=0; i<nTerm; i++){
127879    if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
127880    sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
127881  }
127882  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
127883
127884  sqlite3StrAccumAppend(pStr, zOp, 1);
127885
127886  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
127887  for(i=0; i<nTerm; i++){
127888    if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
127889    sqlite3StrAccumAppend(pStr, "?", 1);
127890  }
127891  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
127892}
127893
127894/*
127895** Argument pLevel describes a strategy for scanning table pTab. This
127896** function appends text to pStr that describes the subset of table
127897** rows scanned by the strategy in the form of an SQL expression.
127898**
127899** For example, if the query:
127900**
127901**   SELECT * FROM t1 WHERE a=1 AND b>2;
127902**
127903** is run and there is an index on (a, b), then this function returns a
127904** string similar to:
127905**
127906**   "a=? AND b>?"
127907*/
127908static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
127909  Index *pIndex = pLoop->u.btree.pIndex;
127910  u16 nEq = pLoop->u.btree.nEq;
127911  u16 nSkip = pLoop->nSkip;
127912  int i, j;
127913
127914  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
127915  sqlite3StrAccumAppend(pStr, " (", 2);
127916  for(i=0; i<nEq; i++){
127917    const char *z = explainIndexColumnName(pIndex, i);
127918    if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
127919    sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
127920  }
127921
127922  j = i;
127923  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
127924    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
127925    i = 1;
127926  }
127927  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
127928    explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
127929  }
127930  sqlite3StrAccumAppend(pStr, ")", 1);
127931}
127932
127933/*
127934** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
127935** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
127936** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
127937** is added to the output to describe the table scan strategy in pLevel.
127938**
127939** If an OP_Explain opcode is added to the VM, its address is returned.
127940** Otherwise, if no OP_Explain is coded, zero is returned.
127941*/
127942SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
127943  Parse *pParse,                  /* Parse context */
127944  SrcList *pTabList,              /* Table list this loop refers to */
127945  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
127946  int iLevel,                     /* Value for "level" column of output */
127947  int iFrom,                      /* Value for "from" column of output */
127948  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
127949){
127950  int ret = 0;
127951#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
127952  if( pParse->explain==2 )
127953#endif
127954  {
127955    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
127956    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
127957    sqlite3 *db = pParse->db;     /* Database handle */
127958    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
127959    int isSearch;                 /* True for a SEARCH. False for SCAN. */
127960    WhereLoop *pLoop;             /* The controlling WhereLoop object */
127961    u32 flags;                    /* Flags that describe this loop */
127962    char *zMsg;                   /* Text to add to EQP output */
127963    StrAccum str;                 /* EQP output string */
127964    char zBuf[100];               /* Initial space for EQP output string */
127965
127966    pLoop = pLevel->pWLoop;
127967    flags = pLoop->wsFlags;
127968    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
127969
127970    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
127971            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
127972            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
127973
127974    sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
127975    sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
127976    if( pItem->pSelect ){
127977      sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
127978    }else{
127979      sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
127980    }
127981
127982    if( pItem->zAlias ){
127983      sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
127984    }
127985    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
127986      const char *zFmt = 0;
127987      Index *pIdx;
127988
127989      assert( pLoop->u.btree.pIndex!=0 );
127990      pIdx = pLoop->u.btree.pIndex;
127991      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
127992      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
127993        if( isSearch ){
127994          zFmt = "PRIMARY KEY";
127995        }
127996      }else if( flags & WHERE_PARTIALIDX ){
127997        zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
127998      }else if( flags & WHERE_AUTO_INDEX ){
127999        zFmt = "AUTOMATIC COVERING INDEX";
128000      }else if( flags & WHERE_IDX_ONLY ){
128001        zFmt = "COVERING INDEX %s";
128002      }else{
128003        zFmt = "INDEX %s";
128004      }
128005      if( zFmt ){
128006        sqlite3StrAccumAppend(&str, " USING ", 7);
128007        sqlite3XPrintf(&str, zFmt, pIdx->zName);
128008        explainIndexRange(&str, pLoop);
128009      }
128010    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
128011      const char *zRangeOp;
128012      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
128013        zRangeOp = "=";
128014      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
128015        zRangeOp = ">? AND rowid<";
128016      }else if( flags&WHERE_BTM_LIMIT ){
128017        zRangeOp = ">";
128018      }else{
128019        assert( flags&WHERE_TOP_LIMIT);
128020        zRangeOp = "<";
128021      }
128022      sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
128023    }
128024#ifndef SQLITE_OMIT_VIRTUALTABLE
128025    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
128026      sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
128027                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
128028    }
128029#endif
128030#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
128031    if( pLoop->nOut>=10 ){
128032      sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
128033    }else{
128034      sqlite3StrAccumAppend(&str, " (~1 row)", 9);
128035    }
128036#endif
128037    zMsg = sqlite3StrAccumFinish(&str);
128038    ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
128039  }
128040  return ret;
128041}
128042#endif /* SQLITE_OMIT_EXPLAIN */
128043
128044#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
128045/*
128046** Configure the VM passed as the first argument with an
128047** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
128048** implement level pLvl. Argument pSrclist is a pointer to the FROM
128049** clause that the scan reads data from.
128050**
128051** If argument addrExplain is not 0, it must be the address of an
128052** OP_Explain instruction that describes the same loop.
128053*/
128054SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
128055  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
128056  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
128057  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
128058  int addrExplain                 /* Address of OP_Explain (or 0) */
128059){
128060  const char *zObj = 0;
128061  WhereLoop *pLoop = pLvl->pWLoop;
128062  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
128063    zObj = pLoop->u.btree.pIndex->zName;
128064  }else{
128065    zObj = pSrclist->a[pLvl->iFrom].zName;
128066  }
128067  sqlite3VdbeScanStatus(
128068      v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
128069  );
128070}
128071#endif
128072
128073
128074/*
128075** Disable a term in the WHERE clause.  Except, do not disable the term
128076** if it controls a LEFT OUTER JOIN and it did not originate in the ON
128077** or USING clause of that join.
128078**
128079** Consider the term t2.z='ok' in the following queries:
128080**
128081**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
128082**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
128083**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
128084**
128085** The t2.z='ok' is disabled in the in (2) because it originates
128086** in the ON clause.  The term is disabled in (3) because it is not part
128087** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
128088**
128089** Disabling a term causes that term to not be tested in the inner loop
128090** of the join.  Disabling is an optimization.  When terms are satisfied
128091** by indices, we disable them to prevent redundant tests in the inner
128092** loop.  We would get the correct results if nothing were ever disabled,
128093** but joins might run a little slower.  The trick is to disable as much
128094** as we can without disabling too much.  If we disabled in (1), we'd get
128095** the wrong answer.  See ticket #813.
128096**
128097** If all the children of a term are disabled, then that term is also
128098** automatically disabled.  In this way, terms get disabled if derived
128099** virtual terms are tested first.  For example:
128100**
128101**      x GLOB 'abc*' AND x>='abc' AND x<'acd'
128102**      \___________/     \______/     \_____/
128103**         parent          child1       child2
128104**
128105** Only the parent term was in the original WHERE clause.  The child1
128106** and child2 terms were added by the LIKE optimization.  If both of
128107** the virtual child terms are valid, then testing of the parent can be
128108** skipped.
128109**
128110** Usually the parent term is marked as TERM_CODED.  But if the parent
128111** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
128112** The TERM_LIKECOND marking indicates that the term should be coded inside
128113** a conditional such that is only evaluated on the second pass of a
128114** LIKE-optimization loop, when scanning BLOBs instead of strings.
128115*/
128116static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
128117  int nLoop = 0;
128118  while( ALWAYS(pTerm!=0)
128119      && (pTerm->wtFlags & TERM_CODED)==0
128120      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
128121      && (pLevel->notReady & pTerm->prereqAll)==0
128122  ){
128123    if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
128124      pTerm->wtFlags |= TERM_LIKECOND;
128125    }else{
128126      pTerm->wtFlags |= TERM_CODED;
128127    }
128128    if( pTerm->iParent<0 ) break;
128129    pTerm = &pTerm->pWC->a[pTerm->iParent];
128130    pTerm->nChild--;
128131    if( pTerm->nChild!=0 ) break;
128132    nLoop++;
128133  }
128134}
128135
128136/*
128137** Code an OP_Affinity opcode to apply the column affinity string zAff
128138** to the n registers starting at base.
128139**
128140** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
128141** beginning and end of zAff are ignored.  If all entries in zAff are
128142** SQLITE_AFF_BLOB, then no code gets generated.
128143**
128144** This routine makes its own copy of zAff so that the caller is free
128145** to modify zAff after this routine returns.
128146*/
128147static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
128148  Vdbe *v = pParse->pVdbe;
128149  if( zAff==0 ){
128150    assert( pParse->db->mallocFailed );
128151    return;
128152  }
128153  assert( v!=0 );
128154
128155  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
128156  ** and end of the affinity string.
128157  */
128158  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
128159    n--;
128160    base++;
128161    zAff++;
128162  }
128163  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
128164    n--;
128165  }
128166
128167  /* Code the OP_Affinity opcode if there is anything left to do. */
128168  if( n>0 ){
128169    sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
128170    sqlite3ExprCacheAffinityChange(pParse, base, n);
128171  }
128172}
128173
128174/*
128175** Expression pRight, which is the RHS of a comparison operation, is
128176** either a vector of n elements or, if n==1, a scalar expression.
128177** Before the comparison operation, affinity zAff is to be applied
128178** to the pRight values. This function modifies characters within the
128179** affinity string to SQLITE_AFF_BLOB if either:
128180**
128181**   * the comparison will be performed with no affinity, or
128182**   * the affinity change in zAff is guaranteed not to change the value.
128183*/
128184static void updateRangeAffinityStr(
128185  Expr *pRight,                   /* RHS of comparison */
128186  int n,                          /* Number of vector elements in comparison */
128187  char *zAff                      /* Affinity string to modify */
128188){
128189  int i;
128190  for(i=0; i<n; i++){
128191    Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
128192    if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
128193     || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
128194    ){
128195      zAff[i] = SQLITE_AFF_BLOB;
128196    }
128197  }
128198}
128199
128200/*
128201** Generate code for a single equality term of the WHERE clause.  An equality
128202** term can be either X=expr or X IN (...).   pTerm is the term to be
128203** coded.
128204**
128205** The current value for the constraint is left in a register, the index
128206** of which is returned.  An attempt is made store the result in iTarget but
128207** this is only guaranteed for TK_ISNULL and TK_IN constraints.  If the
128208** constraint is a TK_EQ or TK_IS, then the current value might be left in
128209** some other register and it is the caller's responsibility to compensate.
128210**
128211** For a constraint of the form X=expr, the expression is evaluated in
128212** straight-line code.  For constraints of the form X IN (...)
128213** this routine sets up a loop that will iterate over all values of X.
128214*/
128215static int codeEqualityTerm(
128216  Parse *pParse,      /* The parsing context */
128217  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
128218  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
128219  int iEq,            /* Index of the equality term within this level */
128220  int bRev,           /* True for reverse-order IN operations */
128221  int iTarget         /* Attempt to leave results in this register */
128222){
128223  Expr *pX = pTerm->pExpr;
128224  Vdbe *v = pParse->pVdbe;
128225  int iReg;                  /* Register holding results */
128226
128227  assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
128228  assert( iTarget>0 );
128229  if( pX->op==TK_EQ || pX->op==TK_IS ){
128230    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
128231  }else if( pX->op==TK_ISNULL ){
128232    iReg = iTarget;
128233    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
128234#ifndef SQLITE_OMIT_SUBQUERY
128235  }else{
128236    int eType = IN_INDEX_NOOP;
128237    int iTab;
128238    struct InLoop *pIn;
128239    WhereLoop *pLoop = pLevel->pWLoop;
128240    int i;
128241    int nEq = 0;
128242    int *aiMap = 0;
128243
128244    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
128245      && pLoop->u.btree.pIndex!=0
128246      && pLoop->u.btree.pIndex->aSortOrder[iEq]
128247    ){
128248      testcase( iEq==0 );
128249      testcase( bRev );
128250      bRev = !bRev;
128251    }
128252    assert( pX->op==TK_IN );
128253    iReg = iTarget;
128254
128255    for(i=0; i<iEq; i++){
128256      if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
128257        disableTerm(pLevel, pTerm);
128258        return iTarget;
128259      }
128260    }
128261    for(i=iEq;i<pLoop->nLTerm; i++){
128262      if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
128263    }
128264
128265    if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
128266      eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
128267    }else{
128268      Select *pSelect = pX->x.pSelect;
128269      sqlite3 *db = pParse->db;
128270      u16 savedDbOptFlags = db->dbOptFlags;
128271      ExprList *pOrigRhs = pSelect->pEList;
128272      ExprList *pOrigLhs = pX->pLeft->x.pList;
128273      ExprList *pRhs = 0;         /* New Select.pEList for RHS */
128274      ExprList *pLhs = 0;         /* New pX->pLeft vector */
128275
128276      for(i=iEq;i<pLoop->nLTerm; i++){
128277        if( pLoop->aLTerm[i]->pExpr==pX ){
128278          int iField = pLoop->aLTerm[i]->iField - 1;
128279          Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
128280          Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
128281
128282          pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
128283          pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
128284        }
128285      }
128286      if( !db->mallocFailed ){
128287        Expr *pLeft = pX->pLeft;
128288
128289        if( pSelect->pOrderBy ){
128290          /* If the SELECT statement has an ORDER BY clause, zero the
128291          ** iOrderByCol variables. These are set to non-zero when an
128292          ** ORDER BY term exactly matches one of the terms of the
128293          ** result-set. Since the result-set of the SELECT statement may
128294          ** have been modified or reordered, these variables are no longer
128295          ** set correctly.  Since setting them is just an optimization,
128296          ** it's easiest just to zero them here.  */
128297          ExprList *pOrderBy = pSelect->pOrderBy;
128298          for(i=0; i<pOrderBy->nExpr; i++){
128299            pOrderBy->a[i].u.x.iOrderByCol = 0;
128300          }
128301        }
128302
128303        /* Take care here not to generate a TK_VECTOR containing only a
128304        ** single value. Since the parser never creates such a vector, some
128305        ** of the subroutines do not handle this case.  */
128306        if( pLhs->nExpr==1 ){
128307          pX->pLeft = pLhs->a[0].pExpr;
128308        }else{
128309          pLeft->x.pList = pLhs;
128310          aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
128311          testcase( aiMap==0 );
128312        }
128313        pSelect->pEList = pRhs;
128314        db->dbOptFlags |= SQLITE_QueryFlattener;
128315        eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
128316        db->dbOptFlags = savedDbOptFlags;
128317        testcase( aiMap!=0 && aiMap[0]!=0 );
128318        pSelect->pEList = pOrigRhs;
128319        pLeft->x.pList = pOrigLhs;
128320        pX->pLeft = pLeft;
128321      }
128322      sqlite3ExprListDelete(pParse->db, pLhs);
128323      sqlite3ExprListDelete(pParse->db, pRhs);
128324    }
128325
128326    if( eType==IN_INDEX_INDEX_DESC ){
128327      testcase( bRev );
128328      bRev = !bRev;
128329    }
128330    iTab = pX->iTable;
128331    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
128332    VdbeCoverageIf(v, bRev);
128333    VdbeCoverageIf(v, !bRev);
128334    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
128335
128336    pLoop->wsFlags |= WHERE_IN_ABLE;
128337    if( pLevel->u.in.nIn==0 ){
128338      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
128339    }
128340
128341    i = pLevel->u.in.nIn;
128342    pLevel->u.in.nIn += nEq;
128343    pLevel->u.in.aInLoop =
128344       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
128345                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
128346    pIn = pLevel->u.in.aInLoop;
128347    if( pIn ){
128348      int iMap = 0;               /* Index in aiMap[] */
128349      pIn += i;
128350      for(i=iEq;i<pLoop->nLTerm; i++){
128351        if( pLoop->aLTerm[i]->pExpr==pX ){
128352          int iOut = iReg + i - iEq;
128353          if( eType==IN_INDEX_ROWID ){
128354            testcase( nEq>1 );  /* Happens with a UNIQUE index on ROWID */
128355            pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
128356          }else{
128357            int iCol = aiMap ? aiMap[iMap++] : 0;
128358            pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
128359          }
128360          sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
128361          if( i==iEq ){
128362            pIn->iCur = iTab;
128363            pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
128364          }else{
128365            pIn->eEndLoopOp = OP_Noop;
128366          }
128367          pIn++;
128368        }
128369      }
128370    }else{
128371      pLevel->u.in.nIn = 0;
128372    }
128373    sqlite3DbFree(pParse->db, aiMap);
128374#endif
128375  }
128376  disableTerm(pLevel, pTerm);
128377  return iReg;
128378}
128379
128380/*
128381** Generate code that will evaluate all == and IN constraints for an
128382** index scan.
128383**
128384** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
128385** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
128386** The index has as many as three equality constraints, but in this
128387** example, the third "c" value is an inequality.  So only two
128388** constraints are coded.  This routine will generate code to evaluate
128389** a==5 and b IN (1,2,3).  The current values for a and b will be stored
128390** in consecutive registers and the index of the first register is returned.
128391**
128392** In the example above nEq==2.  But this subroutine works for any value
128393** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
128394** The only thing it does is allocate the pLevel->iMem memory cell and
128395** compute the affinity string.
128396**
128397** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
128398** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
128399** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
128400** occurs after the nEq quality constraints.
128401**
128402** This routine allocates a range of nEq+nExtraReg memory cells and returns
128403** the index of the first memory cell in that range. The code that
128404** calls this routine will use that memory range to store keys for
128405** start and termination conditions of the loop.
128406** key value of the loop.  If one or more IN operators appear, then
128407** this routine allocates an additional nEq memory cells for internal
128408** use.
128409**
128410** Before returning, *pzAff is set to point to a buffer containing a
128411** copy of the column affinity string of the index allocated using
128412** sqlite3DbMalloc(). Except, entries in the copy of the string associated
128413** with equality constraints that use BLOB or NONE affinity are set to
128414** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
128415**
128416**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
128417**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
128418**
128419** In the example above, the index on t1(a) has TEXT affinity. But since
128420** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
128421** no conversion should be attempted before using a t2.b value as part of
128422** a key to search the index. Hence the first byte in the returned affinity
128423** string in this example would be set to SQLITE_AFF_BLOB.
128424*/
128425static int codeAllEqualityTerms(
128426  Parse *pParse,        /* Parsing context */
128427  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
128428  int bRev,             /* Reverse the order of IN operators */
128429  int nExtraReg,        /* Number of extra registers to allocate */
128430  char **pzAff          /* OUT: Set to point to affinity string */
128431){
128432  u16 nEq;                      /* The number of == or IN constraints to code */
128433  u16 nSkip;                    /* Number of left-most columns to skip */
128434  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
128435  Index *pIdx;                  /* The index being used for this loop */
128436  WhereTerm *pTerm;             /* A single constraint term */
128437  WhereLoop *pLoop;             /* The WhereLoop object */
128438  int j;                        /* Loop counter */
128439  int regBase;                  /* Base register */
128440  int nReg;                     /* Number of registers to allocate */
128441  char *zAff;                   /* Affinity string to return */
128442
128443  /* This module is only called on query plans that use an index. */
128444  pLoop = pLevel->pWLoop;
128445  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
128446  nEq = pLoop->u.btree.nEq;
128447  nSkip = pLoop->nSkip;
128448  pIdx = pLoop->u.btree.pIndex;
128449  assert( pIdx!=0 );
128450
128451  /* Figure out how many memory cells we will need then allocate them.
128452  */
128453  regBase = pParse->nMem + 1;
128454  nReg = pLoop->u.btree.nEq + nExtraReg;
128455  pParse->nMem += nReg;
128456
128457  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
128458  assert( zAff!=0 || pParse->db->mallocFailed );
128459
128460  if( nSkip ){
128461    int iIdxCur = pLevel->iIdxCur;
128462    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
128463    VdbeCoverageIf(v, bRev==0);
128464    VdbeCoverageIf(v, bRev!=0);
128465    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
128466    j = sqlite3VdbeAddOp0(v, OP_Goto);
128467    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
128468                            iIdxCur, 0, regBase, nSkip);
128469    VdbeCoverageIf(v, bRev==0);
128470    VdbeCoverageIf(v, bRev!=0);
128471    sqlite3VdbeJumpHere(v, j);
128472    for(j=0; j<nSkip; j++){
128473      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
128474      testcase( pIdx->aiColumn[j]==XN_EXPR );
128475      VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
128476    }
128477  }
128478
128479  /* Evaluate the equality constraints
128480  */
128481  assert( zAff==0 || (int)strlen(zAff)>=nEq );
128482  for(j=nSkip; j<nEq; j++){
128483    int r1;
128484    pTerm = pLoop->aLTerm[j];
128485    assert( pTerm!=0 );
128486    /* The following testcase is true for indices with redundant columns.
128487    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
128488    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
128489    testcase( pTerm->wtFlags & TERM_VIRTUAL );
128490    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
128491    if( r1!=regBase+j ){
128492      if( nReg==1 ){
128493        sqlite3ReleaseTempReg(pParse, regBase);
128494        regBase = r1;
128495      }else{
128496        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
128497      }
128498    }
128499    if( pTerm->eOperator & WO_IN ){
128500      if( pTerm->pExpr->flags & EP_xIsSelect ){
128501        /* No affinity ever needs to be (or should be) applied to a value
128502        ** from the RHS of an "? IN (SELECT ...)" expression. The
128503        ** sqlite3FindInIndex() routine has already ensured that the
128504        ** affinity of the comparison has been applied to the value.  */
128505        if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
128506      }
128507    }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
128508      Expr *pRight = pTerm->pExpr->pRight;
128509      if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
128510        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
128511        VdbeCoverage(v);
128512      }
128513      if( zAff ){
128514        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
128515          zAff[j] = SQLITE_AFF_BLOB;
128516        }
128517        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
128518          zAff[j] = SQLITE_AFF_BLOB;
128519        }
128520      }
128521    }
128522  }
128523  *pzAff = zAff;
128524  return regBase;
128525}
128526
128527#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
128528/*
128529** If the most recently coded instruction is a constant range constraint
128530** (a string literal) that originated from the LIKE optimization, then
128531** set P3 and P5 on the OP_String opcode so that the string will be cast
128532** to a BLOB at appropriate times.
128533**
128534** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
128535** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
128536** scan loop run twice, once for strings and a second time for BLOBs.
128537** The OP_String opcodes on the second pass convert the upper and lower
128538** bound string constants to blobs.  This routine makes the necessary changes
128539** to the OP_String opcodes for that to happen.
128540**
128541** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
128542** only the one pass through the string space is required, so this routine
128543** becomes a no-op.
128544*/
128545static void whereLikeOptimizationStringFixup(
128546  Vdbe *v,                /* prepared statement under construction */
128547  WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
128548  WhereTerm *pTerm        /* The upper or lower bound just coded */
128549){
128550  if( pTerm->wtFlags & TERM_LIKEOPT ){
128551    VdbeOp *pOp;
128552    assert( pLevel->iLikeRepCntr>0 );
128553    pOp = sqlite3VdbeGetOp(v, -1);
128554    assert( pOp!=0 );
128555    assert( pOp->opcode==OP_String8
128556            || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
128557    pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
128558    pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
128559  }
128560}
128561#else
128562# define whereLikeOptimizationStringFixup(A,B,C)
128563#endif
128564
128565#ifdef SQLITE_ENABLE_CURSOR_HINTS
128566/*
128567** Information is passed from codeCursorHint() down to individual nodes of
128568** the expression tree (by sqlite3WalkExpr()) using an instance of this
128569** structure.
128570*/
128571struct CCurHint {
128572  int iTabCur;    /* Cursor for the main table */
128573  int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
128574  Index *pIdx;    /* The index used to access the table */
128575};
128576
128577/*
128578** This function is called for every node of an expression that is a candidate
128579** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
128580** the table CCurHint.iTabCur, verify that the same column can be
128581** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
128582*/
128583static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
128584  struct CCurHint *pHint = pWalker->u.pCCurHint;
128585  assert( pHint->pIdx!=0 );
128586  if( pExpr->op==TK_COLUMN
128587   && pExpr->iTable==pHint->iTabCur
128588   && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
128589  ){
128590    pWalker->eCode = 1;
128591  }
128592  return WRC_Continue;
128593}
128594
128595/*
128596** Test whether or not expression pExpr, which was part of a WHERE clause,
128597** should be included in the cursor-hint for a table that is on the rhs
128598** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
128599** expression is not suitable.
128600**
128601** An expression is unsuitable if it might evaluate to non NULL even if
128602** a TK_COLUMN node that does affect the value of the expression is set
128603** to NULL. For example:
128604**
128605**   col IS NULL
128606**   col IS NOT NULL
128607**   coalesce(col, 1)
128608**   CASE WHEN col THEN 0 ELSE 1 END
128609*/
128610static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
128611  if( pExpr->op==TK_IS
128612   || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
128613   || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
128614  ){
128615    pWalker->eCode = 1;
128616  }else if( pExpr->op==TK_FUNCTION ){
128617    int d1;
128618    char d2[3];
128619    if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
128620      pWalker->eCode = 1;
128621    }
128622  }
128623
128624  return WRC_Continue;
128625}
128626
128627
128628/*
128629** This function is called on every node of an expression tree used as an
128630** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
128631** that accesses any table other than the one identified by
128632** CCurHint.iTabCur, then do the following:
128633**
128634**   1) allocate a register and code an OP_Column instruction to read
128635**      the specified column into the new register, and
128636**
128637**   2) transform the expression node to a TK_REGISTER node that reads
128638**      from the newly populated register.
128639**
128640** Also, if the node is a TK_COLUMN that does access the table idenified
128641** by pCCurHint.iTabCur, and an index is being used (which we will
128642** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
128643** an access of the index rather than the original table.
128644*/
128645static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
128646  int rc = WRC_Continue;
128647  struct CCurHint *pHint = pWalker->u.pCCurHint;
128648  if( pExpr->op==TK_COLUMN ){
128649    if( pExpr->iTable!=pHint->iTabCur ){
128650      Vdbe *v = pWalker->pParse->pVdbe;
128651      int reg = ++pWalker->pParse->nMem;   /* Register for column value */
128652      sqlite3ExprCodeGetColumnOfTable(
128653          v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
128654      );
128655      pExpr->op = TK_REGISTER;
128656      pExpr->iTable = reg;
128657    }else if( pHint->pIdx!=0 ){
128658      pExpr->iTable = pHint->iIdxCur;
128659      pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
128660      assert( pExpr->iColumn>=0 );
128661    }
128662  }else if( pExpr->op==TK_AGG_FUNCTION ){
128663    /* An aggregate function in the WHERE clause of a query means this must
128664    ** be a correlated sub-query, and expression pExpr is an aggregate from
128665    ** the parent context. Do not walk the function arguments in this case.
128666    **
128667    ** todo: It should be possible to replace this node with a TK_REGISTER
128668    ** expression, as the result of the expression must be stored in a
128669    ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
128670    rc = WRC_Prune;
128671  }
128672  return rc;
128673}
128674
128675/*
128676** Insert an OP_CursorHint instruction if it is appropriate to do so.
128677*/
128678static void codeCursorHint(
128679  struct SrcList_item *pTabItem,  /* FROM clause item */
128680  WhereInfo *pWInfo,    /* The where clause */
128681  WhereLevel *pLevel,   /* Which loop to provide hints for */
128682  WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
128683){
128684  Parse *pParse = pWInfo->pParse;
128685  sqlite3 *db = pParse->db;
128686  Vdbe *v = pParse->pVdbe;
128687  Expr *pExpr = 0;
128688  WhereLoop *pLoop = pLevel->pWLoop;
128689  int iCur;
128690  WhereClause *pWC;
128691  WhereTerm *pTerm;
128692  int i, j;
128693  struct CCurHint sHint;
128694  Walker sWalker;
128695
128696  if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
128697  iCur = pLevel->iTabCur;
128698  assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
128699  sHint.iTabCur = iCur;
128700  sHint.iIdxCur = pLevel->iIdxCur;
128701  sHint.pIdx = pLoop->u.btree.pIndex;
128702  memset(&sWalker, 0, sizeof(sWalker));
128703  sWalker.pParse = pParse;
128704  sWalker.u.pCCurHint = &sHint;
128705  pWC = &pWInfo->sWC;
128706  for(i=0; i<pWC->nTerm; i++){
128707    pTerm = &pWC->a[i];
128708    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
128709    if( pTerm->prereqAll & pLevel->notReady ) continue;
128710
128711    /* Any terms specified as part of the ON(...) clause for any LEFT
128712    ** JOIN for which the current table is not the rhs are omitted
128713    ** from the cursor-hint.
128714    **
128715    ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
128716    ** that were specified as part of the WHERE clause must be excluded.
128717    ** This is to address the following:
128718    **
128719    **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
128720    **
128721    ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
128722    ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
128723    ** pushed down to the cursor, this row is filtered out, causing
128724    ** SQLite to synthesize a row of NULL values. Which does match the
128725    ** WHERE clause, and so the query returns a row. Which is incorrect.
128726    **
128727    ** For the same reason, WHERE terms such as:
128728    **
128729    **   WHERE 1 = (t2.c IS NULL)
128730    **
128731    ** are also excluded. See codeCursorHintIsOrFunction() for details.
128732    */
128733    if( pTabItem->fg.jointype & JT_LEFT ){
128734      Expr *pExpr = pTerm->pExpr;
128735      if( !ExprHasProperty(pExpr, EP_FromJoin)
128736       || pExpr->iRightJoinTable!=pTabItem->iCursor
128737      ){
128738        sWalker.eCode = 0;
128739        sWalker.xExprCallback = codeCursorHintIsOrFunction;
128740        sqlite3WalkExpr(&sWalker, pTerm->pExpr);
128741        if( sWalker.eCode ) continue;
128742      }
128743    }else{
128744      if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
128745    }
128746
128747    /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
128748    ** the cursor.  These terms are not needed as hints for a pure range
128749    ** scan (that has no == terms) so omit them. */
128750    if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
128751      for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
128752      if( j<pLoop->nLTerm ) continue;
128753    }
128754
128755    /* No subqueries or non-deterministic functions allowed */
128756    if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
128757
128758    /* For an index scan, make sure referenced columns are actually in
128759    ** the index. */
128760    if( sHint.pIdx!=0 ){
128761      sWalker.eCode = 0;
128762      sWalker.xExprCallback = codeCursorHintCheckExpr;
128763      sqlite3WalkExpr(&sWalker, pTerm->pExpr);
128764      if( sWalker.eCode ) continue;
128765    }
128766
128767    /* If we survive all prior tests, that means this term is worth hinting */
128768    pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
128769  }
128770  if( pExpr!=0 ){
128771    sWalker.xExprCallback = codeCursorHintFixExpr;
128772    sqlite3WalkExpr(&sWalker, pExpr);
128773    sqlite3VdbeAddOp4(v, OP_CursorHint,
128774                      (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
128775                      (const char*)pExpr, P4_EXPR);
128776  }
128777}
128778#else
128779# define codeCursorHint(A,B,C,D)  /* No-op */
128780#endif /* SQLITE_ENABLE_CURSOR_HINTS */
128781
128782/*
128783** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
128784** a rowid value just read from cursor iIdxCur, open on index pIdx. This
128785** function generates code to do a deferred seek of cursor iCur to the
128786** rowid stored in register iRowid.
128787**
128788** Normally, this is just:
128789**
128790**   OP_DeferredSeek $iCur $iRowid
128791**
128792** However, if the scan currently being coded is a branch of an OR-loop and
128793** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
128794** is set to iIdxCur and P4 is set to point to an array of integers
128795** containing one entry for each column of the table cursor iCur is open
128796** on. For each table column, if the column is the i'th column of the
128797** index, then the corresponding array entry is set to (i+1). If the column
128798** does not appear in the index at all, the array entry is set to 0.
128799*/
128800static void codeDeferredSeek(
128801  WhereInfo *pWInfo,              /* Where clause context */
128802  Index *pIdx,                    /* Index scan is using */
128803  int iCur,                       /* Cursor for IPK b-tree */
128804  int iIdxCur                     /* Index cursor */
128805){
128806  Parse *pParse = pWInfo->pParse; /* Parse context */
128807  Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
128808
128809  assert( iIdxCur>0 );
128810  assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
128811
128812  sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
128813  if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
128814   && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
128815  ){
128816    int i;
128817    Table *pTab = pIdx->pTable;
128818    int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
128819    if( ai ){
128820      ai[0] = pTab->nCol;
128821      for(i=0; i<pIdx->nColumn-1; i++){
128822        assert( pIdx->aiColumn[i]<pTab->nCol );
128823        if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
128824      }
128825      sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
128826    }
128827  }
128828}
128829
128830/*
128831** If the expression passed as the second argument is a vector, generate
128832** code to write the first nReg elements of the vector into an array
128833** of registers starting with iReg.
128834**
128835** If the expression is not a vector, then nReg must be passed 1. In
128836** this case, generate code to evaluate the expression and leave the
128837** result in register iReg.
128838*/
128839static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
128840  assert( nReg>0 );
128841  if( sqlite3ExprIsVector(p) ){
128842#ifndef SQLITE_OMIT_SUBQUERY
128843    if( (p->flags & EP_xIsSelect) ){
128844      Vdbe *v = pParse->pVdbe;
128845      int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
128846      sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
128847    }else
128848#endif
128849    {
128850      int i;
128851      ExprList *pList = p->x.pList;
128852      assert( nReg<=pList->nExpr );
128853      for(i=0; i<nReg; i++){
128854        sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
128855      }
128856    }
128857  }else{
128858    assert( nReg==1 );
128859    sqlite3ExprCode(pParse, p, iReg);
128860  }
128861}
128862
128863/* An instance of the IdxExprTrans object carries information about a
128864** mapping from an expression on table columns into a column in an index
128865** down through the Walker.
128866*/
128867typedef struct IdxExprTrans {
128868  Expr *pIdxExpr;    /* The index expression */
128869  int iTabCur;       /* The cursor of the corresponding table */
128870  int iIdxCur;       /* The cursor for the index */
128871  int iIdxCol;       /* The column for the index */
128872} IdxExprTrans;
128873
128874/* The walker node callback used to transform matching expressions into
128875** a reference to an index column for an index on an expression.
128876**
128877** If pExpr matches, then transform it into a reference to the index column
128878** that contains the value of pExpr.
128879*/
128880static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
128881  IdxExprTrans *pX = p->u.pIdxTrans;
128882  if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
128883    pExpr->op = TK_COLUMN;
128884    pExpr->iTable = pX->iIdxCur;
128885    pExpr->iColumn = pX->iIdxCol;
128886    pExpr->pTab = 0;
128887    return WRC_Prune;
128888  }else{
128889    return WRC_Continue;
128890  }
128891}
128892
128893/*
128894** For an indexes on expression X, locate every instance of expression X in pExpr
128895** and change that subexpression into a reference to the appropriate column of
128896** the index.
128897*/
128898static void whereIndexExprTrans(
128899  Index *pIdx,      /* The Index */
128900  int iTabCur,      /* Cursor of the table that is being indexed */
128901  int iIdxCur,      /* Cursor of the index itself */
128902  WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
128903){
128904  int iIdxCol;               /* Column number of the index */
128905  ExprList *aColExpr;        /* Expressions that are indexed */
128906  Walker w;
128907  IdxExprTrans x;
128908  aColExpr = pIdx->aColExpr;
128909  if( aColExpr==0 ) return;  /* Not an index on expressions */
128910  memset(&w, 0, sizeof(w));
128911  w.xExprCallback = whereIndexExprTransNode;
128912  w.u.pIdxTrans = &x;
128913  x.iTabCur = iTabCur;
128914  x.iIdxCur = iIdxCur;
128915  for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
128916    if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
128917    assert( aColExpr->a[iIdxCol].pExpr!=0 );
128918    x.iIdxCol = iIdxCol;
128919    x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
128920    sqlite3WalkExpr(&w, pWInfo->pWhere);
128921    sqlite3WalkExprList(&w, pWInfo->pOrderBy);
128922    sqlite3WalkExprList(&w, pWInfo->pResultSet);
128923  }
128924}
128925
128926/*
128927** Generate code for the start of the iLevel-th loop in the WHERE clause
128928** implementation described by pWInfo.
128929*/
128930SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
128931  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
128932  int iLevel,          /* Which level of pWInfo->a[] should be coded */
128933  Bitmask notReady     /* Which tables are currently available */
128934){
128935  int j, k;            /* Loop counters */
128936  int iCur;            /* The VDBE cursor for the table */
128937  int addrNxt;         /* Where to jump to continue with the next IN case */
128938  int omitTable;       /* True if we use the index only */
128939  int bRev;            /* True if we need to scan in reverse order */
128940  WhereLevel *pLevel;  /* The where level to be coded */
128941  WhereLoop *pLoop;    /* The WhereLoop object being coded */
128942  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
128943  WhereTerm *pTerm;               /* A WHERE clause term */
128944  Parse *pParse;                  /* Parsing context */
128945  sqlite3 *db;                    /* Database connection */
128946  Vdbe *v;                        /* The prepared stmt under constructions */
128947  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
128948  int addrBrk;                    /* Jump here to break out of the loop */
128949  int addrHalt;                   /* addrBrk for the outermost loop */
128950  int addrCont;                   /* Jump here to continue with next cycle */
128951  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
128952  int iReleaseReg = 0;      /* Temp register to free before returning */
128953  Index *pIdx = 0;          /* Index used by loop (if any) */
128954  int iLoop;                /* Iteration of constraint generator loop */
128955
128956  pParse = pWInfo->pParse;
128957  v = pParse->pVdbe;
128958  pWC = &pWInfo->sWC;
128959  db = pParse->db;
128960  pLevel = &pWInfo->a[iLevel];
128961  pLoop = pLevel->pWLoop;
128962  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
128963  iCur = pTabItem->iCursor;
128964  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
128965  bRev = (pWInfo->revMask>>iLevel)&1;
128966  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
128967           && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
128968  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
128969
128970  /* Create labels for the "break" and "continue" instructions
128971  ** for the current loop.  Jump to addrBrk to break out of a loop.
128972  ** Jump to cont to go immediately to the next iteration of the
128973  ** loop.
128974  **
128975  ** When there is an IN operator, we also have a "addrNxt" label that
128976  ** means to continue with the next IN value combination.  When
128977  ** there are no IN operators in the constraints, the "addrNxt" label
128978  ** is the same as "addrBrk".
128979  */
128980  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
128981  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
128982
128983  /* If this is the right table of a LEFT OUTER JOIN, allocate and
128984  ** initialize a memory cell that records if this table matches any
128985  ** row of the left table of the join.
128986  */
128987  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
128988    pLevel->iLeftJoin = ++pParse->nMem;
128989    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
128990    VdbeComment((v, "init LEFT JOIN no-match flag"));
128991  }
128992
128993  /* Compute a safe address to jump to if we discover that the table for
128994  ** this loop is empty and can never contribute content. */
128995  for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
128996  addrHalt = pWInfo->a[j].addrBrk;
128997
128998  /* Special case of a FROM clause subquery implemented as a co-routine */
128999  if( pTabItem->fg.viaCoroutine ){
129000    int regYield = pTabItem->regReturn;
129001    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
129002    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
129003    VdbeCoverage(v);
129004    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
129005    pLevel->op = OP_Goto;
129006  }else
129007
129008#ifndef SQLITE_OMIT_VIRTUALTABLE
129009  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
129010    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
129011    **          to access the data.
129012    */
129013    int iReg;   /* P3 Value for OP_VFilter */
129014    int addrNotFound;
129015    int nConstraint = pLoop->nLTerm;
129016    int iIn;    /* Counter for IN constraints */
129017
129018    sqlite3ExprCachePush(pParse);
129019    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
129020    addrNotFound = pLevel->addrBrk;
129021    for(j=0; j<nConstraint; j++){
129022      int iTarget = iReg+j+2;
129023      pTerm = pLoop->aLTerm[j];
129024      if( NEVER(pTerm==0) ) continue;
129025      if( pTerm->eOperator & WO_IN ){
129026        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
129027        addrNotFound = pLevel->addrNxt;
129028      }else{
129029        Expr *pRight = pTerm->pExpr->pRight;
129030        codeExprOrVector(pParse, pRight, iTarget, 1);
129031      }
129032    }
129033    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
129034    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
129035    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
129036                      pLoop->u.vtab.idxStr,
129037                      pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
129038    VdbeCoverage(v);
129039    pLoop->u.vtab.needFree = 0;
129040    pLevel->p1 = iCur;
129041    pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
129042    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
129043    iIn = pLevel->u.in.nIn;
129044    for(j=nConstraint-1; j>=0; j--){
129045      pTerm = pLoop->aLTerm[j];
129046      if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
129047        disableTerm(pLevel, pTerm);
129048      }else if( (pTerm->eOperator & WO_IN)!=0 ){
129049        Expr *pCompare;  /* The comparison operator */
129050        Expr *pRight;    /* RHS of the comparison */
129051        VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
129052
129053        /* Reload the constraint value into reg[iReg+j+2].  The same value
129054        ** was loaded into the same register prior to the OP_VFilter, but
129055        ** the xFilter implementation might have changed the datatype or
129056        ** encoding of the value in the register, so it *must* be reloaded. */
129057        assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
129058        if( !db->mallocFailed ){
129059          assert( iIn>0 );
129060          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
129061          assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
129062          assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
129063          assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
129064          testcase( pOp->opcode==OP_Rowid );
129065          sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
129066        }
129067
129068        /* Generate code that will continue to the next row if
129069        ** the IN constraint is not satisfied */
129070        pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
129071        assert( pCompare!=0 || db->mallocFailed );
129072        if( pCompare ){
129073          pCompare->pLeft = pTerm->pExpr->pLeft;
129074          pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
129075          if( pRight ){
129076            pRight->iTable = iReg+j+2;
129077            sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
129078          }
129079          pCompare->pLeft = 0;
129080          sqlite3ExprDelete(db, pCompare);
129081        }
129082      }
129083    }
129084    /* These registers need to be preserved in case there is an IN operator
129085    ** loop.  So we could deallocate the registers here (and potentially
129086    ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
129087    ** simpler and safer to simply not reuse the registers.
129088    **
129089    **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
129090    */
129091    sqlite3ExprCachePop(pParse);
129092  }else
129093#endif /* SQLITE_OMIT_VIRTUALTABLE */
129094
129095  if( (pLoop->wsFlags & WHERE_IPK)!=0
129096   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
129097  ){
129098    /* Case 2:  We can directly reference a single row using an
129099    **          equality comparison against the ROWID field.  Or
129100    **          we reference multiple rows using a "rowid IN (...)"
129101    **          construct.
129102    */
129103    assert( pLoop->u.btree.nEq==1 );
129104    pTerm = pLoop->aLTerm[0];
129105    assert( pTerm!=0 );
129106    assert( pTerm->pExpr!=0 );
129107    assert( omitTable==0 );
129108    testcase( pTerm->wtFlags & TERM_VIRTUAL );
129109    iReleaseReg = ++pParse->nMem;
129110    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
129111    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
129112    addrNxt = pLevel->addrNxt;
129113    sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
129114    VdbeCoverage(v);
129115    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
129116    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129117    VdbeComment((v, "pk"));
129118    pLevel->op = OP_Noop;
129119  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
129120         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
129121  ){
129122    /* Case 3:  We have an inequality comparison against the ROWID field.
129123    */
129124    int testOp = OP_Noop;
129125    int start;
129126    int memEndValue = 0;
129127    WhereTerm *pStart, *pEnd;
129128
129129    assert( omitTable==0 );
129130    j = 0;
129131    pStart = pEnd = 0;
129132    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
129133    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
129134    assert( pStart!=0 || pEnd!=0 );
129135    if( bRev ){
129136      pTerm = pStart;
129137      pStart = pEnd;
129138      pEnd = pTerm;
129139    }
129140    codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
129141    if( pStart ){
129142      Expr *pX;             /* The expression that defines the start bound */
129143      int r1, rTemp;        /* Registers for holding the start boundary */
129144      int op;               /* Cursor seek operation */
129145
129146      /* The following constant maps TK_xx codes into corresponding
129147      ** seek opcodes.  It depends on a particular ordering of TK_xx
129148      */
129149      const u8 aMoveOp[] = {
129150           /* TK_GT */  OP_SeekGT,
129151           /* TK_LE */  OP_SeekLE,
129152           /* TK_LT */  OP_SeekLT,
129153           /* TK_GE */  OP_SeekGE
129154      };
129155      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
129156      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
129157      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
129158
129159      assert( (pStart->wtFlags & TERM_VNULL)==0 );
129160      testcase( pStart->wtFlags & TERM_VIRTUAL );
129161      pX = pStart->pExpr;
129162      assert( pX!=0 );
129163      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
129164      if( sqlite3ExprIsVector(pX->pRight) ){
129165        r1 = rTemp = sqlite3GetTempReg(pParse);
129166        codeExprOrVector(pParse, pX->pRight, r1, 1);
129167        op = aMoveOp[(pX->op - TK_GT) | 0x0001];
129168      }else{
129169        r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
129170        disableTerm(pLevel, pStart);
129171        op = aMoveOp[(pX->op - TK_GT)];
129172      }
129173      sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
129174      VdbeComment((v, "pk"));
129175      VdbeCoverageIf(v, pX->op==TK_GT);
129176      VdbeCoverageIf(v, pX->op==TK_LE);
129177      VdbeCoverageIf(v, pX->op==TK_LT);
129178      VdbeCoverageIf(v, pX->op==TK_GE);
129179      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
129180      sqlite3ReleaseTempReg(pParse, rTemp);
129181    }else{
129182      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
129183      VdbeCoverageIf(v, bRev==0);
129184      VdbeCoverageIf(v, bRev!=0);
129185    }
129186    if( pEnd ){
129187      Expr *pX;
129188      pX = pEnd->pExpr;
129189      assert( pX!=0 );
129190      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
129191      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
129192      testcase( pEnd->wtFlags & TERM_VIRTUAL );
129193      memEndValue = ++pParse->nMem;
129194      codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
129195      if( 0==sqlite3ExprIsVector(pX->pRight)
129196       && (pX->op==TK_LT || pX->op==TK_GT)
129197      ){
129198        testOp = bRev ? OP_Le : OP_Ge;
129199      }else{
129200        testOp = bRev ? OP_Lt : OP_Gt;
129201      }
129202      if( 0==sqlite3ExprIsVector(pX->pRight) ){
129203        disableTerm(pLevel, pEnd);
129204      }
129205    }
129206    start = sqlite3VdbeCurrentAddr(v);
129207    pLevel->op = bRev ? OP_Prev : OP_Next;
129208    pLevel->p1 = iCur;
129209    pLevel->p2 = start;
129210    assert( pLevel->p5==0 );
129211    if( testOp!=OP_Noop ){
129212      iRowidReg = ++pParse->nMem;
129213      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
129214      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129215      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
129216      VdbeCoverageIf(v, testOp==OP_Le);
129217      VdbeCoverageIf(v, testOp==OP_Lt);
129218      VdbeCoverageIf(v, testOp==OP_Ge);
129219      VdbeCoverageIf(v, testOp==OP_Gt);
129220      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
129221    }
129222  }else if( pLoop->wsFlags & WHERE_INDEXED ){
129223    /* Case 4: A scan using an index.
129224    **
129225    **         The WHERE clause may contain zero or more equality
129226    **         terms ("==" or "IN" operators) that refer to the N
129227    **         left-most columns of the index. It may also contain
129228    **         inequality constraints (>, <, >= or <=) on the indexed
129229    **         column that immediately follows the N equalities. Only
129230    **         the right-most column can be an inequality - the rest must
129231    **         use the "==" and "IN" operators. For example, if the
129232    **         index is on (x,y,z), then the following clauses are all
129233    **         optimized:
129234    **
129235    **            x=5
129236    **            x=5 AND y=10
129237    **            x=5 AND y<10
129238    **            x=5 AND y>5 AND y<10
129239    **            x=5 AND y=5 AND z<=10
129240    **
129241    **         The z<10 term of the following cannot be used, only
129242    **         the x=5 term:
129243    **
129244    **            x=5 AND z<10
129245    **
129246    **         N may be zero if there are inequality constraints.
129247    **         If there are no inequality constraints, then N is at
129248    **         least one.
129249    **
129250    **         This case is also used when there are no WHERE clause
129251    **         constraints but an index is selected anyway, in order
129252    **         to force the output order to conform to an ORDER BY.
129253    */
129254    static const u8 aStartOp[] = {
129255      0,
129256      0,
129257      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
129258      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
129259      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
129260      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
129261      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
129262      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
129263    };
129264    static const u8 aEndOp[] = {
129265      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
129266      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
129267      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
129268      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
129269    };
129270    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
129271    u16 nBtm = pLoop->u.btree.nBtm;   /* Length of BTM vector */
129272    u16 nTop = pLoop->u.btree.nTop;   /* Length of TOP vector */
129273    int regBase;                 /* Base register holding constraint values */
129274    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
129275    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
129276    int startEq;                 /* True if range start uses ==, >= or <= */
129277    int endEq;                   /* True if range end uses ==, >= or <= */
129278    int start_constraints;       /* Start of range is constrained */
129279    int nConstraint;             /* Number of constraint terms */
129280    int iIdxCur;                 /* The VDBE cursor for the index */
129281    int nExtraReg = 0;           /* Number of extra registers needed */
129282    int op;                      /* Instruction opcode */
129283    char *zStartAff;             /* Affinity for start of range constraint */
129284    char *zEndAff = 0;           /* Affinity for end of range constraint */
129285    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
129286    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
129287
129288    pIdx = pLoop->u.btree.pIndex;
129289    iIdxCur = pLevel->iIdxCur;
129290    assert( nEq>=pLoop->nSkip );
129291
129292    /* If this loop satisfies a sort order (pOrderBy) request that
129293    ** was passed to this function to implement a "SELECT min(x) ..."
129294    ** query, then the caller will only allow the loop to run for
129295    ** a single iteration. This means that the first row returned
129296    ** should not have a NULL value stored in 'x'. If column 'x' is
129297    ** the first one after the nEq equality constraints in the index,
129298    ** this requires some special handling.
129299    */
129300    assert( pWInfo->pOrderBy==0
129301         || pWInfo->pOrderBy->nExpr==1
129302         || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
129303    if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
129304     && pWInfo->nOBSat>0
129305     && (pIdx->nKeyCol>nEq)
129306    ){
129307      assert( pLoop->nSkip==0 );
129308      bSeekPastNull = 1;
129309      nExtraReg = 1;
129310    }
129311
129312    /* Find any inequality constraint terms for the start and end
129313    ** of the range.
129314    */
129315    j = nEq;
129316    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
129317      pRangeStart = pLoop->aLTerm[j++];
129318      nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
129319      /* Like optimization range constraints always occur in pairs */
129320      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
129321              (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
129322    }
129323    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
129324      pRangeEnd = pLoop->aLTerm[j++];
129325      nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
129326#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
129327      if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
129328        assert( pRangeStart!=0 );                     /* LIKE opt constraints */
129329        assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
129330        pLevel->iLikeRepCntr = (u32)++pParse->nMem;
129331        sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
129332        VdbeComment((v, "LIKE loop counter"));
129333        pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
129334        /* iLikeRepCntr actually stores 2x the counter register number.  The
129335        ** bottom bit indicates whether the search order is ASC or DESC. */
129336        testcase( bRev );
129337        testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
129338        assert( (bRev & ~1)==0 );
129339        pLevel->iLikeRepCntr <<=1;
129340        pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
129341      }
129342#endif
129343      if( pRangeStart==0 ){
129344        j = pIdx->aiColumn[nEq];
129345        if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
129346          bSeekPastNull = 1;
129347        }
129348      }
129349    }
129350    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
129351
129352    /* If we are doing a reverse order scan on an ascending index, or
129353    ** a forward order scan on a descending index, interchange the
129354    ** start and end terms (pRangeStart and pRangeEnd).
129355    */
129356    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
129357     || (bRev && pIdx->nKeyCol==nEq)
129358    ){
129359      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
129360      SWAP(u8, bSeekPastNull, bStopAtNull);
129361      SWAP(u8, nBtm, nTop);
129362    }
129363
129364    /* Generate code to evaluate all constraint terms using == or IN
129365    ** and store the values of those terms in an array of registers
129366    ** starting at regBase.
129367    */
129368    codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
129369    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
129370    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
129371    if( zStartAff && nTop ){
129372      zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
129373    }
129374    addrNxt = pLevel->addrNxt;
129375
129376    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
129377    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
129378    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
129379    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
129380    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
129381    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
129382    start_constraints = pRangeStart || nEq>0;
129383
129384    /* Seek the index cursor to the start of the range. */
129385    nConstraint = nEq;
129386    if( pRangeStart ){
129387      Expr *pRight = pRangeStart->pExpr->pRight;
129388      codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
129389      whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
129390      if( (pRangeStart->wtFlags & TERM_VNULL)==0
129391       && sqlite3ExprCanBeNull(pRight)
129392      ){
129393        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
129394        VdbeCoverage(v);
129395      }
129396      if( zStartAff ){
129397        updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
129398      }
129399      nConstraint += nBtm;
129400      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
129401      if( sqlite3ExprIsVector(pRight)==0 ){
129402        disableTerm(pLevel, pRangeStart);
129403      }else{
129404        startEq = 1;
129405      }
129406      bSeekPastNull = 0;
129407    }else if( bSeekPastNull ){
129408      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
129409      nConstraint++;
129410      startEq = 0;
129411      start_constraints = 1;
129412    }
129413    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
129414    if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
129415      /* The skip-scan logic inside the call to codeAllEqualityConstraints()
129416      ** above has already left the cursor sitting on the correct row,
129417      ** so no further seeking is needed */
129418    }else{
129419      op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
129420      assert( op!=0 );
129421      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
129422      VdbeCoverage(v);
129423      VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
129424      VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
129425      VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
129426      VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
129427      VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
129428      VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
129429    }
129430
129431    /* Load the value for the inequality constraint at the end of the
129432    ** range (if any).
129433    */
129434    nConstraint = nEq;
129435    if( pRangeEnd ){
129436      Expr *pRight = pRangeEnd->pExpr->pRight;
129437      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
129438      codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
129439      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
129440      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
129441       && sqlite3ExprCanBeNull(pRight)
129442      ){
129443        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
129444        VdbeCoverage(v);
129445      }
129446      if( zEndAff ){
129447        updateRangeAffinityStr(pRight, nTop, zEndAff);
129448        codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
129449      }else{
129450        assert( pParse->db->mallocFailed );
129451      }
129452      nConstraint += nTop;
129453      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
129454
129455      if( sqlite3ExprIsVector(pRight)==0 ){
129456        disableTerm(pLevel, pRangeEnd);
129457      }else{
129458        endEq = 1;
129459      }
129460    }else if( bStopAtNull ){
129461      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
129462      endEq = 0;
129463      nConstraint++;
129464    }
129465    sqlite3DbFree(db, zStartAff);
129466    sqlite3DbFree(db, zEndAff);
129467
129468    /* Top of the loop body */
129469    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
129470
129471    /* Check if the index cursor is past the end of the range. */
129472    if( nConstraint ){
129473      op = aEndOp[bRev*2 + endEq];
129474      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
129475      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
129476      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
129477      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
129478      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
129479    }
129480
129481    /* Seek the table cursor, if required */
129482    if( omitTable ){
129483      /* pIdx is a covering index.  No need to access the main table. */
129484    }else if( HasRowid(pIdx->pTable) ){
129485      if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
129486          (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
129487       && (pWInfo->eOnePass==ONEPASS_SINGLE)
129488      )){
129489        iRowidReg = ++pParse->nMem;
129490        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
129491        sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
129492        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
129493        VdbeCoverage(v);
129494      }else{
129495        codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
129496      }
129497    }else if( iCur!=iIdxCur ){
129498      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
129499      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
129500      for(j=0; j<pPk->nKeyCol; j++){
129501        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
129502        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
129503      }
129504      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
129505                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
129506    }
129507
129508    /* If pIdx is an index on one or more expressions, then look through
129509    ** all the expressions in pWInfo and try to transform matching expressions
129510    ** into reference to index columns.
129511    */
129512    whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
129513
129514
129515    /* Record the instruction used to terminate the loop. */
129516    if( pLoop->wsFlags & WHERE_ONEROW ){
129517      pLevel->op = OP_Noop;
129518    }else if( bRev ){
129519      pLevel->op = OP_Prev;
129520    }else{
129521      pLevel->op = OP_Next;
129522    }
129523    pLevel->p1 = iIdxCur;
129524    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
129525    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
129526      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
129527    }else{
129528      assert( pLevel->p5==0 );
129529    }
129530    if( omitTable ) pIdx = 0;
129531  }else
129532
129533#ifndef SQLITE_OMIT_OR_OPTIMIZATION
129534  if( pLoop->wsFlags & WHERE_MULTI_OR ){
129535    /* Case 5:  Two or more separately indexed terms connected by OR
129536    **
129537    ** Example:
129538    **
129539    **   CREATE TABLE t1(a,b,c,d);
129540    **   CREATE INDEX i1 ON t1(a);
129541    **   CREATE INDEX i2 ON t1(b);
129542    **   CREATE INDEX i3 ON t1(c);
129543    **
129544    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
129545    **
129546    ** In the example, there are three indexed terms connected by OR.
129547    ** The top of the loop looks like this:
129548    **
129549    **          Null       1                # Zero the rowset in reg 1
129550    **
129551    ** Then, for each indexed term, the following. The arguments to
129552    ** RowSetTest are such that the rowid of the current row is inserted
129553    ** into the RowSet. If it is already present, control skips the
129554    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
129555    **
129556    **        sqlite3WhereBegin(<term>)
129557    **          RowSetTest                  # Insert rowid into rowset
129558    **          Gosub      2 A
129559    **        sqlite3WhereEnd()
129560    **
129561    ** Following the above, code to terminate the loop. Label A, the target
129562    ** of the Gosub above, jumps to the instruction right after the Goto.
129563    **
129564    **          Null       1                # Zero the rowset in reg 1
129565    **          Goto       B                # The loop is finished.
129566    **
129567    **       A: <loop body>                 # Return data, whatever.
129568    **
129569    **          Return     2                # Jump back to the Gosub
129570    **
129571    **       B: <after the loop>
129572    **
129573    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
129574    ** use an ephemeral index instead of a RowSet to record the primary
129575    ** keys of the rows we have already seen.
129576    **
129577    */
129578    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
129579    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
129580    Index *pCov = 0;             /* Potential covering index (or NULL) */
129581    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
129582
129583    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
129584    int regRowset = 0;                        /* Register for RowSet object */
129585    int regRowid = 0;                         /* Register holding rowid */
129586    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
129587    int iRetInit;                             /* Address of regReturn init */
129588    int untestedTerms = 0;             /* Some terms not completely tested */
129589    int ii;                            /* Loop counter */
129590    u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
129591    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
129592    Table *pTab = pTabItem->pTab;
129593
129594    pTerm = pLoop->aLTerm[0];
129595    assert( pTerm!=0 );
129596    assert( pTerm->eOperator & WO_OR );
129597    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
129598    pOrWc = &pTerm->u.pOrInfo->wc;
129599    pLevel->op = OP_Return;
129600    pLevel->p1 = regReturn;
129601
129602    /* Set up a new SrcList in pOrTab containing the table being scanned
129603    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
129604    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
129605    */
129606    if( pWInfo->nLevel>1 ){
129607      int nNotReady;                 /* The number of notReady tables */
129608      struct SrcList_item *origSrc;     /* Original list of tables */
129609      nNotReady = pWInfo->nLevel - iLevel - 1;
129610      pOrTab = sqlite3StackAllocRaw(db,
129611                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
129612      if( pOrTab==0 ) return notReady;
129613      pOrTab->nAlloc = (u8)(nNotReady + 1);
129614      pOrTab->nSrc = pOrTab->nAlloc;
129615      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
129616      origSrc = pWInfo->pTabList->a;
129617      for(k=1; k<=nNotReady; k++){
129618        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
129619      }
129620    }else{
129621      pOrTab = pWInfo->pTabList;
129622    }
129623
129624    /* Initialize the rowset register to contain NULL. An SQL NULL is
129625    ** equivalent to an empty rowset.  Or, create an ephemeral index
129626    ** capable of holding primary keys in the case of a WITHOUT ROWID.
129627    **
129628    ** Also initialize regReturn to contain the address of the instruction
129629    ** immediately following the OP_Return at the bottom of the loop. This
129630    ** is required in a few obscure LEFT JOIN cases where control jumps
129631    ** over the top of the loop into the body of it. In this case the
129632    ** correct response for the end-of-loop code (the OP_Return) is to
129633    ** fall through to the next instruction, just as an OP_Next does if
129634    ** called on an uninitialized cursor.
129635    */
129636    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
129637      if( HasRowid(pTab) ){
129638        regRowset = ++pParse->nMem;
129639        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
129640      }else{
129641        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
129642        regRowset = pParse->nTab++;
129643        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
129644        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
129645      }
129646      regRowid = ++pParse->nMem;
129647    }
129648    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
129649
129650    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
129651    ** Then for every term xN, evaluate as the subexpression: xN AND z
129652    ** That way, terms in y that are factored into the disjunction will
129653    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
129654    **
129655    ** Actually, each subexpression is converted to "xN AND w" where w is
129656    ** the "interesting" terms of z - terms that did not originate in the
129657    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
129658    ** indices.
129659    **
129660    ** This optimization also only applies if the (x1 OR x2 OR ...) term
129661    ** is not contained in the ON clause of a LEFT JOIN.
129662    ** See ticket http://www.sqlite.org/src/info/f2369304e4
129663    */
129664    if( pWC->nTerm>1 ){
129665      int iTerm;
129666      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
129667        Expr *pExpr = pWC->a[iTerm].pExpr;
129668        if( &pWC->a[iTerm] == pTerm ) continue;
129669        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
129670        testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
129671        testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
129672        if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
129673        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
129674        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
129675        pExpr = sqlite3ExprDup(db, pExpr, 0);
129676        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
129677      }
129678      if( pAndExpr ){
129679        pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
129680      }
129681    }
129682
129683    /* Run a separate WHERE clause for each term of the OR clause.  After
129684    ** eliminating duplicates from other WHERE clauses, the action for each
129685    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
129686    */
129687    wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
129688    for(ii=0; ii<pOrWc->nTerm; ii++){
129689      WhereTerm *pOrTerm = &pOrWc->a[ii];
129690      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
129691        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
129692        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
129693        int jmp1 = 0;                   /* Address of jump operation */
129694        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
129695          pAndExpr->pLeft = pOrExpr;
129696          pOrExpr = pAndExpr;
129697        }
129698        /* Loop through table entries that match term pOrTerm. */
129699        WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
129700        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
129701                                      wctrlFlags, iCovCur);
129702        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
129703        if( pSubWInfo ){
129704          WhereLoop *pSubLoop;
129705          int addrExplain = sqlite3WhereExplainOneScan(
129706              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
129707          );
129708          sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
129709
129710          /* This is the sub-WHERE clause body.  First skip over
129711          ** duplicate rows from prior sub-WHERE clauses, and record the
129712          ** rowid (or PRIMARY KEY) for the current row so that the same
129713          ** row will be skipped in subsequent sub-WHERE clauses.
129714          */
129715          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
129716            int r;
129717            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
129718            if( HasRowid(pTab) ){
129719              r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
129720              jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
129721                                           r,iSet);
129722              VdbeCoverage(v);
129723            }else{
129724              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
129725              int nPk = pPk->nKeyCol;
129726              int iPk;
129727
129728              /* Read the PK into an array of temp registers. */
129729              r = sqlite3GetTempRange(pParse, nPk);
129730              for(iPk=0; iPk<nPk; iPk++){
129731                int iCol = pPk->aiColumn[iPk];
129732                sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
129733              }
129734
129735              /* Check if the temp table already contains this key. If so,
129736              ** the row has already been included in the result set and
129737              ** can be ignored (by jumping past the Gosub below). Otherwise,
129738              ** insert the key into the temp table and proceed with processing
129739              ** the row.
129740              **
129741              ** Use some of the same optimizations as OP_RowSetTest: If iSet
129742              ** is zero, assume that the key cannot already be present in
129743              ** the temp table. And if iSet is -1, assume that there is no
129744              ** need to insert the key into the temp table, as it will never
129745              ** be tested for.  */
129746              if( iSet ){
129747                jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
129748                VdbeCoverage(v);
129749              }
129750              if( iSet>=0 ){
129751                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
129752                sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
129753                                     r, nPk);
129754                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
129755              }
129756
129757              /* Release the array of temp registers */
129758              sqlite3ReleaseTempRange(pParse, r, nPk);
129759            }
129760          }
129761
129762          /* Invoke the main loop body as a subroutine */
129763          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
129764
129765          /* Jump here (skipping the main loop body subroutine) if the
129766          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
129767          if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
129768
129769          /* The pSubWInfo->untestedTerms flag means that this OR term
129770          ** contained one or more AND term from a notReady table.  The
129771          ** terms from the notReady table could not be tested and will
129772          ** need to be tested later.
129773          */
129774          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
129775
129776          /* If all of the OR-connected terms are optimized using the same
129777          ** index, and the index is opened using the same cursor number
129778          ** by each call to sqlite3WhereBegin() made by this loop, it may
129779          ** be possible to use that index as a covering index.
129780          **
129781          ** If the call to sqlite3WhereBegin() above resulted in a scan that
129782          ** uses an index, and this is either the first OR-connected term
129783          ** processed or the index is the same as that used by all previous
129784          ** terms, set pCov to the candidate covering index. Otherwise, set
129785          ** pCov to NULL to indicate that no candidate covering index will
129786          ** be available.
129787          */
129788          pSubLoop = pSubWInfo->a[0].pWLoop;
129789          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
129790          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
129791           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
129792           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
129793          ){
129794            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
129795            pCov = pSubLoop->u.btree.pIndex;
129796          }else{
129797            pCov = 0;
129798          }
129799
129800          /* Finish the loop through table entries that match term pOrTerm. */
129801          sqlite3WhereEnd(pSubWInfo);
129802        }
129803      }
129804    }
129805    pLevel->u.pCovidx = pCov;
129806    if( pCov ) pLevel->iIdxCur = iCovCur;
129807    if( pAndExpr ){
129808      pAndExpr->pLeft = 0;
129809      sqlite3ExprDelete(db, pAndExpr);
129810    }
129811    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
129812    sqlite3VdbeGoto(v, pLevel->addrBrk);
129813    sqlite3VdbeResolveLabel(v, iLoopBody);
129814
129815    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
129816    if( !untestedTerms ) disableTerm(pLevel, pTerm);
129817  }else
129818#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
129819
129820  {
129821    /* Case 6:  There is no usable index.  We must do a complete
129822    **          scan of the entire table.
129823    */
129824    static const u8 aStep[] = { OP_Next, OP_Prev };
129825    static const u8 aStart[] = { OP_Rewind, OP_Last };
129826    assert( bRev==0 || bRev==1 );
129827    if( pTabItem->fg.isRecursive ){
129828      /* Tables marked isRecursive have only a single row that is stored in
129829      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
129830      pLevel->op = OP_Noop;
129831    }else{
129832      codeCursorHint(pTabItem, pWInfo, pLevel, 0);
129833      pLevel->op = aStep[bRev];
129834      pLevel->p1 = iCur;
129835      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
129836      VdbeCoverageIf(v, bRev==0);
129837      VdbeCoverageIf(v, bRev!=0);
129838      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
129839    }
129840  }
129841
129842#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
129843  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
129844#endif
129845
129846  /* Insert code to test every subexpression that can be completely
129847  ** computed using the current set of tables.
129848  **
129849  ** This loop may run between one and three times, depending on the
129850  ** constraints to be generated. The value of stack variable iLoop
129851  ** determines the constraints coded by each iteration, as follows:
129852  **
129853  ** iLoop==1: Code only expressions that are entirely covered by pIdx.
129854  ** iLoop==2: Code remaining expressions that do not contain correlated
129855  **           sub-queries.
129856  ** iLoop==3: Code all remaining expressions.
129857  **
129858  ** An effort is made to skip unnecessary iterations of the loop.
129859  */
129860  iLoop = (pIdx ? 1 : 2);
129861  do{
129862    int iNext = 0;                /* Next value for iLoop */
129863    for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
129864      Expr *pE;
129865      int skipLikeAddr = 0;
129866      testcase( pTerm->wtFlags & TERM_VIRTUAL );
129867      testcase( pTerm->wtFlags & TERM_CODED );
129868      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
129869      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
129870        testcase( pWInfo->untestedTerms==0
129871            && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
129872        pWInfo->untestedTerms = 1;
129873        continue;
129874      }
129875      pE = pTerm->pExpr;
129876      assert( pE!=0 );
129877      if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
129878        continue;
129879      }
129880
129881      if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
129882        iNext = 2;
129883        continue;
129884      }
129885      if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
129886        if( iNext==0 ) iNext = 3;
129887        continue;
129888      }
129889
129890      if( pTerm->wtFlags & TERM_LIKECOND ){
129891        /* If the TERM_LIKECOND flag is set, that means that the range search
129892        ** is sufficient to guarantee that the LIKE operator is true, so we
129893        ** can skip the call to the like(A,B) function.  But this only works
129894        ** for strings.  So do not skip the call to the function on the pass
129895        ** that compares BLOBs. */
129896#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
129897        continue;
129898#else
129899        u32 x = pLevel->iLikeRepCntr;
129900        assert( x>0 );
129901        skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1));
129902        VdbeCoverage(v);
129903#endif
129904      }
129905#ifdef WHERETRACE_ENABLED /* 0xffff */
129906      if( sqlite3WhereTrace ){
129907        VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
129908                         pWC->nTerm-j, pTerm, iLoop));
129909      }
129910#endif
129911      sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
129912      if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
129913      pTerm->wtFlags |= TERM_CODED;
129914    }
129915    iLoop = iNext;
129916  }while( iLoop>0 );
129917
129918  /* Insert code to test for implied constraints based on transitivity
129919  ** of the "==" operator.
129920  **
129921  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
129922  ** and we are coding the t1 loop and the t2 loop has not yet coded,
129923  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
129924  ** the implied "t1.a=123" constraint.
129925  */
129926  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
129927    Expr *pE, sEAlt;
129928    WhereTerm *pAlt;
129929    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
129930    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
129931    if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
129932    if( pTerm->leftCursor!=iCur ) continue;
129933    if( pLevel->iLeftJoin ) continue;
129934    pE = pTerm->pExpr;
129935    assert( !ExprHasProperty(pE, EP_FromJoin) );
129936    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
129937    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
129938                    WO_EQ|WO_IN|WO_IS, 0);
129939    if( pAlt==0 ) continue;
129940    if( pAlt->wtFlags & (TERM_CODED) ) continue;
129941    testcase( pAlt->eOperator & WO_EQ );
129942    testcase( pAlt->eOperator & WO_IS );
129943    testcase( pAlt->eOperator & WO_IN );
129944    VdbeModuleComment((v, "begin transitive constraint"));
129945    sEAlt = *pAlt->pExpr;
129946    sEAlt.pLeft = pE->pLeft;
129947    sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
129948  }
129949
129950  /* For a LEFT OUTER JOIN, generate code that will record the fact that
129951  ** at least one row of the right table has matched the left table.
129952  */
129953  if( pLevel->iLeftJoin ){
129954    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
129955    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
129956    VdbeComment((v, "record LEFT JOIN hit"));
129957    sqlite3ExprCacheClear(pParse);
129958    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
129959      testcase( pTerm->wtFlags & TERM_VIRTUAL );
129960      testcase( pTerm->wtFlags & TERM_CODED );
129961      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
129962      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
129963        assert( pWInfo->untestedTerms );
129964        continue;
129965      }
129966      assert( pTerm->pExpr );
129967      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
129968      pTerm->wtFlags |= TERM_CODED;
129969    }
129970  }
129971
129972  return pLevel->notReady;
129973}
129974
129975/************** End of wherecode.c *******************************************/
129976/************** Begin file whereexpr.c ***************************************/
129977/*
129978** 2015-06-08
129979**
129980** The author disclaims copyright to this source code.  In place of
129981** a legal notice, here is a blessing:
129982**
129983**    May you do good and not evil.
129984**    May you find forgiveness for yourself and forgive others.
129985**    May you share freely, never taking more than you give.
129986**
129987*************************************************************************
129988** This module contains C code that generates VDBE code used to process
129989** the WHERE clause of SQL statements.
129990**
129991** This file was originally part of where.c but was split out to improve
129992** readability and editabiliity.  This file contains utility routines for
129993** analyzing Expr objects in the WHERE clause.
129994*/
129995/* #include "sqliteInt.h" */
129996/* #include "whereInt.h" */
129997
129998/* Forward declarations */
129999static void exprAnalyze(SrcList*, WhereClause*, int);
130000
130001/*
130002** Deallocate all memory associated with a WhereOrInfo object.
130003*/
130004static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
130005  sqlite3WhereClauseClear(&p->wc);
130006  sqlite3DbFree(db, p);
130007}
130008
130009/*
130010** Deallocate all memory associated with a WhereAndInfo object.
130011*/
130012static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
130013  sqlite3WhereClauseClear(&p->wc);
130014  sqlite3DbFree(db, p);
130015}
130016
130017/*
130018** Add a single new WhereTerm entry to the WhereClause object pWC.
130019** The new WhereTerm object is constructed from Expr p and with wtFlags.
130020** The index in pWC->a[] of the new WhereTerm is returned on success.
130021** 0 is returned if the new WhereTerm could not be added due to a memory
130022** allocation error.  The memory allocation failure will be recorded in
130023** the db->mallocFailed flag so that higher-level functions can detect it.
130024**
130025** This routine will increase the size of the pWC->a[] array as necessary.
130026**
130027** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
130028** for freeing the expression p is assumed by the WhereClause object pWC.
130029** This is true even if this routine fails to allocate a new WhereTerm.
130030**
130031** WARNING:  This routine might reallocate the space used to store
130032** WhereTerms.  All pointers to WhereTerms should be invalidated after
130033** calling this routine.  Such pointers may be reinitialized by referencing
130034** the pWC->a[] array.
130035*/
130036static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
130037  WhereTerm *pTerm;
130038  int idx;
130039  testcase( wtFlags & TERM_VIRTUAL );
130040  if( pWC->nTerm>=pWC->nSlot ){
130041    WhereTerm *pOld = pWC->a;
130042    sqlite3 *db = pWC->pWInfo->pParse->db;
130043    pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
130044    if( pWC->a==0 ){
130045      if( wtFlags & TERM_DYNAMIC ){
130046        sqlite3ExprDelete(db, p);
130047      }
130048      pWC->a = pOld;
130049      return 0;
130050    }
130051    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
130052    if( pOld!=pWC->aStatic ){
130053      sqlite3DbFree(db, pOld);
130054    }
130055    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
130056  }
130057  pTerm = &pWC->a[idx = pWC->nTerm++];
130058  if( p && ExprHasProperty(p, EP_Unlikely) ){
130059    pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
130060  }else{
130061    pTerm->truthProb = 1;
130062  }
130063  pTerm->pExpr = sqlite3ExprSkipCollate(p);
130064  pTerm->wtFlags = wtFlags;
130065  pTerm->pWC = pWC;
130066  pTerm->iParent = -1;
130067  memset(&pTerm->eOperator, 0,
130068         sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
130069  return idx;
130070}
130071
130072/*
130073** Return TRUE if the given operator is one of the operators that is
130074** allowed for an indexable WHERE clause term.  The allowed operators are
130075** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
130076*/
130077static int allowedOp(int op){
130078  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
130079  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
130080  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
130081  assert( TK_GE==TK_EQ+4 );
130082  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
130083}
130084
130085/*
130086** Commute a comparison operator.  Expressions of the form "X op Y"
130087** are converted into "Y op X".
130088**
130089** If left/right precedence rules come into play when determining the
130090** collating sequence, then COLLATE operators are adjusted to ensure
130091** that the collating sequence does not change.  For example:
130092** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
130093** the left hand side of a comparison overrides any collation sequence
130094** attached to the right. For the same reason the EP_Collate flag
130095** is not commuted.
130096*/
130097static void exprCommute(Parse *pParse, Expr *pExpr){
130098  u16 expRight = (pExpr->pRight->flags & EP_Collate);
130099  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
130100  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
130101  if( expRight==expLeft ){
130102    /* Either X and Y both have COLLATE operator or neither do */
130103    if( expRight ){
130104      /* Both X and Y have COLLATE operators.  Make sure X is always
130105      ** used by clearing the EP_Collate flag from Y. */
130106      pExpr->pRight->flags &= ~EP_Collate;
130107    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
130108      /* Neither X nor Y have COLLATE operators, but X has a non-default
130109      ** collating sequence.  So add the EP_Collate marker on X to cause
130110      ** it to be searched first. */
130111      pExpr->pLeft->flags |= EP_Collate;
130112    }
130113  }
130114  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
130115  if( pExpr->op>=TK_GT ){
130116    assert( TK_LT==TK_GT+2 );
130117    assert( TK_GE==TK_LE+2 );
130118    assert( TK_GT>TK_EQ );
130119    assert( TK_GT<TK_LE );
130120    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
130121    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
130122  }
130123}
130124
130125/*
130126** Translate from TK_xx operator to WO_xx bitmask.
130127*/
130128static u16 operatorMask(int op){
130129  u16 c;
130130  assert( allowedOp(op) );
130131  if( op==TK_IN ){
130132    c = WO_IN;
130133  }else if( op==TK_ISNULL ){
130134    c = WO_ISNULL;
130135  }else if( op==TK_IS ){
130136    c = WO_IS;
130137  }else{
130138    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
130139    c = (u16)(WO_EQ<<(op-TK_EQ));
130140  }
130141  assert( op!=TK_ISNULL || c==WO_ISNULL );
130142  assert( op!=TK_IN || c==WO_IN );
130143  assert( op!=TK_EQ || c==WO_EQ );
130144  assert( op!=TK_LT || c==WO_LT );
130145  assert( op!=TK_LE || c==WO_LE );
130146  assert( op!=TK_GT || c==WO_GT );
130147  assert( op!=TK_GE || c==WO_GE );
130148  assert( op!=TK_IS || c==WO_IS );
130149  return c;
130150}
130151
130152
130153#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
130154/*
130155** Check to see if the given expression is a LIKE or GLOB operator that
130156** can be optimized using inequality constraints.  Return TRUE if it is
130157** so and false if not.
130158**
130159** In order for the operator to be optimizible, the RHS must be a string
130160** literal that does not begin with a wildcard.  The LHS must be a column
130161** that may only be NULL, a string, or a BLOB, never a number. (This means
130162** that virtual tables cannot participate in the LIKE optimization.)  The
130163** collating sequence for the column on the LHS must be appropriate for
130164** the operator.
130165*/
130166static int isLikeOrGlob(
130167  Parse *pParse,    /* Parsing and code generating context */
130168  Expr *pExpr,      /* Test this expression */
130169  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
130170  int *pisComplete, /* True if the only wildcard is % in the last character */
130171  int *pnoCase      /* True if uppercase is equivalent to lowercase */
130172){
130173  const char *z = 0;         /* String on RHS of LIKE operator */
130174  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
130175  ExprList *pList;           /* List of operands to the LIKE operator */
130176  int c;                     /* One character in z[] */
130177  int cnt;                   /* Number of non-wildcard prefix characters */
130178  char wc[3];                /* Wildcard characters */
130179  sqlite3 *db = pParse->db;  /* Database connection */
130180  sqlite3_value *pVal = 0;
130181  int op;                    /* Opcode of pRight */
130182  int rc;                    /* Result code to return */
130183
130184  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
130185    return 0;
130186  }
130187#ifdef SQLITE_EBCDIC
130188  if( *pnoCase ) return 0;
130189#endif
130190  pList = pExpr->x.pList;
130191  pLeft = pList->a[1].pExpr;
130192
130193  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
130194  op = pRight->op;
130195  if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
130196    Vdbe *pReprepare = pParse->pReprepare;
130197    int iCol = pRight->iColumn;
130198    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
130199    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
130200      z = (char *)sqlite3_value_text(pVal);
130201    }
130202    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
130203    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
130204  }else if( op==TK_STRING ){
130205    z = pRight->u.zToken;
130206  }
130207  if( z ){
130208
130209    /* If the RHS begins with a digit or a minus sign, then the LHS must
130210    ** be an ordinary column (not a virtual table column) with TEXT affinity.
130211    ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
130212    ** even though "lhs LIKE rhs" is true.  But if the RHS does not start
130213    ** with a digit or '-', then "lhs LIKE rhs" will always be false if
130214    ** the LHS is numeric and so the optimization still works.
130215    */
130216    if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
130217      if( pLeft->op!=TK_COLUMN
130218       || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
130219       || IsVirtual(pLeft->pTab)  /* Value might be numeric */
130220      ){
130221        sqlite3ValueFree(pVal);
130222        return 0;
130223      }
130224    }
130225    cnt = 0;
130226    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
130227      cnt++;
130228    }
130229    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
130230      Expr *pPrefix;
130231      *pisComplete = c==wc[0] && z[cnt+1]==0;
130232      pPrefix = sqlite3Expr(db, TK_STRING, z);
130233      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
130234      *ppPrefix = pPrefix;
130235      if( op==TK_VARIABLE ){
130236        Vdbe *v = pParse->pVdbe;
130237        sqlite3VdbeSetVarmask(v, pRight->iColumn);
130238        if( *pisComplete && pRight->u.zToken[1] ){
130239          /* If the rhs of the LIKE expression is a variable, and the current
130240          ** value of the variable means there is no need to invoke the LIKE
130241          ** function, then no OP_Variable will be added to the program.
130242          ** This causes problems for the sqlite3_bind_parameter_name()
130243          ** API. To work around them, add a dummy OP_Variable here.
130244          */
130245          int r1 = sqlite3GetTempReg(pParse);
130246          sqlite3ExprCodeTarget(pParse, pRight, r1);
130247          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
130248          sqlite3ReleaseTempReg(pParse, r1);
130249        }
130250      }
130251    }else{
130252      z = 0;
130253    }
130254  }
130255
130256  rc = (z!=0);
130257  sqlite3ValueFree(pVal);
130258  return rc;
130259}
130260#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
130261
130262
130263#ifndef SQLITE_OMIT_VIRTUALTABLE
130264/*
130265** Check to see if the given expression is of the form
130266**
130267**         column OP expr
130268**
130269** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
130270** column of a virtual table.
130271**
130272** If it is then return TRUE.  If not, return FALSE.
130273*/
130274static int isMatchOfColumn(
130275  Expr *pExpr,                    /* Test this expression */
130276  unsigned char *peOp2            /* OUT: 0 for MATCH, or else an op2 value */
130277){
130278  static const struct Op2 {
130279    const char *zOp;
130280    unsigned char eOp2;
130281  } aOp[] = {
130282    { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
130283    { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
130284    { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
130285    { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
130286  };
130287  ExprList *pList;
130288  Expr *pCol;                     /* Column reference */
130289  int i;
130290
130291  if( pExpr->op!=TK_FUNCTION ){
130292    return 0;
130293  }
130294  pList = pExpr->x.pList;
130295  if( pList==0 || pList->nExpr!=2 ){
130296    return 0;
130297  }
130298  pCol = pList->a[1].pExpr;
130299  if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
130300    return 0;
130301  }
130302  for(i=0; i<ArraySize(aOp); i++){
130303    if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
130304      *peOp2 = aOp[i].eOp2;
130305      return 1;
130306    }
130307  }
130308  return 0;
130309}
130310#endif /* SQLITE_OMIT_VIRTUALTABLE */
130311
130312/*
130313** If the pBase expression originated in the ON or USING clause of
130314** a join, then transfer the appropriate markings over to derived.
130315*/
130316static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
130317  if( pDerived ){
130318    pDerived->flags |= pBase->flags & EP_FromJoin;
130319    pDerived->iRightJoinTable = pBase->iRightJoinTable;
130320  }
130321}
130322
130323/*
130324** Mark term iChild as being a child of term iParent
130325*/
130326static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
130327  pWC->a[iChild].iParent = iParent;
130328  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
130329  pWC->a[iParent].nChild++;
130330}
130331
130332/*
130333** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
130334** a conjunction, then return just pTerm when N==0.  If N is exceeds
130335** the number of available subterms, return NULL.
130336*/
130337static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
130338  if( pTerm->eOperator!=WO_AND ){
130339    return N==0 ? pTerm : 0;
130340  }
130341  if( N<pTerm->u.pAndInfo->wc.nTerm ){
130342    return &pTerm->u.pAndInfo->wc.a[N];
130343  }
130344  return 0;
130345}
130346
130347/*
130348** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
130349** two subterms are in disjunction - they are OR-ed together.
130350**
130351** If these two terms are both of the form:  "A op B" with the same
130352** A and B values but different operators and if the operators are
130353** compatible (if one is = and the other is <, for example) then
130354** add a new virtual AND term to pWC that is the combination of the
130355** two.
130356**
130357** Some examples:
130358**
130359**    x<y OR x=y    -->     x<=y
130360**    x=y OR x=y    -->     x=y
130361**    x<=y OR x<y   -->     x<=y
130362**
130363** The following is NOT generated:
130364**
130365**    x<y OR x>y    -->     x!=y
130366*/
130367static void whereCombineDisjuncts(
130368  SrcList *pSrc,         /* the FROM clause */
130369  WhereClause *pWC,      /* The complete WHERE clause */
130370  WhereTerm *pOne,       /* First disjunct */
130371  WhereTerm *pTwo        /* Second disjunct */
130372){
130373  u16 eOp = pOne->eOperator | pTwo->eOperator;
130374  sqlite3 *db;           /* Database connection (for malloc) */
130375  Expr *pNew;            /* New virtual expression */
130376  int op;                /* Operator for the combined expression */
130377  int idxNew;            /* Index in pWC of the next virtual term */
130378
130379  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
130380  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
130381  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
130382   && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
130383  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
130384  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
130385  if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
130386  if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
130387  /* If we reach this point, it means the two subterms can be combined */
130388  if( (eOp & (eOp-1))!=0 ){
130389    if( eOp & (WO_LT|WO_LE) ){
130390      eOp = WO_LE;
130391    }else{
130392      assert( eOp & (WO_GT|WO_GE) );
130393      eOp = WO_GE;
130394    }
130395  }
130396  db = pWC->pWInfo->pParse->db;
130397  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
130398  if( pNew==0 ) return;
130399  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
130400  pNew->op = op;
130401  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
130402  exprAnalyze(pSrc, pWC, idxNew);
130403}
130404
130405#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
130406/*
130407** Analyze a term that consists of two or more OR-connected
130408** subterms.  So in:
130409**
130410**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
130411**                          ^^^^^^^^^^^^^^^^^^^^
130412**
130413** This routine analyzes terms such as the middle term in the above example.
130414** A WhereOrTerm object is computed and attached to the term under
130415** analysis, regardless of the outcome of the analysis.  Hence:
130416**
130417**     WhereTerm.wtFlags   |=  TERM_ORINFO
130418**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
130419**
130420** The term being analyzed must have two or more of OR-connected subterms.
130421** A single subterm might be a set of AND-connected sub-subterms.
130422** Examples of terms under analysis:
130423**
130424**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
130425**     (B)     x=expr1 OR expr2=x OR x=expr3
130426**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
130427**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
130428**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
130429**     (F)     x>A OR (x=A AND y>=B)
130430**
130431** CASE 1:
130432**
130433** If all subterms are of the form T.C=expr for some single column of C and
130434** a single table T (as shown in example B above) then create a new virtual
130435** term that is an equivalent IN expression.  In other words, if the term
130436** being analyzed is:
130437**
130438**      x = expr1  OR  expr2 = x  OR  x = expr3
130439**
130440** then create a new virtual term like this:
130441**
130442**      x IN (expr1,expr2,expr3)
130443**
130444** CASE 2:
130445**
130446** If there are exactly two disjuncts and one side has x>A and the other side
130447** has x=A (for the same x and A) then add a new virtual conjunct term to the
130448** WHERE clause of the form "x>=A".  Example:
130449**
130450**      x>A OR (x=A AND y>B)    adds:    x>=A
130451**
130452** The added conjunct can sometimes be helpful in query planning.
130453**
130454** CASE 3:
130455**
130456** If all subterms are indexable by a single table T, then set
130457**
130458**     WhereTerm.eOperator              =  WO_OR
130459**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
130460**
130461** A subterm is "indexable" if it is of the form
130462** "T.C <op> <expr>" where C is any column of table T and
130463** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
130464** A subterm is also indexable if it is an AND of two or more
130465** subsubterms at least one of which is indexable.  Indexable AND
130466** subterms have their eOperator set to WO_AND and they have
130467** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
130468**
130469** From another point of view, "indexable" means that the subterm could
130470** potentially be used with an index if an appropriate index exists.
130471** This analysis does not consider whether or not the index exists; that
130472** is decided elsewhere.  This analysis only looks at whether subterms
130473** appropriate for indexing exist.
130474**
130475** All examples A through E above satisfy case 3.  But if a term
130476** also satisfies case 1 (such as B) we know that the optimizer will
130477** always prefer case 1, so in that case we pretend that case 3 is not
130478** satisfied.
130479**
130480** It might be the case that multiple tables are indexable.  For example,
130481** (E) above is indexable on tables P, Q, and R.
130482**
130483** Terms that satisfy case 3 are candidates for lookup by using
130484** separate indices to find rowids for each subterm and composing
130485** the union of all rowids using a RowSet object.  This is similar
130486** to "bitmap indices" in other database engines.
130487**
130488** OTHERWISE:
130489**
130490** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
130491** zero.  This term is not useful for search.
130492*/
130493static void exprAnalyzeOrTerm(
130494  SrcList *pSrc,            /* the FROM clause */
130495  WhereClause *pWC,         /* the complete WHERE clause */
130496  int idxTerm               /* Index of the OR-term to be analyzed */
130497){
130498  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
130499  Parse *pParse = pWInfo->pParse;         /* Parser context */
130500  sqlite3 *db = pParse->db;               /* Database connection */
130501  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
130502  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
130503  int i;                                  /* Loop counters */
130504  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
130505  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
130506  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
130507  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
130508  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
130509
130510  /*
130511  ** Break the OR clause into its separate subterms.  The subterms are
130512  ** stored in a WhereClause structure containing within the WhereOrInfo
130513  ** object that is attached to the original OR clause term.
130514  */
130515  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
130516  assert( pExpr->op==TK_OR );
130517  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
130518  if( pOrInfo==0 ) return;
130519  pTerm->wtFlags |= TERM_ORINFO;
130520  pOrWc = &pOrInfo->wc;
130521  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
130522  sqlite3WhereClauseInit(pOrWc, pWInfo);
130523  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
130524  sqlite3WhereExprAnalyze(pSrc, pOrWc);
130525  if( db->mallocFailed ) return;
130526  assert( pOrWc->nTerm>=2 );
130527
130528  /*
130529  ** Compute the set of tables that might satisfy cases 1 or 3.
130530  */
130531  indexable = ~(Bitmask)0;
130532  chngToIN = ~(Bitmask)0;
130533  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
130534    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
130535      WhereAndInfo *pAndInfo;
130536      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
130537      chngToIN = 0;
130538      pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
130539      if( pAndInfo ){
130540        WhereClause *pAndWC;
130541        WhereTerm *pAndTerm;
130542        int j;
130543        Bitmask b = 0;
130544        pOrTerm->u.pAndInfo = pAndInfo;
130545        pOrTerm->wtFlags |= TERM_ANDINFO;
130546        pOrTerm->eOperator = WO_AND;
130547        pAndWC = &pAndInfo->wc;
130548        memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
130549        sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
130550        sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
130551        sqlite3WhereExprAnalyze(pSrc, pAndWC);
130552        pAndWC->pOuter = pWC;
130553        if( !db->mallocFailed ){
130554          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
130555            assert( pAndTerm->pExpr );
130556            if( allowedOp(pAndTerm->pExpr->op)
130557             || pAndTerm->eOperator==WO_MATCH
130558            ){
130559              b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
130560            }
130561          }
130562        }
130563        indexable &= b;
130564      }
130565    }else if( pOrTerm->wtFlags & TERM_COPIED ){
130566      /* Skip this term for now.  We revisit it when we process the
130567      ** corresponding TERM_VIRTUAL term */
130568    }else{
130569      Bitmask b;
130570      b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
130571      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
130572        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
130573        b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
130574      }
130575      indexable &= b;
130576      if( (pOrTerm->eOperator & WO_EQ)==0 ){
130577        chngToIN = 0;
130578      }else{
130579        chngToIN &= b;
130580      }
130581    }
130582  }
130583
130584  /*
130585  ** Record the set of tables that satisfy case 3.  The set might be
130586  ** empty.
130587  */
130588  pOrInfo->indexable = indexable;
130589  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
130590
130591  /* For a two-way OR, attempt to implementation case 2.
130592  */
130593  if( indexable && pOrWc->nTerm==2 ){
130594    int iOne = 0;
130595    WhereTerm *pOne;
130596    while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
130597      int iTwo = 0;
130598      WhereTerm *pTwo;
130599      while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
130600        whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
130601      }
130602    }
130603  }
130604
130605  /*
130606  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
130607  ** we have to do some additional checking to see if case 1 really
130608  ** is satisfied.
130609  **
130610  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
130611  ** that there is no possibility of transforming the OR clause into an
130612  ** IN operator because one or more terms in the OR clause contain
130613  ** something other than == on a column in the single table.  The 1-bit
130614  ** case means that every term of the OR clause is of the form
130615  ** "table.column=expr" for some single table.  The one bit that is set
130616  ** will correspond to the common table.  We still need to check to make
130617  ** sure the same column is used on all terms.  The 2-bit case is when
130618  ** the all terms are of the form "table1.column=table2.column".  It
130619  ** might be possible to form an IN operator with either table1.column
130620  ** or table2.column as the LHS if either is common to every term of
130621  ** the OR clause.
130622  **
130623  ** Note that terms of the form "table.column1=table.column2" (the
130624  ** same table on both sizes of the ==) cannot be optimized.
130625  */
130626  if( chngToIN ){
130627    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
130628    int iColumn = -1;         /* Column index on lhs of IN operator */
130629    int iCursor = -1;         /* Table cursor common to all terms */
130630    int j = 0;                /* Loop counter */
130631
130632    /* Search for a table and column that appears on one side or the
130633    ** other of the == operator in every subterm.  That table and column
130634    ** will be recorded in iCursor and iColumn.  There might not be any
130635    ** such table and column.  Set okToChngToIN if an appropriate table
130636    ** and column is found but leave okToChngToIN false if not found.
130637    */
130638    for(j=0; j<2 && !okToChngToIN; j++){
130639      pOrTerm = pOrWc->a;
130640      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
130641        assert( pOrTerm->eOperator & WO_EQ );
130642        pOrTerm->wtFlags &= ~TERM_OR_OK;
130643        if( pOrTerm->leftCursor==iCursor ){
130644          /* This is the 2-bit case and we are on the second iteration and
130645          ** current term is from the first iteration.  So skip this term. */
130646          assert( j==1 );
130647          continue;
130648        }
130649        if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
130650                                            pOrTerm->leftCursor))==0 ){
130651          /* This term must be of the form t1.a==t2.b where t2 is in the
130652          ** chngToIN set but t1 is not.  This term will be either preceded
130653          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
130654          ** and use its inversion. */
130655          testcase( pOrTerm->wtFlags & TERM_COPIED );
130656          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
130657          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
130658          continue;
130659        }
130660        iColumn = pOrTerm->u.leftColumn;
130661        iCursor = pOrTerm->leftCursor;
130662        break;
130663      }
130664      if( i<0 ){
130665        /* No candidate table+column was found.  This can only occur
130666        ** on the second iteration */
130667        assert( j==1 );
130668        assert( IsPowerOfTwo(chngToIN) );
130669        assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
130670        break;
130671      }
130672      testcase( j==1 );
130673
130674      /* We have found a candidate table and column.  Check to see if that
130675      ** table and column is common to every term in the OR clause */
130676      okToChngToIN = 1;
130677      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
130678        assert( pOrTerm->eOperator & WO_EQ );
130679        if( pOrTerm->leftCursor!=iCursor ){
130680          pOrTerm->wtFlags &= ~TERM_OR_OK;
130681        }else if( pOrTerm->u.leftColumn!=iColumn ){
130682          okToChngToIN = 0;
130683        }else{
130684          int affLeft, affRight;
130685          /* If the right-hand side is also a column, then the affinities
130686          ** of both right and left sides must be such that no type
130687          ** conversions are required on the right.  (Ticket #2249)
130688          */
130689          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
130690          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
130691          if( affRight!=0 && affRight!=affLeft ){
130692            okToChngToIN = 0;
130693          }else{
130694            pOrTerm->wtFlags |= TERM_OR_OK;
130695          }
130696        }
130697      }
130698    }
130699
130700    /* At this point, okToChngToIN is true if original pTerm satisfies
130701    ** case 1.  In that case, construct a new virtual term that is
130702    ** pTerm converted into an IN operator.
130703    */
130704    if( okToChngToIN ){
130705      Expr *pDup;            /* A transient duplicate expression */
130706      ExprList *pList = 0;   /* The RHS of the IN operator */
130707      Expr *pLeft = 0;       /* The LHS of the IN operator */
130708      Expr *pNew;            /* The complete IN operator */
130709
130710      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
130711        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
130712        assert( pOrTerm->eOperator & WO_EQ );
130713        assert( pOrTerm->leftCursor==iCursor );
130714        assert( pOrTerm->u.leftColumn==iColumn );
130715        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
130716        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
130717        pLeft = pOrTerm->pExpr->pLeft;
130718      }
130719      assert( pLeft!=0 );
130720      pDup = sqlite3ExprDup(db, pLeft, 0);
130721      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
130722      if( pNew ){
130723        int idxNew;
130724        transferJoinMarkings(pNew, pExpr);
130725        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
130726        pNew->x.pList = pList;
130727        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
130728        testcase( idxNew==0 );
130729        exprAnalyze(pSrc, pWC, idxNew);
130730        pTerm = &pWC->a[idxTerm];
130731        markTermAsChild(pWC, idxNew, idxTerm);
130732      }else{
130733        sqlite3ExprListDelete(db, pList);
130734      }
130735      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
130736    }
130737  }
130738}
130739#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
130740
130741/*
130742** We already know that pExpr is a binary operator where both operands are
130743** column references.  This routine checks to see if pExpr is an equivalence
130744** relation:
130745**   1.  The SQLITE_Transitive optimization must be enabled
130746**   2.  Must be either an == or an IS operator
130747**   3.  Not originating in the ON clause of an OUTER JOIN
130748**   4.  The affinities of A and B must be compatible
130749**   5a. Both operands use the same collating sequence OR
130750**   5b. The overall collating sequence is BINARY
130751** If this routine returns TRUE, that means that the RHS can be substituted
130752** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
130753** This is an optimization.  No harm comes from returning 0.  But if 1 is
130754** returned when it should not be, then incorrect answers might result.
130755*/
130756static int termIsEquivalence(Parse *pParse, Expr *pExpr){
130757  char aff1, aff2;
130758  CollSeq *pColl;
130759  const char *zColl1, *zColl2;
130760  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
130761  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
130762  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
130763  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
130764  aff2 = sqlite3ExprAffinity(pExpr->pRight);
130765  if( aff1!=aff2
130766   && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
130767  ){
130768    return 0;
130769  }
130770  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
130771  if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
130772  pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
130773  zColl1 = pColl ? pColl->zName : 0;
130774  pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
130775  zColl2 = pColl ? pColl->zName : 0;
130776  return sqlite3_stricmp(zColl1, zColl2)==0;
130777}
130778
130779/*
130780** Recursively walk the expressions of a SELECT statement and generate
130781** a bitmask indicating which tables are used in that expression
130782** tree.
130783*/
130784static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
130785  Bitmask mask = 0;
130786  while( pS ){
130787    SrcList *pSrc = pS->pSrc;
130788    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
130789    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
130790    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
130791    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
130792    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
130793    if( ALWAYS(pSrc!=0) ){
130794      int i;
130795      for(i=0; i<pSrc->nSrc; i++){
130796        mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
130797        mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
130798      }
130799    }
130800    pS = pS->pPrior;
130801  }
130802  return mask;
130803}
130804
130805/*
130806** Expression pExpr is one operand of a comparison operator that might
130807** be useful for indexing.  This routine checks to see if pExpr appears
130808** in any index.  Return TRUE (1) if pExpr is an indexed term and return
130809** FALSE (0) if not.  If TRUE is returned, also set aiCurCol[0] to the cursor
130810** number of the table that is indexed and aiCurCol[1] to the column number
130811** of the column that is indexed, or XN_EXPR (-2) if an expression is being
130812** indexed.
130813**
130814** If pExpr is a TK_COLUMN column reference, then this routine always returns
130815** true even if that particular column is not indexed, because the column
130816** might be added to an automatic index later.
130817*/
130818static SQLITE_NOINLINE int exprMightBeIndexed2(
130819  SrcList *pFrom,        /* The FROM clause */
130820  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
130821  int *aiCurCol,         /* Write the referenced table cursor and column here */
130822  Expr *pExpr            /* An operand of a comparison operator */
130823){
130824  Index *pIdx;
130825  int i;
130826  int iCur;
130827  for(i=0; mPrereq>1; i++, mPrereq>>=1){}
130828  iCur = pFrom->a[i].iCursor;
130829  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
130830    if( pIdx->aColExpr==0 ) continue;
130831    for(i=0; i<pIdx->nKeyCol; i++){
130832      if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
130833      if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
130834        aiCurCol[0] = iCur;
130835        aiCurCol[1] = XN_EXPR;
130836        return 1;
130837      }
130838    }
130839  }
130840  return 0;
130841}
130842static int exprMightBeIndexed(
130843  SrcList *pFrom,        /* The FROM clause */
130844  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
130845  int *aiCurCol,         /* Write the referenced table cursor & column here */
130846  Expr *pExpr,           /* An operand of a comparison operator */
130847  int op                 /* The specific comparison operator */
130848){
130849  /* If this expression is a vector to the left or right of a
130850  ** inequality constraint (>, <, >= or <=), perform the processing
130851  ** on the first element of the vector.  */
130852  assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
130853  assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
130854  assert( op<=TK_GE );
130855  if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
130856    pExpr = pExpr->x.pList->a[0].pExpr;
130857  }
130858
130859  if( pExpr->op==TK_COLUMN ){
130860    aiCurCol[0] = pExpr->iTable;
130861    aiCurCol[1] = pExpr->iColumn;
130862    return 1;
130863  }
130864  if( mPrereq==0 ) return 0;                 /* No table references */
130865  if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
130866  return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
130867}
130868
130869/*
130870** The input to this routine is an WhereTerm structure with only the
130871** "pExpr" field filled in.  The job of this routine is to analyze the
130872** subexpression and populate all the other fields of the WhereTerm
130873** structure.
130874**
130875** If the expression is of the form "<expr> <op> X" it gets commuted
130876** to the standard form of "X <op> <expr>".
130877**
130878** If the expression is of the form "X <op> Y" where both X and Y are
130879** columns, then the original expression is unchanged and a new virtual
130880** term of the form "Y <op> X" is added to the WHERE clause and
130881** analyzed separately.  The original term is marked with TERM_COPIED
130882** and the new term is marked with TERM_DYNAMIC (because it's pExpr
130883** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
130884** is a commuted copy of a prior term.)  The original term has nChild=1
130885** and the copy has idxParent set to the index of the original term.
130886*/
130887static void exprAnalyze(
130888  SrcList *pSrc,            /* the FROM clause */
130889  WhereClause *pWC,         /* the WHERE clause */
130890  int idxTerm               /* Index of the term to be analyzed */
130891){
130892  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
130893  WhereTerm *pTerm;                /* The term to be analyzed */
130894  WhereMaskSet *pMaskSet;          /* Set of table index masks */
130895  Expr *pExpr;                     /* The expression to be analyzed */
130896  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
130897  Bitmask prereqAll;               /* Prerequesites of pExpr */
130898  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
130899  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
130900  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
130901  int noCase = 0;                  /* uppercase equivalent to lowercase */
130902  int op;                          /* Top-level operator.  pExpr->op */
130903  Parse *pParse = pWInfo->pParse;  /* Parsing context */
130904  sqlite3 *db = pParse->db;        /* Database connection */
130905  unsigned char eOp2;              /* op2 value for LIKE/REGEXP/GLOB */
130906  int nLeft;                       /* Number of elements on left side vector */
130907
130908  if( db->mallocFailed ){
130909    return;
130910  }
130911  pTerm = &pWC->a[idxTerm];
130912  pMaskSet = &pWInfo->sMaskSet;
130913  pExpr = pTerm->pExpr;
130914  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
130915  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
130916  op = pExpr->op;
130917  if( op==TK_IN ){
130918    assert( pExpr->pRight==0 );
130919    if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
130920    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
130921      pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
130922    }else{
130923      pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
130924    }
130925  }else if( op==TK_ISNULL ){
130926    pTerm->prereqRight = 0;
130927  }else{
130928    pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
130929  }
130930  pMaskSet->bVarSelect = 0;
130931  prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
130932  if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
130933  if( ExprHasProperty(pExpr, EP_FromJoin) ){
130934    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
130935    prereqAll |= x;
130936    extraRight = x-1;  /* ON clause terms may not be used with an index
130937                       ** on left table of a LEFT JOIN.  Ticket #3015 */
130938    if( (prereqAll>>1)>=x ){
130939      sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
130940      return;
130941    }
130942  }
130943  pTerm->prereqAll = prereqAll;
130944  pTerm->leftCursor = -1;
130945  pTerm->iParent = -1;
130946  pTerm->eOperator = 0;
130947  if( allowedOp(op) ){
130948    int aiCurCol[2];
130949    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
130950    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
130951    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
130952
130953    if( pTerm->iField>0 ){
130954      assert( op==TK_IN );
130955      assert( pLeft->op==TK_VECTOR );
130956      pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
130957    }
130958
130959    if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
130960      pTerm->leftCursor = aiCurCol[0];
130961      pTerm->u.leftColumn = aiCurCol[1];
130962      pTerm->eOperator = operatorMask(op) & opMask;
130963    }
130964    if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
130965    if( pRight
130966     && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
130967    ){
130968      WhereTerm *pNew;
130969      Expr *pDup;
130970      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
130971      assert( pTerm->iField==0 );
130972      if( pTerm->leftCursor>=0 ){
130973        int idxNew;
130974        pDup = sqlite3ExprDup(db, pExpr, 0);
130975        if( db->mallocFailed ){
130976          sqlite3ExprDelete(db, pDup);
130977          return;
130978        }
130979        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
130980        if( idxNew==0 ) return;
130981        pNew = &pWC->a[idxNew];
130982        markTermAsChild(pWC, idxNew, idxTerm);
130983        if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
130984        pTerm = &pWC->a[idxTerm];
130985        pTerm->wtFlags |= TERM_COPIED;
130986
130987        if( termIsEquivalence(pParse, pDup) ){
130988          pTerm->eOperator |= WO_EQUIV;
130989          eExtraOp = WO_EQUIV;
130990        }
130991      }else{
130992        pDup = pExpr;
130993        pNew = pTerm;
130994      }
130995      exprCommute(pParse, pDup);
130996      pNew->leftCursor = aiCurCol[0];
130997      pNew->u.leftColumn = aiCurCol[1];
130998      testcase( (prereqLeft | extraRight) != prereqLeft );
130999      pNew->prereqRight = prereqLeft | extraRight;
131000      pNew->prereqAll = prereqAll;
131001      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
131002    }
131003  }
131004
131005#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
131006  /* If a term is the BETWEEN operator, create two new virtual terms
131007  ** that define the range that the BETWEEN implements.  For example:
131008  **
131009  **      a BETWEEN b AND c
131010  **
131011  ** is converted into:
131012  **
131013  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
131014  **
131015  ** The two new terms are added onto the end of the WhereClause object.
131016  ** The new terms are "dynamic" and are children of the original BETWEEN
131017  ** term.  That means that if the BETWEEN term is coded, the children are
131018  ** skipped.  Or, if the children are satisfied by an index, the original
131019  ** BETWEEN term is skipped.
131020  */
131021  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
131022    ExprList *pList = pExpr->x.pList;
131023    int i;
131024    static const u8 ops[] = {TK_GE, TK_LE};
131025    assert( pList!=0 );
131026    assert( pList->nExpr==2 );
131027    for(i=0; i<2; i++){
131028      Expr *pNewExpr;
131029      int idxNew;
131030      pNewExpr = sqlite3PExpr(pParse, ops[i],
131031                             sqlite3ExprDup(db, pExpr->pLeft, 0),
131032                             sqlite3ExprDup(db, pList->a[i].pExpr, 0));
131033      transferJoinMarkings(pNewExpr, pExpr);
131034      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
131035      testcase( idxNew==0 );
131036      exprAnalyze(pSrc, pWC, idxNew);
131037      pTerm = &pWC->a[idxTerm];
131038      markTermAsChild(pWC, idxNew, idxTerm);
131039    }
131040  }
131041#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
131042
131043#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
131044  /* Analyze a term that is composed of two or more subterms connected by
131045  ** an OR operator.
131046  */
131047  else if( pExpr->op==TK_OR ){
131048    assert( pWC->op==TK_AND );
131049    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
131050    pTerm = &pWC->a[idxTerm];
131051  }
131052#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
131053
131054#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
131055  /* Add constraints to reduce the search space on a LIKE or GLOB
131056  ** operator.
131057  **
131058  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
131059  **
131060  **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
131061  **
131062  ** The last character of the prefix "abc" is incremented to form the
131063  ** termination condition "abd".  If case is not significant (the default
131064  ** for LIKE) then the lower-bound is made all uppercase and the upper-
131065  ** bound is made all lowercase so that the bounds also work when comparing
131066  ** BLOBs.
131067  */
131068  if( pWC->op==TK_AND
131069   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
131070  ){
131071    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
131072    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
131073    Expr *pNewExpr1;
131074    Expr *pNewExpr2;
131075    int idxNew1;
131076    int idxNew2;
131077    const char *zCollSeqName;     /* Name of collating sequence */
131078    const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
131079
131080    pLeft = pExpr->x.pList->a[1].pExpr;
131081    pStr2 = sqlite3ExprDup(db, pStr1, 0);
131082
131083    /* Convert the lower bound to upper-case and the upper bound to
131084    ** lower-case (upper-case is less than lower-case in ASCII) so that
131085    ** the range constraints also work for BLOBs
131086    */
131087    if( noCase && !pParse->db->mallocFailed ){
131088      int i;
131089      char c;
131090      pTerm->wtFlags |= TERM_LIKE;
131091      for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
131092        pStr1->u.zToken[i] = sqlite3Toupper(c);
131093        pStr2->u.zToken[i] = sqlite3Tolower(c);
131094      }
131095    }
131096
131097    if( !db->mallocFailed ){
131098      u8 c, *pC;       /* Last character before the first wildcard */
131099      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
131100      c = *pC;
131101      if( noCase ){
131102        /* The point is to increment the last character before the first
131103        ** wildcard.  But if we increment '@', that will push it into the
131104        ** alphabetic range where case conversions will mess up the
131105        ** inequality.  To avoid this, make sure to also run the full
131106        ** LIKE on all candidate expressions by clearing the isComplete flag
131107        */
131108        if( c=='A'-1 ) isComplete = 0;
131109        c = sqlite3UpperToLower[c];
131110      }
131111      *pC = c + 1;
131112    }
131113    zCollSeqName = noCase ? "NOCASE" : "BINARY";
131114    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
131115    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
131116           sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
131117           pStr1);
131118    transferJoinMarkings(pNewExpr1, pExpr);
131119    idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
131120    testcase( idxNew1==0 );
131121    exprAnalyze(pSrc, pWC, idxNew1);
131122    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
131123    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
131124           sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
131125           pStr2);
131126    transferJoinMarkings(pNewExpr2, pExpr);
131127    idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
131128    testcase( idxNew2==0 );
131129    exprAnalyze(pSrc, pWC, idxNew2);
131130    pTerm = &pWC->a[idxTerm];
131131    if( isComplete ){
131132      markTermAsChild(pWC, idxNew1, idxTerm);
131133      markTermAsChild(pWC, idxNew2, idxTerm);
131134    }
131135  }
131136#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
131137
131138#ifndef SQLITE_OMIT_VIRTUALTABLE
131139  /* Add a WO_MATCH auxiliary term to the constraint set if the
131140  ** current expression is of the form:  column MATCH expr.
131141  ** This information is used by the xBestIndex methods of
131142  ** virtual tables.  The native query optimizer does not attempt
131143  ** to do anything with MATCH functions.
131144  */
131145  if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
131146    int idxNew;
131147    Expr *pRight, *pLeft;
131148    WhereTerm *pNewTerm;
131149    Bitmask prereqColumn, prereqExpr;
131150
131151    pRight = pExpr->x.pList->a[0].pExpr;
131152    pLeft = pExpr->x.pList->a[1].pExpr;
131153    prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
131154    prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
131155    if( (prereqExpr & prereqColumn)==0 ){
131156      Expr *pNewExpr;
131157      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
131158                              0, sqlite3ExprDup(db, pRight, 0));
131159      if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
131160        ExprSetProperty(pNewExpr, EP_FromJoin);
131161      }
131162      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
131163      testcase( idxNew==0 );
131164      pNewTerm = &pWC->a[idxNew];
131165      pNewTerm->prereqRight = prereqExpr;
131166      pNewTerm->leftCursor = pLeft->iTable;
131167      pNewTerm->u.leftColumn = pLeft->iColumn;
131168      pNewTerm->eOperator = WO_MATCH;
131169      pNewTerm->eMatchOp = eOp2;
131170      markTermAsChild(pWC, idxNew, idxTerm);
131171      pTerm = &pWC->a[idxTerm];
131172      pTerm->wtFlags |= TERM_COPIED;
131173      pNewTerm->prereqAll = pTerm->prereqAll;
131174    }
131175  }
131176#endif /* SQLITE_OMIT_VIRTUALTABLE */
131177
131178  /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
131179  ** new terms for each component comparison - "a = ?" and "b = ?".  The
131180  ** new terms completely replace the original vector comparison, which is
131181  ** no longer used.
131182  **
131183  ** This is only required if at least one side of the comparison operation
131184  ** is not a sub-select.  */
131185  if( pWC->op==TK_AND
131186  && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
131187  && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
131188  && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
131189  && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
131190    || (pExpr->pRight->flags & EP_xIsSelect)==0)
131191  ){
131192    int i;
131193    for(i=0; i<nLeft; i++){
131194      int idxNew;
131195      Expr *pNew;
131196      Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
131197      Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
131198
131199      pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
131200      transferJoinMarkings(pNew, pExpr);
131201      idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
131202      exprAnalyze(pSrc, pWC, idxNew);
131203    }
131204    pTerm = &pWC->a[idxTerm];
131205    pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
131206    pTerm->eOperator = 0;
131207  }
131208
131209  /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
131210  ** a virtual term for each vector component. The expression object
131211  ** used by each such virtual term is pExpr (the full vector IN(...)
131212  ** expression). The WhereTerm.iField variable identifies the index within
131213  ** the vector on the LHS that the virtual term represents.
131214  **
131215  ** This only works if the RHS is a simple SELECT, not a compound
131216  */
131217  if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
131218   && pExpr->pLeft->op==TK_VECTOR
131219   && pExpr->x.pSelect->pPrior==0
131220  ){
131221    int i;
131222    for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
131223      int idxNew;
131224      idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
131225      pWC->a[idxNew].iField = i+1;
131226      exprAnalyze(pSrc, pWC, idxNew);
131227      markTermAsChild(pWC, idxNew, idxTerm);
131228    }
131229  }
131230
131231#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
131232  /* When sqlite_stat3 histogram data is available an operator of the
131233  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
131234  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
131235  ** virtual term of that form.
131236  **
131237  ** Note that the virtual term must be tagged with TERM_VNULL.
131238  */
131239  if( pExpr->op==TK_NOTNULL
131240   && pExpr->pLeft->op==TK_COLUMN
131241   && pExpr->pLeft->iColumn>=0
131242   && OptimizationEnabled(db, SQLITE_Stat34)
131243  ){
131244    Expr *pNewExpr;
131245    Expr *pLeft = pExpr->pLeft;
131246    int idxNew;
131247    WhereTerm *pNewTerm;
131248
131249    pNewExpr = sqlite3PExpr(pParse, TK_GT,
131250                            sqlite3ExprDup(db, pLeft, 0),
131251                            sqlite3ExprAlloc(db, TK_NULL, 0, 0));
131252
131253    idxNew = whereClauseInsert(pWC, pNewExpr,
131254                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
131255    if( idxNew ){
131256      pNewTerm = &pWC->a[idxNew];
131257      pNewTerm->prereqRight = 0;
131258      pNewTerm->leftCursor = pLeft->iTable;
131259      pNewTerm->u.leftColumn = pLeft->iColumn;
131260      pNewTerm->eOperator = WO_GT;
131261      markTermAsChild(pWC, idxNew, idxTerm);
131262      pTerm = &pWC->a[idxTerm];
131263      pTerm->wtFlags |= TERM_COPIED;
131264      pNewTerm->prereqAll = pTerm->prereqAll;
131265    }
131266  }
131267#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
131268
131269  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
131270  ** an index for tables to the left of the join.
131271  */
131272  testcase( pTerm!=&pWC->a[idxTerm] );
131273  pTerm = &pWC->a[idxTerm];
131274  pTerm->prereqRight |= extraRight;
131275}
131276
131277/***************************************************************************
131278** Routines with file scope above.  Interface to the rest of the where.c
131279** subsystem follows.
131280***************************************************************************/
131281
131282/*
131283** This routine identifies subexpressions in the WHERE clause where
131284** each subexpression is separated by the AND operator or some other
131285** operator specified in the op parameter.  The WhereClause structure
131286** is filled with pointers to subexpressions.  For example:
131287**
131288**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
131289**           \________/     \_______________/     \________________/
131290**            slot[0]            slot[1]               slot[2]
131291**
131292** The original WHERE clause in pExpr is unaltered.  All this routine
131293** does is make slot[] entries point to substructure within pExpr.
131294**
131295** In the previous sentence and in the diagram, "slot[]" refers to
131296** the WhereClause.a[] array.  The slot[] array grows as needed to contain
131297** all terms of the WHERE clause.
131298*/
131299SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
131300  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
131301  pWC->op = op;
131302  if( pE2==0 ) return;
131303  if( pE2->op!=op ){
131304    whereClauseInsert(pWC, pExpr, 0);
131305  }else{
131306    sqlite3WhereSplit(pWC, pE2->pLeft, op);
131307    sqlite3WhereSplit(pWC, pE2->pRight, op);
131308  }
131309}
131310
131311/*
131312** Initialize a preallocated WhereClause structure.
131313*/
131314SQLITE_PRIVATE void sqlite3WhereClauseInit(
131315  WhereClause *pWC,        /* The WhereClause to be initialized */
131316  WhereInfo *pWInfo        /* The WHERE processing context */
131317){
131318  pWC->pWInfo = pWInfo;
131319  pWC->pOuter = 0;
131320  pWC->nTerm = 0;
131321  pWC->nSlot = ArraySize(pWC->aStatic);
131322  pWC->a = pWC->aStatic;
131323}
131324
131325/*
131326** Deallocate a WhereClause structure.  The WhereClause structure
131327** itself is not freed.  This routine is the inverse of
131328** sqlite3WhereClauseInit().
131329*/
131330SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
131331  int i;
131332  WhereTerm *a;
131333  sqlite3 *db = pWC->pWInfo->pParse->db;
131334  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
131335    if( a->wtFlags & TERM_DYNAMIC ){
131336      sqlite3ExprDelete(db, a->pExpr);
131337    }
131338    if( a->wtFlags & TERM_ORINFO ){
131339      whereOrInfoDelete(db, a->u.pOrInfo);
131340    }else if( a->wtFlags & TERM_ANDINFO ){
131341      whereAndInfoDelete(db, a->u.pAndInfo);
131342    }
131343  }
131344  if( pWC->a!=pWC->aStatic ){
131345    sqlite3DbFree(db, pWC->a);
131346  }
131347}
131348
131349
131350/*
131351** These routines walk (recursively) an expression tree and generate
131352** a bitmask indicating which tables are used in that expression
131353** tree.
131354*/
131355SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
131356  Bitmask mask;
131357  if( p==0 ) return 0;
131358  if( p->op==TK_COLUMN ){
131359    return sqlite3WhereGetMask(pMaskSet, p->iTable);
131360  }
131361  mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
131362  assert( !ExprHasProperty(p, EP_TokenOnly) );
131363  if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
131364  if( p->pRight ){
131365    mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
131366    assert( p->x.pList==0 );
131367  }else if( ExprHasProperty(p, EP_xIsSelect) ){
131368    if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
131369    mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
131370  }else if( p->x.pList ){
131371    mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
131372  }
131373  return mask;
131374}
131375SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
131376  int i;
131377  Bitmask mask = 0;
131378  if( pList ){
131379    for(i=0; i<pList->nExpr; i++){
131380      mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
131381    }
131382  }
131383  return mask;
131384}
131385
131386
131387/*
131388** Call exprAnalyze on all terms in a WHERE clause.
131389**
131390** Note that exprAnalyze() might add new virtual terms onto the
131391** end of the WHERE clause.  We do not want to analyze these new
131392** virtual terms, so start analyzing at the end and work forward
131393** so that the added virtual terms are never processed.
131394*/
131395SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
131396  SrcList *pTabList,       /* the FROM clause */
131397  WhereClause *pWC         /* the WHERE clause to be analyzed */
131398){
131399  int i;
131400  for(i=pWC->nTerm-1; i>=0; i--){
131401    exprAnalyze(pTabList, pWC, i);
131402  }
131403}
131404
131405/*
131406** For table-valued-functions, transform the function arguments into
131407** new WHERE clause terms.
131408**
131409** Each function argument translates into an equality constraint against
131410** a HIDDEN column in the table.
131411*/
131412SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
131413  Parse *pParse,                    /* Parsing context */
131414  struct SrcList_item *pItem,       /* The FROM clause term to process */
131415  WhereClause *pWC                  /* Xfer function arguments to here */
131416){
131417  Table *pTab;
131418  int j, k;
131419  ExprList *pArgs;
131420  Expr *pColRef;
131421  Expr *pTerm;
131422  if( pItem->fg.isTabFunc==0 ) return;
131423  pTab = pItem->pTab;
131424  assert( pTab!=0 );
131425  pArgs = pItem->u1.pFuncArg;
131426  if( pArgs==0 ) return;
131427  for(j=k=0; j<pArgs->nExpr; j++){
131428    while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
131429    if( k>=pTab->nCol ){
131430      sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
131431                      pTab->zName, j);
131432      return;
131433    }
131434    pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
131435    if( pColRef==0 ) return;
131436    pColRef->iTable = pItem->iCursor;
131437    pColRef->iColumn = k++;
131438    pColRef->pTab = pTab;
131439    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
131440                         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
131441    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
131442  }
131443}
131444
131445/************** End of whereexpr.c *******************************************/
131446/************** Begin file where.c *******************************************/
131447/*
131448** 2001 September 15
131449**
131450** The author disclaims copyright to this source code.  In place of
131451** a legal notice, here is a blessing:
131452**
131453**    May you do good and not evil.
131454**    May you find forgiveness for yourself and forgive others.
131455**    May you share freely, never taking more than you give.
131456**
131457*************************************************************************
131458** This module contains C code that generates VDBE code used to process
131459** the WHERE clause of SQL statements.  This module is responsible for
131460** generating the code that loops through a table looking for applicable
131461** rows.  Indices are selected and used to speed the search when doing
131462** so is applicable.  Because this module is responsible for selecting
131463** indices, you might also think of this module as the "query optimizer".
131464*/
131465/* #include "sqliteInt.h" */
131466/* #include "whereInt.h" */
131467
131468/* Forward declaration of methods */
131469static int whereLoopResize(sqlite3*, WhereLoop*, int);
131470
131471/* Test variable that can be set to enable WHERE tracing */
131472#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
131473/***/ int sqlite3WhereTrace = 0;
131474#endif
131475
131476
131477/*
131478** Return the estimated number of output rows from a WHERE clause
131479*/
131480SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
131481  return pWInfo->nRowOut;
131482}
131483
131484/*
131485** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
131486** WHERE clause returns outputs for DISTINCT processing.
131487*/
131488SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
131489  return pWInfo->eDistinct;
131490}
131491
131492/*
131493** Return TRUE if the WHERE clause returns rows in ORDER BY order.
131494** Return FALSE if the output needs to be sorted.
131495*/
131496SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
131497  return pWInfo->nOBSat;
131498}
131499
131500/*
131501** Return TRUE if the innermost loop of the WHERE clause implementation
131502** returns rows in ORDER BY order for complete run of the inner loop.
131503**
131504** Across multiple iterations of outer loops, the output rows need not be
131505** sorted.  As long as rows are sorted for just the innermost loop, this
131506** routine can return TRUE.
131507*/
131508SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
131509  return pWInfo->bOrderedInnerLoop;
131510}
131511
131512/*
131513** Return the VDBE address or label to jump to in order to continue
131514** immediately with the next row of a WHERE clause.
131515*/
131516SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
131517  assert( pWInfo->iContinue!=0 );
131518  return pWInfo->iContinue;
131519}
131520
131521/*
131522** Return the VDBE address or label to jump to in order to break
131523** out of a WHERE loop.
131524*/
131525SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
131526  return pWInfo->iBreak;
131527}
131528
131529/*
131530** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
131531** operate directly on the rowis returned by a WHERE clause.  Return
131532** ONEPASS_SINGLE (1) if the statement can operation directly because only
131533** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
131534** optimization can be used on multiple
131535**
131536** If the ONEPASS optimization is used (if this routine returns true)
131537** then also write the indices of open cursors used by ONEPASS
131538** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
131539** table and iaCur[1] gets the cursor used by an auxiliary index.
131540** Either value may be -1, indicating that cursor is not used.
131541** Any cursors returned will have been opened for writing.
131542**
131543** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
131544** unable to use the ONEPASS optimization.
131545*/
131546SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
131547  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
131548#ifdef WHERETRACE_ENABLED
131549  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
131550    sqlite3DebugPrintf("%s cursors: %d %d\n",
131551         pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
131552         aiCur[0], aiCur[1]);
131553  }
131554#endif
131555  return pWInfo->eOnePass;
131556}
131557
131558/*
131559** Move the content of pSrc into pDest
131560*/
131561static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
131562  pDest->n = pSrc->n;
131563  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
131564}
131565
131566/*
131567** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
131568**
131569** The new entry might overwrite an existing entry, or it might be
131570** appended, or it might be discarded.  Do whatever is the right thing
131571** so that pSet keeps the N_OR_COST best entries seen so far.
131572*/
131573static int whereOrInsert(
131574  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
131575  Bitmask prereq,        /* Prerequisites of the new entry */
131576  LogEst rRun,           /* Run-cost of the new entry */
131577  LogEst nOut            /* Number of outputs for the new entry */
131578){
131579  u16 i;
131580  WhereOrCost *p;
131581  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
131582    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
131583      goto whereOrInsert_done;
131584    }
131585    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
131586      return 0;
131587    }
131588  }
131589  if( pSet->n<N_OR_COST ){
131590    p = &pSet->a[pSet->n++];
131591    p->nOut = nOut;
131592  }else{
131593    p = pSet->a;
131594    for(i=1; i<pSet->n; i++){
131595      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
131596    }
131597    if( p->rRun<=rRun ) return 0;
131598  }
131599whereOrInsert_done:
131600  p->prereq = prereq;
131601  p->rRun = rRun;
131602  if( p->nOut>nOut ) p->nOut = nOut;
131603  return 1;
131604}
131605
131606/*
131607** Return the bitmask for the given cursor number.  Return 0 if
131608** iCursor is not in the set.
131609*/
131610SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
131611  int i;
131612  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
131613  for(i=0; i<pMaskSet->n; i++){
131614    if( pMaskSet->ix[i]==iCursor ){
131615      return MASKBIT(i);
131616    }
131617  }
131618  return 0;
131619}
131620
131621/*
131622** Create a new mask for cursor iCursor.
131623**
131624** There is one cursor per table in the FROM clause.  The number of
131625** tables in the FROM clause is limited by a test early in the
131626** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
131627** array will never overflow.
131628*/
131629static void createMask(WhereMaskSet *pMaskSet, int iCursor){
131630  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
131631  pMaskSet->ix[pMaskSet->n++] = iCursor;
131632}
131633
131634/*
131635** Advance to the next WhereTerm that matches according to the criteria
131636** established when the pScan object was initialized by whereScanInit().
131637** Return NULL if there are no more matching WhereTerms.
131638*/
131639static WhereTerm *whereScanNext(WhereScan *pScan){
131640  int iCur;            /* The cursor on the LHS of the term */
131641  i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
131642  Expr *pX;            /* An expression being tested */
131643  WhereClause *pWC;    /* Shorthand for pScan->pWC */
131644  WhereTerm *pTerm;    /* The term being tested */
131645  int k = pScan->k;    /* Where to start scanning */
131646
131647  assert( pScan->iEquiv<=pScan->nEquiv );
131648  pWC = pScan->pWC;
131649  while(1){
131650    iColumn = pScan->aiColumn[pScan->iEquiv-1];
131651    iCur = pScan->aiCur[pScan->iEquiv-1];
131652    assert( pWC!=0 );
131653    do{
131654      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
131655        if( pTerm->leftCursor==iCur
131656         && pTerm->u.leftColumn==iColumn
131657         && (iColumn!=XN_EXPR
131658             || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
131659                                       pScan->pIdxExpr,iCur)==0)
131660         && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
131661        ){
131662          if( (pTerm->eOperator & WO_EQUIV)!=0
131663           && pScan->nEquiv<ArraySize(pScan->aiCur)
131664           && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
131665          ){
131666            int j;
131667            for(j=0; j<pScan->nEquiv; j++){
131668              if( pScan->aiCur[j]==pX->iTable
131669               && pScan->aiColumn[j]==pX->iColumn ){
131670                  break;
131671              }
131672            }
131673            if( j==pScan->nEquiv ){
131674              pScan->aiCur[j] = pX->iTable;
131675              pScan->aiColumn[j] = pX->iColumn;
131676              pScan->nEquiv++;
131677            }
131678          }
131679          if( (pTerm->eOperator & pScan->opMask)!=0 ){
131680            /* Verify the affinity and collating sequence match */
131681            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
131682              CollSeq *pColl;
131683              Parse *pParse = pWC->pWInfo->pParse;
131684              pX = pTerm->pExpr;
131685              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
131686                continue;
131687              }
131688              assert(pX->pLeft);
131689              pColl = sqlite3BinaryCompareCollSeq(pParse,
131690                                                  pX->pLeft, pX->pRight);
131691              if( pColl==0 ) pColl = pParse->db->pDfltColl;
131692              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
131693                continue;
131694              }
131695            }
131696            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
131697             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
131698             && pX->iTable==pScan->aiCur[0]
131699             && pX->iColumn==pScan->aiColumn[0]
131700            ){
131701              testcase( pTerm->eOperator & WO_IS );
131702              continue;
131703            }
131704            pScan->pWC = pWC;
131705            pScan->k = k+1;
131706            return pTerm;
131707          }
131708        }
131709      }
131710      pWC = pWC->pOuter;
131711      k = 0;
131712    }while( pWC!=0 );
131713    if( pScan->iEquiv>=pScan->nEquiv ) break;
131714    pWC = pScan->pOrigWC;
131715    k = 0;
131716    pScan->iEquiv++;
131717  }
131718  return 0;
131719}
131720
131721/*
131722** Initialize a WHERE clause scanner object.  Return a pointer to the
131723** first match.  Return NULL if there are no matches.
131724**
131725** The scanner will be searching the WHERE clause pWC.  It will look
131726** for terms of the form "X <op> <expr>" where X is column iColumn of table
131727** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
131728** must be one of the indexes of table iCur.
131729**
131730** The <op> must be one of the operators described by opMask.
131731**
131732** If the search is for X and the WHERE clause contains terms of the
131733** form X=Y then this routine might also return terms of the form
131734** "Y <op> <expr>".  The number of levels of transitivity is limited,
131735** but is enough to handle most commonly occurring SQL statements.
131736**
131737** If X is not the INTEGER PRIMARY KEY then X must be compatible with
131738** index pIdx.
131739*/
131740static WhereTerm *whereScanInit(
131741  WhereScan *pScan,       /* The WhereScan object being initialized */
131742  WhereClause *pWC,       /* The WHERE clause to be scanned */
131743  int iCur,               /* Cursor to scan for */
131744  int iColumn,            /* Column to scan for */
131745  u32 opMask,             /* Operator(s) to scan for */
131746  Index *pIdx             /* Must be compatible with this index */
131747){
131748  pScan->pOrigWC = pWC;
131749  pScan->pWC = pWC;
131750  pScan->pIdxExpr = 0;
131751  pScan->idxaff = 0;
131752  pScan->zCollName = 0;
131753  if( pIdx ){
131754    int j = iColumn;
131755    iColumn = pIdx->aiColumn[j];
131756    if( iColumn==XN_EXPR ){
131757      pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
131758      pScan->zCollName = pIdx->azColl[j];
131759    }else if( iColumn==pIdx->pTable->iPKey ){
131760      iColumn = XN_ROWID;
131761    }else if( iColumn>=0 ){
131762      pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
131763      pScan->zCollName = pIdx->azColl[j];
131764    }
131765  }else if( iColumn==XN_EXPR ){
131766    return 0;
131767  }
131768  pScan->opMask = opMask;
131769  pScan->k = 0;
131770  pScan->aiCur[0] = iCur;
131771  pScan->aiColumn[0] = iColumn;
131772  pScan->nEquiv = 1;
131773  pScan->iEquiv = 1;
131774  return whereScanNext(pScan);
131775}
131776
131777/*
131778** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
131779** where X is a reference to the iColumn of table iCur or of index pIdx
131780** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
131781** the op parameter.  Return a pointer to the term.  Return 0 if not found.
131782**
131783** If pIdx!=0 then it must be one of the indexes of table iCur.
131784** Search for terms matching the iColumn-th column of pIdx
131785** rather than the iColumn-th column of table iCur.
131786**
131787** The term returned might by Y=<expr> if there is another constraint in
131788** the WHERE clause that specifies that X=Y.  Any such constraints will be
131789** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
131790** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
131791** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
131792** other equivalent values.  Hence a search for X will return <expr> if X=A1
131793** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
131794**
131795** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
131796** then try for the one with no dependencies on <expr> - in other words where
131797** <expr> is a constant expression of some kind.  Only return entries of
131798** the form "X <op> Y" where Y is a column in another table if no terms of
131799** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
131800** exist, try to return a term that does not use WO_EQUIV.
131801*/
131802SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
131803  WhereClause *pWC,     /* The WHERE clause to be searched */
131804  int iCur,             /* Cursor number of LHS */
131805  int iColumn,          /* Column number of LHS */
131806  Bitmask notReady,     /* RHS must not overlap with this mask */
131807  u32 op,               /* Mask of WO_xx values describing operator */
131808  Index *pIdx           /* Must be compatible with this index, if not NULL */
131809){
131810  WhereTerm *pResult = 0;
131811  WhereTerm *p;
131812  WhereScan scan;
131813
131814  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
131815  op &= WO_EQ|WO_IS;
131816  while( p ){
131817    if( (p->prereqRight & notReady)==0 ){
131818      if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
131819        testcase( p->eOperator & WO_IS );
131820        return p;
131821      }
131822      if( pResult==0 ) pResult = p;
131823    }
131824    p = whereScanNext(&scan);
131825  }
131826  return pResult;
131827}
131828
131829/*
131830** This function searches pList for an entry that matches the iCol-th column
131831** of index pIdx.
131832**
131833** If such an expression is found, its index in pList->a[] is returned. If
131834** no expression is found, -1 is returned.
131835*/
131836static int findIndexCol(
131837  Parse *pParse,                  /* Parse context */
131838  ExprList *pList,                /* Expression list to search */
131839  int iBase,                      /* Cursor for table associated with pIdx */
131840  Index *pIdx,                    /* Index to match column of */
131841  int iCol                        /* Column of index to match */
131842){
131843  int i;
131844  const char *zColl = pIdx->azColl[iCol];
131845
131846  for(i=0; i<pList->nExpr; i++){
131847    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
131848    if( p->op==TK_COLUMN
131849     && p->iColumn==pIdx->aiColumn[iCol]
131850     && p->iTable==iBase
131851    ){
131852      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
131853      if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
131854        return i;
131855      }
131856    }
131857  }
131858
131859  return -1;
131860}
131861
131862/*
131863** Return TRUE if the iCol-th column of index pIdx is NOT NULL
131864*/
131865static int indexColumnNotNull(Index *pIdx, int iCol){
131866  int j;
131867  assert( pIdx!=0 );
131868  assert( iCol>=0 && iCol<pIdx->nColumn );
131869  j = pIdx->aiColumn[iCol];
131870  if( j>=0 ){
131871    return pIdx->pTable->aCol[j].notNull;
131872  }else if( j==(-1) ){
131873    return 1;
131874  }else{
131875    assert( j==(-2) );
131876    return 0;  /* Assume an indexed expression can always yield a NULL */
131877
131878  }
131879}
131880
131881/*
131882** Return true if the DISTINCT expression-list passed as the third argument
131883** is redundant.
131884**
131885** A DISTINCT list is redundant if any subset of the columns in the
131886** DISTINCT list are collectively unique and individually non-null.
131887*/
131888static int isDistinctRedundant(
131889  Parse *pParse,            /* Parsing context */
131890  SrcList *pTabList,        /* The FROM clause */
131891  WhereClause *pWC,         /* The WHERE clause */
131892  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
131893){
131894  Table *pTab;
131895  Index *pIdx;
131896  int i;
131897  int iBase;
131898
131899  /* If there is more than one table or sub-select in the FROM clause of
131900  ** this query, then it will not be possible to show that the DISTINCT
131901  ** clause is redundant. */
131902  if( pTabList->nSrc!=1 ) return 0;
131903  iBase = pTabList->a[0].iCursor;
131904  pTab = pTabList->a[0].pTab;
131905
131906  /* If any of the expressions is an IPK column on table iBase, then return
131907  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
131908  ** current SELECT is a correlated sub-query.
131909  */
131910  for(i=0; i<pDistinct->nExpr; i++){
131911    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
131912    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
131913  }
131914
131915  /* Loop through all indices on the table, checking each to see if it makes
131916  ** the DISTINCT qualifier redundant. It does so if:
131917  **
131918  **   1. The index is itself UNIQUE, and
131919  **
131920  **   2. All of the columns in the index are either part of the pDistinct
131921  **      list, or else the WHERE clause contains a term of the form "col=X",
131922  **      where X is a constant value. The collation sequences of the
131923  **      comparison and select-list expressions must match those of the index.
131924  **
131925  **   3. All of those index columns for which the WHERE clause does not
131926  **      contain a "col=X" term are subject to a NOT NULL constraint.
131927  */
131928  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
131929    if( !IsUniqueIndex(pIdx) ) continue;
131930    for(i=0; i<pIdx->nKeyCol; i++){
131931      if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
131932        if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
131933        if( indexColumnNotNull(pIdx, i)==0 ) break;
131934      }
131935    }
131936    if( i==pIdx->nKeyCol ){
131937      /* This index implies that the DISTINCT qualifier is redundant. */
131938      return 1;
131939    }
131940  }
131941
131942  return 0;
131943}
131944
131945
131946/*
131947** Estimate the logarithm of the input value to base 2.
131948*/
131949static LogEst estLog(LogEst N){
131950  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
131951}
131952
131953/*
131954** Convert OP_Column opcodes to OP_Copy in previously generated code.
131955**
131956** This routine runs over generated VDBE code and translates OP_Column
131957** opcodes into OP_Copy when the table is being accessed via co-routine
131958** instead of via table lookup.
131959**
131960** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
131961** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
131962** then each OP_Rowid is transformed into an instruction to increment the
131963** value stored in its output register.
131964*/
131965static void translateColumnToCopy(
131966  Parse *pParse,      /* Parsing context */
131967  int iStart,         /* Translate from this opcode to the end */
131968  int iTabCur,        /* OP_Column/OP_Rowid references to this table */
131969  int iRegister,      /* The first column is in this register */
131970  int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
131971){
131972  Vdbe *v = pParse->pVdbe;
131973  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
131974  int iEnd = sqlite3VdbeCurrentAddr(v);
131975  if( pParse->db->mallocFailed ) return;
131976  for(; iStart<iEnd; iStart++, pOp++){
131977    if( pOp->p1!=iTabCur ) continue;
131978    if( pOp->opcode==OP_Column ){
131979      pOp->opcode = OP_Copy;
131980      pOp->p1 = pOp->p2 + iRegister;
131981      pOp->p2 = pOp->p3;
131982      pOp->p3 = 0;
131983    }else if( pOp->opcode==OP_Rowid ){
131984      if( bIncrRowid ){
131985        /* Increment the value stored in the P2 operand of the OP_Rowid. */
131986        pOp->opcode = OP_AddImm;
131987        pOp->p1 = pOp->p2;
131988        pOp->p2 = 1;
131989      }else{
131990        pOp->opcode = OP_Null;
131991        pOp->p1 = 0;
131992        pOp->p3 = 0;
131993      }
131994    }
131995  }
131996}
131997
131998/*
131999** Two routines for printing the content of an sqlite3_index_info
132000** structure.  Used for testing and debugging only.  If neither
132001** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
132002** are no-ops.
132003*/
132004#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
132005static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
132006  int i;
132007  if( !sqlite3WhereTrace ) return;
132008  for(i=0; i<p->nConstraint; i++){
132009    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
132010       i,
132011       p->aConstraint[i].iColumn,
132012       p->aConstraint[i].iTermOffset,
132013       p->aConstraint[i].op,
132014       p->aConstraint[i].usable);
132015  }
132016  for(i=0; i<p->nOrderBy; i++){
132017    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
132018       i,
132019       p->aOrderBy[i].iColumn,
132020       p->aOrderBy[i].desc);
132021  }
132022}
132023static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
132024  int i;
132025  if( !sqlite3WhereTrace ) return;
132026  for(i=0; i<p->nConstraint; i++){
132027    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
132028       i,
132029       p->aConstraintUsage[i].argvIndex,
132030       p->aConstraintUsage[i].omit);
132031  }
132032  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
132033  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
132034  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
132035  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
132036  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
132037}
132038#else
132039#define TRACE_IDX_INPUTS(A)
132040#define TRACE_IDX_OUTPUTS(A)
132041#endif
132042
132043#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132044/*
132045** Return TRUE if the WHERE clause term pTerm is of a form where it
132046** could be used with an index to access pSrc, assuming an appropriate
132047** index existed.
132048*/
132049static int termCanDriveIndex(
132050  WhereTerm *pTerm,              /* WHERE clause term to check */
132051  struct SrcList_item *pSrc,     /* Table we are trying to access */
132052  Bitmask notReady               /* Tables in outer loops of the join */
132053){
132054  char aff;
132055  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
132056  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
132057  if( (pSrc->fg.jointype & JT_LEFT)
132058   && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
132059   && (pTerm->eOperator & WO_IS)
132060  ){
132061    /* Cannot use an IS term from the WHERE clause as an index driver for
132062    ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
132063    ** the ON clause.  */
132064    return 0;
132065  }
132066  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
132067  if( pTerm->u.leftColumn<0 ) return 0;
132068  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
132069  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
132070  testcase( pTerm->pExpr->op==TK_IS );
132071  return 1;
132072}
132073#endif
132074
132075
132076#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132077/*
132078** Generate code to construct the Index object for an automatic index
132079** and to set up the WhereLevel object pLevel so that the code generator
132080** makes use of the automatic index.
132081*/
132082static void constructAutomaticIndex(
132083  Parse *pParse,              /* The parsing context */
132084  WhereClause *pWC,           /* The WHERE clause */
132085  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
132086  Bitmask notReady,           /* Mask of cursors that are not available */
132087  WhereLevel *pLevel          /* Write new index here */
132088){
132089  int nKeyCol;                /* Number of columns in the constructed index */
132090  WhereTerm *pTerm;           /* A single term of the WHERE clause */
132091  WhereTerm *pWCEnd;          /* End of pWC->a[] */
132092  Index *pIdx;                /* Object describing the transient index */
132093  Vdbe *v;                    /* Prepared statement under construction */
132094  int addrInit;               /* Address of the initialization bypass jump */
132095  Table *pTable;              /* The table being indexed */
132096  int addrTop;                /* Top of the index fill loop */
132097  int regRecord;              /* Register holding an index record */
132098  int n;                      /* Column counter */
132099  int i;                      /* Loop counter */
132100  int mxBitCol;               /* Maximum column in pSrc->colUsed */
132101  CollSeq *pColl;             /* Collating sequence to on a column */
132102  WhereLoop *pLoop;           /* The Loop object */
132103  char *zNotUsed;             /* Extra space on the end of pIdx */
132104  Bitmask idxCols;            /* Bitmap of columns used for indexing */
132105  Bitmask extraCols;          /* Bitmap of additional columns */
132106  u8 sentWarning = 0;         /* True if a warnning has been issued */
132107  Expr *pPartial = 0;         /* Partial Index Expression */
132108  int iContinue = 0;          /* Jump here to skip excluded rows */
132109  struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
132110  int addrCounter = 0;        /* Address where integer counter is initialized */
132111  int regBase;                /* Array of registers where record is assembled */
132112
132113  /* Generate code to skip over the creation and initialization of the
132114  ** transient index on 2nd and subsequent iterations of the loop. */
132115  v = pParse->pVdbe;
132116  assert( v!=0 );
132117  addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
132118
132119  /* Count the number of columns that will be added to the index
132120  ** and used to match WHERE clause constraints */
132121  nKeyCol = 0;
132122  pTable = pSrc->pTab;
132123  pWCEnd = &pWC->a[pWC->nTerm];
132124  pLoop = pLevel->pWLoop;
132125  idxCols = 0;
132126  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
132127    Expr *pExpr = pTerm->pExpr;
132128    assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
132129         || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
132130         || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
132131    if( pLoop->prereq==0
132132     && (pTerm->wtFlags & TERM_VIRTUAL)==0
132133     && !ExprHasProperty(pExpr, EP_FromJoin)
132134     && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
132135      pPartial = sqlite3ExprAnd(pParse->db, pPartial,
132136                                sqlite3ExprDup(pParse->db, pExpr, 0));
132137    }
132138    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
132139      int iCol = pTerm->u.leftColumn;
132140      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
132141      testcase( iCol==BMS );
132142      testcase( iCol==BMS-1 );
132143      if( !sentWarning ){
132144        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
132145            "automatic index on %s(%s)", pTable->zName,
132146            pTable->aCol[iCol].zName);
132147        sentWarning = 1;
132148      }
132149      if( (idxCols & cMask)==0 ){
132150        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
132151          goto end_auto_index_create;
132152        }
132153        pLoop->aLTerm[nKeyCol++] = pTerm;
132154        idxCols |= cMask;
132155      }
132156    }
132157  }
132158  assert( nKeyCol>0 );
132159  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
132160  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
132161                     | WHERE_AUTO_INDEX;
132162
132163  /* Count the number of additional columns needed to create a
132164  ** covering index.  A "covering index" is an index that contains all
132165  ** columns that are needed by the query.  With a covering index, the
132166  ** original table never needs to be accessed.  Automatic indices must
132167  ** be a covering index because the index will not be updated if the
132168  ** original table changes and the index and table cannot both be used
132169  ** if they go out of sync.
132170  */
132171  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
132172  mxBitCol = MIN(BMS-1,pTable->nCol);
132173  testcase( pTable->nCol==BMS-1 );
132174  testcase( pTable->nCol==BMS-2 );
132175  for(i=0; i<mxBitCol; i++){
132176    if( extraCols & MASKBIT(i) ) nKeyCol++;
132177  }
132178  if( pSrc->colUsed & MASKBIT(BMS-1) ){
132179    nKeyCol += pTable->nCol - BMS + 1;
132180  }
132181
132182  /* Construct the Index object to describe this index */
132183  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
132184  if( pIdx==0 ) goto end_auto_index_create;
132185  pLoop->u.btree.pIndex = pIdx;
132186  pIdx->zName = "auto-index";
132187  pIdx->pTable = pTable;
132188  n = 0;
132189  idxCols = 0;
132190  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
132191    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
132192      int iCol = pTerm->u.leftColumn;
132193      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
132194      testcase( iCol==BMS-1 );
132195      testcase( iCol==BMS );
132196      if( (idxCols & cMask)==0 ){
132197        Expr *pX = pTerm->pExpr;
132198        idxCols |= cMask;
132199        pIdx->aiColumn[n] = pTerm->u.leftColumn;
132200        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
132201        pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
132202        n++;
132203      }
132204    }
132205  }
132206  assert( (u32)n==pLoop->u.btree.nEq );
132207
132208  /* Add additional columns needed to make the automatic index into
132209  ** a covering index */
132210  for(i=0; i<mxBitCol; i++){
132211    if( extraCols & MASKBIT(i) ){
132212      pIdx->aiColumn[n] = i;
132213      pIdx->azColl[n] = sqlite3StrBINARY;
132214      n++;
132215    }
132216  }
132217  if( pSrc->colUsed & MASKBIT(BMS-1) ){
132218    for(i=BMS-1; i<pTable->nCol; i++){
132219      pIdx->aiColumn[n] = i;
132220      pIdx->azColl[n] = sqlite3StrBINARY;
132221      n++;
132222    }
132223  }
132224  assert( n==nKeyCol );
132225  pIdx->aiColumn[n] = XN_ROWID;
132226  pIdx->azColl[n] = sqlite3StrBINARY;
132227
132228  /* Create the automatic index */
132229  assert( pLevel->iIdxCur>=0 );
132230  pLevel->iIdxCur = pParse->nTab++;
132231  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
132232  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
132233  VdbeComment((v, "for %s", pTable->zName));
132234
132235  /* Fill the automatic index with content */
132236  sqlite3ExprCachePush(pParse);
132237  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
132238  if( pTabItem->fg.viaCoroutine ){
132239    int regYield = pTabItem->regReturn;
132240    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
132241    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
132242    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
132243    VdbeCoverage(v);
132244    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
132245  }else{
132246    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
132247  }
132248  if( pPartial ){
132249    iContinue = sqlite3VdbeMakeLabel(v);
132250    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
132251    pLoop->wsFlags |= WHERE_PARTIALIDX;
132252  }
132253  regRecord = sqlite3GetTempReg(pParse);
132254  regBase = sqlite3GenerateIndexKey(
132255      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
132256  );
132257  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
132258  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
132259  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
132260  if( pTabItem->fg.viaCoroutine ){
132261    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
132262    testcase( pParse->db->mallocFailed );
132263    translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
132264                          pTabItem->regResult, 1);
132265    sqlite3VdbeGoto(v, addrTop);
132266    pTabItem->fg.viaCoroutine = 0;
132267  }else{
132268    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
132269  }
132270  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
132271  sqlite3VdbeJumpHere(v, addrTop);
132272  sqlite3ReleaseTempReg(pParse, regRecord);
132273  sqlite3ExprCachePop(pParse);
132274
132275  /* Jump here when skipping the initialization */
132276  sqlite3VdbeJumpHere(v, addrInit);
132277
132278end_auto_index_create:
132279  sqlite3ExprDelete(pParse->db, pPartial);
132280}
132281#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
132282
132283#ifndef SQLITE_OMIT_VIRTUALTABLE
132284/*
132285** Allocate and populate an sqlite3_index_info structure. It is the
132286** responsibility of the caller to eventually release the structure
132287** by passing the pointer returned by this function to sqlite3_free().
132288*/
132289static sqlite3_index_info *allocateIndexInfo(
132290  Parse *pParse,
132291  WhereClause *pWC,
132292  Bitmask mUnusable,              /* Ignore terms with these prereqs */
132293  struct SrcList_item *pSrc,
132294  ExprList *pOrderBy,
132295  u16 *pmNoOmit                   /* Mask of terms not to omit */
132296){
132297  int i, j;
132298  int nTerm;
132299  struct sqlite3_index_constraint *pIdxCons;
132300  struct sqlite3_index_orderby *pIdxOrderBy;
132301  struct sqlite3_index_constraint_usage *pUsage;
132302  WhereTerm *pTerm;
132303  int nOrderBy;
132304  sqlite3_index_info *pIdxInfo;
132305  u16 mNoOmit = 0;
132306
132307  /* Count the number of possible WHERE clause constraints referring
132308  ** to this virtual table */
132309  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
132310    if( pTerm->leftCursor != pSrc->iCursor ) continue;
132311    if( pTerm->prereqRight & mUnusable ) continue;
132312    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
132313    testcase( pTerm->eOperator & WO_IN );
132314    testcase( pTerm->eOperator & WO_ISNULL );
132315    testcase( pTerm->eOperator & WO_IS );
132316    testcase( pTerm->eOperator & WO_ALL );
132317    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
132318    if( pTerm->wtFlags & TERM_VNULL ) continue;
132319    assert( pTerm->u.leftColumn>=(-1) );
132320    nTerm++;
132321  }
132322
132323  /* If the ORDER BY clause contains only columns in the current
132324  ** virtual table then allocate space for the aOrderBy part of
132325  ** the sqlite3_index_info structure.
132326  */
132327  nOrderBy = 0;
132328  if( pOrderBy ){
132329    int n = pOrderBy->nExpr;
132330    for(i=0; i<n; i++){
132331      Expr *pExpr = pOrderBy->a[i].pExpr;
132332      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
132333    }
132334    if( i==n){
132335      nOrderBy = n;
132336    }
132337  }
132338
132339  /* Allocate the sqlite3_index_info structure
132340  */
132341  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
132342                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
132343                           + sizeof(*pIdxOrderBy)*nOrderBy );
132344  if( pIdxInfo==0 ){
132345    sqlite3ErrorMsg(pParse, "out of memory");
132346    return 0;
132347  }
132348
132349  /* Initialize the structure.  The sqlite3_index_info structure contains
132350  ** many fields that are declared "const" to prevent xBestIndex from
132351  ** changing them.  We have to do some funky casting in order to
132352  ** initialize those fields.
132353  */
132354  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
132355  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
132356  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
132357  *(int*)&pIdxInfo->nConstraint = nTerm;
132358  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
132359  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
132360  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
132361  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
132362                                                                   pUsage;
132363
132364  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
132365    u8 op;
132366    if( pTerm->leftCursor != pSrc->iCursor ) continue;
132367    if( pTerm->prereqRight & mUnusable ) continue;
132368    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
132369    testcase( pTerm->eOperator & WO_IN );
132370    testcase( pTerm->eOperator & WO_IS );
132371    testcase( pTerm->eOperator & WO_ISNULL );
132372    testcase( pTerm->eOperator & WO_ALL );
132373    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
132374    if( pTerm->wtFlags & TERM_VNULL ) continue;
132375    assert( pTerm->u.leftColumn>=(-1) );
132376    pIdxCons[j].iColumn = pTerm->u.leftColumn;
132377    pIdxCons[j].iTermOffset = i;
132378    op = (u8)pTerm->eOperator & WO_ALL;
132379    if( op==WO_IN ) op = WO_EQ;
132380    if( op==WO_MATCH ){
132381      op = pTerm->eMatchOp;
132382    }
132383    pIdxCons[j].op = op;
132384    /* The direct assignment in the previous line is possible only because
132385    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
132386    ** following asserts verify this fact. */
132387    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
132388    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
132389    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
132390    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
132391    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
132392    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
132393    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
132394
132395    if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
132396     && sqlite3ExprIsVector(pTerm->pExpr->pRight)
132397    ){
132398      if( i<16 ) mNoOmit |= (1 << i);
132399      if( op==WO_LT ) pIdxCons[j].op = WO_LE;
132400      if( op==WO_GT ) pIdxCons[j].op = WO_GE;
132401    }
132402
132403    j++;
132404  }
132405  for(i=0; i<nOrderBy; i++){
132406    Expr *pExpr = pOrderBy->a[i].pExpr;
132407    pIdxOrderBy[i].iColumn = pExpr->iColumn;
132408    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
132409  }
132410
132411  *pmNoOmit = mNoOmit;
132412  return pIdxInfo;
132413}
132414
132415/*
132416** The table object reference passed as the second argument to this function
132417** must represent a virtual table. This function invokes the xBestIndex()
132418** method of the virtual table with the sqlite3_index_info object that
132419** comes in as the 3rd argument to this function.
132420**
132421** If an error occurs, pParse is populated with an error message and a
132422** non-zero value is returned. Otherwise, 0 is returned and the output
132423** part of the sqlite3_index_info structure is left populated.
132424**
132425** Whether or not an error is returned, it is the responsibility of the
132426** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
132427** that this is required.
132428*/
132429static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
132430  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
132431  int rc;
132432
132433  TRACE_IDX_INPUTS(p);
132434  rc = pVtab->pModule->xBestIndex(pVtab, p);
132435  TRACE_IDX_OUTPUTS(p);
132436
132437  if( rc!=SQLITE_OK ){
132438    if( rc==SQLITE_NOMEM ){
132439      sqlite3OomFault(pParse->db);
132440    }else if( !pVtab->zErrMsg ){
132441      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
132442    }else{
132443      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
132444    }
132445  }
132446  sqlite3_free(pVtab->zErrMsg);
132447  pVtab->zErrMsg = 0;
132448
132449#if 0
132450  /* This error is now caught by the caller.
132451  ** Search for "xBestIndex malfunction" below */
132452  for(i=0; i<p->nConstraint; i++){
132453    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
132454      sqlite3ErrorMsg(pParse,
132455          "table %s: xBestIndex returned an invalid plan", pTab->zName);
132456    }
132457  }
132458#endif
132459
132460  return pParse->nErr;
132461}
132462#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
132463
132464#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132465/*
132466** Estimate the location of a particular key among all keys in an
132467** index.  Store the results in aStat as follows:
132468**
132469**    aStat[0]      Est. number of rows less than pRec
132470**    aStat[1]      Est. number of rows equal to pRec
132471**
132472** Return the index of the sample that is the smallest sample that
132473** is greater than or equal to pRec. Note that this index is not an index
132474** into the aSample[] array - it is an index into a virtual set of samples
132475** based on the contents of aSample[] and the number of fields in record
132476** pRec.
132477*/
132478static int whereKeyStats(
132479  Parse *pParse,              /* Database connection */
132480  Index *pIdx,                /* Index to consider domain of */
132481  UnpackedRecord *pRec,       /* Vector of values to consider */
132482  int roundUp,                /* Round up if true.  Round down if false */
132483  tRowcnt *aStat              /* OUT: stats written here */
132484){
132485  IndexSample *aSample = pIdx->aSample;
132486  int iCol;                   /* Index of required stats in anEq[] etc. */
132487  int i;                      /* Index of first sample >= pRec */
132488  int iSample;                /* Smallest sample larger than or equal to pRec */
132489  int iMin = 0;               /* Smallest sample not yet tested */
132490  int iTest;                  /* Next sample to test */
132491  int res;                    /* Result of comparison operation */
132492  int nField;                 /* Number of fields in pRec */
132493  tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
132494
132495#ifndef SQLITE_DEBUG
132496  UNUSED_PARAMETER( pParse );
132497#endif
132498  assert( pRec!=0 );
132499  assert( pIdx->nSample>0 );
132500  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
132501
132502  /* Do a binary search to find the first sample greater than or equal
132503  ** to pRec. If pRec contains a single field, the set of samples to search
132504  ** is simply the aSample[] array. If the samples in aSample[] contain more
132505  ** than one fields, all fields following the first are ignored.
132506  **
132507  ** If pRec contains N fields, where N is more than one, then as well as the
132508  ** samples in aSample[] (truncated to N fields), the search also has to
132509  ** consider prefixes of those samples. For example, if the set of samples
132510  ** in aSample is:
132511  **
132512  **     aSample[0] = (a, 5)
132513  **     aSample[1] = (a, 10)
132514  **     aSample[2] = (b, 5)
132515  **     aSample[3] = (c, 100)
132516  **     aSample[4] = (c, 105)
132517  **
132518  ** Then the search space should ideally be the samples above and the
132519  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
132520  ** the code actually searches this set:
132521  **
132522  **     0: (a)
132523  **     1: (a, 5)
132524  **     2: (a, 10)
132525  **     3: (a, 10)
132526  **     4: (b)
132527  **     5: (b, 5)
132528  **     6: (c)
132529  **     7: (c, 100)
132530  **     8: (c, 105)
132531  **     9: (c, 105)
132532  **
132533  ** For each sample in the aSample[] array, N samples are present in the
132534  ** effective sample array. In the above, samples 0 and 1 are based on
132535  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
132536  **
132537  ** Often, sample i of each block of N effective samples has (i+1) fields.
132538  ** Except, each sample may be extended to ensure that it is greater than or
132539  ** equal to the previous sample in the array. For example, in the above,
132540  ** sample 2 is the first sample of a block of N samples, so at first it
132541  ** appears that it should be 1 field in size. However, that would make it
132542  ** smaller than sample 1, so the binary search would not work. As a result,
132543  ** it is extended to two fields. The duplicates that this creates do not
132544  ** cause any problems.
132545  */
132546  nField = pRec->nField;
132547  iCol = 0;
132548  iSample = pIdx->nSample * nField;
132549  do{
132550    int iSamp;                    /* Index in aSample[] of test sample */
132551    int n;                        /* Number of fields in test sample */
132552
132553    iTest = (iMin+iSample)/2;
132554    iSamp = iTest / nField;
132555    if( iSamp>0 ){
132556      /* The proposed effective sample is a prefix of sample aSample[iSamp].
132557      ** Specifically, the shortest prefix of at least (1 + iTest%nField)
132558      ** fields that is greater than the previous effective sample.  */
132559      for(n=(iTest % nField) + 1; n<nField; n++){
132560        if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
132561      }
132562    }else{
132563      n = iTest + 1;
132564    }
132565
132566    pRec->nField = n;
132567    res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
132568    if( res<0 ){
132569      iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
132570      iMin = iTest+1;
132571    }else if( res==0 && n<nField ){
132572      iLower = aSample[iSamp].anLt[n-1];
132573      iMin = iTest+1;
132574      res = -1;
132575    }else{
132576      iSample = iTest;
132577      iCol = n-1;
132578    }
132579  }while( res && iMin<iSample );
132580  i = iSample / nField;
132581
132582#ifdef SQLITE_DEBUG
132583  /* The following assert statements check that the binary search code
132584  ** above found the right answer. This block serves no purpose other
132585  ** than to invoke the asserts.  */
132586  if( pParse->db->mallocFailed==0 ){
132587    if( res==0 ){
132588      /* If (res==0) is true, then pRec must be equal to sample i. */
132589      assert( i<pIdx->nSample );
132590      assert( iCol==nField-1 );
132591      pRec->nField = nField;
132592      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
132593           || pParse->db->mallocFailed
132594      );
132595    }else{
132596      /* Unless i==pIdx->nSample, indicating that pRec is larger than
132597      ** all samples in the aSample[] array, pRec must be smaller than the
132598      ** (iCol+1) field prefix of sample i.  */
132599      assert( i<=pIdx->nSample && i>=0 );
132600      pRec->nField = iCol+1;
132601      assert( i==pIdx->nSample
132602           || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
132603           || pParse->db->mallocFailed );
132604
132605      /* if i==0 and iCol==0, then record pRec is smaller than all samples
132606      ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
132607      ** be greater than or equal to the (iCol) field prefix of sample i.
132608      ** If (i>0), then pRec must also be greater than sample (i-1).  */
132609      if( iCol>0 ){
132610        pRec->nField = iCol;
132611        assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
132612             || pParse->db->mallocFailed );
132613      }
132614      if( i>0 ){
132615        pRec->nField = nField;
132616        assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
132617             || pParse->db->mallocFailed );
132618      }
132619    }
132620  }
132621#endif /* ifdef SQLITE_DEBUG */
132622
132623  if( res==0 ){
132624    /* Record pRec is equal to sample i */
132625    assert( iCol==nField-1 );
132626    aStat[0] = aSample[i].anLt[iCol];
132627    aStat[1] = aSample[i].anEq[iCol];
132628  }else{
132629    /* At this point, the (iCol+1) field prefix of aSample[i] is the first
132630    ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
132631    ** is larger than all samples in the array. */
132632    tRowcnt iUpper, iGap;
132633    if( i>=pIdx->nSample ){
132634      iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
132635    }else{
132636      iUpper = aSample[i].anLt[iCol];
132637    }
132638
132639    if( iLower>=iUpper ){
132640      iGap = 0;
132641    }else{
132642      iGap = iUpper - iLower;
132643    }
132644    if( roundUp ){
132645      iGap = (iGap*2)/3;
132646    }else{
132647      iGap = iGap/3;
132648    }
132649    aStat[0] = iLower + iGap;
132650    aStat[1] = pIdx->aAvgEq[nField-1];
132651  }
132652
132653  /* Restore the pRec->nField value before returning.  */
132654  pRec->nField = nField;
132655  return i;
132656}
132657#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
132658
132659/*
132660** If it is not NULL, pTerm is a term that provides an upper or lower
132661** bound on a range scan. Without considering pTerm, it is estimated
132662** that the scan will visit nNew rows. This function returns the number
132663** estimated to be visited after taking pTerm into account.
132664**
132665** If the user explicitly specified a likelihood() value for this term,
132666** then the return value is the likelihood multiplied by the number of
132667** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
132668** has a likelihood of 0.50, and any other term a likelihood of 0.25.
132669*/
132670static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
132671  LogEst nRet = nNew;
132672  if( pTerm ){
132673    if( pTerm->truthProb<=0 ){
132674      nRet += pTerm->truthProb;
132675    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
132676      nRet -= 20;        assert( 20==sqlite3LogEst(4) );
132677    }
132678  }
132679  return nRet;
132680}
132681
132682
132683#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132684/*
132685** Return the affinity for a single column of an index.
132686*/
132687SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
132688  assert( iCol>=0 && iCol<pIdx->nColumn );
132689  if( !pIdx->zColAff ){
132690    if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
132691  }
132692  return pIdx->zColAff[iCol];
132693}
132694#endif
132695
132696
132697#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132698/*
132699** This function is called to estimate the number of rows visited by a
132700** range-scan on a skip-scan index. For example:
132701**
132702**   CREATE INDEX i1 ON t1(a, b, c);
132703**   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
132704**
132705** Value pLoop->nOut is currently set to the estimated number of rows
132706** visited for scanning (a=? AND b=?). This function reduces that estimate
132707** by some factor to account for the (c BETWEEN ? AND ?) expression based
132708** on the stat4 data for the index. this scan will be peformed multiple
132709** times (once for each (a,b) combination that matches a=?) is dealt with
132710** by the caller.
132711**
132712** It does this by scanning through all stat4 samples, comparing values
132713** extracted from pLower and pUpper with the corresponding column in each
132714** sample. If L and U are the number of samples found to be less than or
132715** equal to the values extracted from pLower and pUpper respectively, and
132716** N is the total number of samples, the pLoop->nOut value is adjusted
132717** as follows:
132718**
132719**   nOut = nOut * ( min(U - L, 1) / N )
132720**
132721** If pLower is NULL, or a value cannot be extracted from the term, L is
132722** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
132723** U is set to N.
132724**
132725** Normally, this function sets *pbDone to 1 before returning. However,
132726** if no value can be extracted from either pLower or pUpper (and so the
132727** estimate of the number of rows delivered remains unchanged), *pbDone
132728** is left as is.
132729**
132730** If an error occurs, an SQLite error code is returned. Otherwise,
132731** SQLITE_OK.
132732*/
132733static int whereRangeSkipScanEst(
132734  Parse *pParse,       /* Parsing & code generating context */
132735  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
132736  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
132737  WhereLoop *pLoop,    /* Update the .nOut value of this loop */
132738  int *pbDone          /* Set to true if at least one expr. value extracted */
132739){
132740  Index *p = pLoop->u.btree.pIndex;
132741  int nEq = pLoop->u.btree.nEq;
132742  sqlite3 *db = pParse->db;
132743  int nLower = -1;
132744  int nUpper = p->nSample+1;
132745  int rc = SQLITE_OK;
132746  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
132747  CollSeq *pColl;
132748
132749  sqlite3_value *p1 = 0;          /* Value extracted from pLower */
132750  sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
132751  sqlite3_value *pVal = 0;        /* Value extracted from record */
132752
132753  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
132754  if( pLower ){
132755    rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
132756    nLower = 0;
132757  }
132758  if( pUpper && rc==SQLITE_OK ){
132759    rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
132760    nUpper = p2 ? 0 : p->nSample;
132761  }
132762
132763  if( p1 || p2 ){
132764    int i;
132765    int nDiff;
132766    for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
132767      rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
132768      if( rc==SQLITE_OK && p1 ){
132769        int res = sqlite3MemCompare(p1, pVal, pColl);
132770        if( res>=0 ) nLower++;
132771      }
132772      if( rc==SQLITE_OK && p2 ){
132773        int res = sqlite3MemCompare(p2, pVal, pColl);
132774        if( res>=0 ) nUpper++;
132775      }
132776    }
132777    nDiff = (nUpper - nLower);
132778    if( nDiff<=0 ) nDiff = 1;
132779
132780    /* If there is both an upper and lower bound specified, and the
132781    ** comparisons indicate that they are close together, use the fallback
132782    ** method (assume that the scan visits 1/64 of the rows) for estimating
132783    ** the number of rows visited. Otherwise, estimate the number of rows
132784    ** using the method described in the header comment for this function. */
132785    if( nDiff!=1 || pUpper==0 || pLower==0 ){
132786      int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
132787      pLoop->nOut -= nAdjust;
132788      *pbDone = 1;
132789      WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
132790                           nLower, nUpper, nAdjust*-1, pLoop->nOut));
132791    }
132792
132793  }else{
132794    assert( *pbDone==0 );
132795  }
132796
132797  sqlite3ValueFree(p1);
132798  sqlite3ValueFree(p2);
132799  sqlite3ValueFree(pVal);
132800
132801  return rc;
132802}
132803#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
132804
132805/*
132806** This function is used to estimate the number of rows that will be visited
132807** by scanning an index for a range of values. The range may have an upper
132808** bound, a lower bound, or both. The WHERE clause terms that set the upper
132809** and lower bounds are represented by pLower and pUpper respectively. For
132810** example, assuming that index p is on t1(a):
132811**
132812**   ... FROM t1 WHERE a > ? AND a < ? ...
132813**                    |_____|   |_____|
132814**                       |         |
132815**                     pLower    pUpper
132816**
132817** If either of the upper or lower bound is not present, then NULL is passed in
132818** place of the corresponding WhereTerm.
132819**
132820** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
132821** column subject to the range constraint. Or, equivalently, the number of
132822** equality constraints optimized by the proposed index scan. For example,
132823** assuming index p is on t1(a, b), and the SQL query is:
132824**
132825**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
132826**
132827** then nEq is set to 1 (as the range restricted column, b, is the second
132828** left-most column of the index). Or, if the query is:
132829**
132830**   ... FROM t1 WHERE a > ? AND a < ? ...
132831**
132832** then nEq is set to 0.
132833**
132834** When this function is called, *pnOut is set to the sqlite3LogEst() of the
132835** number of rows that the index scan is expected to visit without
132836** considering the range constraints. If nEq is 0, then *pnOut is the number of
132837** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
132838** to account for the range constraints pLower and pUpper.
132839**
132840** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
132841** used, a single range inequality reduces the search space by a factor of 4.
132842** and a pair of constraints (x>? AND x<?) reduces the expected number of
132843** rows visited by a factor of 64.
132844*/
132845static int whereRangeScanEst(
132846  Parse *pParse,       /* Parsing & code generating context */
132847  WhereLoopBuilder *pBuilder,
132848  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
132849  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
132850  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
132851){
132852  int rc = SQLITE_OK;
132853  int nOut = pLoop->nOut;
132854  LogEst nNew;
132855
132856#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
132857  Index *p = pLoop->u.btree.pIndex;
132858  int nEq = pLoop->u.btree.nEq;
132859
132860  if( p->nSample>0 && nEq<p->nSampleCol ){
132861    if( nEq==pBuilder->nRecValid ){
132862      UnpackedRecord *pRec = pBuilder->pRec;
132863      tRowcnt a[2];
132864      int nBtm = pLoop->u.btree.nBtm;
132865      int nTop = pLoop->u.btree.nTop;
132866
132867      /* Variable iLower will be set to the estimate of the number of rows in
132868      ** the index that are less than the lower bound of the range query. The
132869      ** lower bound being the concatenation of $P and $L, where $P is the
132870      ** key-prefix formed by the nEq values matched against the nEq left-most
132871      ** columns of the index, and $L is the value in pLower.
132872      **
132873      ** Or, if pLower is NULL or $L cannot be extracted from it (because it
132874      ** is not a simple variable or literal value), the lower bound of the
132875      ** range is $P. Due to a quirk in the way whereKeyStats() works, even
132876      ** if $L is available, whereKeyStats() is called for both ($P) and
132877      ** ($P:$L) and the larger of the two returned values is used.
132878      **
132879      ** Similarly, iUpper is to be set to the estimate of the number of rows
132880      ** less than the upper bound of the range query. Where the upper bound
132881      ** is either ($P) or ($P:$U). Again, even if $U is available, both values
132882      ** of iUpper are requested of whereKeyStats() and the smaller used.
132883      **
132884      ** The number of rows between the two bounds is then just iUpper-iLower.
132885      */
132886      tRowcnt iLower;     /* Rows less than the lower bound */
132887      tRowcnt iUpper;     /* Rows less than the upper bound */
132888      int iLwrIdx = -2;   /* aSample[] for the lower bound */
132889      int iUprIdx = -1;   /* aSample[] for the upper bound */
132890
132891      if( pRec ){
132892        testcase( pRec->nField!=pBuilder->nRecValid );
132893        pRec->nField = pBuilder->nRecValid;
132894      }
132895      /* Determine iLower and iUpper using ($P) only. */
132896      if( nEq==0 ){
132897        iLower = 0;
132898        iUpper = p->nRowEst0;
132899      }else{
132900        /* Note: this call could be optimized away - since the same values must
132901        ** have been requested when testing key $P in whereEqualScanEst().  */
132902        whereKeyStats(pParse, p, pRec, 0, a);
132903        iLower = a[0];
132904        iUpper = a[0] + a[1];
132905      }
132906
132907      assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
132908      assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
132909      assert( p->aSortOrder!=0 );
132910      if( p->aSortOrder[nEq] ){
132911        /* The roles of pLower and pUpper are swapped for a DESC index */
132912        SWAP(WhereTerm*, pLower, pUpper);
132913        SWAP(int, nBtm, nTop);
132914      }
132915
132916      /* If possible, improve on the iLower estimate using ($P:$L). */
132917      if( pLower ){
132918        int n;                    /* Values extracted from pExpr */
132919        Expr *pExpr = pLower->pExpr->pRight;
132920        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
132921        if( rc==SQLITE_OK && n ){
132922          tRowcnt iNew;
132923          u16 mask = WO_GT|WO_LE;
132924          if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
132925          iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
132926          iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
132927          if( iNew>iLower ) iLower = iNew;
132928          nOut--;
132929          pLower = 0;
132930        }
132931      }
132932
132933      /* If possible, improve on the iUpper estimate using ($P:$U). */
132934      if( pUpper ){
132935        int n;                    /* Values extracted from pExpr */
132936        Expr *pExpr = pUpper->pExpr->pRight;
132937        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
132938        if( rc==SQLITE_OK && n ){
132939          tRowcnt iNew;
132940          u16 mask = WO_GT|WO_LE;
132941          if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
132942          iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
132943          iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
132944          if( iNew<iUpper ) iUpper = iNew;
132945          nOut--;
132946          pUpper = 0;
132947        }
132948      }
132949
132950      pBuilder->pRec = pRec;
132951      if( rc==SQLITE_OK ){
132952        if( iUpper>iLower ){
132953          nNew = sqlite3LogEst(iUpper - iLower);
132954          /* TUNING:  If both iUpper and iLower are derived from the same
132955          ** sample, then assume they are 4x more selective.  This brings
132956          ** the estimated selectivity more in line with what it would be
132957          ** if estimated without the use of STAT3/4 tables. */
132958          if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
132959        }else{
132960          nNew = 10;        assert( 10==sqlite3LogEst(2) );
132961        }
132962        if( nNew<nOut ){
132963          nOut = nNew;
132964        }
132965        WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
132966                           (u32)iLower, (u32)iUpper, nOut));
132967      }
132968    }else{
132969      int bDone = 0;
132970      rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
132971      if( bDone ) return rc;
132972    }
132973  }
132974#else
132975  UNUSED_PARAMETER(pParse);
132976  UNUSED_PARAMETER(pBuilder);
132977  assert( pLower || pUpper );
132978#endif
132979  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
132980  nNew = whereRangeAdjust(pLower, nOut);
132981  nNew = whereRangeAdjust(pUpper, nNew);
132982
132983  /* TUNING: If there is both an upper and lower limit and neither limit
132984  ** has an application-defined likelihood(), assume the range is
132985  ** reduced by an additional 75%. This means that, by default, an open-ended
132986  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
132987  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
132988  ** match 1/64 of the index. */
132989  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
132990    nNew -= 20;
132991  }
132992
132993  nOut -= (pLower!=0) + (pUpper!=0);
132994  if( nNew<10 ) nNew = 10;
132995  if( nNew<nOut ) nOut = nNew;
132996#if defined(WHERETRACE_ENABLED)
132997  if( pLoop->nOut>nOut ){
132998    WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
132999                    pLoop->nOut, nOut));
133000  }
133001#endif
133002  pLoop->nOut = (LogEst)nOut;
133003  return rc;
133004}
133005
133006#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133007/*
133008** Estimate the number of rows that will be returned based on
133009** an equality constraint x=VALUE and where that VALUE occurs in
133010** the histogram data.  This only works when x is the left-most
133011** column of an index and sqlite_stat3 histogram data is available
133012** for that index.  When pExpr==NULL that means the constraint is
133013** "x IS NULL" instead of "x=VALUE".
133014**
133015** Write the estimated row count into *pnRow and return SQLITE_OK.
133016** If unable to make an estimate, leave *pnRow unchanged and return
133017** non-zero.
133018**
133019** This routine can fail if it is unable to load a collating sequence
133020** required for string comparison, or if unable to allocate memory
133021** for a UTF conversion required for comparison.  The error is stored
133022** in the pParse structure.
133023*/
133024static int whereEqualScanEst(
133025  Parse *pParse,       /* Parsing & code generating context */
133026  WhereLoopBuilder *pBuilder,
133027  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
133028  tRowcnt *pnRow       /* Write the revised row estimate here */
133029){
133030  Index *p = pBuilder->pNew->u.btree.pIndex;
133031  int nEq = pBuilder->pNew->u.btree.nEq;
133032  UnpackedRecord *pRec = pBuilder->pRec;
133033  int rc;                   /* Subfunction return code */
133034  tRowcnt a[2];             /* Statistics */
133035  int bOk;
133036
133037  assert( nEq>=1 );
133038  assert( nEq<=p->nColumn );
133039  assert( p->aSample!=0 );
133040  assert( p->nSample>0 );
133041  assert( pBuilder->nRecValid<nEq );
133042
133043  /* If values are not available for all fields of the index to the left
133044  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
133045  if( pBuilder->nRecValid<(nEq-1) ){
133046    return SQLITE_NOTFOUND;
133047  }
133048
133049  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
133050  ** below would return the same value.  */
133051  if( nEq>=p->nColumn ){
133052    *pnRow = 1;
133053    return SQLITE_OK;
133054  }
133055
133056  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
133057  pBuilder->pRec = pRec;
133058  if( rc!=SQLITE_OK ) return rc;
133059  if( bOk==0 ) return SQLITE_NOTFOUND;
133060  pBuilder->nRecValid = nEq;
133061
133062  whereKeyStats(pParse, p, pRec, 0, a);
133063  WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
133064                   p->zName, nEq-1, (int)a[1]));
133065  *pnRow = a[1];
133066
133067  return rc;
133068}
133069#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133070
133071#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133072/*
133073** Estimate the number of rows that will be returned based on
133074** an IN constraint where the right-hand side of the IN operator
133075** is a list of values.  Example:
133076**
133077**        WHERE x IN (1,2,3,4)
133078**
133079** Write the estimated row count into *pnRow and return SQLITE_OK.
133080** If unable to make an estimate, leave *pnRow unchanged and return
133081** non-zero.
133082**
133083** This routine can fail if it is unable to load a collating sequence
133084** required for string comparison, or if unable to allocate memory
133085** for a UTF conversion required for comparison.  The error is stored
133086** in the pParse structure.
133087*/
133088static int whereInScanEst(
133089  Parse *pParse,       /* Parsing & code generating context */
133090  WhereLoopBuilder *pBuilder,
133091  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
133092  tRowcnt *pnRow       /* Write the revised row estimate here */
133093){
133094  Index *p = pBuilder->pNew->u.btree.pIndex;
133095  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
133096  int nRecValid = pBuilder->nRecValid;
133097  int rc = SQLITE_OK;     /* Subfunction return code */
133098  tRowcnt nEst;           /* Number of rows for a single term */
133099  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
133100  int i;                  /* Loop counter */
133101
133102  assert( p->aSample!=0 );
133103  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
133104    nEst = nRow0;
133105    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
133106    nRowEst += nEst;
133107    pBuilder->nRecValid = nRecValid;
133108  }
133109
133110  if( rc==SQLITE_OK ){
133111    if( nRowEst > nRow0 ) nRowEst = nRow0;
133112    *pnRow = nRowEst;
133113    WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
133114  }
133115  assert( pBuilder->nRecValid==nRecValid );
133116  return rc;
133117}
133118#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
133119
133120
133121#ifdef WHERETRACE_ENABLED
133122/*
133123** Print the content of a WhereTerm object
133124*/
133125static void whereTermPrint(WhereTerm *pTerm, int iTerm){
133126  if( pTerm==0 ){
133127    sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
133128  }else{
133129    char zType[4];
133130    char zLeft[50];
133131    memcpy(zType, "...", 4);
133132    if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
133133    if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
133134    if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
133135    if( pTerm->eOperator & WO_SINGLE ){
133136      sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
133137                       pTerm->leftCursor, pTerm->u.leftColumn);
133138    }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
133139      sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
133140                       pTerm->u.pOrInfo->indexable);
133141    }else{
133142      sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
133143    }
133144    sqlite3DebugPrintf(
133145       "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
133146       iTerm, pTerm, zType, zLeft, pTerm->truthProb,
133147       pTerm->eOperator, pTerm->wtFlags);
133148    if( pTerm->iField ){
133149      sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
133150    }else{
133151      sqlite3DebugPrintf("\n");
133152    }
133153    sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
133154  }
133155}
133156#endif
133157
133158#ifdef WHERETRACE_ENABLED
133159/*
133160** Show the complete content of a WhereClause
133161*/
133162SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
133163  int i;
133164  for(i=0; i<pWC->nTerm; i++){
133165    whereTermPrint(&pWC->a[i], i);
133166  }
133167}
133168#endif
133169
133170#ifdef WHERETRACE_ENABLED
133171/*
133172** Print a WhereLoop object for debugging purposes
133173*/
133174static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
133175  WhereInfo *pWInfo = pWC->pWInfo;
133176  int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
133177  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
133178  Table *pTab = pItem->pTab;
133179  Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
133180  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
133181                     p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
133182  sqlite3DebugPrintf(" %12s",
133183                     pItem->zAlias ? pItem->zAlias : pTab->zName);
133184  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
133185    const char *zName;
133186    if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
133187      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
133188        int i = sqlite3Strlen30(zName) - 1;
133189        while( zName[i]!='_' ) i--;
133190        zName += i;
133191      }
133192      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
133193    }else{
133194      sqlite3DebugPrintf("%20s","");
133195    }
133196  }else{
133197    char *z;
133198    if( p->u.vtab.idxStr ){
133199      z = sqlite3_mprintf("(%d,\"%s\",%x)",
133200                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
133201    }else{
133202      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
133203    }
133204    sqlite3DebugPrintf(" %-19s", z);
133205    sqlite3_free(z);
133206  }
133207  if( p->wsFlags & WHERE_SKIPSCAN ){
133208    sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
133209  }else{
133210    sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
133211  }
133212  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
133213  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
133214    int i;
133215    for(i=0; i<p->nLTerm; i++){
133216      whereTermPrint(p->aLTerm[i], i);
133217    }
133218  }
133219}
133220#endif
133221
133222/*
133223** Convert bulk memory into a valid WhereLoop that can be passed
133224** to whereLoopClear harmlessly.
133225*/
133226static void whereLoopInit(WhereLoop *p){
133227  p->aLTerm = p->aLTermSpace;
133228  p->nLTerm = 0;
133229  p->nLSlot = ArraySize(p->aLTermSpace);
133230  p->wsFlags = 0;
133231}
133232
133233/*
133234** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
133235*/
133236static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
133237  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
133238    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
133239      sqlite3_free(p->u.vtab.idxStr);
133240      p->u.vtab.needFree = 0;
133241      p->u.vtab.idxStr = 0;
133242    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
133243      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
133244      sqlite3DbFreeNN(db, p->u.btree.pIndex);
133245      p->u.btree.pIndex = 0;
133246    }
133247  }
133248}
133249
133250/*
133251** Deallocate internal memory used by a WhereLoop object
133252*/
133253static void whereLoopClear(sqlite3 *db, WhereLoop *p){
133254  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
133255  whereLoopClearUnion(db, p);
133256  whereLoopInit(p);
133257}
133258
133259/*
133260** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
133261*/
133262static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
133263  WhereTerm **paNew;
133264  if( p->nLSlot>=n ) return SQLITE_OK;
133265  n = (n+7)&~7;
133266  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
133267  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
133268  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
133269  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
133270  p->aLTerm = paNew;
133271  p->nLSlot = n;
133272  return SQLITE_OK;
133273}
133274
133275/*
133276** Transfer content from the second pLoop into the first.
133277*/
133278static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
133279  whereLoopClearUnion(db, pTo);
133280  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
133281    memset(&pTo->u, 0, sizeof(pTo->u));
133282    return SQLITE_NOMEM_BKPT;
133283  }
133284  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
133285  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
133286  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
133287    pFrom->u.vtab.needFree = 0;
133288  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
133289    pFrom->u.btree.pIndex = 0;
133290  }
133291  return SQLITE_OK;
133292}
133293
133294/*
133295** Delete a WhereLoop object
133296*/
133297static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
133298  whereLoopClear(db, p);
133299  sqlite3DbFreeNN(db, p);
133300}
133301
133302/*
133303** Free a WhereInfo structure
133304*/
133305static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
133306  if( ALWAYS(pWInfo) ){
133307    int i;
133308    for(i=0; i<pWInfo->nLevel; i++){
133309      WhereLevel *pLevel = &pWInfo->a[i];
133310      if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
133311        sqlite3DbFree(db, pLevel->u.in.aInLoop);
133312      }
133313    }
133314    sqlite3WhereClauseClear(&pWInfo->sWC);
133315    while( pWInfo->pLoops ){
133316      WhereLoop *p = pWInfo->pLoops;
133317      pWInfo->pLoops = p->pNextLoop;
133318      whereLoopDelete(db, p);
133319    }
133320    sqlite3DbFreeNN(db, pWInfo);
133321  }
133322}
133323
133324/*
133325** Return TRUE if all of the following are true:
133326**
133327**   (1)  X has the same or lower cost that Y
133328**   (2)  X is a proper subset of Y
133329**   (3)  X skips at least as many columns as Y
133330**
133331** By "proper subset" we mean that X uses fewer WHERE clause terms
133332** than Y and that every WHERE clause term used by X is also used
133333** by Y.
133334**
133335** If X is a proper subset of Y then Y is a better choice and ought
133336** to have a lower cost.  This routine returns TRUE when that cost
133337** relationship is inverted and needs to be adjusted.  The third rule
133338** was added because if X uses skip-scan less than Y it still might
133339** deserve a lower cost even if it is a proper subset of Y.
133340*/
133341static int whereLoopCheaperProperSubset(
133342  const WhereLoop *pX,       /* First WhereLoop to compare */
133343  const WhereLoop *pY        /* Compare against this WhereLoop */
133344){
133345  int i, j;
133346  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
133347    return 0; /* X is not a subset of Y */
133348  }
133349  if( pY->nSkip > pX->nSkip ) return 0;
133350  if( pX->rRun >= pY->rRun ){
133351    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
133352    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
133353  }
133354  for(i=pX->nLTerm-1; i>=0; i--){
133355    if( pX->aLTerm[i]==0 ) continue;
133356    for(j=pY->nLTerm-1; j>=0; j--){
133357      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
133358    }
133359    if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
133360  }
133361  return 1;  /* All conditions meet */
133362}
133363
133364/*
133365** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
133366** that:
133367**
133368**   (1) pTemplate costs less than any other WhereLoops that are a proper
133369**       subset of pTemplate
133370**
133371**   (2) pTemplate costs more than any other WhereLoops for which pTemplate
133372**       is a proper subset.
133373**
133374** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
133375** WHERE clause terms than Y and that every WHERE clause term used by X is
133376** also used by Y.
133377*/
133378static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
133379  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
133380  for(; p; p=p->pNextLoop){
133381    if( p->iTab!=pTemplate->iTab ) continue;
133382    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
133383    if( whereLoopCheaperProperSubset(p, pTemplate) ){
133384      /* Adjust pTemplate cost downward so that it is cheaper than its
133385      ** subset p. */
133386      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
133387                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
133388      pTemplate->rRun = p->rRun;
133389      pTemplate->nOut = p->nOut - 1;
133390    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
133391      /* Adjust pTemplate cost upward so that it is costlier than p since
133392      ** pTemplate is a proper subset of p */
133393      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
133394                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
133395      pTemplate->rRun = p->rRun;
133396      pTemplate->nOut = p->nOut + 1;
133397    }
133398  }
133399}
133400
133401/*
133402** Search the list of WhereLoops in *ppPrev looking for one that can be
133403** replaced by pTemplate.
133404**
133405** Return NULL if pTemplate does not belong on the WhereLoop list.
133406** In other words if pTemplate ought to be dropped from further consideration.
133407**
133408** If pX is a WhereLoop that pTemplate can replace, then return the
133409** link that points to pX.
133410**
133411** If pTemplate cannot replace any existing element of the list but needs
133412** to be added to the list as a new entry, then return a pointer to the
133413** tail of the list.
133414*/
133415static WhereLoop **whereLoopFindLesser(
133416  WhereLoop **ppPrev,
133417  const WhereLoop *pTemplate
133418){
133419  WhereLoop *p;
133420  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
133421    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
133422      /* If either the iTab or iSortIdx values for two WhereLoop are different
133423      ** then those WhereLoops need to be considered separately.  Neither is
133424      ** a candidate to replace the other. */
133425      continue;
133426    }
133427    /* In the current implementation, the rSetup value is either zero
133428    ** or the cost of building an automatic index (NlogN) and the NlogN
133429    ** is the same for compatible WhereLoops. */
133430    assert( p->rSetup==0 || pTemplate->rSetup==0
133431                 || p->rSetup==pTemplate->rSetup );
133432
133433    /* whereLoopAddBtree() always generates and inserts the automatic index
133434    ** case first.  Hence compatible candidate WhereLoops never have a larger
133435    ** rSetup. Call this SETUP-INVARIANT */
133436    assert( p->rSetup>=pTemplate->rSetup );
133437
133438    /* Any loop using an appliation-defined index (or PRIMARY KEY or
133439    ** UNIQUE constraint) with one or more == constraints is better
133440    ** than an automatic index. Unless it is a skip-scan. */
133441    if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
133442     && (pTemplate->nSkip)==0
133443     && (pTemplate->wsFlags & WHERE_INDEXED)!=0
133444     && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
133445     && (p->prereq & pTemplate->prereq)==pTemplate->prereq
133446    ){
133447      break;
133448    }
133449
133450    /* If existing WhereLoop p is better than pTemplate, pTemplate can be
133451    ** discarded.  WhereLoop p is better if:
133452    **   (1)  p has no more dependencies than pTemplate, and
133453    **   (2)  p has an equal or lower cost than pTemplate
133454    */
133455    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
133456     && p->rSetup<=pTemplate->rSetup                  /* (2a) */
133457     && p->rRun<=pTemplate->rRun                      /* (2b) */
133458     && p->nOut<=pTemplate->nOut                      /* (2c) */
133459    ){
133460      return 0;  /* Discard pTemplate */
133461    }
133462
133463    /* If pTemplate is always better than p, then cause p to be overwritten
133464    ** with pTemplate.  pTemplate is better than p if:
133465    **   (1)  pTemplate has no more dependences than p, and
133466    **   (2)  pTemplate has an equal or lower cost than p.
133467    */
133468    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
133469     && p->rRun>=pTemplate->rRun                             /* (2a) */
133470     && p->nOut>=pTemplate->nOut                             /* (2b) */
133471    ){
133472      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
133473      break;   /* Cause p to be overwritten by pTemplate */
133474    }
133475  }
133476  return ppPrev;
133477}
133478
133479/*
133480** Insert or replace a WhereLoop entry using the template supplied.
133481**
133482** An existing WhereLoop entry might be overwritten if the new template
133483** is better and has fewer dependencies.  Or the template will be ignored
133484** and no insert will occur if an existing WhereLoop is faster and has
133485** fewer dependencies than the template.  Otherwise a new WhereLoop is
133486** added based on the template.
133487**
133488** If pBuilder->pOrSet is not NULL then we care about only the
133489** prerequisites and rRun and nOut costs of the N best loops.  That
133490** information is gathered in the pBuilder->pOrSet object.  This special
133491** processing mode is used only for OR clause processing.
133492**
133493** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
133494** still might overwrite similar loops with the new template if the
133495** new template is better.  Loops may be overwritten if the following
133496** conditions are met:
133497**
133498**    (1)  They have the same iTab.
133499**    (2)  They have the same iSortIdx.
133500**    (3)  The template has same or fewer dependencies than the current loop
133501**    (4)  The template has the same or lower cost than the current loop
133502*/
133503static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
133504  WhereLoop **ppPrev, *p;
133505  WhereInfo *pWInfo = pBuilder->pWInfo;
133506  sqlite3 *db = pWInfo->pParse->db;
133507  int rc;
133508
133509  /* If pBuilder->pOrSet is defined, then only keep track of the costs
133510  ** and prereqs.
133511  */
133512  if( pBuilder->pOrSet!=0 ){
133513    if( pTemplate->nLTerm ){
133514#if WHERETRACE_ENABLED
133515      u16 n = pBuilder->pOrSet->n;
133516      int x =
133517#endif
133518      whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
133519                                    pTemplate->nOut);
133520#if WHERETRACE_ENABLED /* 0x8 */
133521      if( sqlite3WhereTrace & 0x8 ){
133522        sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
133523        whereLoopPrint(pTemplate, pBuilder->pWC);
133524      }
133525#endif
133526    }
133527    return SQLITE_OK;
133528  }
133529
133530  /* Look for an existing WhereLoop to replace with pTemplate
133531  */
133532  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
133533  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
133534
133535  if( ppPrev==0 ){
133536    /* There already exists a WhereLoop on the list that is better
133537    ** than pTemplate, so just ignore pTemplate */
133538#if WHERETRACE_ENABLED /* 0x8 */
133539    if( sqlite3WhereTrace & 0x8 ){
133540      sqlite3DebugPrintf("   skip: ");
133541      whereLoopPrint(pTemplate, pBuilder->pWC);
133542    }
133543#endif
133544    return SQLITE_OK;
133545  }else{
133546    p = *ppPrev;
133547  }
133548
133549  /* If we reach this point it means that either p[] should be overwritten
133550  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
133551  ** WhereLoop and insert it.
133552  */
133553#if WHERETRACE_ENABLED /* 0x8 */
133554  if( sqlite3WhereTrace & 0x8 ){
133555    if( p!=0 ){
133556      sqlite3DebugPrintf("replace: ");
133557      whereLoopPrint(p, pBuilder->pWC);
133558      sqlite3DebugPrintf("   with: ");
133559    }else{
133560      sqlite3DebugPrintf("    add: ");
133561    }
133562    whereLoopPrint(pTemplate, pBuilder->pWC);
133563  }
133564#endif
133565  if( p==0 ){
133566    /* Allocate a new WhereLoop to add to the end of the list */
133567    *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
133568    if( p==0 ) return SQLITE_NOMEM_BKPT;
133569    whereLoopInit(p);
133570    p->pNextLoop = 0;
133571  }else{
133572    /* We will be overwriting WhereLoop p[].  But before we do, first
133573    ** go through the rest of the list and delete any other entries besides
133574    ** p[] that are also supplated by pTemplate */
133575    WhereLoop **ppTail = &p->pNextLoop;
133576    WhereLoop *pToDel;
133577    while( *ppTail ){
133578      ppTail = whereLoopFindLesser(ppTail, pTemplate);
133579      if( ppTail==0 ) break;
133580      pToDel = *ppTail;
133581      if( pToDel==0 ) break;
133582      *ppTail = pToDel->pNextLoop;
133583#if WHERETRACE_ENABLED /* 0x8 */
133584      if( sqlite3WhereTrace & 0x8 ){
133585        sqlite3DebugPrintf(" delete: ");
133586        whereLoopPrint(pToDel, pBuilder->pWC);
133587      }
133588#endif
133589      whereLoopDelete(db, pToDel);
133590    }
133591  }
133592  rc = whereLoopXfer(db, p, pTemplate);
133593  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
133594    Index *pIndex = p->u.btree.pIndex;
133595    if( pIndex && pIndex->tnum==0 ){
133596      p->u.btree.pIndex = 0;
133597    }
133598  }
133599  return rc;
133600}
133601
133602/*
133603** Adjust the WhereLoop.nOut value downward to account for terms of the
133604** WHERE clause that reference the loop but which are not used by an
133605** index.
133606*
133607** For every WHERE clause term that is not used by the index
133608** and which has a truth probability assigned by one of the likelihood(),
133609** likely(), or unlikely() SQL functions, reduce the estimated number
133610** of output rows by the probability specified.
133611**
133612** TUNING:  For every WHERE clause term that is not used by the index
133613** and which does not have an assigned truth probability, heuristics
133614** described below are used to try to estimate the truth probability.
133615** TODO --> Perhaps this is something that could be improved by better
133616** table statistics.
133617**
133618** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
133619** value corresponds to -1 in LogEst notation, so this means decrement
133620** the WhereLoop.nOut field for every such WHERE clause term.
133621**
133622** Heuristic 2:  If there exists one or more WHERE clause terms of the
133623** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
133624** final output row estimate is no greater than 1/4 of the total number
133625** of rows in the table.  In other words, assume that x==EXPR will filter
133626** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
133627** "x" column is boolean or else -1 or 0 or 1 is a common default value
133628** on the "x" column and so in that case only cap the output row estimate
133629** at 1/2 instead of 1/4.
133630*/
133631static void whereLoopOutputAdjust(
133632  WhereClause *pWC,      /* The WHERE clause */
133633  WhereLoop *pLoop,      /* The loop to adjust downward */
133634  LogEst nRow            /* Number of rows in the entire table */
133635){
133636  WhereTerm *pTerm, *pX;
133637  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
133638  int i, j, k;
133639  LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
133640
133641  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
133642  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
133643    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
133644    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
133645    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
133646    for(j=pLoop->nLTerm-1; j>=0; j--){
133647      pX = pLoop->aLTerm[j];
133648      if( pX==0 ) continue;
133649      if( pX==pTerm ) break;
133650      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
133651    }
133652    if( j<0 ){
133653      if( pTerm->truthProb<=0 ){
133654        /* If a truth probability is specified using the likelihood() hints,
133655        ** then use the probability provided by the application. */
133656        pLoop->nOut += pTerm->truthProb;
133657      }else{
133658        /* In the absence of explicit truth probabilities, use heuristics to
133659        ** guess a reasonable truth probability. */
133660        pLoop->nOut--;
133661        if( pTerm->eOperator&(WO_EQ|WO_IS) ){
133662          Expr *pRight = pTerm->pExpr->pRight;
133663          testcase( pTerm->pExpr->op==TK_IS );
133664          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
133665            k = 10;
133666          }else{
133667            k = 20;
133668          }
133669          if( iReduce<k ) iReduce = k;
133670        }
133671      }
133672    }
133673  }
133674  if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
133675}
133676
133677/*
133678** Term pTerm is a vector range comparison operation. The first comparison
133679** in the vector can be optimized using column nEq of the index. This
133680** function returns the total number of vector elements that can be used
133681** as part of the range comparison.
133682**
133683** For example, if the query is:
133684**
133685**   WHERE a = ? AND (b, c, d) > (?, ?, ?)
133686**
133687** and the index:
133688**
133689**   CREATE INDEX ... ON (a, b, c, d, e)
133690**
133691** then this function would be invoked with nEq=1. The value returned in
133692** this case is 3.
133693*/
133694static int whereRangeVectorLen(
133695  Parse *pParse,       /* Parsing context */
133696  int iCur,            /* Cursor open on pIdx */
133697  Index *pIdx,         /* The index to be used for a inequality constraint */
133698  int nEq,             /* Number of prior equality constraints on same index */
133699  WhereTerm *pTerm     /* The vector inequality constraint */
133700){
133701  int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
133702  int i;
133703
133704  nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
133705  for(i=1; i<nCmp; i++){
133706    /* Test if comparison i of pTerm is compatible with column (i+nEq)
133707    ** of the index. If not, exit the loop.  */
133708    char aff;                     /* Comparison affinity */
133709    char idxaff = 0;              /* Indexed columns affinity */
133710    CollSeq *pColl;               /* Comparison collation sequence */
133711    Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
133712    Expr *pRhs = pTerm->pExpr->pRight;
133713    if( pRhs->flags & EP_xIsSelect ){
133714      pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
133715    }else{
133716      pRhs = pRhs->x.pList->a[i].pExpr;
133717    }
133718
133719    /* Check that the LHS of the comparison is a column reference to
133720    ** the right column of the right source table. And that the sort
133721    ** order of the index column is the same as the sort order of the
133722    ** leftmost index column.  */
133723    if( pLhs->op!=TK_COLUMN
133724     || pLhs->iTable!=iCur
133725     || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
133726     || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
133727    ){
133728      break;
133729    }
133730
133731    testcase( pLhs->iColumn==XN_ROWID );
133732    aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
133733    idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
133734    if( aff!=idxaff ) break;
133735
133736    pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
133737    if( pColl==0 ) break;
133738    if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
133739  }
133740  return i;
133741}
133742
133743/*
133744** Adjust the cost C by the costMult facter T.  This only occurs if
133745** compiled with -DSQLITE_ENABLE_COSTMULT
133746*/
133747#ifdef SQLITE_ENABLE_COSTMULT
133748# define ApplyCostMultiplier(C,T)  C += T
133749#else
133750# define ApplyCostMultiplier(C,T)
133751#endif
133752
133753/*
133754** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
133755** index pIndex. Try to match one more.
133756**
133757** When this function is called, pBuilder->pNew->nOut contains the
133758** number of rows expected to be visited by filtering using the nEq
133759** terms only. If it is modified, this value is restored before this
133760** function returns.
133761**
133762** If pProbe->tnum==0, that means pIndex is a fake index used for the
133763** INTEGER PRIMARY KEY.
133764*/
133765static int whereLoopAddBtreeIndex(
133766  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
133767  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
133768  Index *pProbe,                  /* An index on pSrc */
133769  LogEst nInMul                   /* log(Number of iterations due to IN) */
133770){
133771  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
133772  Parse *pParse = pWInfo->pParse;        /* Parsing context */
133773  sqlite3 *db = pParse->db;       /* Database connection malloc context */
133774  WhereLoop *pNew;                /* Template WhereLoop under construction */
133775  WhereTerm *pTerm;               /* A WhereTerm under consideration */
133776  int opMask;                     /* Valid operators for constraints */
133777  WhereScan scan;                 /* Iterator for WHERE terms */
133778  Bitmask saved_prereq;           /* Original value of pNew->prereq */
133779  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
133780  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
133781  u16 saved_nBtm;                 /* Original value of pNew->u.btree.nBtm */
133782  u16 saved_nTop;                 /* Original value of pNew->u.btree.nTop */
133783  u16 saved_nSkip;                /* Original value of pNew->nSkip */
133784  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
133785  LogEst saved_nOut;              /* Original value of pNew->nOut */
133786  int rc = SQLITE_OK;             /* Return code */
133787  LogEst rSize;                   /* Number of rows in the table */
133788  LogEst rLogSize;                /* Logarithm of table size */
133789  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
133790
133791  pNew = pBuilder->pNew;
133792  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
133793  WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
133794                     pProbe->zName, pNew->u.btree.nEq));
133795
133796  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
133797  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
133798  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
133799    opMask = WO_LT|WO_LE;
133800  }else{
133801    assert( pNew->u.btree.nBtm==0 );
133802    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
133803  }
133804  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
133805
133806  assert( pNew->u.btree.nEq<pProbe->nColumn );
133807
133808  saved_nEq = pNew->u.btree.nEq;
133809  saved_nBtm = pNew->u.btree.nBtm;
133810  saved_nTop = pNew->u.btree.nTop;
133811  saved_nSkip = pNew->nSkip;
133812  saved_nLTerm = pNew->nLTerm;
133813  saved_wsFlags = pNew->wsFlags;
133814  saved_prereq = pNew->prereq;
133815  saved_nOut = pNew->nOut;
133816  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
133817                        opMask, pProbe);
133818  pNew->rSetup = 0;
133819  rSize = pProbe->aiRowLogEst[0];
133820  rLogSize = estLog(rSize);
133821  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
133822    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
133823    LogEst rCostIdx;
133824    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
133825    int nIn = 0;
133826#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133827    int nRecValid = pBuilder->nRecValid;
133828#endif
133829    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
133830     && indexColumnNotNull(pProbe, saved_nEq)
133831    ){
133832      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
133833    }
133834    if( pTerm->prereqRight & pNew->maskSelf ) continue;
133835
133836    /* Do not allow the upper bound of a LIKE optimization range constraint
133837    ** to mix with a lower range bound from some other source */
133838    if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
133839
133840    /* Do not allow IS constraints from the WHERE clause to be used by the
133841    ** right table of a LEFT JOIN.  Only constraints in the ON clause are
133842    ** allowed */
133843    if( (pSrc->fg.jointype & JT_LEFT)!=0
133844     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
133845     && (eOp & (WO_IS|WO_ISNULL))!=0
133846    ){
133847      testcase( eOp & WO_IS );
133848      testcase( eOp & WO_ISNULL );
133849      continue;
133850    }
133851
133852    if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
133853      pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
133854    }else{
133855      pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
133856    }
133857    pNew->wsFlags = saved_wsFlags;
133858    pNew->u.btree.nEq = saved_nEq;
133859    pNew->u.btree.nBtm = saved_nBtm;
133860    pNew->u.btree.nTop = saved_nTop;
133861    pNew->nLTerm = saved_nLTerm;
133862    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
133863    pNew->aLTerm[pNew->nLTerm++] = pTerm;
133864    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
133865
133866    assert( nInMul==0
133867        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
133868        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
133869        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
133870    );
133871
133872    if( eOp & WO_IN ){
133873      Expr *pExpr = pTerm->pExpr;
133874      pNew->wsFlags |= WHERE_COLUMN_IN;
133875      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
133876        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
133877        int i;
133878        nIn = 46;  assert( 46==sqlite3LogEst(25) );
133879
133880        /* The expression may actually be of the form (x, y) IN (SELECT...).
133881        ** In this case there is a separate term for each of (x) and (y).
133882        ** However, the nIn multiplier should only be applied once, not once
133883        ** for each such term. The following loop checks that pTerm is the
133884        ** first such term in use, and sets nIn back to 0 if it is not. */
133885        for(i=0; i<pNew->nLTerm-1; i++){
133886          if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
133887        }
133888      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
133889        /* "x IN (value, value, ...)" */
133890        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
133891        assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
133892                          ** changes "x IN (?)" into "x=?". */
133893      }
133894    }else if( eOp & (WO_EQ|WO_IS) ){
133895      int iCol = pProbe->aiColumn[saved_nEq];
133896      pNew->wsFlags |= WHERE_COLUMN_EQ;
133897      assert( saved_nEq==pNew->u.btree.nEq );
133898      if( iCol==XN_ROWID
133899       || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
133900      ){
133901        if( iCol>=0 && pProbe->uniqNotNull==0 ){
133902          pNew->wsFlags |= WHERE_UNQ_WANTED;
133903        }else{
133904          pNew->wsFlags |= WHERE_ONEROW;
133905        }
133906      }
133907    }else if( eOp & WO_ISNULL ){
133908      pNew->wsFlags |= WHERE_COLUMN_NULL;
133909    }else if( eOp & (WO_GT|WO_GE) ){
133910      testcase( eOp & WO_GT );
133911      testcase( eOp & WO_GE );
133912      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
133913      pNew->u.btree.nBtm = whereRangeVectorLen(
133914          pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
133915      );
133916      pBtm = pTerm;
133917      pTop = 0;
133918      if( pTerm->wtFlags & TERM_LIKEOPT ){
133919        /* Range contraints that come from the LIKE optimization are
133920        ** always used in pairs. */
133921        pTop = &pTerm[1];
133922        assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
133923        assert( pTop->wtFlags & TERM_LIKEOPT );
133924        assert( pTop->eOperator==WO_LT );
133925        if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
133926        pNew->aLTerm[pNew->nLTerm++] = pTop;
133927        pNew->wsFlags |= WHERE_TOP_LIMIT;
133928        pNew->u.btree.nTop = 1;
133929      }
133930    }else{
133931      assert( eOp & (WO_LT|WO_LE) );
133932      testcase( eOp & WO_LT );
133933      testcase( eOp & WO_LE );
133934      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
133935      pNew->u.btree.nTop = whereRangeVectorLen(
133936          pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
133937      );
133938      pTop = pTerm;
133939      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
133940                     pNew->aLTerm[pNew->nLTerm-2] : 0;
133941    }
133942
133943    /* At this point pNew->nOut is set to the number of rows expected to
133944    ** be visited by the index scan before considering term pTerm, or the
133945    ** values of nIn and nInMul. In other words, assuming that all
133946    ** "x IN(...)" terms are replaced with "x = ?". This block updates
133947    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
133948    assert( pNew->nOut==saved_nOut );
133949    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
133950      /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
133951      ** data, using some other estimate.  */
133952      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
133953    }else{
133954      int nEq = ++pNew->u.btree.nEq;
133955      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
133956
133957      assert( pNew->nOut==saved_nOut );
133958      if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
133959        assert( (eOp & WO_IN) || nIn==0 );
133960        testcase( eOp & WO_IN );
133961        pNew->nOut += pTerm->truthProb;
133962        pNew->nOut -= nIn;
133963      }else{
133964#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
133965        tRowcnt nOut = 0;
133966        if( nInMul==0
133967         && pProbe->nSample
133968         && pNew->u.btree.nEq<=pProbe->nSampleCol
133969         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
133970        ){
133971          Expr *pExpr = pTerm->pExpr;
133972          if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
133973            testcase( eOp & WO_EQ );
133974            testcase( eOp & WO_IS );
133975            testcase( eOp & WO_ISNULL );
133976            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
133977          }else{
133978            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
133979          }
133980          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
133981          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
133982          if( nOut ){
133983            pNew->nOut = sqlite3LogEst(nOut);
133984            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
133985            pNew->nOut -= nIn;
133986          }
133987        }
133988        if( nOut==0 )
133989#endif
133990        {
133991          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
133992          if( eOp & WO_ISNULL ){
133993            /* TUNING: If there is no likelihood() value, assume that a
133994            ** "col IS NULL" expression matches twice as many rows
133995            ** as (col=?). */
133996            pNew->nOut += 10;
133997          }
133998        }
133999      }
134000    }
134001
134002    /* Set rCostIdx to the cost of visiting selected rows in index. Add
134003    ** it to pNew->rRun, which is currently set to the cost of the index
134004    ** seek only. Then, if this is a non-covering index, add the cost of
134005    ** visiting the rows in the main table.  */
134006    rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
134007    pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
134008    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
134009      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
134010    }
134011    ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
134012
134013    nOutUnadjusted = pNew->nOut;
134014    pNew->rRun += nInMul + nIn;
134015    pNew->nOut += nInMul + nIn;
134016    whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
134017    rc = whereLoopInsert(pBuilder, pNew);
134018
134019    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
134020      pNew->nOut = saved_nOut;
134021    }else{
134022      pNew->nOut = nOutUnadjusted;
134023    }
134024
134025    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
134026     && pNew->u.btree.nEq<pProbe->nColumn
134027    ){
134028      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
134029    }
134030    pNew->nOut = saved_nOut;
134031#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134032    pBuilder->nRecValid = nRecValid;
134033#endif
134034  }
134035  pNew->prereq = saved_prereq;
134036  pNew->u.btree.nEq = saved_nEq;
134037  pNew->u.btree.nBtm = saved_nBtm;
134038  pNew->u.btree.nTop = saved_nTop;
134039  pNew->nSkip = saved_nSkip;
134040  pNew->wsFlags = saved_wsFlags;
134041  pNew->nOut = saved_nOut;
134042  pNew->nLTerm = saved_nLTerm;
134043
134044  /* Consider using a skip-scan if there are no WHERE clause constraints
134045  ** available for the left-most terms of the index, and if the average
134046  ** number of repeats in the left-most terms is at least 18.
134047  **
134048  ** The magic number 18 is selected on the basis that scanning 17 rows
134049  ** is almost always quicker than an index seek (even though if the index
134050  ** contains fewer than 2^17 rows we assume otherwise in other parts of
134051  ** the code). And, even if it is not, it should not be too much slower.
134052  ** On the other hand, the extra seeks could end up being significantly
134053  ** more expensive.  */
134054  assert( 42==sqlite3LogEst(18) );
134055  if( saved_nEq==saved_nSkip
134056   && saved_nEq+1<pProbe->nKeyCol
134057   && pProbe->noSkipScan==0
134058   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
134059   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
134060  ){
134061    LogEst nIter;
134062    pNew->u.btree.nEq++;
134063    pNew->nSkip++;
134064    pNew->aLTerm[pNew->nLTerm++] = 0;
134065    pNew->wsFlags |= WHERE_SKIPSCAN;
134066    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
134067    pNew->nOut -= nIter;
134068    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
134069    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
134070    nIter += 5;
134071    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
134072    pNew->nOut = saved_nOut;
134073    pNew->u.btree.nEq = saved_nEq;
134074    pNew->nSkip = saved_nSkip;
134075    pNew->wsFlags = saved_wsFlags;
134076  }
134077
134078  WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
134079                      pProbe->zName, saved_nEq, rc));
134080  return rc;
134081}
134082
134083/*
134084** Return True if it is possible that pIndex might be useful in
134085** implementing the ORDER BY clause in pBuilder.
134086**
134087** Return False if pBuilder does not contain an ORDER BY clause or
134088** if there is no way for pIndex to be useful in implementing that
134089** ORDER BY clause.
134090*/
134091static int indexMightHelpWithOrderBy(
134092  WhereLoopBuilder *pBuilder,
134093  Index *pIndex,
134094  int iCursor
134095){
134096  ExprList *pOB;
134097  ExprList *aColExpr;
134098  int ii, jj;
134099
134100  if( pIndex->bUnordered ) return 0;
134101  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
134102  for(ii=0; ii<pOB->nExpr; ii++){
134103    Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
134104    if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
134105      if( pExpr->iColumn<0 ) return 1;
134106      for(jj=0; jj<pIndex->nKeyCol; jj++){
134107        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
134108      }
134109    }else if( (aColExpr = pIndex->aColExpr)!=0 ){
134110      for(jj=0; jj<pIndex->nKeyCol; jj++){
134111        if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
134112        if( sqlite3ExprCompare(0, pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
134113          return 1;
134114        }
134115      }
134116    }
134117  }
134118  return 0;
134119}
134120
134121/*
134122** Return a bitmask where 1s indicate that the corresponding column of
134123** the table is used by an index.  Only the first 63 columns are considered.
134124*/
134125static Bitmask columnsInIndex(Index *pIdx){
134126  Bitmask m = 0;
134127  int j;
134128  for(j=pIdx->nColumn-1; j>=0; j--){
134129    int x = pIdx->aiColumn[j];
134130    if( x>=0 ){
134131      testcase( x==BMS-1 );
134132      testcase( x==BMS-2 );
134133      if( x<BMS-1 ) m |= MASKBIT(x);
134134    }
134135  }
134136  return m;
134137}
134138
134139/* Check to see if a partial index with pPartIndexWhere can be used
134140** in the current query.  Return true if it can be and false if not.
134141*/
134142static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
134143  int i;
134144  WhereTerm *pTerm;
134145  Parse *pParse = pWC->pWInfo->pParse;
134146  while( pWhere->op==TK_AND ){
134147    if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
134148    pWhere = pWhere->pRight;
134149  }
134150  if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
134151  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
134152    Expr *pExpr = pTerm->pExpr;
134153    if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
134154     && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
134155    ){
134156      return 1;
134157    }
134158  }
134159  return 0;
134160}
134161
134162/*
134163** Add all WhereLoop objects for a single table of the join where the table
134164** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be
134165** a b-tree table, not a virtual table.
134166**
134167** The costs (WhereLoop.rRun) of the b-tree loops added by this function
134168** are calculated as follows:
134169**
134170** For a full scan, assuming the table (or index) contains nRow rows:
134171**
134172**     cost = nRow * 3.0                    // full-table scan
134173**     cost = nRow * K                      // scan of covering index
134174**     cost = nRow * (K+3.0)                // scan of non-covering index
134175**
134176** where K is a value between 1.1 and 3.0 set based on the relative
134177** estimated average size of the index and table records.
134178**
134179** For an index scan, where nVisit is the number of index rows visited
134180** by the scan, and nSeek is the number of seek operations required on
134181** the index b-tree:
134182**
134183**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
134184**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
134185**
134186** Normally, nSeek is 1. nSeek values greater than 1 come about if the
134187** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
134188** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
134189**
134190** The estimated values (nRow, nVisit, nSeek) often contain a large amount
134191** of uncertainty.  For this reason, scoring is designed to pick plans that
134192** "do the least harm" if the estimates are inaccurate.  For example, a
134193** log(nRow) factor is omitted from a non-covering index scan in order to
134194** bias the scoring in favor of using an index, since the worst-case
134195** performance of using an index is far better than the worst-case performance
134196** of a full table scan.
134197*/
134198static int whereLoopAddBtree(
134199  WhereLoopBuilder *pBuilder, /* WHERE clause information */
134200  Bitmask mPrereq             /* Extra prerequesites for using this table */
134201){
134202  WhereInfo *pWInfo;          /* WHERE analysis context */
134203  Index *pProbe;              /* An index we are evaluating */
134204  Index sPk;                  /* A fake index object for the primary key */
134205  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
134206  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
134207  SrcList *pTabList;          /* The FROM clause */
134208  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
134209  WhereLoop *pNew;            /* Template WhereLoop object */
134210  int rc = SQLITE_OK;         /* Return code */
134211  int iSortIdx = 1;           /* Index number */
134212  int b;                      /* A boolean value */
134213  LogEst rSize;               /* number of rows in the table */
134214  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
134215  WhereClause *pWC;           /* The parsed WHERE clause */
134216  Table *pTab;                /* Table being queried */
134217
134218  pNew = pBuilder->pNew;
134219  pWInfo = pBuilder->pWInfo;
134220  pTabList = pWInfo->pTabList;
134221  pSrc = pTabList->a + pNew->iTab;
134222  pTab = pSrc->pTab;
134223  pWC = pBuilder->pWC;
134224  assert( !IsVirtual(pSrc->pTab) );
134225
134226  if( pSrc->pIBIndex ){
134227    /* An INDEXED BY clause specifies a particular index to use */
134228    pProbe = pSrc->pIBIndex;
134229  }else if( !HasRowid(pTab) ){
134230    pProbe = pTab->pIndex;
134231  }else{
134232    /* There is no INDEXED BY clause.  Create a fake Index object in local
134233    ** variable sPk to represent the rowid primary key index.  Make this
134234    ** fake index the first in a chain of Index objects with all of the real
134235    ** indices to follow */
134236    Index *pFirst;                  /* First of real indices on the table */
134237    memset(&sPk, 0, sizeof(Index));
134238    sPk.nKeyCol = 1;
134239    sPk.nColumn = 1;
134240    sPk.aiColumn = &aiColumnPk;
134241    sPk.aiRowLogEst = aiRowEstPk;
134242    sPk.onError = OE_Replace;
134243    sPk.pTable = pTab;
134244    sPk.szIdxRow = pTab->szTabRow;
134245    aiRowEstPk[0] = pTab->nRowLogEst;
134246    aiRowEstPk[1] = 0;
134247    pFirst = pSrc->pTab->pIndex;
134248    if( pSrc->fg.notIndexed==0 ){
134249      /* The real indices of the table are only considered if the
134250      ** NOT INDEXED qualifier is omitted from the FROM clause */
134251      sPk.pNext = pFirst;
134252    }
134253    pProbe = &sPk;
134254  }
134255  rSize = pTab->nRowLogEst;
134256  rLogSize = estLog(rSize);
134257
134258#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
134259  /* Automatic indexes */
134260  if( !pBuilder->pOrSet      /* Not part of an OR optimization */
134261   && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
134262   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
134263   && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
134264   && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
134265   && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
134266   && !pSrc->fg.isCorrelated /* Not a correlated subquery */
134267   && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
134268  ){
134269    /* Generate auto-index WhereLoops */
134270    WhereTerm *pTerm;
134271    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
134272    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
134273      if( pTerm->prereqRight & pNew->maskSelf ) continue;
134274      if( termCanDriveIndex(pTerm, pSrc, 0) ){
134275        pNew->u.btree.nEq = 1;
134276        pNew->nSkip = 0;
134277        pNew->u.btree.pIndex = 0;
134278        pNew->nLTerm = 1;
134279        pNew->aLTerm[0] = pTerm;
134280        /* TUNING: One-time cost for computing the automatic index is
134281        ** estimated to be X*N*log2(N) where N is the number of rows in
134282        ** the table being indexed and where X is 7 (LogEst=28) for normal
134283        ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
134284        ** of X is smaller for views and subqueries so that the query planner
134285        ** will be more aggressive about generating automatic indexes for
134286        ** those objects, since there is no opportunity to add schema
134287        ** indexes on subqueries and views. */
134288        pNew->rSetup = rLogSize + rSize + 4;
134289        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
134290          pNew->rSetup += 24;
134291        }
134292        ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
134293        if( pNew->rSetup<0 ) pNew->rSetup = 0;
134294        /* TUNING: Each index lookup yields 20 rows in the table.  This
134295        ** is more than the usual guess of 10 rows, since we have no way
134296        ** of knowing how selective the index will ultimately be.  It would
134297        ** not be unreasonable to make this value much larger. */
134298        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
134299        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
134300        pNew->wsFlags = WHERE_AUTO_INDEX;
134301        pNew->prereq = mPrereq | pTerm->prereqRight;
134302        rc = whereLoopInsert(pBuilder, pNew);
134303      }
134304    }
134305  }
134306#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
134307
134308  /* Loop over all indices
134309  */
134310  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
134311    if( pProbe->pPartIdxWhere!=0
134312     && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
134313      testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
134314      continue;  /* Partial index inappropriate for this query */
134315    }
134316    rSize = pProbe->aiRowLogEst[0];
134317    pNew->u.btree.nEq = 0;
134318    pNew->u.btree.nBtm = 0;
134319    pNew->u.btree.nTop = 0;
134320    pNew->nSkip = 0;
134321    pNew->nLTerm = 0;
134322    pNew->iSortIdx = 0;
134323    pNew->rSetup = 0;
134324    pNew->prereq = mPrereq;
134325    pNew->nOut = rSize;
134326    pNew->u.btree.pIndex = pProbe;
134327    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
134328    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
134329    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
134330    if( pProbe->tnum<=0 ){
134331      /* Integer primary key index */
134332      pNew->wsFlags = WHERE_IPK;
134333
134334      /* Full table scan */
134335      pNew->iSortIdx = b ? iSortIdx : 0;
134336      /* TUNING: Cost of full table scan is (N*3.0). */
134337      pNew->rRun = rSize + 16;
134338      ApplyCostMultiplier(pNew->rRun, pTab->costMult);
134339      whereLoopOutputAdjust(pWC, pNew, rSize);
134340      rc = whereLoopInsert(pBuilder, pNew);
134341      pNew->nOut = rSize;
134342      if( rc ) break;
134343    }else{
134344      Bitmask m;
134345      if( pProbe->isCovering ){
134346        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
134347        m = 0;
134348      }else{
134349        m = pSrc->colUsed & ~columnsInIndex(pProbe);
134350        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
134351      }
134352
134353      /* Full scan via index */
134354      if( b
134355       || !HasRowid(pTab)
134356       || pProbe->pPartIdxWhere!=0
134357       || ( m==0
134358         && pProbe->bUnordered==0
134359         && (pProbe->szIdxRow<pTab->szTabRow)
134360         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
134361         && sqlite3GlobalConfig.bUseCis
134362         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
134363          )
134364      ){
134365        pNew->iSortIdx = b ? iSortIdx : 0;
134366
134367        /* The cost of visiting the index rows is N*K, where K is
134368        ** between 1.1 and 3.0, depending on the relative sizes of the
134369        ** index and table rows. */
134370        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
134371        if( m!=0 ){
134372          /* If this is a non-covering index scan, add in the cost of
134373          ** doing table lookups.  The cost will be 3x the number of
134374          ** lookups.  Take into account WHERE clause terms that can be
134375          ** satisfied using just the index, and that do not require a
134376          ** table lookup. */
134377          LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
134378          int ii;
134379          int iCur = pSrc->iCursor;
134380          WhereClause *pWC2 = &pWInfo->sWC;
134381          for(ii=0; ii<pWC2->nTerm; ii++){
134382            WhereTerm *pTerm = &pWC2->a[ii];
134383            if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
134384              break;
134385            }
134386            /* pTerm can be evaluated using just the index.  So reduce
134387            ** the expected number of table lookups accordingly */
134388            if( pTerm->truthProb<=0 ){
134389              nLookup += pTerm->truthProb;
134390            }else{
134391              nLookup--;
134392              if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
134393            }
134394          }
134395
134396          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
134397        }
134398        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
134399        whereLoopOutputAdjust(pWC, pNew, rSize);
134400        rc = whereLoopInsert(pBuilder, pNew);
134401        pNew->nOut = rSize;
134402        if( rc ) break;
134403      }
134404    }
134405
134406    pBuilder->bldFlags = 0;
134407    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
134408    if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
134409      /* If a non-unique index is used, or if a prefix of the key for
134410      ** unique index is used (making the index functionally non-unique)
134411      ** then the sqlite_stat1 data becomes important for scoring the
134412      ** plan */
134413      pTab->tabFlags |= TF_StatsUsed;
134414    }
134415#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
134416    sqlite3Stat4ProbeFree(pBuilder->pRec);
134417    pBuilder->nRecValid = 0;
134418    pBuilder->pRec = 0;
134419#endif
134420
134421    /* If there was an INDEXED BY clause, then only that one index is
134422    ** considered. */
134423    if( pSrc->pIBIndex ) break;
134424  }
134425  return rc;
134426}
134427
134428#ifndef SQLITE_OMIT_VIRTUALTABLE
134429
134430/*
134431** Argument pIdxInfo is already populated with all constraints that may
134432** be used by the virtual table identified by pBuilder->pNew->iTab. This
134433** function marks a subset of those constraints usable, invokes the
134434** xBestIndex method and adds the returned plan to pBuilder.
134435**
134436** A constraint is marked usable if:
134437**
134438**   * Argument mUsable indicates that its prerequisites are available, and
134439**
134440**   * It is not one of the operators specified in the mExclude mask passed
134441**     as the fourth argument (which in practice is either WO_IN or 0).
134442**
134443** Argument mPrereq is a mask of tables that must be scanned before the
134444** virtual table in question. These are added to the plans prerequisites
134445** before it is added to pBuilder.
134446**
134447** Output parameter *pbIn is set to true if the plan added to pBuilder
134448** uses one or more WO_IN terms, or false otherwise.
134449*/
134450static int whereLoopAddVirtualOne(
134451  WhereLoopBuilder *pBuilder,
134452  Bitmask mPrereq,                /* Mask of tables that must be used. */
134453  Bitmask mUsable,                /* Mask of usable tables */
134454  u16 mExclude,                   /* Exclude terms using these operators */
134455  sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
134456  u16 mNoOmit,                    /* Do not omit these constraints */
134457  int *pbIn                       /* OUT: True if plan uses an IN(...) op */
134458){
134459  WhereClause *pWC = pBuilder->pWC;
134460  struct sqlite3_index_constraint *pIdxCons;
134461  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
134462  int i;
134463  int mxTerm;
134464  int rc = SQLITE_OK;
134465  WhereLoop *pNew = pBuilder->pNew;
134466  Parse *pParse = pBuilder->pWInfo->pParse;
134467  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
134468  int nConstraint = pIdxInfo->nConstraint;
134469
134470  assert( (mUsable & mPrereq)==mPrereq );
134471  *pbIn = 0;
134472  pNew->prereq = mPrereq;
134473
134474  /* Set the usable flag on the subset of constraints identified by
134475  ** arguments mUsable and mExclude. */
134476  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
134477  for(i=0; i<nConstraint; i++, pIdxCons++){
134478    WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
134479    pIdxCons->usable = 0;
134480    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
134481     && (pTerm->eOperator & mExclude)==0
134482    ){
134483      pIdxCons->usable = 1;
134484    }
134485  }
134486
134487  /* Initialize the output fields of the sqlite3_index_info structure */
134488  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
134489  assert( pIdxInfo->needToFreeIdxStr==0 );
134490  pIdxInfo->idxStr = 0;
134491  pIdxInfo->idxNum = 0;
134492  pIdxInfo->orderByConsumed = 0;
134493  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
134494  pIdxInfo->estimatedRows = 25;
134495  pIdxInfo->idxFlags = 0;
134496  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
134497
134498  /* Invoke the virtual table xBestIndex() method */
134499  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
134500  if( rc ) return rc;
134501
134502  mxTerm = -1;
134503  assert( pNew->nLSlot>=nConstraint );
134504  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
134505  pNew->u.vtab.omitMask = 0;
134506  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
134507  for(i=0; i<nConstraint; i++, pIdxCons++){
134508    int iTerm;
134509    if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
134510      WhereTerm *pTerm;
134511      int j = pIdxCons->iTermOffset;
134512      if( iTerm>=nConstraint
134513       || j<0
134514       || j>=pWC->nTerm
134515       || pNew->aLTerm[iTerm]!=0
134516       || pIdxCons->usable==0
134517      ){
134518        rc = SQLITE_ERROR;
134519        sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
134520        return rc;
134521      }
134522      testcase( iTerm==nConstraint-1 );
134523      testcase( j==0 );
134524      testcase( j==pWC->nTerm-1 );
134525      pTerm = &pWC->a[j];
134526      pNew->prereq |= pTerm->prereqRight;
134527      assert( iTerm<pNew->nLSlot );
134528      pNew->aLTerm[iTerm] = pTerm;
134529      if( iTerm>mxTerm ) mxTerm = iTerm;
134530      testcase( iTerm==15 );
134531      testcase( iTerm==16 );
134532      if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
134533      if( (pTerm->eOperator & WO_IN)!=0 ){
134534        /* A virtual table that is constrained by an IN clause may not
134535        ** consume the ORDER BY clause because (1) the order of IN terms
134536        ** is not necessarily related to the order of output terms and
134537        ** (2) Multiple outputs from a single IN value will not merge
134538        ** together.  */
134539        pIdxInfo->orderByConsumed = 0;
134540        pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
134541        *pbIn = 1; assert( (mExclude & WO_IN)==0 );
134542      }
134543    }
134544  }
134545  pNew->u.vtab.omitMask &= ~mNoOmit;
134546
134547  pNew->nLTerm = mxTerm+1;
134548  assert( pNew->nLTerm<=pNew->nLSlot );
134549  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
134550  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
134551  pIdxInfo->needToFreeIdxStr = 0;
134552  pNew->u.vtab.idxStr = pIdxInfo->idxStr;
134553  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
134554      pIdxInfo->nOrderBy : 0);
134555  pNew->rSetup = 0;
134556  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
134557  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
134558
134559  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
134560  ** that the scan will visit at most one row. Clear it otherwise. */
134561  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
134562    pNew->wsFlags |= WHERE_ONEROW;
134563  }else{
134564    pNew->wsFlags &= ~WHERE_ONEROW;
134565  }
134566  rc = whereLoopInsert(pBuilder, pNew);
134567  if( pNew->u.vtab.needFree ){
134568    sqlite3_free(pNew->u.vtab.idxStr);
134569    pNew->u.vtab.needFree = 0;
134570  }
134571  WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
134572                      *pbIn, (sqlite3_uint64)mPrereq,
134573                      (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
134574
134575  return rc;
134576}
134577
134578
134579/*
134580** Add all WhereLoop objects for a table of the join identified by
134581** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
134582**
134583** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
134584** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
134585** entries that occur before the virtual table in the FROM clause and are
134586** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
134587** mUnusable mask contains all FROM clause entries that occur after the
134588** virtual table and are separated from it by at least one LEFT or
134589** CROSS JOIN.
134590**
134591** For example, if the query were:
134592**
134593**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
134594**
134595** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
134596**
134597** All the tables in mPrereq must be scanned before the current virtual
134598** table. So any terms for which all prerequisites are satisfied by
134599** mPrereq may be specified as "usable" in all calls to xBestIndex.
134600** Conversely, all tables in mUnusable must be scanned after the current
134601** virtual table, so any terms for which the prerequisites overlap with
134602** mUnusable should always be configured as "not-usable" for xBestIndex.
134603*/
134604static int whereLoopAddVirtual(
134605  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
134606  Bitmask mPrereq,             /* Tables that must be scanned before this one */
134607  Bitmask mUnusable            /* Tables that must be scanned after this one */
134608){
134609  int rc = SQLITE_OK;          /* Return code */
134610  WhereInfo *pWInfo;           /* WHERE analysis context */
134611  Parse *pParse;               /* The parsing context */
134612  WhereClause *pWC;            /* The WHERE clause */
134613  struct SrcList_item *pSrc;   /* The FROM clause term to search */
134614  sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
134615  int nConstraint;             /* Number of constraints in p */
134616  int bIn;                     /* True if plan uses IN(...) operator */
134617  WhereLoop *pNew;
134618  Bitmask mBest;               /* Tables used by best possible plan */
134619  u16 mNoOmit;
134620
134621  assert( (mPrereq & mUnusable)==0 );
134622  pWInfo = pBuilder->pWInfo;
134623  pParse = pWInfo->pParse;
134624  pWC = pBuilder->pWC;
134625  pNew = pBuilder->pNew;
134626  pSrc = &pWInfo->pTabList->a[pNew->iTab];
134627  assert( IsVirtual(pSrc->pTab) );
134628  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
134629      &mNoOmit);
134630  if( p==0 ) return SQLITE_NOMEM_BKPT;
134631  pNew->rSetup = 0;
134632  pNew->wsFlags = WHERE_VIRTUALTABLE;
134633  pNew->nLTerm = 0;
134634  pNew->u.vtab.needFree = 0;
134635  nConstraint = p->nConstraint;
134636  if( whereLoopResize(pParse->db, pNew, nConstraint) ){
134637    sqlite3DbFree(pParse->db, p);
134638    return SQLITE_NOMEM_BKPT;
134639  }
134640
134641  /* First call xBestIndex() with all constraints usable. */
134642  WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
134643  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
134644
134645  /* If the call to xBestIndex() with all terms enabled produced a plan
134646  ** that does not require any source tables (IOW: a plan with mBest==0),
134647  ** then there is no point in making any further calls to xBestIndex()
134648  ** since they will all return the same result (if the xBestIndex()
134649  ** implementation is sane). */
134650  if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
134651    int seenZero = 0;             /* True if a plan with no prereqs seen */
134652    int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
134653    Bitmask mPrev = 0;
134654    Bitmask mBestNoIn = 0;
134655
134656    /* If the plan produced by the earlier call uses an IN(...) term, call
134657    ** xBestIndex again, this time with IN(...) terms disabled. */
134658    if( bIn ){
134659      WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
134660      rc = whereLoopAddVirtualOne(
134661          pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
134662      assert( bIn==0 );
134663      mBestNoIn = pNew->prereq & ~mPrereq;
134664      if( mBestNoIn==0 ){
134665        seenZero = 1;
134666        seenZeroNoIN = 1;
134667      }
134668    }
134669
134670    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
134671    ** in the set of terms that apply to the current virtual table.  */
134672    while( rc==SQLITE_OK ){
134673      int i;
134674      Bitmask mNext = ALLBITS;
134675      assert( mNext>0 );
134676      for(i=0; i<nConstraint; i++){
134677        Bitmask mThis = (
134678            pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
134679        );
134680        if( mThis>mPrev && mThis<mNext ) mNext = mThis;
134681      }
134682      mPrev = mNext;
134683      if( mNext==ALLBITS ) break;
134684      if( mNext==mBest || mNext==mBestNoIn ) continue;
134685      WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
134686                       (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
134687      rc = whereLoopAddVirtualOne(
134688          pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
134689      if( pNew->prereq==mPrereq ){
134690        seenZero = 1;
134691        if( bIn==0 ) seenZeroNoIN = 1;
134692      }
134693    }
134694
134695    /* If the calls to xBestIndex() in the above loop did not find a plan
134696    ** that requires no source tables at all (i.e. one guaranteed to be
134697    ** usable), make a call here with all source tables disabled */
134698    if( rc==SQLITE_OK && seenZero==0 ){
134699      WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
134700      rc = whereLoopAddVirtualOne(
134701          pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
134702      if( bIn==0 ) seenZeroNoIN = 1;
134703    }
134704
134705    /* If the calls to xBestIndex() have so far failed to find a plan
134706    ** that requires no source tables at all and does not use an IN(...)
134707    ** operator, make a final call to obtain one here.  */
134708    if( rc==SQLITE_OK && seenZeroNoIN==0 ){
134709      WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
134710      rc = whereLoopAddVirtualOne(
134711          pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
134712    }
134713  }
134714
134715  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
134716  sqlite3DbFreeNN(pParse->db, p);
134717  return rc;
134718}
134719#endif /* SQLITE_OMIT_VIRTUALTABLE */
134720
134721/*
134722** Add WhereLoop entries to handle OR terms.  This works for either
134723** btrees or virtual tables.
134724*/
134725static int whereLoopAddOr(
134726  WhereLoopBuilder *pBuilder,
134727  Bitmask mPrereq,
134728  Bitmask mUnusable
134729){
134730  WhereInfo *pWInfo = pBuilder->pWInfo;
134731  WhereClause *pWC;
134732  WhereLoop *pNew;
134733  WhereTerm *pTerm, *pWCEnd;
134734  int rc = SQLITE_OK;
134735  int iCur;
134736  WhereClause tempWC;
134737  WhereLoopBuilder sSubBuild;
134738  WhereOrSet sSum, sCur;
134739  struct SrcList_item *pItem;
134740
134741  pWC = pBuilder->pWC;
134742  pWCEnd = pWC->a + pWC->nTerm;
134743  pNew = pBuilder->pNew;
134744  memset(&sSum, 0, sizeof(sSum));
134745  pItem = pWInfo->pTabList->a + pNew->iTab;
134746  iCur = pItem->iCursor;
134747
134748  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
134749    if( (pTerm->eOperator & WO_OR)!=0
134750     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
134751    ){
134752      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
134753      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
134754      WhereTerm *pOrTerm;
134755      int once = 1;
134756      int i, j;
134757
134758      sSubBuild = *pBuilder;
134759      sSubBuild.pOrderBy = 0;
134760      sSubBuild.pOrSet = &sCur;
134761
134762      WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
134763      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
134764        if( (pOrTerm->eOperator & WO_AND)!=0 ){
134765          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
134766        }else if( pOrTerm->leftCursor==iCur ){
134767          tempWC.pWInfo = pWC->pWInfo;
134768          tempWC.pOuter = pWC;
134769          tempWC.op = TK_AND;
134770          tempWC.nTerm = 1;
134771          tempWC.a = pOrTerm;
134772          sSubBuild.pWC = &tempWC;
134773        }else{
134774          continue;
134775        }
134776        sCur.n = 0;
134777#ifdef WHERETRACE_ENABLED
134778        WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
134779                   (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
134780        if( sqlite3WhereTrace & 0x400 ){
134781          sqlite3WhereClausePrint(sSubBuild.pWC);
134782        }
134783#endif
134784#ifndef SQLITE_OMIT_VIRTUALTABLE
134785        if( IsVirtual(pItem->pTab) ){
134786          rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
134787        }else
134788#endif
134789        {
134790          rc = whereLoopAddBtree(&sSubBuild, mPrereq);
134791        }
134792        if( rc==SQLITE_OK ){
134793          rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
134794        }
134795        assert( rc==SQLITE_OK || sCur.n==0 );
134796        if( sCur.n==0 ){
134797          sSum.n = 0;
134798          break;
134799        }else if( once ){
134800          whereOrMove(&sSum, &sCur);
134801          once = 0;
134802        }else{
134803          WhereOrSet sPrev;
134804          whereOrMove(&sPrev, &sSum);
134805          sSum.n = 0;
134806          for(i=0; i<sPrev.n; i++){
134807            for(j=0; j<sCur.n; j++){
134808              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
134809                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
134810                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
134811            }
134812          }
134813        }
134814      }
134815      pNew->nLTerm = 1;
134816      pNew->aLTerm[0] = pTerm;
134817      pNew->wsFlags = WHERE_MULTI_OR;
134818      pNew->rSetup = 0;
134819      pNew->iSortIdx = 0;
134820      memset(&pNew->u, 0, sizeof(pNew->u));
134821      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
134822        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
134823        ** of all sub-scans required by the OR-scan. However, due to rounding
134824        ** errors, it may be that the cost of the OR-scan is equal to its
134825        ** most expensive sub-scan. Add the smallest possible penalty
134826        ** (equivalent to multiplying the cost by 1.07) to ensure that
134827        ** this does not happen. Otherwise, for WHERE clauses such as the
134828        ** following where there is an index on "y":
134829        **
134830        **     WHERE likelihood(x=?, 0.99) OR y=?
134831        **
134832        ** the planner may elect to "OR" together a full-table scan and an
134833        ** index lookup. And other similarly odd results.  */
134834        pNew->rRun = sSum.a[i].rRun + 1;
134835        pNew->nOut = sSum.a[i].nOut;
134836        pNew->prereq = sSum.a[i].prereq;
134837        rc = whereLoopInsert(pBuilder, pNew);
134838      }
134839      WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
134840    }
134841  }
134842  return rc;
134843}
134844
134845/*
134846** Add all WhereLoop objects for all tables
134847*/
134848static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
134849  WhereInfo *pWInfo = pBuilder->pWInfo;
134850  Bitmask mPrereq = 0;
134851  Bitmask mPrior = 0;
134852  int iTab;
134853  SrcList *pTabList = pWInfo->pTabList;
134854  struct SrcList_item *pItem;
134855  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
134856  sqlite3 *db = pWInfo->pParse->db;
134857  int rc = SQLITE_OK;
134858  WhereLoop *pNew;
134859  u8 priorJointype = 0;
134860
134861  /* Loop over the tables in the join, from left to right */
134862  pNew = pBuilder->pNew;
134863  whereLoopInit(pNew);
134864  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
134865    Bitmask mUnusable = 0;
134866    pNew->iTab = iTab;
134867    pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
134868    if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
134869      /* This condition is true when pItem is the FROM clause term on the
134870      ** right-hand-side of a LEFT or CROSS JOIN.  */
134871      mPrereq = mPrior;
134872    }
134873    priorJointype = pItem->fg.jointype;
134874#ifndef SQLITE_OMIT_VIRTUALTABLE
134875    if( IsVirtual(pItem->pTab) ){
134876      struct SrcList_item *p;
134877      for(p=&pItem[1]; p<pEnd; p++){
134878        if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
134879          mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
134880        }
134881      }
134882      rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
134883    }else
134884#endif /* SQLITE_OMIT_VIRTUALTABLE */
134885    {
134886      rc = whereLoopAddBtree(pBuilder, mPrereq);
134887    }
134888    if( rc==SQLITE_OK ){
134889      rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
134890    }
134891    mPrior |= pNew->maskSelf;
134892    if( rc || db->mallocFailed ) break;
134893  }
134894
134895  whereLoopClear(db, pNew);
134896  return rc;
134897}
134898
134899/*
134900** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
134901** parameters) to see if it outputs rows in the requested ORDER BY
134902** (or GROUP BY) without requiring a separate sort operation.  Return N:
134903**
134904**   N>0:   N terms of the ORDER BY clause are satisfied
134905**   N==0:  No terms of the ORDER BY clause are satisfied
134906**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
134907**
134908** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
134909** strict.  With GROUP BY and DISTINCT the only requirement is that
134910** equivalent rows appear immediately adjacent to one another.  GROUP BY
134911** and DISTINCT do not require rows to appear in any particular order as long
134912** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
134913** the pOrderBy terms can be matched in any order.  With ORDER BY, the
134914** pOrderBy terms must be matched in strict left-to-right order.
134915*/
134916static i8 wherePathSatisfiesOrderBy(
134917  WhereInfo *pWInfo,    /* The WHERE clause */
134918  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
134919  WherePath *pPath,     /* The WherePath to check */
134920  u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
134921  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
134922  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
134923  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
134924){
134925  u8 revSet;            /* True if rev is known */
134926  u8 rev;               /* Composite sort order */
134927  u8 revIdx;            /* Index sort order */
134928  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
134929  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
134930  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
134931  u16 eqOpMask;         /* Allowed equality operators */
134932  u16 nKeyCol;          /* Number of key columns in pIndex */
134933  u16 nColumn;          /* Total number of ordered columns in the index */
134934  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
134935  int iLoop;            /* Index of WhereLoop in pPath being processed */
134936  int i, j;             /* Loop counters */
134937  int iCur;             /* Cursor number for current WhereLoop */
134938  int iColumn;          /* A column number within table iCur */
134939  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
134940  WhereTerm *pTerm;     /* A single term of the WHERE clause */
134941  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
134942  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
134943  Index *pIndex;        /* The index associated with pLoop */
134944  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
134945  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
134946  Bitmask obDone;       /* Mask of all ORDER BY terms */
134947  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
134948  Bitmask ready;              /* Mask of inner loops */
134949
134950  /*
134951  ** We say the WhereLoop is "one-row" if it generates no more than one
134952  ** row of output.  A WhereLoop is one-row if all of the following are true:
134953  **  (a) All index columns match with WHERE_COLUMN_EQ.
134954  **  (b) The index is unique
134955  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
134956  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
134957  **
134958  ** We say the WhereLoop is "order-distinct" if the set of columns from
134959  ** that WhereLoop that are in the ORDER BY clause are different for every
134960  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
134961  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
134962  ** is not order-distinct. To be order-distinct is not quite the same as being
134963  ** UNIQUE since a UNIQUE column or index can have multiple rows that
134964  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
134965  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
134966  **
134967  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
134968  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
134969  ** automatically order-distinct.
134970  */
134971
134972  assert( pOrderBy!=0 );
134973  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
134974
134975  nOrderBy = pOrderBy->nExpr;
134976  testcase( nOrderBy==BMS-1 );
134977  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
134978  isOrderDistinct = 1;
134979  obDone = MASKBIT(nOrderBy)-1;
134980  orderDistinctMask = 0;
134981  ready = 0;
134982  eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
134983  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
134984  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
134985    if( iLoop>0 ) ready |= pLoop->maskSelf;
134986    if( iLoop<nLoop ){
134987      pLoop = pPath->aLoop[iLoop];
134988      if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
134989    }else{
134990      pLoop = pLast;
134991    }
134992    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
134993      if( pLoop->u.vtab.isOrdered ) obSat = obDone;
134994      break;
134995    }else{
134996      pLoop->u.btree.nIdxCol = 0;
134997    }
134998    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
134999
135000    /* Mark off any ORDER BY term X that is a column in the table of
135001    ** the current loop for which there is term in the WHERE
135002    ** clause of the form X IS NULL or X=? that reference only outer
135003    ** loops.
135004    */
135005    for(i=0; i<nOrderBy; i++){
135006      if( MASKBIT(i) & obSat ) continue;
135007      pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
135008      if( pOBExpr->op!=TK_COLUMN ) continue;
135009      if( pOBExpr->iTable!=iCur ) continue;
135010      pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
135011                       ~ready, eqOpMask, 0);
135012      if( pTerm==0 ) continue;
135013      if( pTerm->eOperator==WO_IN ){
135014        /* IN terms are only valid for sorting in the ORDER BY LIMIT
135015        ** optimization, and then only if they are actually used
135016        ** by the query plan */
135017        assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
135018        for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
135019        if( j>=pLoop->nLTerm ) continue;
135020      }
135021      if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
135022        const char *z1, *z2;
135023        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
135024        if( !pColl ) pColl = db->pDfltColl;
135025        z1 = pColl->zName;
135026        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
135027        if( !pColl ) pColl = db->pDfltColl;
135028        z2 = pColl->zName;
135029        if( sqlite3StrICmp(z1, z2)!=0 ) continue;
135030        testcase( pTerm->pExpr->op==TK_IS );
135031      }
135032      obSat |= MASKBIT(i);
135033    }
135034
135035    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
135036      if( pLoop->wsFlags & WHERE_IPK ){
135037        pIndex = 0;
135038        nKeyCol = 0;
135039        nColumn = 1;
135040      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
135041        return 0;
135042      }else{
135043        nKeyCol = pIndex->nKeyCol;
135044        nColumn = pIndex->nColumn;
135045        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
135046        assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
135047                          || !HasRowid(pIndex->pTable));
135048        isOrderDistinct = IsUniqueIndex(pIndex);
135049      }
135050
135051      /* Loop through all columns of the index and deal with the ones
135052      ** that are not constrained by == or IN.
135053      */
135054      rev = revSet = 0;
135055      distinctColumns = 0;
135056      for(j=0; j<nColumn; j++){
135057        u8 bOnce = 1; /* True to run the ORDER BY search loop */
135058
135059        assert( j>=pLoop->u.btree.nEq
135060            || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
135061        );
135062        if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
135063          u16 eOp = pLoop->aLTerm[j]->eOperator;
135064
135065          /* Skip over == and IS and ISNULL terms.  (Also skip IN terms when
135066          ** doing WHERE_ORDERBY_LIMIT processing).
135067          **
135068          ** If the current term is a column of an ((?,?) IN (SELECT...))
135069          ** expression for which the SELECT returns more than one column,
135070          ** check that it is the only column used by this loop. Otherwise,
135071          ** if it is one of two or more, none of the columns can be
135072          ** considered to match an ORDER BY term.  */
135073          if( (eOp & eqOpMask)!=0 ){
135074            if( eOp & WO_ISNULL ){
135075              testcase( isOrderDistinct );
135076              isOrderDistinct = 0;
135077            }
135078            continue;
135079          }else if( ALWAYS(eOp & WO_IN) ){
135080            /* ALWAYS() justification: eOp is an equality operator due to the
135081            ** j<pLoop->u.btree.nEq constraint above.  Any equality other
135082            ** than WO_IN is captured by the previous "if".  So this one
135083            ** always has to be WO_IN. */
135084            Expr *pX = pLoop->aLTerm[j]->pExpr;
135085            for(i=j+1; i<pLoop->u.btree.nEq; i++){
135086              if( pLoop->aLTerm[i]->pExpr==pX ){
135087                assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
135088                bOnce = 0;
135089                break;
135090              }
135091            }
135092          }
135093        }
135094
135095        /* Get the column number in the table (iColumn) and sort order
135096        ** (revIdx) for the j-th column of the index.
135097        */
135098        if( pIndex ){
135099          iColumn = pIndex->aiColumn[j];
135100          revIdx = pIndex->aSortOrder[j];
135101          if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
135102        }else{
135103          iColumn = XN_ROWID;
135104          revIdx = 0;
135105        }
135106
135107        /* An unconstrained column that might be NULL means that this
135108        ** WhereLoop is not well-ordered
135109        */
135110        if( isOrderDistinct
135111         && iColumn>=0
135112         && j>=pLoop->u.btree.nEq
135113         && pIndex->pTable->aCol[iColumn].notNull==0
135114        ){
135115          isOrderDistinct = 0;
135116        }
135117
135118        /* Find the ORDER BY term that corresponds to the j-th column
135119        ** of the index and mark that ORDER BY term off
135120        */
135121        isMatch = 0;
135122        for(i=0; bOnce && i<nOrderBy; i++){
135123          if( MASKBIT(i) & obSat ) continue;
135124          pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
135125          testcase( wctrlFlags & WHERE_GROUPBY );
135126          testcase( wctrlFlags & WHERE_DISTINCTBY );
135127          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
135128          if( iColumn>=(-1) ){
135129            if( pOBExpr->op!=TK_COLUMN ) continue;
135130            if( pOBExpr->iTable!=iCur ) continue;
135131            if( pOBExpr->iColumn!=iColumn ) continue;
135132          }else{
135133            if( sqlite3ExprCompare(0,
135134                  pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
135135              continue;
135136            }
135137          }
135138          if( iColumn>=0 ){
135139            pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
135140            if( !pColl ) pColl = db->pDfltColl;
135141            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
135142          }
135143          pLoop->u.btree.nIdxCol = j+1;
135144          isMatch = 1;
135145          break;
135146        }
135147        if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
135148          /* Make sure the sort order is compatible in an ORDER BY clause.
135149          ** Sort order is irrelevant for a GROUP BY clause. */
135150          if( revSet ){
135151            if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
135152          }else{
135153            rev = revIdx ^ pOrderBy->a[i].sortOrder;
135154            if( rev ) *pRevMask |= MASKBIT(iLoop);
135155            revSet = 1;
135156          }
135157        }
135158        if( isMatch ){
135159          if( iColumn==XN_ROWID ){
135160            testcase( distinctColumns==0 );
135161            distinctColumns = 1;
135162          }
135163          obSat |= MASKBIT(i);
135164        }else{
135165          /* No match found */
135166          if( j==0 || j<nKeyCol ){
135167            testcase( isOrderDistinct!=0 );
135168            isOrderDistinct = 0;
135169          }
135170          break;
135171        }
135172      } /* end Loop over all index columns */
135173      if( distinctColumns ){
135174        testcase( isOrderDistinct==0 );
135175        isOrderDistinct = 1;
135176      }
135177    } /* end-if not one-row */
135178
135179    /* Mark off any other ORDER BY terms that reference pLoop */
135180    if( isOrderDistinct ){
135181      orderDistinctMask |= pLoop->maskSelf;
135182      for(i=0; i<nOrderBy; i++){
135183        Expr *p;
135184        Bitmask mTerm;
135185        if( MASKBIT(i) & obSat ) continue;
135186        p = pOrderBy->a[i].pExpr;
135187        mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
135188        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
135189        if( (mTerm&~orderDistinctMask)==0 ){
135190          obSat |= MASKBIT(i);
135191        }
135192      }
135193    }
135194  } /* End the loop over all WhereLoops from outer-most down to inner-most */
135195  if( obSat==obDone ) return (i8)nOrderBy;
135196  if( !isOrderDistinct ){
135197    for(i=nOrderBy-1; i>0; i--){
135198      Bitmask m = MASKBIT(i) - 1;
135199      if( (obSat&m)==m ) return i;
135200    }
135201    return 0;
135202  }
135203  return -1;
135204}
135205
135206
135207/*
135208** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
135209** the planner assumes that the specified pOrderBy list is actually a GROUP
135210** BY clause - and so any order that groups rows as required satisfies the
135211** request.
135212**
135213** Normally, in this case it is not possible for the caller to determine
135214** whether or not the rows are really being delivered in sorted order, or
135215** just in some other order that provides the required grouping. However,
135216** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
135217** this function may be called on the returned WhereInfo object. It returns
135218** true if the rows really will be sorted in the specified order, or false
135219** otherwise.
135220**
135221** For example, assuming:
135222**
135223**   CREATE INDEX i1 ON t1(x, Y);
135224**
135225** then
135226**
135227**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
135228**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
135229*/
135230SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
135231  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
135232  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
135233  return pWInfo->sorted;
135234}
135235
135236#ifdef WHERETRACE_ENABLED
135237/* For debugging use only: */
135238static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
135239  static char zName[65];
135240  int i;
135241  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
135242  if( pLast ) zName[i++] = pLast->cId;
135243  zName[i] = 0;
135244  return zName;
135245}
135246#endif
135247
135248/*
135249** Return the cost of sorting nRow rows, assuming that the keys have
135250** nOrderby columns and that the first nSorted columns are already in
135251** order.
135252*/
135253static LogEst whereSortingCost(
135254  WhereInfo *pWInfo,
135255  LogEst nRow,
135256  int nOrderBy,
135257  int nSorted
135258){
135259  /* TUNING: Estimated cost of a full external sort, where N is
135260  ** the number of rows to sort is:
135261  **
135262  **   cost = (3.0 * N * log(N)).
135263  **
135264  ** Or, if the order-by clause has X terms but only the last Y
135265  ** terms are out of order, then block-sorting will reduce the
135266  ** sorting cost to:
135267  **
135268  **   cost = (3.0 * N * log(N)) * (Y/X)
135269  **
135270  ** The (Y/X) term is implemented using stack variable rScale
135271  ** below.  */
135272  LogEst rScale, rSortCost;
135273  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
135274  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
135275  rSortCost = nRow + rScale + 16;
135276
135277  /* Multiple by log(M) where M is the number of output rows.
135278  ** Use the LIMIT for M if it is smaller */
135279  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
135280    nRow = pWInfo->iLimit;
135281  }
135282  rSortCost += estLog(nRow);
135283  return rSortCost;
135284}
135285
135286/*
135287** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
135288** attempts to find the lowest cost path that visits each WhereLoop
135289** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
135290**
135291** Assume that the total number of output rows that will need to be sorted
135292** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
135293** costs if nRowEst==0.
135294**
135295** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
135296** error occurs.
135297*/
135298static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
135299  int mxChoice;             /* Maximum number of simultaneous paths tracked */
135300  int nLoop;                /* Number of terms in the join */
135301  Parse *pParse;            /* Parsing context */
135302  sqlite3 *db;              /* The database connection */
135303  int iLoop;                /* Loop counter over the terms of the join */
135304  int ii, jj;               /* Loop counters */
135305  int mxI = 0;              /* Index of next entry to replace */
135306  int nOrderBy;             /* Number of ORDER BY clause terms */
135307  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
135308  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
135309  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
135310  WherePath *aFrom;         /* All nFrom paths at the previous level */
135311  WherePath *aTo;           /* The nTo best paths at the current level */
135312  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
135313  WherePath *pTo;           /* An element of aTo[] that we are working on */
135314  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
135315  WhereLoop **pX;           /* Used to divy up the pSpace memory */
135316  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
135317  char *pSpace;             /* Temporary memory used by this routine */
135318  int nSpace;               /* Bytes of space allocated at pSpace */
135319
135320  pParse = pWInfo->pParse;
135321  db = pParse->db;
135322  nLoop = pWInfo->nLevel;
135323  /* TUNING: For simple queries, only the best path is tracked.
135324  ** For 2-way joins, the 5 best paths are followed.
135325  ** For joins of 3 or more tables, track the 10 best paths */
135326  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
135327  assert( nLoop<=pWInfo->pTabList->nSrc );
135328  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
135329
135330  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
135331  ** case the purpose of this call is to estimate the number of rows returned
135332  ** by the overall query. Once this estimate has been obtained, the caller
135333  ** will invoke this function a second time, passing the estimate as the
135334  ** nRowEst parameter.  */
135335  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
135336    nOrderBy = 0;
135337  }else{
135338    nOrderBy = pWInfo->pOrderBy->nExpr;
135339  }
135340
135341  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
135342  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
135343  nSpace += sizeof(LogEst) * nOrderBy;
135344  pSpace = sqlite3DbMallocRawNN(db, nSpace);
135345  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
135346  aTo = (WherePath*)pSpace;
135347  aFrom = aTo+mxChoice;
135348  memset(aFrom, 0, sizeof(aFrom[0]));
135349  pX = (WhereLoop**)(aFrom+mxChoice);
135350  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
135351    pFrom->aLoop = pX;
135352  }
135353  if( nOrderBy ){
135354    /* If there is an ORDER BY clause and it is not being ignored, set up
135355    ** space for the aSortCost[] array. Each element of the aSortCost array
135356    ** is either zero - meaning it has not yet been initialized - or the
135357    ** cost of sorting nRowEst rows of data where the first X terms of
135358    ** the ORDER BY clause are already in order, where X is the array
135359    ** index.  */
135360    aSortCost = (LogEst*)pX;
135361    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
135362  }
135363  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
135364  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
135365
135366  /* Seed the search with a single WherePath containing zero WhereLoops.
135367  **
135368  ** TUNING: Do not let the number of iterations go above 28.  If the cost
135369  ** of computing an automatic index is not paid back within the first 28
135370  ** rows, then do not use the automatic index. */
135371  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
135372  nFrom = 1;
135373  assert( aFrom[0].isOrdered==0 );
135374  if( nOrderBy ){
135375    /* If nLoop is zero, then there are no FROM terms in the query. Since
135376    ** in this case the query may return a maximum of one row, the results
135377    ** are already in the requested order. Set isOrdered to nOrderBy to
135378    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
135379    ** -1, indicating that the result set may or may not be ordered,
135380    ** depending on the loops added to the current plan.  */
135381    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
135382  }
135383
135384  /* Compute successively longer WherePaths using the previous generation
135385  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
135386  ** best paths at each generation */
135387  for(iLoop=0; iLoop<nLoop; iLoop++){
135388    nTo = 0;
135389    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
135390      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
135391        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
135392        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
135393        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
135394        i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
135395        Bitmask maskNew;                  /* Mask of src visited by (..) */
135396        Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
135397
135398        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
135399        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
135400        if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
135401          /* Do not use an automatic index if the this loop is expected
135402          ** to run less than 2 times. */
135403          assert( 10==sqlite3LogEst(2) );
135404          continue;
135405        }
135406        /* At this point, pWLoop is a candidate to be the next loop.
135407        ** Compute its cost */
135408        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
135409        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
135410        nOut = pFrom->nRow + pWLoop->nOut;
135411        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
135412        if( isOrdered<0 ){
135413          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
135414                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
135415                       iLoop, pWLoop, &revMask);
135416        }else{
135417          revMask = pFrom->revLoop;
135418        }
135419        if( isOrdered>=0 && isOrdered<nOrderBy ){
135420          if( aSortCost[isOrdered]==0 ){
135421            aSortCost[isOrdered] = whereSortingCost(
135422                pWInfo, nRowEst, nOrderBy, isOrdered
135423            );
135424          }
135425          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
135426
135427          WHERETRACE(0x002,
135428              ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
135429               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
135430               rUnsorted, rCost));
135431        }else{
135432          rCost = rUnsorted;
135433          rUnsorted -= 2;  /* TUNING:  Slight bias in favor of no-sort plans */
135434        }
135435
135436        /* Check to see if pWLoop should be added to the set of
135437        ** mxChoice best-so-far paths.
135438        **
135439        ** First look for an existing path among best-so-far paths
135440        ** that covers the same set of loops and has the same isOrdered
135441        ** setting as the current path candidate.
135442        **
135443        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
135444        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
135445        ** of legal values for isOrdered, -1..64.
135446        */
135447        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
135448          if( pTo->maskLoop==maskNew
135449           && ((pTo->isOrdered^isOrdered)&0x80)==0
135450          ){
135451            testcase( jj==nTo-1 );
135452            break;
135453          }
135454        }
135455        if( jj>=nTo ){
135456          /* None of the existing best-so-far paths match the candidate. */
135457          if( nTo>=mxChoice
135458           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
135459          ){
135460            /* The current candidate is no better than any of the mxChoice
135461            ** paths currently in the best-so-far buffer.  So discard
135462            ** this candidate as not viable. */
135463#ifdef WHERETRACE_ENABLED /* 0x4 */
135464            if( sqlite3WhereTrace&0x4 ){
135465              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d,%3d order=%c\n",
135466                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135467                  isOrdered>=0 ? isOrdered+'0' : '?');
135468            }
135469#endif
135470            continue;
135471          }
135472          /* If we reach this points it means that the new candidate path
135473          ** needs to be added to the set of best-so-far paths. */
135474          if( nTo<mxChoice ){
135475            /* Increase the size of the aTo set by one */
135476            jj = nTo++;
135477          }else{
135478            /* New path replaces the prior worst to keep count below mxChoice */
135479            jj = mxI;
135480          }
135481          pTo = &aTo[jj];
135482#ifdef WHERETRACE_ENABLED /* 0x4 */
135483          if( sqlite3WhereTrace&0x4 ){
135484            sqlite3DebugPrintf("New    %s cost=%-3d,%3d,%3d order=%c\n",
135485                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135486                isOrdered>=0 ? isOrdered+'0' : '?');
135487          }
135488#endif
135489        }else{
135490          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
135491          ** same set of loops and has the same isOrdered setting as the
135492          ** candidate path.  Check to see if the candidate should replace
135493          ** pTo or if the candidate should be skipped.
135494          **
135495          ** The conditional is an expanded vector comparison equivalent to:
135496          **   (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
135497          */
135498          if( pTo->rCost<rCost
135499           || (pTo->rCost==rCost
135500               && (pTo->nRow<nOut
135501                   || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
135502                  )
135503              )
135504          ){
135505#ifdef WHERETRACE_ENABLED /* 0x4 */
135506            if( sqlite3WhereTrace&0x4 ){
135507              sqlite3DebugPrintf(
135508                  "Skip   %s cost=%-3d,%3d,%3d order=%c",
135509                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135510                  isOrdered>=0 ? isOrdered+'0' : '?');
135511              sqlite3DebugPrintf("   vs %s cost=%-3d,%3d,%3d order=%c\n",
135512                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135513                  pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
135514            }
135515#endif
135516            /* Discard the candidate path from further consideration */
135517            testcase( pTo->rCost==rCost );
135518            continue;
135519          }
135520          testcase( pTo->rCost==rCost+1 );
135521          /* Control reaches here if the candidate path is better than the
135522          ** pTo path.  Replace pTo with the candidate. */
135523#ifdef WHERETRACE_ENABLED /* 0x4 */
135524          if( sqlite3WhereTrace&0x4 ){
135525            sqlite3DebugPrintf(
135526                "Update %s cost=%-3d,%3d,%3d order=%c",
135527                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
135528                isOrdered>=0 ? isOrdered+'0' : '?');
135529            sqlite3DebugPrintf("  was %s cost=%-3d,%3d,%3d order=%c\n",
135530                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135531                pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
135532          }
135533#endif
135534        }
135535        /* pWLoop is a winner.  Add it to the set of best so far */
135536        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
135537        pTo->revLoop = revMask;
135538        pTo->nRow = nOut;
135539        pTo->rCost = rCost;
135540        pTo->rUnsorted = rUnsorted;
135541        pTo->isOrdered = isOrdered;
135542        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
135543        pTo->aLoop[iLoop] = pWLoop;
135544        if( nTo>=mxChoice ){
135545          mxI = 0;
135546          mxCost = aTo[0].rCost;
135547          mxUnsorted = aTo[0].nRow;
135548          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
135549            if( pTo->rCost>mxCost
135550             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
135551            ){
135552              mxCost = pTo->rCost;
135553              mxUnsorted = pTo->rUnsorted;
135554              mxI = jj;
135555            }
135556          }
135557        }
135558      }
135559    }
135560
135561#ifdef WHERETRACE_ENABLED  /* >=2 */
135562    if( sqlite3WhereTrace & 0x02 ){
135563      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
135564      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
135565        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
135566           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
135567           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
135568        if( pTo->isOrdered>0 ){
135569          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
135570        }else{
135571          sqlite3DebugPrintf("\n");
135572        }
135573      }
135574    }
135575#endif
135576
135577    /* Swap the roles of aFrom and aTo for the next generation */
135578    pFrom = aTo;
135579    aTo = aFrom;
135580    aFrom = pFrom;
135581    nFrom = nTo;
135582  }
135583
135584  if( nFrom==0 ){
135585    sqlite3ErrorMsg(pParse, "no query solution");
135586    sqlite3DbFreeNN(db, pSpace);
135587    return SQLITE_ERROR;
135588  }
135589
135590  /* Find the lowest cost path.  pFrom will be left pointing to that path */
135591  pFrom = aFrom;
135592  for(ii=1; ii<nFrom; ii++){
135593    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
135594  }
135595  assert( pWInfo->nLevel==nLoop );
135596  /* Load the lowest cost path into pWInfo */
135597  for(iLoop=0; iLoop<nLoop; iLoop++){
135598    WhereLevel *pLevel = pWInfo->a + iLoop;
135599    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
135600    pLevel->iFrom = pWLoop->iTab;
135601    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
135602  }
135603  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
135604   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
135605   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
135606   && nRowEst
135607  ){
135608    Bitmask notUsed;
135609    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
135610                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
135611    if( rc==pWInfo->pResultSet->nExpr ){
135612      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
135613    }
135614  }
135615  if( pWInfo->pOrderBy ){
135616    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
135617      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
135618        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
135619      }
135620    }else{
135621      pWInfo->nOBSat = pFrom->isOrdered;
135622      pWInfo->revMask = pFrom->revLoop;
135623      if( pWInfo->nOBSat<=0 ){
135624        pWInfo->nOBSat = 0;
135625        if( nLoop>0 ){
135626          u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
135627          if( (wsFlags & WHERE_ONEROW)==0
135628           && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
135629          ){
135630            Bitmask m = 0;
135631            int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
135632                      WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
135633            testcase( wsFlags & WHERE_IPK );
135634            testcase( wsFlags & WHERE_COLUMN_IN );
135635            if( rc==pWInfo->pOrderBy->nExpr ){
135636              pWInfo->bOrderedInnerLoop = 1;
135637              pWInfo->revMask = m;
135638            }
135639          }
135640        }
135641      }
135642    }
135643    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
135644        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
135645    ){
135646      Bitmask revMask = 0;
135647      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
135648          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
135649      );
135650      assert( pWInfo->sorted==0 );
135651      if( nOrder==pWInfo->pOrderBy->nExpr ){
135652        pWInfo->sorted = 1;
135653        pWInfo->revMask = revMask;
135654      }
135655    }
135656  }
135657
135658
135659  pWInfo->nRowOut = pFrom->nRow;
135660
135661  /* Free temporary memory and return success */
135662  sqlite3DbFreeNN(db, pSpace);
135663  return SQLITE_OK;
135664}
135665
135666/*
135667** Most queries use only a single table (they are not joins) and have
135668** simple == constraints against indexed fields.  This routine attempts
135669** to plan those simple cases using much less ceremony than the
135670** general-purpose query planner, and thereby yield faster sqlite3_prepare()
135671** times for the common case.
135672**
135673** Return non-zero on success, if this query can be handled by this
135674** no-frills query planner.  Return zero if this query needs the
135675** general-purpose query planner.
135676*/
135677static int whereShortCut(WhereLoopBuilder *pBuilder){
135678  WhereInfo *pWInfo;
135679  struct SrcList_item *pItem;
135680  WhereClause *pWC;
135681  WhereTerm *pTerm;
135682  WhereLoop *pLoop;
135683  int iCur;
135684  int j;
135685  Table *pTab;
135686  Index *pIdx;
135687
135688  pWInfo = pBuilder->pWInfo;
135689  if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
135690  assert( pWInfo->pTabList->nSrc>=1 );
135691  pItem = pWInfo->pTabList->a;
135692  pTab = pItem->pTab;
135693  if( IsVirtual(pTab) ) return 0;
135694  if( pItem->fg.isIndexedBy ) return 0;
135695  iCur = pItem->iCursor;
135696  pWC = &pWInfo->sWC;
135697  pLoop = pBuilder->pNew;
135698  pLoop->wsFlags = 0;
135699  pLoop->nSkip = 0;
135700  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
135701  if( pTerm ){
135702    testcase( pTerm->eOperator & WO_IS );
135703    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
135704    pLoop->aLTerm[0] = pTerm;
135705    pLoop->nLTerm = 1;
135706    pLoop->u.btree.nEq = 1;
135707    /* TUNING: Cost of a rowid lookup is 10 */
135708    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
135709  }else{
135710    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
135711      int opMask;
135712      assert( pLoop->aLTermSpace==pLoop->aLTerm );
135713      if( !IsUniqueIndex(pIdx)
135714       || pIdx->pPartIdxWhere!=0
135715       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
135716      ) continue;
135717      opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
135718      for(j=0; j<pIdx->nKeyCol; j++){
135719        pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
135720        if( pTerm==0 ) break;
135721        testcase( pTerm->eOperator & WO_IS );
135722        pLoop->aLTerm[j] = pTerm;
135723      }
135724      if( j!=pIdx->nKeyCol ) continue;
135725      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
135726      if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
135727        pLoop->wsFlags |= WHERE_IDX_ONLY;
135728      }
135729      pLoop->nLTerm = j;
135730      pLoop->u.btree.nEq = j;
135731      pLoop->u.btree.pIndex = pIdx;
135732      /* TUNING: Cost of a unique index lookup is 15 */
135733      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
135734      break;
135735    }
135736  }
135737  if( pLoop->wsFlags ){
135738    pLoop->nOut = (LogEst)1;
135739    pWInfo->a[0].pWLoop = pLoop;
135740    assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
135741    pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
135742    pWInfo->a[0].iTabCur = iCur;
135743    pWInfo->nRowOut = 1;
135744    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
135745    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
135746      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
135747    }
135748#ifdef SQLITE_DEBUG
135749    pLoop->cId = '0';
135750#endif
135751    return 1;
135752  }
135753  return 0;
135754}
135755
135756/*
135757** Helper function for exprIsDeterministic().
135758*/
135759static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
135760  if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
135761    pWalker->eCode = 0;
135762    return WRC_Abort;
135763  }
135764  return WRC_Continue;
135765}
135766
135767/*
135768** Return true if the expression contains no non-deterministic SQL
135769** functions. Do not consider non-deterministic SQL functions that are
135770** part of sub-select statements.
135771*/
135772static int exprIsDeterministic(Expr *p){
135773  Walker w;
135774  memset(&w, 0, sizeof(w));
135775  w.eCode = 1;
135776  w.xExprCallback = exprNodeIsDeterministic;
135777  sqlite3WalkExpr(&w, p);
135778  return w.eCode;
135779}
135780
135781/*
135782** Generate the beginning of the loop used for WHERE clause processing.
135783** The return value is a pointer to an opaque structure that contains
135784** information needed to terminate the loop.  Later, the calling routine
135785** should invoke sqlite3WhereEnd() with the return value of this function
135786** in order to complete the WHERE clause processing.
135787**
135788** If an error occurs, this routine returns NULL.
135789**
135790** The basic idea is to do a nested loop, one loop for each table in
135791** the FROM clause of a select.  (INSERT and UPDATE statements are the
135792** same as a SELECT with only a single table in the FROM clause.)  For
135793** example, if the SQL is this:
135794**
135795**       SELECT * FROM t1, t2, t3 WHERE ...;
135796**
135797** Then the code generated is conceptually like the following:
135798**
135799**      foreach row1 in t1 do       \    Code generated
135800**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
135801**          foreach row3 in t3 do   /
135802**            ...
135803**          end                     \    Code generated
135804**        end                        |-- by sqlite3WhereEnd()
135805**      end                         /
135806**
135807** Note that the loops might not be nested in the order in which they
135808** appear in the FROM clause if a different order is better able to make
135809** use of indices.  Note also that when the IN operator appears in
135810** the WHERE clause, it might result in additional nested loops for
135811** scanning through all values on the right-hand side of the IN.
135812**
135813** There are Btree cursors associated with each table.  t1 uses cursor
135814** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
135815** And so forth.  This routine generates code to open those VDBE cursors
135816** and sqlite3WhereEnd() generates the code to close them.
135817**
135818** The code that sqlite3WhereBegin() generates leaves the cursors named
135819** in pTabList pointing at their appropriate entries.  The [...] code
135820** can use OP_Column and OP_Rowid opcodes on these cursors to extract
135821** data from the various tables of the loop.
135822**
135823** If the WHERE clause is empty, the foreach loops must each scan their
135824** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
135825** the tables have indices and there are terms in the WHERE clause that
135826** refer to those indices, a complete table scan can be avoided and the
135827** code will run much faster.  Most of the work of this routine is checking
135828** to see if there are indices that can be used to speed up the loop.
135829**
135830** Terms of the WHERE clause are also used to limit which rows actually
135831** make it to the "..." in the middle of the loop.  After each "foreach",
135832** terms of the WHERE clause that use only terms in that loop and outer
135833** loops are evaluated and if false a jump is made around all subsequent
135834** inner loops (or around the "..." if the test occurs within the inner-
135835** most loop)
135836**
135837** OUTER JOINS
135838**
135839** An outer join of tables t1 and t2 is conceptally coded as follows:
135840**
135841**    foreach row1 in t1 do
135842**      flag = 0
135843**      foreach row2 in t2 do
135844**        start:
135845**          ...
135846**          flag = 1
135847**      end
135848**      if flag==0 then
135849**        move the row2 cursor to a null row
135850**        goto start
135851**      fi
135852**    end
135853**
135854** ORDER BY CLAUSE PROCESSING
135855**
135856** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
135857** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
135858** if there is one.  If there is no ORDER BY clause or if this routine
135859** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
135860**
135861** The iIdxCur parameter is the cursor number of an index.  If
135862** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
135863** to use for OR clause processing.  The WHERE clause should use this
135864** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
135865** the first cursor in an array of cursors for all indices.  iIdxCur should
135866** be used to compute the appropriate cursor depending on which index is
135867** used.
135868*/
135869SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
135870  Parse *pParse,          /* The parser context */
135871  SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
135872  Expr *pWhere,           /* The WHERE clause */
135873  ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
135874  ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */
135875  u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
135876  int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
135877                          ** If WHERE_USE_LIMIT, then the limit amount */
135878){
135879  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
135880  int nTabList;              /* Number of elements in pTabList */
135881  WhereInfo *pWInfo;         /* Will become the return value of this function */
135882  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
135883  Bitmask notReady;          /* Cursors that are not yet positioned */
135884  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
135885  WhereMaskSet *pMaskSet;    /* The expression mask set */
135886  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
135887  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
135888  int ii;                    /* Loop counter */
135889  sqlite3 *db;               /* Database connection */
135890  int rc;                    /* Return code */
135891  u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
135892
135893  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
135894        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
135895     && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
135896  ));
135897
135898  /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
135899  assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
135900            || (wctrlFlags & WHERE_USE_LIMIT)==0 );
135901
135902  /* Variable initialization */
135903  db = pParse->db;
135904  memset(&sWLB, 0, sizeof(sWLB));
135905
135906  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
135907  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
135908  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
135909  sWLB.pOrderBy = pOrderBy;
135910
135911  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
135912  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
135913  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
135914    wctrlFlags &= ~WHERE_WANT_DISTINCT;
135915  }
135916
135917  /* The number of tables in the FROM clause is limited by the number of
135918  ** bits in a Bitmask
135919  */
135920  testcase( pTabList->nSrc==BMS );
135921  if( pTabList->nSrc>BMS ){
135922    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
135923    return 0;
135924  }
135925
135926  /* This function normally generates a nested loop for all tables in
135927  ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
135928  ** only generate code for the first table in pTabList and assume that
135929  ** any cursors associated with subsequent tables are uninitialized.
135930  */
135931  nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
135932
135933  /* Allocate and initialize the WhereInfo structure that will become the
135934  ** return value. A single allocation is used to store the WhereInfo
135935  ** struct, the contents of WhereInfo.a[], the WhereClause structure
135936  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
135937  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
135938  ** some architectures. Hence the ROUND8() below.
135939  */
135940  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
135941  pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
135942  if( db->mallocFailed ){
135943    sqlite3DbFree(db, pWInfo);
135944    pWInfo = 0;
135945    goto whereBeginError;
135946  }
135947  pWInfo->pParse = pParse;
135948  pWInfo->pTabList = pTabList;
135949  pWInfo->pOrderBy = pOrderBy;
135950  pWInfo->pWhere = pWhere;
135951  pWInfo->pResultSet = pResultSet;
135952  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
135953  pWInfo->nLevel = nTabList;
135954  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
135955  pWInfo->wctrlFlags = wctrlFlags;
135956  pWInfo->iLimit = iAuxArg;
135957  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
135958  memset(&pWInfo->nOBSat, 0,
135959         offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
135960  memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
135961  assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
135962  pMaskSet = &pWInfo->sMaskSet;
135963  sWLB.pWInfo = pWInfo;
135964  sWLB.pWC = &pWInfo->sWC;
135965  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
135966  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
135967  whereLoopInit(sWLB.pNew);
135968#ifdef SQLITE_DEBUG
135969  sWLB.pNew->cId = '*';
135970#endif
135971
135972  /* Split the WHERE clause into separate subexpressions where each
135973  ** subexpression is separated by an AND operator.
135974  */
135975  initMaskSet(pMaskSet);
135976  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
135977  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
135978
135979  /* Special case: No FROM clause
135980  */
135981  if( nTabList==0 ){
135982    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
135983    if( wctrlFlags & WHERE_WANT_DISTINCT ){
135984      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
135985    }
135986  }
135987
135988  /* Assign a bit from the bitmask to every term in the FROM clause.
135989  **
135990  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
135991  **
135992  ** The rule of the previous sentence ensures thta if X is the bitmask for
135993  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
135994  ** Knowing the bitmask for all tables to the left of a left join is
135995  ** important.  Ticket #3015.
135996  **
135997  ** Note that bitmasks are created for all pTabList->nSrc tables in
135998  ** pTabList, not just the first nTabList tables.  nTabList is normally
135999  ** equal to pTabList->nSrc but might be shortened to 1 if the
136000  ** WHERE_OR_SUBCLAUSE flag is set.
136001  */
136002  for(ii=0; ii<pTabList->nSrc; ii++){
136003    createMask(pMaskSet, pTabList->a[ii].iCursor);
136004    sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
136005  }
136006#ifdef SQLITE_DEBUG
136007  {
136008    Bitmask mx = 0;
136009    for(ii=0; ii<pTabList->nSrc; ii++){
136010      Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
136011      assert( m>=mx );
136012      mx = m;
136013    }
136014  }
136015#endif
136016
136017  /* Analyze all of the subexpressions. */
136018  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
136019  if( db->mallocFailed ) goto whereBeginError;
136020
136021  /* Special case: WHERE terms that do not refer to any tables in the join
136022  ** (constant expressions). Evaluate each such term, and jump over all the
136023  ** generated code if the result is not true.
136024  **
136025  ** Do not do this if the expression contains non-deterministic functions
136026  ** that are not within a sub-select. This is not strictly required, but
136027  ** preserves SQLite's legacy behaviour in the following two cases:
136028  **
136029  **   FROM ... WHERE random()>0;           -- eval random() once per row
136030  **   FROM ... WHERE (SELECT random())>0;  -- eval random() once overall
136031  */
136032  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
136033    WhereTerm *pT = &sWLB.pWC->a[ii];
136034    if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
136035      sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
136036      pT->wtFlags |= TERM_CODED;
136037    }
136038  }
136039
136040  if( wctrlFlags & WHERE_WANT_DISTINCT ){
136041    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
136042      /* The DISTINCT marking is pointless.  Ignore it. */
136043      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
136044    }else if( pOrderBy==0 ){
136045      /* Try to ORDER BY the result set to make distinct processing easier */
136046      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
136047      pWInfo->pOrderBy = pResultSet;
136048    }
136049  }
136050
136051  /* Construct the WhereLoop objects */
136052#if defined(WHERETRACE_ENABLED)
136053  if( sqlite3WhereTrace & 0xffff ){
136054    sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
136055    if( wctrlFlags & WHERE_USE_LIMIT ){
136056      sqlite3DebugPrintf(", limit: %d", iAuxArg);
136057    }
136058    sqlite3DebugPrintf(")\n");
136059  }
136060  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
136061    sqlite3WhereClausePrint(sWLB.pWC);
136062  }
136063#endif
136064
136065  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
136066    rc = whereLoopAddAll(&sWLB);
136067    if( rc ) goto whereBeginError;
136068
136069#ifdef WHERETRACE_ENABLED
136070    if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
136071      WhereLoop *p;
136072      int i;
136073      static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
136074                                             "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
136075      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
136076        p->cId = zLabel[i%(sizeof(zLabel)-1)];
136077        whereLoopPrint(p, sWLB.pWC);
136078      }
136079    }
136080#endif
136081
136082    wherePathSolver(pWInfo, 0);
136083    if( db->mallocFailed ) goto whereBeginError;
136084    if( pWInfo->pOrderBy ){
136085       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
136086       if( db->mallocFailed ) goto whereBeginError;
136087    }
136088  }
136089  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
136090     pWInfo->revMask = ALLBITS;
136091  }
136092  if( pParse->nErr || NEVER(db->mallocFailed) ){
136093    goto whereBeginError;
136094  }
136095#ifdef WHERETRACE_ENABLED
136096  if( sqlite3WhereTrace ){
136097    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
136098    if( pWInfo->nOBSat>0 ){
136099      sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
136100    }
136101    switch( pWInfo->eDistinct ){
136102      case WHERE_DISTINCT_UNIQUE: {
136103        sqlite3DebugPrintf("  DISTINCT=unique");
136104        break;
136105      }
136106      case WHERE_DISTINCT_ORDERED: {
136107        sqlite3DebugPrintf("  DISTINCT=ordered");
136108        break;
136109      }
136110      case WHERE_DISTINCT_UNORDERED: {
136111        sqlite3DebugPrintf("  DISTINCT=unordered");
136112        break;
136113      }
136114    }
136115    sqlite3DebugPrintf("\n");
136116    for(ii=0; ii<pWInfo->nLevel; ii++){
136117      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
136118    }
136119  }
136120#endif
136121  /* Attempt to omit tables from the join that do not effect the result */
136122  if( pWInfo->nLevel>=2
136123   && pResultSet!=0
136124   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
136125  ){
136126    Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
136127    if( sWLB.pOrderBy ){
136128      tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
136129    }
136130    while( pWInfo->nLevel>=2 ){
136131      WhereTerm *pTerm, *pEnd;
136132      pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
136133      if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
136134      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
136135       && (pLoop->wsFlags & WHERE_ONEROW)==0
136136      ){
136137        break;
136138      }
136139      if( (tabUsed & pLoop->maskSelf)!=0 ) break;
136140      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
136141      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
136142        if( (pTerm->prereqAll & pLoop->maskSelf)!=0
136143         && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
136144        ){
136145          break;
136146        }
136147      }
136148      if( pTerm<pEnd ) break;
136149      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
136150      pWInfo->nLevel--;
136151      nTabList--;
136152    }
136153  }
136154  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
136155  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
136156
136157  /* If the caller is an UPDATE or DELETE statement that is requesting
136158  ** to use a one-pass algorithm, determine if this is appropriate.
136159  */
136160  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
136161  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
136162    int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
136163    int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
136164    if( bOnerow
136165     || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
136166           && 0==(wsFlags & WHERE_VIRTUALTABLE))
136167    ){
136168      pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
136169      if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
136170        if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
136171          bFordelete = OPFLAG_FORDELETE;
136172        }
136173        pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
136174      }
136175    }
136176  }
136177
136178  /* Open all tables in the pTabList and any indices selected for
136179  ** searching those tables.
136180  */
136181  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
136182    Table *pTab;     /* Table to open */
136183    int iDb;         /* Index of database containing table/index */
136184    struct SrcList_item *pTabItem;
136185
136186    pTabItem = &pTabList->a[pLevel->iFrom];
136187    pTab = pTabItem->pTab;
136188    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
136189    pLoop = pLevel->pWLoop;
136190    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
136191      /* Do nothing */
136192    }else
136193#ifndef SQLITE_OMIT_VIRTUALTABLE
136194    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
136195      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
136196      int iCur = pTabItem->iCursor;
136197      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
136198    }else if( IsVirtual(pTab) ){
136199      /* noop */
136200    }else
136201#endif
136202    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
136203         && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
136204      int op = OP_OpenRead;
136205      if( pWInfo->eOnePass!=ONEPASS_OFF ){
136206        op = OP_OpenWrite;
136207        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
136208      };
136209      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
136210      assert( pTabItem->iCursor==pLevel->iTabCur );
136211      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
136212      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
136213      if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
136214        Bitmask b = pTabItem->colUsed;
136215        int n = 0;
136216        for(; b; b=b>>1, n++){}
136217        sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
136218        assert( n<=pTab->nCol );
136219      }
136220#ifdef SQLITE_ENABLE_CURSOR_HINTS
136221      if( pLoop->u.btree.pIndex!=0 ){
136222        sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
136223      }else
136224#endif
136225      {
136226        sqlite3VdbeChangeP5(v, bFordelete);
136227      }
136228#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
136229      sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
136230                            (const u8*)&pTabItem->colUsed, P4_INT64);
136231#endif
136232    }else{
136233      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
136234    }
136235    if( pLoop->wsFlags & WHERE_INDEXED ){
136236      Index *pIx = pLoop->u.btree.pIndex;
136237      int iIndexCur;
136238      int op = OP_OpenRead;
136239      /* iAuxArg is always set if to a positive value if ONEPASS is possible */
136240      assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
136241      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
136242       && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
136243      ){
136244        /* This is one term of an OR-optimization using the PRIMARY KEY of a
136245        ** WITHOUT ROWID table.  No need for a separate index */
136246        iIndexCur = pLevel->iTabCur;
136247        op = 0;
136248      }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
136249        Index *pJ = pTabItem->pTab->pIndex;
136250        iIndexCur = iAuxArg;
136251        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
136252        while( ALWAYS(pJ) && pJ!=pIx ){
136253          iIndexCur++;
136254          pJ = pJ->pNext;
136255        }
136256        op = OP_OpenWrite;
136257        pWInfo->aiCurOnePass[1] = iIndexCur;
136258      }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
136259        iIndexCur = iAuxArg;
136260        op = OP_ReopenIdx;
136261      }else{
136262        iIndexCur = pParse->nTab++;
136263      }
136264      pLevel->iIdxCur = iIndexCur;
136265      assert( pIx->pSchema==pTab->pSchema );
136266      assert( iIndexCur>=0 );
136267      if( op ){
136268        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
136269        sqlite3VdbeSetP4KeyInfo(pParse, pIx);
136270        if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
136271         && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
136272         && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
136273         && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
136274        ){
136275          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
136276        }
136277        VdbeComment((v, "%s", pIx->zName));
136278#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
136279        {
136280          u64 colUsed = 0;
136281          int ii, jj;
136282          for(ii=0; ii<pIx->nColumn; ii++){
136283            jj = pIx->aiColumn[ii];
136284            if( jj<0 ) continue;
136285            if( jj>63 ) jj = 63;
136286            if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
136287            colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
136288          }
136289          sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
136290                                (u8*)&colUsed, P4_INT64);
136291        }
136292#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
136293      }
136294    }
136295    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
136296  }
136297  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
136298  if( db->mallocFailed ) goto whereBeginError;
136299
136300  /* Generate the code to do the search.  Each iteration of the for
136301  ** loop below generates code for a single nested loop of the VM
136302  ** program.
136303  */
136304  notReady = ~(Bitmask)0;
136305  for(ii=0; ii<nTabList; ii++){
136306    int addrExplain;
136307    int wsFlags;
136308    pLevel = &pWInfo->a[ii];
136309    wsFlags = pLevel->pWLoop->wsFlags;
136310#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
136311    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
136312      constructAutomaticIndex(pParse, &pWInfo->sWC,
136313                &pTabList->a[pLevel->iFrom], notReady, pLevel);
136314      if( db->mallocFailed ) goto whereBeginError;
136315    }
136316#endif
136317    addrExplain = sqlite3WhereExplainOneScan(
136318        pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
136319    );
136320    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
136321    notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
136322    pWInfo->iContinue = pLevel->addrCont;
136323    if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
136324      sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
136325    }
136326  }
136327
136328  /* Done. */
136329  VdbeModuleComment((v, "Begin WHERE-core"));
136330  return pWInfo;
136331
136332  /* Jump here if malloc fails */
136333whereBeginError:
136334  if( pWInfo ){
136335    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
136336    whereInfoFree(db, pWInfo);
136337  }
136338  return 0;
136339}
136340
136341/*
136342** Generate the end of the WHERE loop.  See comments on
136343** sqlite3WhereBegin() for additional information.
136344*/
136345SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
136346  Parse *pParse = pWInfo->pParse;
136347  Vdbe *v = pParse->pVdbe;
136348  int i;
136349  WhereLevel *pLevel;
136350  WhereLoop *pLoop;
136351  SrcList *pTabList = pWInfo->pTabList;
136352  sqlite3 *db = pParse->db;
136353
136354  /* Generate loop termination code.
136355  */
136356  VdbeModuleComment((v, "End WHERE-core"));
136357  sqlite3ExprCacheClear(pParse);
136358  for(i=pWInfo->nLevel-1; i>=0; i--){
136359    int addr;
136360    pLevel = &pWInfo->a[i];
136361    pLoop = pLevel->pWLoop;
136362    if( pLevel->op!=OP_Noop ){
136363#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
136364      int addrSeek = 0;
136365      Index *pIdx;
136366      int n;
136367      if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
136368       && (pLoop->wsFlags & WHERE_INDEXED)!=0
136369       && (pIdx = pLoop->u.btree.pIndex)->hasStat1
136370       && (n = pLoop->u.btree.nIdxCol)>0
136371       && pIdx->aiRowLogEst[n]>=36
136372      ){
136373        int r1 = pParse->nMem+1;
136374        int j, op;
136375        for(j=0; j<n; j++){
136376          sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
136377        }
136378        pParse->nMem += n+1;
136379        op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
136380        addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
136381        VdbeCoverageIf(v, op==OP_SeekLT);
136382        VdbeCoverageIf(v, op==OP_SeekGT);
136383        sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
136384      }
136385#endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
136386      /* The common case: Advance to the next row */
136387      sqlite3VdbeResolveLabel(v, pLevel->addrCont);
136388      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
136389      sqlite3VdbeChangeP5(v, pLevel->p5);
136390      VdbeCoverage(v);
136391      VdbeCoverageIf(v, pLevel->op==OP_Next);
136392      VdbeCoverageIf(v, pLevel->op==OP_Prev);
136393      VdbeCoverageIf(v, pLevel->op==OP_VNext);
136394#ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
136395      if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
136396#endif
136397    }else{
136398      sqlite3VdbeResolveLabel(v, pLevel->addrCont);
136399    }
136400    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
136401      struct InLoop *pIn;
136402      int j;
136403      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
136404      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
136405        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
136406        if( pIn->eEndLoopOp!=OP_Noop ){
136407          sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
136408          VdbeCoverage(v);
136409          VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
136410          VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
136411        }
136412        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
136413      }
136414    }
136415    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
136416    if( pLevel->addrSkip ){
136417      sqlite3VdbeGoto(v, pLevel->addrSkip);
136418      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
136419      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
136420      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
136421    }
136422#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
136423    if( pLevel->addrLikeRep ){
136424      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
136425                        pLevel->addrLikeRep);
136426      VdbeCoverage(v);
136427    }
136428#endif
136429    if( pLevel->iLeftJoin ){
136430      int ws = pLoop->wsFlags;
136431      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
136432      assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
136433      if( (ws & WHERE_IDX_ONLY)==0 ){
136434        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
136435      }
136436      if( (ws & WHERE_INDEXED)
136437       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
136438      ){
136439        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
136440      }
136441      if( pLevel->op==OP_Return ){
136442        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
136443      }else{
136444        sqlite3VdbeGoto(v, pLevel->addrFirst);
136445      }
136446      sqlite3VdbeJumpHere(v, addr);
136447    }
136448    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
136449                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
136450  }
136451
136452  /* The "break" point is here, just past the end of the outer loop.
136453  ** Set it.
136454  */
136455  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
136456
136457  assert( pWInfo->nLevel<=pTabList->nSrc );
136458  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
136459    int k, last;
136460    VdbeOp *pOp;
136461    Index *pIdx = 0;
136462    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
136463    Table *pTab = pTabItem->pTab;
136464    assert( pTab!=0 );
136465    pLoop = pLevel->pWLoop;
136466
136467    /* For a co-routine, change all OP_Column references to the table of
136468    ** the co-routine into OP_Copy of result contained in a register.
136469    ** OP_Rowid becomes OP_Null.
136470    */
136471    if( pTabItem->fg.viaCoroutine ){
136472      testcase( pParse->db->mallocFailed );
136473      translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
136474                            pTabItem->regResult, 0);
136475      continue;
136476    }
136477
136478    /* If this scan uses an index, make VDBE code substitutions to read data
136479    ** from the index instead of from the table where possible.  In some cases
136480    ** this optimization prevents the table from ever being read, which can
136481    ** yield a significant performance boost.
136482    **
136483    ** Calls to the code generator in between sqlite3WhereBegin and
136484    ** sqlite3WhereEnd will have created code that references the table
136485    ** directly.  This loop scans all that code looking for opcodes
136486    ** that reference the table and converts them into opcodes that
136487    ** reference the index.
136488    */
136489    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
136490      pIdx = pLoop->u.btree.pIndex;
136491    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
136492      pIdx = pLevel->u.pCovidx;
136493    }
136494    if( pIdx
136495     && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
136496     && !db->mallocFailed
136497    ){
136498      last = sqlite3VdbeCurrentAddr(v);
136499      k = pLevel->addrBody;
136500      pOp = sqlite3VdbeGetOp(v, k);
136501      for(; k<last; k++, pOp++){
136502        if( pOp->p1!=pLevel->iTabCur ) continue;
136503        if( pOp->opcode==OP_Column ){
136504          int x = pOp->p2;
136505          assert( pIdx->pTable==pTab );
136506          if( !HasRowid(pTab) ){
136507            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
136508            x = pPk->aiColumn[x];
136509            assert( x>=0 );
136510          }
136511          x = sqlite3ColumnOfIndex(pIdx, x);
136512          if( x>=0 ){
136513            pOp->p2 = x;
136514            pOp->p1 = pLevel->iIdxCur;
136515          }
136516          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
136517              || pWInfo->eOnePass );
136518        }else if( pOp->opcode==OP_Rowid ){
136519          pOp->p1 = pLevel->iIdxCur;
136520          pOp->opcode = OP_IdxRowid;
136521        }else if( pOp->opcode==OP_IfNullRow ){
136522          pOp->p1 = pLevel->iIdxCur;
136523        }
136524      }
136525    }
136526  }
136527
136528  /* Final cleanup
136529  */
136530  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
136531  whereInfoFree(db, pWInfo);
136532  return;
136533}
136534
136535/************** End of where.c ***********************************************/
136536/************** Begin file parse.c *******************************************/
136537/*
136538** 2000-05-29
136539**
136540** The author disclaims copyright to this source code.  In place of
136541** a legal notice, here is a blessing:
136542**
136543**    May you do good and not evil.
136544**    May you find forgiveness for yourself and forgive others.
136545**    May you share freely, never taking more than you give.
136546**
136547*************************************************************************
136548** Driver template for the LEMON parser generator.
136549**
136550** The "lemon" program processes an LALR(1) input grammar file, then uses
136551** this template to construct a parser.  The "lemon" program inserts text
136552** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
136553** interstitial "-" characters) contained in this template is changed into
136554** the value of the %name directive from the grammar.  Otherwise, the content
136555** of this template is copied straight through into the generate parser
136556** source file.
136557**
136558** The following is the concatenation of all %include directives from the
136559** input grammar file:
136560*/
136561/* #include <stdio.h> */
136562/************ Begin %include sections from the grammar ************************/
136563
136564/* #include "sqliteInt.h" */
136565
136566/*
136567** Disable all error recovery processing in the parser push-down
136568** automaton.
136569*/
136570#define YYNOERRORRECOVERY 1
136571
136572/*
136573** Make yytestcase() the same as testcase()
136574*/
136575#define yytestcase(X) testcase(X)
136576
136577/*
136578** Indicate that sqlite3ParserFree() will never be called with a null
136579** pointer.
136580*/
136581#define YYPARSEFREENEVERNULL 1
136582
136583/*
136584** In the amalgamation, the parse.c file generated by lemon and the
136585** tokenize.c file are concatenated.  In that case, sqlite3RunParser()
136586** has access to the the size of the yyParser object and so the parser
136587** engine can be allocated from stack.  In that case, only the
136588** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
136589** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
136590** omitted.
136591*/
136592#ifdef SQLITE_AMALGAMATION
136593# define sqlite3Parser_ENGINEALWAYSONSTACK 1
136594#endif
136595
136596/*
136597** Alternative datatype for the argument to the malloc() routine passed
136598** into sqlite3ParserAlloc().  The default is size_t.
136599*/
136600#define YYMALLOCARGTYPE  u64
136601
136602/*
136603** An instance of this structure holds information about the
136604** LIMIT clause of a SELECT statement.
136605*/
136606struct LimitVal {
136607  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
136608  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
136609};
136610
136611/*
136612** An instance of the following structure describes the event of a
136613** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
136614** TK_DELETE, or TK_INSTEAD.  If the event is of the form
136615**
136616**      UPDATE ON (a,b,c)
136617**
136618** Then the "b" IdList records the list "a,b,c".
136619*/
136620struct TrigEvent { int a; IdList * b; };
136621
136622/*
136623** Disable lookaside memory allocation for objects that might be
136624** shared across database connections.
136625*/
136626static void disableLookaside(Parse *pParse){
136627  pParse->disableLookaside++;
136628  pParse->db->lookaside.bDisable++;
136629}
136630
136631
136632  /*
136633  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
136634  ** all elements in the list.  And make sure list length does not exceed
136635  ** SQLITE_LIMIT_COMPOUND_SELECT.
136636  */
136637  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
136638    if( p->pPrior ){
136639      Select *pNext = 0, *pLoop;
136640      int mxSelect, cnt = 0;
136641      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
136642        pLoop->pNext = pNext;
136643        pLoop->selFlags |= SF_Compound;
136644      }
136645      if( (p->selFlags & SF_MultiValue)==0 &&
136646        (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
136647        cnt>mxSelect
136648      ){
136649        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
136650      }
136651    }
136652  }
136653
136654  /* This is a utility routine used to set the ExprSpan.zStart and
136655  ** ExprSpan.zEnd values of pOut so that the span covers the complete
136656  ** range of text beginning with pStart and going to the end of pEnd.
136657  */
136658  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
136659    pOut->zStart = pStart->z;
136660    pOut->zEnd = &pEnd->z[pEnd->n];
136661  }
136662
136663  /* Construct a new Expr object from a single identifier.  Use the
136664  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
136665  ** that created the expression.
136666  */
136667  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
136668    Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
136669    if( p ){
136670      memset(p, 0, sizeof(Expr));
136671      p->op = (u8)op;
136672      p->flags = EP_Leaf;
136673      p->iAgg = -1;
136674      p->u.zToken = (char*)&p[1];
136675      memcpy(p->u.zToken, t.z, t.n);
136676      p->u.zToken[t.n] = 0;
136677      if( sqlite3Isquote(p->u.zToken[0]) ){
136678        if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
136679        sqlite3Dequote(p->u.zToken);
136680      }
136681#if SQLITE_MAX_EXPR_DEPTH>0
136682      p->nHeight = 1;
136683#endif
136684    }
136685    pOut->pExpr = p;
136686    pOut->zStart = t.z;
136687    pOut->zEnd = &t.z[t.n];
136688  }
136689
136690  /* This routine constructs a binary expression node out of two ExprSpan
136691  ** objects and uses the result to populate a new ExprSpan object.
136692  */
136693  static void spanBinaryExpr(
136694    Parse *pParse,      /* The parsing context.  Errors accumulate here */
136695    int op,             /* The binary operation */
136696    ExprSpan *pLeft,    /* The left operand, and output */
136697    ExprSpan *pRight    /* The right operand */
136698  ){
136699    pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr);
136700    pLeft->zEnd = pRight->zEnd;
136701  }
136702
136703  /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
136704  ** outside of *ppExpr.
136705  */
136706  static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
136707    if( doNot ){
136708      pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0);
136709    }
136710  }
136711
136712  /* Construct an expression node for a unary postfix operator
136713  */
136714  static void spanUnaryPostfix(
136715    Parse *pParse,         /* Parsing context to record errors */
136716    int op,                /* The operator */
136717    ExprSpan *pOperand,    /* The operand, and output */
136718    Token *pPostOp         /* The operand token for setting the span */
136719  ){
136720    pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
136721    pOperand->zEnd = &pPostOp->z[pPostOp->n];
136722  }
136723
136724  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
136725  ** unary TK_ISNULL or TK_NOTNULL expression. */
136726  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
136727    sqlite3 *db = pParse->db;
136728    if( pA && pY && pY->op==TK_NULL ){
136729      pA->op = (u8)op;
136730      sqlite3ExprDelete(db, pA->pRight);
136731      pA->pRight = 0;
136732    }
136733  }
136734
136735  /* Construct an expression node for a unary prefix operator
136736  */
136737  static void spanUnaryPrefix(
136738    ExprSpan *pOut,        /* Write the new expression node here */
136739    Parse *pParse,         /* Parsing context to record errors */
136740    int op,                /* The operator */
136741    ExprSpan *pOperand,    /* The operand */
136742    Token *pPreOp         /* The operand token for setting the span */
136743  ){
136744    pOut->zStart = pPreOp->z;
136745    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
136746    pOut->zEnd = pOperand->zEnd;
136747  }
136748
136749  /* Add a single new term to an ExprList that is used to store a
136750  ** list of identifiers.  Report an error if the ID list contains
136751  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
136752  ** error while parsing a legacy schema.
136753  */
136754  static ExprList *parserAddExprIdListTerm(
136755    Parse *pParse,
136756    ExprList *pPrior,
136757    Token *pIdToken,
136758    int hasCollate,
136759    int sortOrder
136760  ){
136761    ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
136762    if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
136763        && pParse->db->init.busy==0
136764    ){
136765      sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
136766                         pIdToken->n, pIdToken->z);
136767    }
136768    sqlite3ExprListSetName(pParse, p, pIdToken, 1);
136769    return p;
136770  }
136771/**************** End of %include directives **********************************/
136772/* These constants specify the various numeric values for terminal symbols
136773** in a format understandable to "makeheaders".  This section is blank unless
136774** "lemon" is run with the "-m" command-line option.
136775***************** Begin makeheaders token definitions *************************/
136776/**************** End makeheaders token definitions ***************************/
136777
136778/* The next sections is a series of control #defines.
136779** various aspects of the generated parser.
136780**    YYCODETYPE         is the data type used to store the integer codes
136781**                       that represent terminal and non-terminal symbols.
136782**                       "unsigned char" is used if there are fewer than
136783**                       256 symbols.  Larger types otherwise.
136784**    YYNOCODE           is a number of type YYCODETYPE that is not used for
136785**                       any terminal or nonterminal symbol.
136786**    YYFALLBACK         If defined, this indicates that one or more tokens
136787**                       (also known as: "terminal symbols") have fall-back
136788**                       values which should be used if the original symbol
136789**                       would not parse.  This permits keywords to sometimes
136790**                       be used as identifiers, for example.
136791**    YYACTIONTYPE       is the data type used for "action codes" - numbers
136792**                       that indicate what to do in response to the next
136793**                       token.
136794**    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
136795**                       symbols.  Background: A "minor type" is a semantic
136796**                       value associated with a terminal or non-terminal
136797**                       symbols.  For example, for an "ID" terminal symbol,
136798**                       the minor type might be the name of the identifier.
136799**                       Each non-terminal can have a different minor type.
136800**                       Terminal symbols all have the same minor type, though.
136801**                       This macros defines the minor type for terminal
136802**                       symbols.
136803**    YYMINORTYPE        is the data type used for all minor types.
136804**                       This is typically a union of many types, one of
136805**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
136806**                       for terminal symbols is called "yy0".
136807**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
136808**                       zero the stack is dynamically sized using realloc()
136809**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
136810**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
136811**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
136812**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
136813**    YYERRORSYMBOL      is the code number of the error symbol.  If not
136814**                       defined, then do no error processing.
136815**    YYNSTATE           the combined number of states.
136816**    YYNRULE            the number of rules in the grammar
136817**    YY_MAX_SHIFT       Maximum value for shift actions
136818**    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
136819**    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
136820**    YY_MIN_REDUCE      Maximum value for reduce actions
136821**    YY_ERROR_ACTION    The yy_action[] code for syntax error
136822**    YY_ACCEPT_ACTION   The yy_action[] code for accept
136823**    YY_NO_ACTION       The yy_action[] code for no-op
136824*/
136825#ifndef INTERFACE
136826# define INTERFACE 1
136827#endif
136828/************* Begin control #defines *****************************************/
136829#define YYCODETYPE unsigned char
136830#define YYNOCODE 252
136831#define YYACTIONTYPE unsigned short int
136832#define YYWILDCARD 69
136833#define sqlite3ParserTOKENTYPE Token
136834typedef union {
136835  int yyinit;
136836  sqlite3ParserTOKENTYPE yy0;
136837  Expr* yy72;
136838  TriggerStep* yy145;
136839  ExprList* yy148;
136840  SrcList* yy185;
136841  ExprSpan yy190;
136842  int yy194;
136843  Select* yy243;
136844  IdList* yy254;
136845  With* yy285;
136846  struct TrigEvent yy332;
136847  struct LimitVal yy354;
136848  struct {int value; int mask;} yy497;
136849} YYMINORTYPE;
136850#ifndef YYSTACKDEPTH
136851#define YYSTACKDEPTH 100
136852#endif
136853#define sqlite3ParserARG_SDECL Parse *pParse;
136854#define sqlite3ParserARG_PDECL ,Parse *pParse
136855#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
136856#define sqlite3ParserARG_STORE yypParser->pParse = pParse
136857#define YYFALLBACK 1
136858#define YYNSTATE             455
136859#define YYNRULE              329
136860#define YY_MAX_SHIFT         454
136861#define YY_MIN_SHIFTREDUCE   664
136862#define YY_MAX_SHIFTREDUCE   992
136863#define YY_MIN_REDUCE        993
136864#define YY_MAX_REDUCE        1321
136865#define YY_ERROR_ACTION      1322
136866#define YY_ACCEPT_ACTION     1323
136867#define YY_NO_ACTION         1324
136868/************* End control #defines *******************************************/
136869
136870/* Define the yytestcase() macro to be a no-op if is not already defined
136871** otherwise.
136872**
136873** Applications can choose to define yytestcase() in the %include section
136874** to a macro that can assist in verifying code coverage.  For production
136875** code the yytestcase() macro should be turned off.  But it is useful
136876** for testing.
136877*/
136878#ifndef yytestcase
136879# define yytestcase(X)
136880#endif
136881
136882
136883/* Next are the tables used to determine what action to take based on the
136884** current state and lookahead token.  These tables are used to implement
136885** functions that take a state number and lookahead value and return an
136886** action integer.
136887**
136888** Suppose the action integer is N.  Then the action is determined as
136889** follows
136890**
136891**   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
136892**                                      token onto the stack and goto state N.
136893**
136894**   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
136895**     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
136896**
136897**   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
136898**     and YY_MAX_REDUCE
136899**
136900**   N == YY_ERROR_ACTION               A syntax error has occurred.
136901**
136902**   N == YY_ACCEPT_ACTION              The parser accepts its input.
136903**
136904**   N == YY_NO_ACTION                  No such action.  Denotes unused
136905**                                      slots in the yy_action[] table.
136906**
136907** The action table is constructed as a single large table named yy_action[].
136908** Given state S and lookahead X, the action is computed as either:
136909**
136910**    (A)   N = yy_action[ yy_shift_ofst[S] + X ]
136911**    (B)   N = yy_default[S]
136912**
136913** The (A) formula is preferred.  The B formula is used instead if:
136914**    (1)  The yy_shift_ofst[S]+X value is out of range, or
136915**    (2)  yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
136916**    (3)  yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
136917** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
136918** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
136919** Hence only tests (1) and (2) need to be evaluated.)
136920**
136921** The formulas above are for computing the action when the lookahead is
136922** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
136923** a reduce action) then the yy_reduce_ofst[] array is used in place of
136924** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
136925** YY_SHIFT_USE_DFLT.
136926**
136927** The following are the tables generated in this section:
136928**
136929**  yy_action[]        A single table containing all actions.
136930**  yy_lookahead[]     A table containing the lookahead for each entry in
136931**                     yy_action.  Used to detect hash collisions.
136932**  yy_shift_ofst[]    For each state, the offset into yy_action for
136933**                     shifting terminals.
136934**  yy_reduce_ofst[]   For each state, the offset into yy_action for
136935**                     shifting non-terminals after a reduce.
136936**  yy_default[]       Default action for each state.
136937**
136938*********** Begin parsing tables **********************************************/
136939#define YY_ACTTAB_COUNT (1565)
136940static const YYACTIONTYPE yy_action[] = {
136941 /*     0 */   324,  410,  342,  747,  747,  203,  939,  353,  969,   98,
136942 /*    10 */    98,   98,   98,   91,   96,   96,   96,   96,   95,   95,
136943 /*    20 */    94,   94,   94,   93,  350, 1323,  155,  155,    2,  808,
136944 /*    30 */   971,  971,   98,   98,   98,   98,   20,   96,   96,   96,
136945 /*    40 */    96,   95,   95,   94,   94,   94,   93,  350,   92,   89,
136946 /*    50 */   178,   99,  100,   90,  847,  850,  839,  839,   97,   97,
136947 /*    60 */    98,   98,   98,   98,  350,   96,   96,   96,   96,   95,
136948 /*    70 */    95,   94,   94,   94,   93,  350,  324,  339,  969,  262,
136949 /*    80 */   364,  251,  212,  169,  287,  404,  282,  403,  199,  786,
136950 /*    90 */   242,  411,   21,  950,  378,  280,   93,  350,  787,   95,
136951 /*   100 */    95,   94,   94,   94,   93,  350,  971,  971,   96,   96,
136952 /*   110 */    96,   96,   95,   95,   94,   94,   94,   93,  350,  808,
136953 /*   120 */   328,  242,  411, 1235,  826, 1235,  132,   99,  100,   90,
136954 /*   130 */   847,  850,  839,  839,   97,   97,   98,   98,   98,   98,
136955 /*   140 */   449,   96,   96,   96,   96,   95,   95,   94,   94,   94,
136956 /*   150 */    93,  350,  324,  819,  348,  347,  120,  818,  120,   75,
136957 /*   160 */    52,   52,  950,  951,  952, 1084,  977,  146,  360,  262,
136958 /*   170 */   369,  261,  950,  975,  954,  976,   92,   89,  178,  370,
136959 /*   180 */   230,  370,  971,  971, 1141,  360,  359,  101,  818,  818,
136960 /*   190 */   820,  383,   24, 1286,  380,  427,  412,  368,  978,  379,
136961 /*   200 */   978, 1032,  324,   99,  100,   90,  847,  850,  839,  839,
136962 /*   210 */    97,   97,   98,   98,   98,   98,  372,   96,   96,   96,
136963 /*   220 */    96,   95,   95,   94,   94,   94,   93,  350,  950,  132,
136964 /*   230 */   890,  449,  971,  971,  890,   60,   94,   94,   94,   93,
136965 /*   240 */   350,  950,  951,  952,  954,  103,  360,  950,  384,  333,
136966 /*   250 */   697,   52,   52,   99,  100,   90,  847,  850,  839,  839,
136967 /*   260 */    97,   97,   98,   98,   98,   98, 1022,   96,   96,   96,
136968 /*   270 */    96,   95,   95,   94,   94,   94,   93,  350,  324,  454,
136969 /*   280 */   995,  449,  227,   61,  157,  243,  343,  114, 1025, 1211,
136970 /*   290 */   147,  826,  950,  372, 1071,  950,  319,  950,  951,  952,
136971 /*   300 */   194,   10,   10,  401,  398,  397, 1211, 1213,  971,  971,
136972 /*   310 */   757,  171,  170,  157,  396,  336,  950,  951,  952,  697,
136973 /*   320 */   819,  310,  153,  950,  818,  320,   82,   23,   80,   99,
136974 /*   330 */   100,   90,  847,  850,  839,  839,   97,   97,   98,   98,
136975 /*   340 */    98,   98,  888,   96,   96,   96,   96,   95,   95,   94,
136976 /*   350 */    94,   94,   93,  350,  324,  818,  818,  820,  277,  231,
136977 /*   360 */   300,  950,  951,  952,  950,  951,  952, 1211,  194,   25,
136978 /*   370 */   449,  401,  398,  397,  950,  354,  300,  449,  950,   74,
136979 /*   380 */   449,    1,  396,  132,  971,  971,  950,  224,  224,  808,
136980 /*   390 */    10,   10,  950,  951,  952, 1290,  132,   52,   52,  414,
136981 /*   400 */    52,   52, 1063, 1063,  338,   99,  100,   90,  847,  850,
136982 /*   410 */   839,  839,   97,   97,   98,   98,   98,   98, 1114,   96,
136983 /*   420 */    96,   96,   96,   95,   95,   94,   94,   94,   93,  350,
136984 /*   430 */   324, 1113,  427,  417,  701,  427,  426, 1260, 1260,  262,
136985 /*   440 */   369,  261,  950,  950,  951,  952,  752,  950,  951,  952,
136986 /*   450 */   449,  751,  449, 1058, 1037,  950,  951,  952,  442,  706,
136987 /*   460 */   971,  971, 1058,  393,   92,   89,  178,  446,  446,  446,
136988 /*   470 */    51,   51,   52,   52,  438,  773, 1024,   92,   89,  178,
136989 /*   480 */   172,   99,  100,   90,  847,  850,  839,  839,   97,   97,
136990 /*   490 */    98,   98,   98,   98,  198,   96,   96,   96,   96,   95,
136991 /*   500 */    95,   94,   94,   94,   93,  350,  324,  427,  407,  909,
136992 /*   510 */   694,  950,  951,  952,   92,   89,  178,  224,  224,  157,
136993 /*   520 */   241,  221,  418,  299,  771,  910,  415,  374,  449,  414,
136994 /*   530 */    58,  323, 1061, 1061, 1242,  378,  971,  971,  378,  772,
136995 /*   540 */   448,  911,  362,  735,  296,  681,    9,    9,   52,   52,
136996 /*   550 */   234,  329,  234,  256,  416,  736,  280,   99,  100,   90,
136997 /*   560 */   847,  850,  839,  839,   97,   97,   98,   98,   98,   98,
136998 /*   570 */   449,   96,   96,   96,   96,   95,   95,   94,   94,   94,
136999 /*   580 */    93,  350,  324,  422,   72,  449,  827,  120,  367,  449,
137000 /*   590 */    10,   10,    5,  301,  203,  449,  177,  969,  253,  419,
137001 /*   600 */   255,  771,  200,  175,  233,   10,   10,  836,  836,   36,
137002 /*   610 */    36, 1289,  971,  971,  724,   37,   37,  348,  347,  424,
137003 /*   620 */   203,  260,  771,  969,  232,  930, 1316,  870,  337, 1316,
137004 /*   630 */   421,  848,  851,   99,  100,   90,  847,  850,  839,  839,
137005 /*   640 */    97,   97,   98,   98,   98,   98,  268,   96,   96,   96,
137006 /*   650 */    96,   95,   95,   94,   94,   94,   93,  350,  324,  840,
137007 /*   660 */   449,  978,  813,  978, 1200,  449,  909,  969,  715,  349,
137008 /*   670 */   349,  349,  928,  177,  449,  930, 1317,  254,  198, 1317,
137009 /*   680 */    12,   12,  910,  402,  449,   27,   27,  250,  971,  971,
137010 /*   690 */   118,  716,  162,  969,   38,   38,  268,  176,  911,  771,
137011 /*   700 */   432, 1265,  939,  353,   39,   39,  316,  991,  324,   99,
137012 /*   710 */   100,   90,  847,  850,  839,  839,   97,   97,   98,   98,
137013 /*   720 */    98,   98,  928,   96,   96,   96,   96,   95,   95,   94,
137014 /*   730 */    94,   94,   93,  350,  449,  329,  449,  357,  971,  971,
137015 /*   740 */  1041,  316,  929,  340,  893,  893,  386,  669,  670,  671,
137016 /*   750 */   275, 1318,  317,  992,   40,   40,   41,   41,  268,   99,
137017 /*   760 */   100,   90,  847,  850,  839,  839,   97,   97,   98,   98,
137018 /*   770 */    98,   98,  449,   96,   96,   96,   96,   95,   95,   94,
137019 /*   780 */    94,   94,   93,  350,  324,  449,  355,  449,  992,  449,
137020 /*   790 */  1016,  330,   42,   42,  786,  270,  449,  273,  449,  228,
137021 /*   800 */   449,  298,  449,  787,  449,   28,   28,   29,   29,   31,
137022 /*   810 */    31,  449, 1141,  449,  971,  971,   43,   43,   44,   44,
137023 /*   820 */    45,   45,   11,   11,   46,   46,  887,   78,  887,  268,
137024 /*   830 */   268,  105,  105,   47,   47,   99,  100,   90,  847,  850,
137025 /*   840 */   839,  839,   97,   97,   98,   98,   98,   98,  449,   96,
137026 /*   850 */    96,   96,   96,   95,   95,   94,   94,   94,   93,  350,
137027 /*   860 */   324,  449,  117,  449, 1073,  158,  449,  691,   48,   48,
137028 /*   870 */   229, 1241,  449, 1250,  449,  414,  449,  334,  449,  245,
137029 /*   880 */   449,   33,   33,   49,   49,  449,   50,   50,  246, 1141,
137030 /*   890 */   971,  971,   34,   34,  122,  122,  123,  123,  124,  124,
137031 /*   900 */    56,   56,  268,   81,  249,   35,   35,  197,  196,  195,
137032 /*   910 */   324,   99,  100,   90,  847,  850,  839,  839,   97,   97,
137033 /*   920 */    98,   98,   98,   98,  449,   96,   96,   96,   96,   95,
137034 /*   930 */    95,   94,   94,   94,   93,  350,  449,  691,  449, 1141,
137035 /*   940 */   971,  971,  968, 1207,  106,  106,  268, 1209,  268, 1266,
137036 /*   950 */     2,  886,  268,  886,  335, 1040,   53,   53,  107,  107,
137037 /*   960 */   324,   99,  100,   90,  847,  850,  839,  839,   97,   97,
137038 /*   970 */    98,   98,   98,   98,  449,   96,   96,   96,   96,   95,
137039 /*   980 */    95,   94,   94,   94,   93,  350,  449, 1070,  449, 1066,
137040 /*   990 */   971,  971, 1039,  267,  108,  108,  445,  330,  331,  133,
137041 /*  1000 */   223,  175,  301,  225,  385, 1255,  104,  104,  121,  121,
137042 /*  1010 */   324,   99,   88,   90,  847,  850,  839,  839,   97,   97,
137043 /*  1020 */    98,   98,   98,   98, 1141,   96,   96,   96,   96,   95,
137044 /*  1030 */    95,   94,   94,   94,   93,  350,  449,  346,  449,  167,
137045 /*  1040 */   971,  971,  925,  810,  371,  318,  202,  202,  373,  263,
137046 /*  1050 */   394,  202,   74,  208,  721,  722,  119,  119,  112,  112,
137047 /*  1060 */   324,  406,  100,   90,  847,  850,  839,  839,   97,   97,
137048 /*  1070 */    98,   98,   98,   98,  449,   96,   96,   96,   96,   95,
137049 /*  1080 */    95,   94,   94,   94,   93,  350,  449,  752,  449,  344,
137050 /*  1090 */   971,  971,  751,  278,  111,  111,   74,  714,  713,  704,
137051 /*  1100 */   286,  877,  749, 1279,  257,   77,  109,  109,  110,  110,
137052 /*  1110 */  1230,  285, 1134,   90,  847,  850,  839,  839,   97,   97,
137053 /*  1120 */    98,   98,   98,   98, 1233,   96,   96,   96,   96,   95,
137054 /*  1130 */    95,   94,   94,   94,   93,  350,   86,  444,  449,    3,
137055 /*  1140 */  1193,  449, 1069,  132,  351,  120, 1013,   86,  444,  780,
137056 /*  1150 */     3, 1091,  202,  376,  447,  351, 1229,  120,   55,   55,
137057 /*  1160 */   449,   57,   57,  822,  873,  447,  449,  208,  449,  704,
137058 /*  1170 */   449,  877,  237,  433,  435,  120,  439,  428,  361,  120,
137059 /*  1180 */    54,   54,  132,  449,  433,  826,   52,   52,   26,   26,
137060 /*  1190 */    30,   30,  381,  132,  408,  443,  826,  689,  264,  389,
137061 /*  1200 */   116,  269,  272,   32,   32,   83,   84,  120,  274,  120,
137062 /*  1210 */   120,  276,   85,  351,  451,  450,   83,   84,  818, 1054,
137063 /*  1220 */  1038,  427,  429,   85,  351,  451,  450,  120,  120,  818,
137064 /*  1230 */   377,  218,  281,  822, 1107, 1140,   86,  444,  409,    3,
137065 /*  1240 */  1087, 1098,  430,  431,  351,  302,  303, 1146, 1021,  818,
137066 /*  1250 */   818,  820,  821,   19,  447, 1015, 1004, 1003, 1005, 1273,
137067 /*  1260 */   818,  818,  820,  821,   19,  289,  159,  291,  293,    7,
137068 /*  1270 */   315,  173,  259,  433, 1129,  363,  252, 1232,  375, 1037,
137069 /*  1280 */   295,  434,  168,  986,  399,  826,  284, 1204, 1203,  205,
137070 /*  1290 */  1276,  308, 1249,   86,  444,  983,    3, 1247,  332,  144,
137071 /*  1300 */   130,  351,   72,  135,   59,   83,   84,  756,  137,  365,
137072 /*  1310 */  1126,  447,   85,  351,  451,  450,  139,  226,  818,  140,
137073 /*  1320 */   156,   62,  314,  314,  313,  215,  311,  366,  392,  678,
137074 /*  1330 */   433,  185,  141, 1234,  142,  160,  148, 1136, 1198,  382,
137075 /*  1340 */   189,   67,  826,  180,  388,  248, 1218, 1099,  219,  818,
137076 /*  1350 */   818,  820,  821,   19,  247,  190,  266,  154,  390,  271,
137077 /*  1360 */   191,  192,   83,   84, 1006,  405, 1057,  182,  321,   85,
137078 /*  1370 */   351,  451,  450, 1056,  183,  818,  341,  132,  181,  706,
137079 /*  1380 */  1055,  420,   76,  444, 1029,    3,  322, 1028,  283, 1048,
137080 /*  1390 */   351, 1095, 1027, 1288, 1047,   71,  204,    6,  288,  290,
137081 /*  1400 */   447, 1096, 1094, 1093,   79,  292,  818,  818,  820,  821,
137082 /*  1410 */    19,  294,  297,  437,  345,  441,  102, 1184, 1077,  433,
137083 /*  1420 */   238,  425,   73,  305,  239,  304,  325,  240,  423,  306,
137084 /*  1430 */   307,  826,  213, 1012,   22,  945,  452,  214,  216,  217,
137085 /*  1440 */   453, 1001,  115,  996,  125,  126,  235,  127,  665,  352,
137086 /*  1450 */   326,   83,   84,  358,  166,  244,  179,  327,   85,  351,
137087 /*  1460 */   451,  450,  134,  356,  818,  113,  885,  806,  883,  136,
137088 /*  1470 */   128,  138,  738,  258,  184,  899,  143,  145,   63,   64,
137089 /*  1480 */    65,   66,  129,  902,  187,  186,  898,    8,   13,  188,
137090 /*  1490 */   265,  891,  149,  202,  980,  818,  818,  820,  821,   19,
137091 /*  1500 */   150,  387,  161,  680,  285,  391,  151,  395,  400,  193,
137092 /*  1510 */    68,   14,  236,  279,   15,   69,  717,  825,  131,  824,
137093 /*  1520 */   853,   70,  746,   16,  413,  750,    4,  174,  220,  222,
137094 /*  1530 */   152,  779,  857,  774,  201,   77,   74,  868,   17,  854,
137095 /*  1540 */   852,  908,   18,  907,  207,  206,  934,  163,  436,  210,
137096 /*  1550 */   935,  164,  209,  165,  440,  856,  823,  690,   87,  211,
137097 /*  1560 */   309,  312, 1281,  940, 1280,
137098};
137099static const YYCODETYPE yy_lookahead[] = {
137100 /*     0 */    19,  115,   19,  117,  118,   24,    1,    2,   27,   79,
137101 /*    10 */    80,   81,   82,   83,   84,   85,   86,   87,   88,   89,
137102 /*    20 */    90,   91,   92,   93,   94,  144,  145,  146,  147,   58,
137103 /*    30 */    49,   50,   79,   80,   81,   82,   22,   84,   85,   86,
137104 /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,  221,  222,
137105 /*    50 */   223,   70,   71,   72,   73,   74,   75,   76,   77,   78,
137106 /*    60 */    79,   80,   81,   82,   94,   84,   85,   86,   87,   88,
137107 /*    70 */    89,   90,   91,   92,   93,   94,   19,   94,   97,  108,
137108 /*    80 */   109,  110,   99,  100,  101,  102,  103,  104,  105,   32,
137109 /*    90 */   119,  120,   78,   27,  152,  112,   93,   94,   41,   88,
137110 /*   100 */    89,   90,   91,   92,   93,   94,   49,   50,   84,   85,
137111 /*   110 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   58,
137112 /*   120 */   157,  119,  120,  163,   68,  163,   65,   70,   71,   72,
137113 /*   130 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
137114 /*   140 */   152,   84,   85,   86,   87,   88,   89,   90,   91,   92,
137115 /*   150 */    93,   94,   19,   97,   88,   89,  196,  101,  196,   26,
137116 /*   160 */   172,  173,   96,   97,   98,  210,  100,   22,  152,  108,
137117 /*   170 */   109,  110,   27,  107,   27,  109,  221,  222,  223,  219,
137118 /*   180 */   238,  219,   49,   50,  152,  169,  170,   54,  132,  133,
137119 /*   190 */   134,  228,  232,  171,  231,  207,  208,  237,  132,  237,
137120 /*   200 */   134,  179,   19,   70,   71,   72,   73,   74,   75,   76,
137121 /*   210 */    77,   78,   79,   80,   81,   82,  152,   84,   85,   86,
137122 /*   220 */    87,   88,   89,   90,   91,   92,   93,   94,   27,   65,
137123 /*   230 */    30,  152,   49,   50,   34,   52,   90,   91,   92,   93,
137124 /*   240 */    94,   96,   97,   98,   97,   22,  230,   27,   48,  217,
137125 /*   250 */    27,  172,  173,   70,   71,   72,   73,   74,   75,   76,
137126 /*   260 */    77,   78,   79,   80,   81,   82,  172,   84,   85,   86,
137127 /*   270 */    87,   88,   89,   90,   91,   92,   93,   94,   19,  148,
137128 /*   280 */   149,  152,  218,   24,  152,  154,  207,  156,  172,  152,
137129 /*   290 */    22,   68,   27,  152,  163,   27,  164,   96,   97,   98,
137130 /*   300 */    99,  172,  173,  102,  103,  104,  169,  170,   49,   50,
137131 /*   310 */    90,   88,   89,  152,  113,  186,   96,   97,   98,   96,
137132 /*   320 */    97,  160,   57,   27,  101,  164,  137,  196,  139,   70,
137133 /*   330 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
137134 /*   340 */    81,   82,   11,   84,   85,   86,   87,   88,   89,   90,
137135 /*   350 */    91,   92,   93,   94,   19,  132,  133,  134,   23,  218,
137136 /*   360 */   152,   96,   97,   98,   96,   97,   98,  230,   99,   22,
137137 /*   370 */   152,  102,  103,  104,   27,  244,  152,  152,   27,   26,
137138 /*   380 */   152,   22,  113,   65,   49,   50,   27,  194,  195,   58,
137139 /*   390 */   172,  173,   96,   97,   98,  185,   65,  172,  173,  206,
137140 /*   400 */   172,  173,  190,  191,  186,   70,   71,   72,   73,   74,
137141 /*   410 */    75,   76,   77,   78,   79,   80,   81,   82,  175,   84,
137142 /*   420 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
137143 /*   430 */    19,  175,  207,  208,   23,  207,  208,  119,  120,  108,
137144 /*   440 */   109,  110,   27,   96,   97,   98,  116,   96,   97,   98,
137145 /*   450 */   152,  121,  152,  179,  180,   96,   97,   98,  250,  106,
137146 /*   460 */    49,   50,  188,   19,  221,  222,  223,  168,  169,  170,
137147 /*   470 */   172,  173,  172,  173,  250,  124,  172,  221,  222,  223,
137148 /*   480 */    26,   70,   71,   72,   73,   74,   75,   76,   77,   78,
137149 /*   490 */    79,   80,   81,   82,   50,   84,   85,   86,   87,   88,
137150 /*   500 */    89,   90,   91,   92,   93,   94,   19,  207,  208,   12,
137151 /*   510 */    23,   96,   97,   98,  221,  222,  223,  194,  195,  152,
137152 /*   520 */   199,   23,   19,  225,   26,   28,  152,  152,  152,  206,
137153 /*   530 */   209,  164,  190,  191,  241,  152,   49,   50,  152,  124,
137154 /*   540 */   152,   44,  219,   46,  152,   21,  172,  173,  172,  173,
137155 /*   550 */   183,  107,  185,   16,  163,   58,  112,   70,   71,   72,
137156 /*   560 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
137157 /*   570 */   152,   84,   85,   86,   87,   88,   89,   90,   91,   92,
137158 /*   580 */    93,   94,   19,  207,  130,  152,   23,  196,   64,  152,
137159 /*   590 */   172,  173,   22,  152,   24,  152,   98,   27,   61,   96,
137160 /*   600 */    63,   26,  211,  212,  186,  172,  173,   49,   50,  172,
137161 /*   610 */   173,   23,   49,   50,   26,  172,  173,   88,   89,  186,
137162 /*   620 */    24,  238,  124,   27,  238,   22,   23,  103,  187,   26,
137163 /*   630 */   152,   73,   74,   70,   71,   72,   73,   74,   75,   76,
137164 /*   640 */    77,   78,   79,   80,   81,   82,  152,   84,   85,   86,
137165 /*   650 */    87,   88,   89,   90,   91,   92,   93,   94,   19,  101,
137166 /*   660 */   152,  132,   23,  134,  140,  152,   12,   97,   36,  168,
137167 /*   670 */   169,  170,   69,   98,  152,   22,   23,  140,   50,   26,
137168 /*   680 */   172,  173,   28,   51,  152,  172,  173,  193,   49,   50,
137169 /*   690 */    22,   59,   24,   97,  172,  173,  152,  152,   44,  124,
137170 /*   700 */    46,    0,    1,    2,  172,  173,   22,   23,   19,   70,
137171 /*   710 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
137172 /*   720 */    81,   82,   69,   84,   85,   86,   87,   88,   89,   90,
137173 /*   730 */    91,   92,   93,   94,  152,  107,  152,  193,   49,   50,
137174 /*   740 */   181,   22,   23,  111,  108,  109,  110,    7,    8,    9,
137175 /*   750 */    16,  247,  248,   69,  172,  173,  172,  173,  152,   70,
137176 /*   760 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
137177 /*   770 */    81,   82,  152,   84,   85,   86,   87,   88,   89,   90,
137178 /*   780 */    91,   92,   93,   94,   19,  152,  242,  152,   69,  152,
137179 /*   790 */   166,  167,  172,  173,   32,   61,  152,   63,  152,  193,
137180 /*   800 */   152,  152,  152,   41,  152,  172,  173,  172,  173,  172,
137181 /*   810 */   173,  152,  152,  152,   49,   50,  172,  173,  172,  173,
137182 /*   820 */   172,  173,  172,  173,  172,  173,  132,  138,  134,  152,
137183 /*   830 */   152,  172,  173,  172,  173,   70,   71,   72,   73,   74,
137184 /*   840 */    75,   76,   77,   78,   79,   80,   81,   82,  152,   84,
137185 /*   850 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
137186 /*   860 */    19,  152,   22,  152,  195,   24,  152,   27,  172,  173,
137187 /*   870 */   193,  193,  152,  152,  152,  206,  152,  217,  152,  152,
137188 /*   880 */   152,  172,  173,  172,  173,  152,  172,  173,  152,  152,
137189 /*   890 */    49,   50,  172,  173,  172,  173,  172,  173,  172,  173,
137190 /*   900 */   172,  173,  152,  138,  152,  172,  173,  108,  109,  110,
137191 /*   910 */    19,   70,   71,   72,   73,   74,   75,   76,   77,   78,
137192 /*   920 */    79,   80,   81,   82,  152,   84,   85,   86,   87,   88,
137193 /*   930 */    89,   90,   91,   92,   93,   94,  152,   97,  152,  152,
137194 /*   940 */    49,   50,   26,  193,  172,  173,  152,  152,  152,  146,
137195 /*   950 */   147,  132,  152,  134,  217,  181,  172,  173,  172,  173,
137196 /*   960 */    19,   70,   71,   72,   73,   74,   75,   76,   77,   78,
137197 /*   970 */    79,   80,   81,   82,  152,   84,   85,   86,   87,   88,
137198 /*   980 */    89,   90,   91,   92,   93,   94,  152,  193,  152,  193,
137199 /*   990 */    49,   50,  181,  193,  172,  173,  166,  167,  245,  246,
137200 /*  1000 */   211,  212,  152,   22,  217,  152,  172,  173,  172,  173,
137201 /*  1010 */    19,   70,   71,   72,   73,   74,   75,   76,   77,   78,
137202 /*  1020 */    79,   80,   81,   82,  152,   84,   85,   86,   87,   88,
137203 /*  1030 */    89,   90,   91,   92,   93,   94,  152,  187,  152,  123,
137204 /*  1040 */    49,   50,   23,   23,   23,   26,   26,   26,   23,   23,
137205 /*  1050 */    23,   26,   26,   26,    7,    8,  172,  173,  172,  173,
137206 /*  1060 */    19,   90,   71,   72,   73,   74,   75,   76,   77,   78,
137207 /*  1070 */    79,   80,   81,   82,  152,   84,   85,   86,   87,   88,
137208 /*  1080 */    89,   90,   91,   92,   93,   94,  152,  116,  152,  217,
137209 /*  1090 */    49,   50,  121,   23,  172,  173,   26,  100,  101,   27,
137210 /*  1100 */   101,   27,   23,  122,  152,   26,  172,  173,  172,  173,
137211 /*  1110 */   152,  112,  163,   72,   73,   74,   75,   76,   77,   78,
137212 /*  1120 */    79,   80,   81,   82,  163,   84,   85,   86,   87,   88,
137213 /*  1130 */    89,   90,   91,   92,   93,   94,   19,   20,  152,   22,
137214 /*  1140 */    23,  152,  163,   65,   27,  196,  163,   19,   20,   23,
137215 /*  1150 */    22,  213,   26,   19,   37,   27,  152,  196,  172,  173,
137216 /*  1160 */   152,  172,  173,   27,   23,   37,  152,   26,  152,   97,
137217 /*  1170 */   152,   97,  210,   56,  163,  196,  163,  163,  100,  196,
137218 /*  1180 */   172,  173,   65,  152,   56,   68,  172,  173,  172,  173,
137219 /*  1190 */   172,  173,  152,   65,  163,  163,   68,   23,  152,  234,
137220 /*  1200 */    26,  152,  152,  172,  173,   88,   89,  196,  152,  196,
137221 /*  1210 */   196,  152,   95,   96,   97,   98,   88,   89,  101,  152,
137222 /*  1220 */   152,  207,  208,   95,   96,   97,   98,  196,  196,  101,
137223 /*  1230 */    96,  233,  152,   97,  152,  152,   19,   20,  207,   22,
137224 /*  1240 */   152,  152,  152,  191,   27,  152,  152,  152,  152,  132,
137225 /*  1250 */   133,  134,  135,  136,   37,  152,  152,  152,  152,  152,
137226 /*  1260 */   132,  133,  134,  135,  136,  210,  197,  210,  210,  198,
137227 /*  1270 */   150,  184,  239,   56,  201,  214,  214,  201,  239,  180,
137228 /*  1280 */   214,  227,  198,   38,  176,   68,  175,  175,  175,  122,
137229 /*  1290 */   155,  200,  159,   19,   20,   40,   22,  159,  159,   22,
137230 /*  1300 */    70,   27,  130,  243,  240,   88,   89,   90,  189,   18,
137231 /*  1310 */   201,   37,   95,   96,   97,   98,  192,    5,  101,  192,
137232 /*  1320 */   220,  240,   10,   11,   12,   13,   14,  159,   18,   17,
137233 /*  1330 */    56,  158,  192,  201,  192,  220,  189,  189,  201,  159,
137234 /*  1340 */   158,  137,   68,   31,   45,   33,  236,  159,  159,  132,
137235 /*  1350 */   133,  134,  135,  136,   42,  158,  235,   22,  177,  159,
137236 /*  1360 */   158,  158,   88,   89,  159,  107,  174,   55,  177,   95,
137237 /*  1370 */    96,   97,   98,  174,   62,  101,   47,   65,   66,  106,
137238 /*  1380 */   174,  125,   19,   20,  174,   22,  177,  176,  174,  182,
137239 /*  1390 */    27,  216,  174,  174,  182,  107,  159,   22,  215,  215,
137240 /*  1400 */    37,  216,  216,  216,  137,  215,  132,  133,  134,  135,
137241 /*  1410 */   136,  215,  159,  177,   94,  177,  129,  224,  205,   56,
137242 /*  1420 */   226,  126,  128,  203,  229,  204,  114,  229,  127,  202,
137243 /*  1430 */   201,   68,   25,  162,   26,   13,  161,  153,  153,    6,
137244 /*  1440 */   151,  151,  178,  151,  165,  165,  178,  165,    4,    3,
137245 /*  1450 */   249,   88,   89,  141,   22,  142,   15,  249,   95,   96,
137246 /*  1460 */    97,   98,  246,   67,  101,   16,   23,  120,   23,  131,
137247 /*  1470 */   111,  123,   20,   16,  125,    1,  123,  131,   78,   78,
137248 /*  1480 */    78,   78,  111,   96,  122,   35,    1,    5,   22,  107,
137249 /*  1490 */   140,   53,   53,   26,   60,  132,  133,  134,  135,  136,
137250 /*  1500 */   107,   43,   24,   20,  112,   19,   22,   52,   52,  105,
137251 /*  1510 */    22,   22,   52,   23,   22,   22,   29,   23,   39,   23,
137252 /*  1520 */    23,   26,  116,   22,   26,   23,   22,  122,   23,   23,
137253 /*  1530 */    22,   96,   11,  124,   35,   26,   26,   23,   35,   23,
137254 /*  1540 */    23,   23,   35,   23,   22,   26,   23,   22,   24,  122,
137255 /*  1550 */    23,   22,   26,   22,   24,   23,   23,   23,   22,  122,
137256 /*  1560 */    23,   15,  122,    1,  122,
137257};
137258#define YY_SHIFT_USE_DFLT (1565)
137259#define YY_SHIFT_COUNT    (454)
137260#define YY_SHIFT_MIN      (-114)
137261#define YY_SHIFT_MAX      (1562)
137262static const short yy_shift_ofst[] = {
137263 /*     0 */     5, 1117, 1312, 1128, 1274, 1274, 1274, 1274,   61,  -19,
137264 /*    10 */    57,   57,  183, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
137265 /*    20 */    66,   66,  201,  -29,  331,  318,  133,  259,  335,  411,
137266 /*    30 */   487,  563,  639,  689,  765,  841,  891,  891,  891,  891,
137267 /*    40 */   891,  891,  891,  891,  891,  891,  891,  891,  891,  891,
137268 /*    50 */   891,  891,  891,  941,  891,  991, 1041, 1041, 1217, 1274,
137269 /*    60 */  1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
137270 /*    70 */  1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
137271 /*    80 */  1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
137272 /*    90 */  1363, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
137273 /*   100 */  1274, 1274, 1274, 1274,  -70,  -47,  -47,  -47,  -47,  -47,
137274 /*   110 */    24,   11,  146,  296,  524,  444,  529,  529,  296,    3,
137275 /*   120 */     2,  -30, 1565, 1565, 1565,  -17,  -17,  -17,  145,  145,
137276 /*   130 */   497,  497,  265,  603,  653,  296,  296,  296,  296,  296,
137277 /*   140 */   296,  296,  296,  296,  296,  296,  296,  296,  296,  296,
137278 /*   150 */   296,  296,  296,  296,  296,  701, 1078,  147,  147,    2,
137279 /*   160 */   164,  164,  164,  164,  164,  164, 1565, 1565, 1565,  223,
137280 /*   170 */    56,   56,  268,  269,  220,  347,  351,  415,  359,  296,
137281 /*   180 */   296,  296,  296,  296,  296,  296,  296,  296,  296,  296,
137282 /*   190 */   296,  296,  296,  296,  296,  632,  632,  632,  296,  296,
137283 /*   200 */   498,  296,  296,  296,  570,  296,  296,  654,  296,  296,
137284 /*   210 */   296,  296,  296,  296,  296,  296,  296,  296,  636,  200,
137285 /*   220 */   596,  596,  596,  575, -114,  971,  740,  454,  503,  503,
137286 /*   230 */  1134,  454, 1134,  353,  588,  628,  762,  503,  189,  762,
137287 /*   240 */   762,  916,  330,  668, 1245, 1167, 1167, 1255, 1255, 1167,
137288 /*   250 */  1277, 1230, 1172, 1291, 1291, 1291, 1291, 1167, 1310, 1172,
137289 /*   260 */  1277, 1230, 1230, 1172, 1167, 1310, 1204, 1299, 1167, 1167,
137290 /*   270 */  1310, 1335, 1167, 1310, 1167, 1310, 1335, 1258, 1258, 1258,
137291 /*   280 */  1329, 1335, 1258, 1273, 1258, 1329, 1258, 1258, 1256, 1288,
137292 /*   290 */  1256, 1288, 1256, 1288, 1256, 1288, 1167, 1375, 1167, 1267,
137293 /*   300 */  1335, 1320, 1320, 1335, 1287, 1295, 1294, 1301, 1172, 1407,
137294 /*   310 */  1408, 1422, 1422, 1433, 1433, 1433, 1565, 1565, 1565, 1565,
137295 /*   320 */  1565, 1565, 1565, 1565,  558,  537,  684,  719,  734,  799,
137296 /*   330 */   840, 1019,   14, 1020, 1021, 1025, 1026, 1027, 1070, 1072,
137297 /*   340 */   997, 1047,  999, 1079, 1126, 1074, 1141,  694,  819, 1174,
137298 /*   350 */  1136,  981, 1444, 1446, 1432, 1313, 1441, 1396, 1449, 1443,
137299 /*   360 */  1445, 1347, 1338, 1359, 1348, 1452, 1349, 1457, 1474, 1353,
137300 /*   370 */  1346, 1400, 1401, 1402, 1403, 1371, 1387, 1450, 1362, 1485,
137301 /*   380 */  1482, 1466, 1382, 1350, 1438, 1467, 1439, 1434, 1458, 1393,
137302 /*   390 */  1478, 1483, 1486, 1392, 1404, 1484, 1455, 1488, 1489, 1490,
137303 /*   400 */  1492, 1456, 1487, 1493, 1460, 1479, 1494, 1496, 1497, 1495,
137304 /*   410 */  1406, 1501, 1502, 1504, 1498, 1405, 1505, 1506, 1435, 1499,
137305 /*   420 */  1508, 1409, 1509, 1503, 1510, 1507, 1514, 1509, 1516, 1517,
137306 /*   430 */  1518, 1519, 1520, 1522, 1521, 1523, 1525, 1524, 1526, 1527,
137307 /*   440 */  1529, 1530, 1526, 1532, 1531, 1533, 1534, 1536, 1427, 1437,
137308 /*   450 */  1440, 1442, 1537, 1546, 1562,
137309};
137310#define YY_REDUCE_USE_DFLT (-174)
137311#define YY_REDUCE_COUNT (323)
137312#define YY_REDUCE_MIN   (-173)
137313#define YY_REDUCE_MAX   (1292)
137314static const short yy_reduce_ofst[] = {
137315 /*     0 */  -119, 1014,  131, 1031,  -12,  225,  228,  300,  -40,  -45,
137316 /*    10 */   243,  256,  293,  129,  218,  418,   79,  376,  433,  298,
137317 /*    20 */    16,  137,  367,  323,  -38,  391, -173, -173, -173, -173,
137318 /*    30 */  -173, -173, -173, -173, -173, -173, -173, -173, -173, -173,
137319 /*    40 */  -173, -173, -173, -173, -173, -173, -173, -173, -173, -173,
137320 /*    50 */  -173, -173, -173, -173, -173, -173, -173, -173,  374,  437,
137321 /*    60 */   443,  508,  513,  522,  532,  582,  584,  620,  633,  635,
137322 /*    70 */   637,  644,  646,  648,  650,  652,  659,  661,  696,  709,
137323 /*    80 */   711,  714,  720,  722,  724,  726,  728,  733,  772,  784,
137324 /*    90 */   786,  822,  834,  836,  884,  886,  922,  934,  936,  986,
137325 /*   100 */   989, 1008, 1016, 1018, -173, -173, -173, -173, -173, -173,
137326 /*   110 */  -173, -173, -173,  544,  -37,  274,  299,  501,  161, -173,
137327 /*   120 */   193, -173, -173, -173, -173,   22,   22,   22,   64,  141,
137328 /*   130 */   212,  342,  208,  504,  504,  132,  494,  606,  677,  678,
137329 /*   140 */   750,  794,  796,  -58,   32,  383,  660,  737,  386,  787,
137330 /*   150 */   800,  441,  872,  224,  850,  803,  949,  624,  830,  669,
137331 /*   160 */   961,  979,  983, 1011, 1013, 1032,  753,  789,  321,   94,
137332 /*   170 */   116,  304,  375,  210,  388,  392,  478,  545,  649,  721,
137333 /*   180 */   727,  736,  752,  795,  853,  952,  958, 1004, 1040, 1046,
137334 /*   190 */  1049, 1050, 1056, 1059, 1067,  559,  774,  811, 1068, 1080,
137335 /*   200 */   938, 1082, 1083, 1088,  962, 1089, 1090, 1052, 1093, 1094,
137336 /*   210 */  1095,  388, 1096, 1103, 1104, 1105, 1106, 1107,  965,  998,
137337 /*   220 */  1055, 1057, 1058,  938, 1069, 1071, 1120, 1073, 1061, 1062,
137338 /*   230 */  1033, 1076, 1039, 1108, 1087, 1099, 1111, 1066, 1054, 1112,
137339 /*   240 */  1113, 1091, 1084, 1135, 1060, 1133, 1138, 1064, 1081, 1139,
137340 /*   250 */  1100, 1119, 1109, 1124, 1127, 1140, 1142, 1168, 1173, 1132,
137341 /*   260 */  1115, 1147, 1148, 1137, 1180, 1182, 1110, 1121, 1188, 1189,
137342 /*   270 */  1197, 1181, 1200, 1202, 1205, 1203, 1191, 1192, 1199, 1206,
137343 /*   280 */  1207, 1209, 1210, 1211, 1214, 1212, 1218, 1219, 1175, 1183,
137344 /*   290 */  1185, 1184, 1186, 1190, 1187, 1196, 1237, 1193, 1253, 1194,
137345 /*   300 */  1236, 1195, 1198, 1238, 1213, 1221, 1220, 1227, 1229, 1271,
137346 /*   310 */  1275, 1284, 1285, 1289, 1290, 1292, 1201, 1208, 1216, 1279,
137347 /*   320 */  1280, 1264, 1268, 1282,
137348};
137349static const YYACTIONTYPE yy_default[] = {
137350 /*     0 */  1270, 1260, 1260, 1260, 1193, 1193, 1193, 1193, 1260, 1088,
137351 /*    10 */  1117, 1117, 1244, 1322, 1322, 1322, 1322, 1322, 1322, 1192,
137352 /*    20 */  1322, 1322, 1322, 1322, 1260, 1092, 1123, 1322, 1322, 1322,
137353 /*    30 */  1322, 1194, 1195, 1322, 1322, 1322, 1243, 1245, 1133, 1132,
137354 /*    40 */  1131, 1130, 1226, 1104, 1128, 1121, 1125, 1194, 1188, 1189,
137355 /*    50 */  1187, 1191, 1195, 1322, 1124, 1158, 1172, 1157, 1322, 1322,
137356 /*    60 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137357 /*    70 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137358 /*    80 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137359 /*    90 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137360 /*   100 */  1322, 1322, 1322, 1322, 1166, 1171, 1178, 1170, 1167, 1160,
137361 /*   110 */  1159, 1161, 1162, 1322, 1011, 1059, 1322, 1322, 1322, 1163,
137362 /*   120 */  1322, 1164, 1175, 1174, 1173, 1251, 1278, 1277, 1322, 1322,
137363 /*   130 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137364 /*   140 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137365 /*   150 */  1322, 1322, 1322, 1322, 1322, 1270, 1260, 1017, 1017, 1322,
137366 /*   160 */  1260, 1260, 1260, 1260, 1260, 1260, 1256, 1092, 1083, 1322,
137367 /*   170 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137368 /*   180 */  1248, 1246, 1322, 1208, 1322, 1322, 1322, 1322, 1322, 1322,
137369 /*   190 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137370 /*   200 */  1322, 1322, 1322, 1322, 1088, 1322, 1322, 1322, 1322, 1322,
137371 /*   210 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1272, 1322, 1221,
137372 /*   220 */  1088, 1088, 1088, 1090, 1072, 1082,  997, 1127, 1106, 1106,
137373 /*   230 */  1311, 1127, 1311, 1034, 1292, 1031, 1117, 1106, 1190, 1117,
137374 /*   240 */  1117, 1089, 1082, 1322, 1314, 1097, 1097, 1313, 1313, 1097,
137375 /*   250 */  1138, 1062, 1127, 1068, 1068, 1068, 1068, 1097, 1008, 1127,
137376 /*   260 */  1138, 1062, 1062, 1127, 1097, 1008, 1225, 1308, 1097, 1097,
137377 /*   270 */  1008, 1201, 1097, 1008, 1097, 1008, 1201, 1060, 1060, 1060,
137378 /*   280 */  1049, 1201, 1060, 1034, 1060, 1049, 1060, 1060, 1110, 1105,
137379 /*   290 */  1110, 1105, 1110, 1105, 1110, 1105, 1097, 1196, 1097, 1322,
137380 /*   300 */  1201, 1205, 1205, 1201, 1122, 1111, 1120, 1118, 1127, 1014,
137381 /*   310 */  1052, 1275, 1275, 1271, 1271, 1271, 1319, 1319, 1256, 1287,
137382 /*   320 */  1287, 1036, 1036, 1287, 1322, 1322, 1322, 1322, 1322, 1322,
137383 /*   330 */  1282, 1322, 1210, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137384 /*   340 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137385 /*   350 */  1322, 1143, 1322,  993, 1253, 1322, 1322, 1252, 1322, 1322,
137386 /*   360 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137387 /*   370 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1310, 1322,
137388 /*   380 */  1322, 1322, 1322, 1322, 1322, 1224, 1223, 1322, 1322, 1322,
137389 /*   390 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137390 /*   400 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
137391 /*   410 */  1074, 1322, 1322, 1322, 1296, 1322, 1322, 1322, 1322, 1322,
137392 /*   420 */  1322, 1322, 1119, 1322, 1112, 1322, 1322, 1301, 1322, 1322,
137393 /*   430 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1262, 1322,
137394 /*   440 */  1322, 1322, 1261, 1322, 1322, 1322, 1322, 1322, 1145, 1322,
137395 /*   450 */  1144, 1148, 1322, 1002, 1322,
137396};
137397/********** End of lemon-generated parsing tables *****************************/
137398
137399/* The next table maps tokens (terminal symbols) into fallback tokens.
137400** If a construct like the following:
137401**
137402**      %fallback ID X Y Z.
137403**
137404** appears in the grammar, then ID becomes a fallback token for X, Y,
137405** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
137406** but it does not parse, the type of the token is changed to ID and
137407** the parse is retried before an error is thrown.
137408**
137409** This feature can be used, for example, to cause some keywords in a language
137410** to revert to identifiers if they keyword does not apply in the context where
137411** it appears.
137412*/
137413#ifdef YYFALLBACK
137414static const YYCODETYPE yyFallback[] = {
137415    0,  /*          $ => nothing */
137416    0,  /*       SEMI => nothing */
137417   27,  /*    EXPLAIN => ID */
137418   27,  /*      QUERY => ID */
137419   27,  /*       PLAN => ID */
137420   27,  /*      BEGIN => ID */
137421    0,  /* TRANSACTION => nothing */
137422   27,  /*   DEFERRED => ID */
137423   27,  /*  IMMEDIATE => ID */
137424   27,  /*  EXCLUSIVE => ID */
137425    0,  /*     COMMIT => nothing */
137426   27,  /*        END => ID */
137427   27,  /*   ROLLBACK => ID */
137428   27,  /*  SAVEPOINT => ID */
137429   27,  /*    RELEASE => ID */
137430    0,  /*         TO => nothing */
137431    0,  /*      TABLE => nothing */
137432    0,  /*     CREATE => nothing */
137433   27,  /*         IF => ID */
137434    0,  /*        NOT => nothing */
137435    0,  /*     EXISTS => nothing */
137436   27,  /*       TEMP => ID */
137437    0,  /*         LP => nothing */
137438    0,  /*         RP => nothing */
137439    0,  /*         AS => nothing */
137440   27,  /*    WITHOUT => ID */
137441    0,  /*      COMMA => nothing */
137442    0,  /*         ID => nothing */
137443   27,  /*      ABORT => ID */
137444   27,  /*     ACTION => ID */
137445   27,  /*      AFTER => ID */
137446   27,  /*    ANALYZE => ID */
137447   27,  /*        ASC => ID */
137448   27,  /*     ATTACH => ID */
137449   27,  /*     BEFORE => ID */
137450   27,  /*         BY => ID */
137451   27,  /*    CASCADE => ID */
137452   27,  /*       CAST => ID */
137453   27,  /*   COLUMNKW => ID */
137454   27,  /*   CONFLICT => ID */
137455   27,  /*   DATABASE => ID */
137456   27,  /*       DESC => ID */
137457   27,  /*     DETACH => ID */
137458   27,  /*       EACH => ID */
137459   27,  /*       FAIL => ID */
137460   27,  /*        FOR => ID */
137461   27,  /*     IGNORE => ID */
137462   27,  /*  INITIALLY => ID */
137463   27,  /*    INSTEAD => ID */
137464   27,  /*    LIKE_KW => ID */
137465   27,  /*      MATCH => ID */
137466   27,  /*         NO => ID */
137467   27,  /*        KEY => ID */
137468   27,  /*         OF => ID */
137469   27,  /*     OFFSET => ID */
137470   27,  /*     PRAGMA => ID */
137471   27,  /*      RAISE => ID */
137472   27,  /*  RECURSIVE => ID */
137473   27,  /*    REPLACE => ID */
137474   27,  /*   RESTRICT => ID */
137475   27,  /*        ROW => ID */
137476   27,  /*    TRIGGER => ID */
137477   27,  /*     VACUUM => ID */
137478   27,  /*       VIEW => ID */
137479   27,  /*    VIRTUAL => ID */
137480   27,  /*       WITH => ID */
137481   27,  /*    REINDEX => ID */
137482   27,  /*     RENAME => ID */
137483   27,  /*   CTIME_KW => ID */
137484};
137485#endif /* YYFALLBACK */
137486
137487/* The following structure represents a single element of the
137488** parser's stack.  Information stored includes:
137489**
137490**   +  The state number for the parser at this level of the stack.
137491**
137492**   +  The value of the token stored at this level of the stack.
137493**      (In other words, the "major" token.)
137494**
137495**   +  The semantic value stored at this level of the stack.  This is
137496**      the information used by the action routines in the grammar.
137497**      It is sometimes called the "minor" token.
137498**
137499** After the "shift" half of a SHIFTREDUCE action, the stateno field
137500** actually contains the reduce action for the second half of the
137501** SHIFTREDUCE.
137502*/
137503struct yyStackEntry {
137504  YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
137505  YYCODETYPE major;      /* The major token value.  This is the code
137506                         ** number for the token at this stack level */
137507  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
137508                         ** is the value of the token  */
137509};
137510typedef struct yyStackEntry yyStackEntry;
137511
137512/* The state of the parser is completely contained in an instance of
137513** the following structure */
137514struct yyParser {
137515  yyStackEntry *yytos;          /* Pointer to top element of the stack */
137516#ifdef YYTRACKMAXSTACKDEPTH
137517  int yyhwm;                    /* High-water mark of the stack */
137518#endif
137519#ifndef YYNOERRORRECOVERY
137520  int yyerrcnt;                 /* Shifts left before out of the error */
137521#endif
137522  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
137523#if YYSTACKDEPTH<=0
137524  int yystksz;                  /* Current side of the stack */
137525  yyStackEntry *yystack;        /* The parser's stack */
137526  yyStackEntry yystk0;          /* First stack entry */
137527#else
137528  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
137529  yyStackEntry *yystackEnd;            /* Last entry in the stack */
137530#endif
137531};
137532typedef struct yyParser yyParser;
137533
137534#ifndef NDEBUG
137535/* #include <stdio.h> */
137536static FILE *yyTraceFILE = 0;
137537static char *yyTracePrompt = 0;
137538#endif /* NDEBUG */
137539
137540#ifndef NDEBUG
137541/*
137542** Turn parser tracing on by giving a stream to which to write the trace
137543** and a prompt to preface each trace message.  Tracing is turned off
137544** by making either argument NULL
137545**
137546** Inputs:
137547** <ul>
137548** <li> A FILE* to which trace output should be written.
137549**      If NULL, then tracing is turned off.
137550** <li> A prefix string written at the beginning of every
137551**      line of trace output.  If NULL, then tracing is
137552**      turned off.
137553** </ul>
137554**
137555** Outputs:
137556** None.
137557*/
137558SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
137559  yyTraceFILE = TraceFILE;
137560  yyTracePrompt = zTracePrompt;
137561  if( yyTraceFILE==0 ) yyTracePrompt = 0;
137562  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
137563}
137564#endif /* NDEBUG */
137565
137566#ifndef NDEBUG
137567/* For tracing shifts, the names of all terminals and nonterminals
137568** are required.  The following table supplies these names */
137569static const char *const yyTokenName[] = {
137570  "$",             "SEMI",          "EXPLAIN",       "QUERY",
137571  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
137572  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
137573  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
137574  "TABLE",         "CREATE",        "IF",            "NOT",
137575  "EXISTS",        "TEMP",          "LP",            "RP",
137576  "AS",            "WITHOUT",       "COMMA",         "ID",
137577  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
137578  "ASC",           "ATTACH",        "BEFORE",        "BY",
137579  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
137580  "DATABASE",      "DESC",          "DETACH",        "EACH",
137581  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
137582  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
137583  "KEY",           "OF",            "OFFSET",        "PRAGMA",
137584  "RAISE",         "RECURSIVE",     "REPLACE",       "RESTRICT",
137585  "ROW",           "TRIGGER",       "VACUUM",        "VIEW",
137586  "VIRTUAL",       "WITH",          "REINDEX",       "RENAME",
137587  "CTIME_KW",      "ANY",           "OR",            "AND",
137588  "IS",            "BETWEEN",       "IN",            "ISNULL",
137589  "NOTNULL",       "NE",            "EQ",            "GT",
137590  "LE",            "LT",            "GE",            "ESCAPE",
137591  "BITAND",        "BITOR",         "LSHIFT",        "RSHIFT",
137592  "PLUS",          "MINUS",         "STAR",          "SLASH",
137593  "REM",           "CONCAT",        "COLLATE",       "BITNOT",
137594  "INDEXED",       "STRING",        "JOIN_KW",       "CONSTRAINT",
137595  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
137596  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
137597  "INSERT",        "DELETE",        "UPDATE",        "SET",
137598  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
137599  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
137600  "VALUES",        "DISTINCT",      "DOT",           "FROM",
137601  "JOIN",          "USING",         "ORDER",         "GROUP",
137602  "HAVING",        "LIMIT",         "WHERE",         "INTO",
137603  "FLOAT",         "BLOB",          "INTEGER",       "VARIABLE",
137604  "CASE",          "WHEN",          "THEN",          "ELSE",
137605  "INDEX",         "ALTER",         "ADD",           "error",
137606  "input",         "cmdlist",       "ecmd",          "explain",
137607  "cmdx",          "cmd",           "transtype",     "trans_opt",
137608  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
137609  "createkw",      "temp",          "ifnotexists",   "dbnm",
137610  "columnlist",    "conslist_opt",  "table_options",  "select",
137611  "columnname",    "carglist",      "typetoken",     "typename",
137612  "signed",        "plus_num",      "minus_num",     "ccons",
137613  "term",          "expr",          "onconf",        "sortorder",
137614  "autoinc",       "eidlist_opt",   "refargs",       "defer_subclause",
137615  "refarg",        "refact",        "init_deferred_pred_opt",  "conslist",
137616  "tconscomma",    "tcons",         "sortlist",      "eidlist",
137617  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
137618  "ifexists",      "fullname",      "selectnowith",  "oneselect",
137619  "with",          "multiselect_op",  "distinct",      "selcollist",
137620  "from",          "where_opt",     "groupby_opt",   "having_opt",
137621  "orderby_opt",   "limit_opt",     "values",        "nexprlist",
137622  "exprlist",      "sclp",          "as",            "seltablist",
137623  "stl_prefix",    "joinop",        "indexed_opt",   "on_opt",
137624  "using_opt",     "idlist",        "setlist",       "insert_cmd",
137625  "idlist_opt",    "likeop",        "between_op",    "in_op",
137626  "paren_exprlist",  "case_operand",  "case_exprlist",  "case_else",
137627  "uniqueflag",    "collate",       "nmnum",         "trigger_decl",
137628  "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
137629  "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
137630  "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
137631  "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
137632  "lp",            "anylist",       "wqlist",
137633};
137634#endif /* NDEBUG */
137635
137636#ifndef NDEBUG
137637/* For tracing reduce actions, the names of all rules are required.
137638*/
137639static const char *const yyRuleName[] = {
137640 /*   0 */ "explain ::= EXPLAIN",
137641 /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
137642 /*   2 */ "cmdx ::= cmd",
137643 /*   3 */ "cmd ::= BEGIN transtype trans_opt",
137644 /*   4 */ "transtype ::=",
137645 /*   5 */ "transtype ::= DEFERRED",
137646 /*   6 */ "transtype ::= IMMEDIATE",
137647 /*   7 */ "transtype ::= EXCLUSIVE",
137648 /*   8 */ "cmd ::= COMMIT|END trans_opt",
137649 /*   9 */ "cmd ::= ROLLBACK trans_opt",
137650 /*  10 */ "cmd ::= SAVEPOINT nm",
137651 /*  11 */ "cmd ::= RELEASE savepoint_opt nm",
137652 /*  12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
137653 /*  13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
137654 /*  14 */ "createkw ::= CREATE",
137655 /*  15 */ "ifnotexists ::=",
137656 /*  16 */ "ifnotexists ::= IF NOT EXISTS",
137657 /*  17 */ "temp ::= TEMP",
137658 /*  18 */ "temp ::=",
137659 /*  19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
137660 /*  20 */ "create_table_args ::= AS select",
137661 /*  21 */ "table_options ::=",
137662 /*  22 */ "table_options ::= WITHOUT nm",
137663 /*  23 */ "columnname ::= nm typetoken",
137664 /*  24 */ "typetoken ::=",
137665 /*  25 */ "typetoken ::= typename LP signed RP",
137666 /*  26 */ "typetoken ::= typename LP signed COMMA signed RP",
137667 /*  27 */ "typename ::= typename ID|STRING",
137668 /*  28 */ "ccons ::= CONSTRAINT nm",
137669 /*  29 */ "ccons ::= DEFAULT term",
137670 /*  30 */ "ccons ::= DEFAULT LP expr RP",
137671 /*  31 */ "ccons ::= DEFAULT PLUS term",
137672 /*  32 */ "ccons ::= DEFAULT MINUS term",
137673 /*  33 */ "ccons ::= DEFAULT ID|INDEXED",
137674 /*  34 */ "ccons ::= NOT NULL onconf",
137675 /*  35 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
137676 /*  36 */ "ccons ::= UNIQUE onconf",
137677 /*  37 */ "ccons ::= CHECK LP expr RP",
137678 /*  38 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
137679 /*  39 */ "ccons ::= defer_subclause",
137680 /*  40 */ "ccons ::= COLLATE ID|STRING",
137681 /*  41 */ "autoinc ::=",
137682 /*  42 */ "autoinc ::= AUTOINCR",
137683 /*  43 */ "refargs ::=",
137684 /*  44 */ "refargs ::= refargs refarg",
137685 /*  45 */ "refarg ::= MATCH nm",
137686 /*  46 */ "refarg ::= ON INSERT refact",
137687 /*  47 */ "refarg ::= ON DELETE refact",
137688 /*  48 */ "refarg ::= ON UPDATE refact",
137689 /*  49 */ "refact ::= SET NULL",
137690 /*  50 */ "refact ::= SET DEFAULT",
137691 /*  51 */ "refact ::= CASCADE",
137692 /*  52 */ "refact ::= RESTRICT",
137693 /*  53 */ "refact ::= NO ACTION",
137694 /*  54 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
137695 /*  55 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
137696 /*  56 */ "init_deferred_pred_opt ::=",
137697 /*  57 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
137698 /*  58 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
137699 /*  59 */ "conslist_opt ::=",
137700 /*  60 */ "tconscomma ::= COMMA",
137701 /*  61 */ "tcons ::= CONSTRAINT nm",
137702 /*  62 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
137703 /*  63 */ "tcons ::= UNIQUE LP sortlist RP onconf",
137704 /*  64 */ "tcons ::= CHECK LP expr RP onconf",
137705 /*  65 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
137706 /*  66 */ "defer_subclause_opt ::=",
137707 /*  67 */ "onconf ::=",
137708 /*  68 */ "onconf ::= ON CONFLICT resolvetype",
137709 /*  69 */ "orconf ::=",
137710 /*  70 */ "orconf ::= OR resolvetype",
137711 /*  71 */ "resolvetype ::= IGNORE",
137712 /*  72 */ "resolvetype ::= REPLACE",
137713 /*  73 */ "cmd ::= DROP TABLE ifexists fullname",
137714 /*  74 */ "ifexists ::= IF EXISTS",
137715 /*  75 */ "ifexists ::=",
137716 /*  76 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
137717 /*  77 */ "cmd ::= DROP VIEW ifexists fullname",
137718 /*  78 */ "cmd ::= select",
137719 /*  79 */ "select ::= with selectnowith",
137720 /*  80 */ "selectnowith ::= selectnowith multiselect_op oneselect",
137721 /*  81 */ "multiselect_op ::= UNION",
137722 /*  82 */ "multiselect_op ::= UNION ALL",
137723 /*  83 */ "multiselect_op ::= EXCEPT|INTERSECT",
137724 /*  84 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
137725 /*  85 */ "values ::= VALUES LP nexprlist RP",
137726 /*  86 */ "values ::= values COMMA LP exprlist RP",
137727 /*  87 */ "distinct ::= DISTINCT",
137728 /*  88 */ "distinct ::= ALL",
137729 /*  89 */ "distinct ::=",
137730 /*  90 */ "sclp ::=",
137731 /*  91 */ "selcollist ::= sclp expr as",
137732 /*  92 */ "selcollist ::= sclp STAR",
137733 /*  93 */ "selcollist ::= sclp nm DOT STAR",
137734 /*  94 */ "as ::= AS nm",
137735 /*  95 */ "as ::=",
137736 /*  96 */ "from ::=",
137737 /*  97 */ "from ::= FROM seltablist",
137738 /*  98 */ "stl_prefix ::= seltablist joinop",
137739 /*  99 */ "stl_prefix ::=",
137740 /* 100 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
137741 /* 101 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
137742 /* 102 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
137743 /* 103 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
137744 /* 104 */ "dbnm ::=",
137745 /* 105 */ "dbnm ::= DOT nm",
137746 /* 106 */ "fullname ::= nm dbnm",
137747 /* 107 */ "joinop ::= COMMA|JOIN",
137748 /* 108 */ "joinop ::= JOIN_KW JOIN",
137749 /* 109 */ "joinop ::= JOIN_KW nm JOIN",
137750 /* 110 */ "joinop ::= JOIN_KW nm nm JOIN",
137751 /* 111 */ "on_opt ::= ON expr",
137752 /* 112 */ "on_opt ::=",
137753 /* 113 */ "indexed_opt ::=",
137754 /* 114 */ "indexed_opt ::= INDEXED BY nm",
137755 /* 115 */ "indexed_opt ::= NOT INDEXED",
137756 /* 116 */ "using_opt ::= USING LP idlist RP",
137757 /* 117 */ "using_opt ::=",
137758 /* 118 */ "orderby_opt ::=",
137759 /* 119 */ "orderby_opt ::= ORDER BY sortlist",
137760 /* 120 */ "sortlist ::= sortlist COMMA expr sortorder",
137761 /* 121 */ "sortlist ::= expr sortorder",
137762 /* 122 */ "sortorder ::= ASC",
137763 /* 123 */ "sortorder ::= DESC",
137764 /* 124 */ "sortorder ::=",
137765 /* 125 */ "groupby_opt ::=",
137766 /* 126 */ "groupby_opt ::= GROUP BY nexprlist",
137767 /* 127 */ "having_opt ::=",
137768 /* 128 */ "having_opt ::= HAVING expr",
137769 /* 129 */ "limit_opt ::=",
137770 /* 130 */ "limit_opt ::= LIMIT expr",
137771 /* 131 */ "limit_opt ::= LIMIT expr OFFSET expr",
137772 /* 132 */ "limit_opt ::= LIMIT expr COMMA expr",
137773 /* 133 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
137774 /* 134 */ "where_opt ::=",
137775 /* 135 */ "where_opt ::= WHERE expr",
137776 /* 136 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
137777 /* 137 */ "setlist ::= setlist COMMA nm EQ expr",
137778 /* 138 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
137779 /* 139 */ "setlist ::= nm EQ expr",
137780 /* 140 */ "setlist ::= LP idlist RP EQ expr",
137781 /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
137782 /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
137783 /* 143 */ "insert_cmd ::= INSERT orconf",
137784 /* 144 */ "insert_cmd ::= REPLACE",
137785 /* 145 */ "idlist_opt ::=",
137786 /* 146 */ "idlist_opt ::= LP idlist RP",
137787 /* 147 */ "idlist ::= idlist COMMA nm",
137788 /* 148 */ "idlist ::= nm",
137789 /* 149 */ "expr ::= LP expr RP",
137790 /* 150 */ "expr ::= ID|INDEXED",
137791 /* 151 */ "expr ::= JOIN_KW",
137792 /* 152 */ "expr ::= nm DOT nm",
137793 /* 153 */ "expr ::= nm DOT nm DOT nm",
137794 /* 154 */ "term ::= NULL|FLOAT|BLOB",
137795 /* 155 */ "term ::= STRING",
137796 /* 156 */ "term ::= INTEGER",
137797 /* 157 */ "expr ::= VARIABLE",
137798 /* 158 */ "expr ::= expr COLLATE ID|STRING",
137799 /* 159 */ "expr ::= CAST LP expr AS typetoken RP",
137800 /* 160 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
137801 /* 161 */ "expr ::= ID|INDEXED LP STAR RP",
137802 /* 162 */ "term ::= CTIME_KW",
137803 /* 163 */ "expr ::= LP nexprlist COMMA expr RP",
137804 /* 164 */ "expr ::= expr AND expr",
137805 /* 165 */ "expr ::= expr OR expr",
137806 /* 166 */ "expr ::= expr LT|GT|GE|LE expr",
137807 /* 167 */ "expr ::= expr EQ|NE expr",
137808 /* 168 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
137809 /* 169 */ "expr ::= expr PLUS|MINUS expr",
137810 /* 170 */ "expr ::= expr STAR|SLASH|REM expr",
137811 /* 171 */ "expr ::= expr CONCAT expr",
137812 /* 172 */ "likeop ::= NOT LIKE_KW|MATCH",
137813 /* 173 */ "expr ::= expr likeop expr",
137814 /* 174 */ "expr ::= expr likeop expr ESCAPE expr",
137815 /* 175 */ "expr ::= expr ISNULL|NOTNULL",
137816 /* 176 */ "expr ::= expr NOT NULL",
137817 /* 177 */ "expr ::= expr IS expr",
137818 /* 178 */ "expr ::= expr IS NOT expr",
137819 /* 179 */ "expr ::= NOT expr",
137820 /* 180 */ "expr ::= BITNOT expr",
137821 /* 181 */ "expr ::= MINUS expr",
137822 /* 182 */ "expr ::= PLUS expr",
137823 /* 183 */ "between_op ::= BETWEEN",
137824 /* 184 */ "between_op ::= NOT BETWEEN",
137825 /* 185 */ "expr ::= expr between_op expr AND expr",
137826 /* 186 */ "in_op ::= IN",
137827 /* 187 */ "in_op ::= NOT IN",
137828 /* 188 */ "expr ::= expr in_op LP exprlist RP",
137829 /* 189 */ "expr ::= LP select RP",
137830 /* 190 */ "expr ::= expr in_op LP select RP",
137831 /* 191 */ "expr ::= expr in_op nm dbnm paren_exprlist",
137832 /* 192 */ "expr ::= EXISTS LP select RP",
137833 /* 193 */ "expr ::= CASE case_operand case_exprlist case_else END",
137834 /* 194 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
137835 /* 195 */ "case_exprlist ::= WHEN expr THEN expr",
137836 /* 196 */ "case_else ::= ELSE expr",
137837 /* 197 */ "case_else ::=",
137838 /* 198 */ "case_operand ::= expr",
137839 /* 199 */ "case_operand ::=",
137840 /* 200 */ "exprlist ::=",
137841 /* 201 */ "nexprlist ::= nexprlist COMMA expr",
137842 /* 202 */ "nexprlist ::= expr",
137843 /* 203 */ "paren_exprlist ::=",
137844 /* 204 */ "paren_exprlist ::= LP exprlist RP",
137845 /* 205 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
137846 /* 206 */ "uniqueflag ::= UNIQUE",
137847 /* 207 */ "uniqueflag ::=",
137848 /* 208 */ "eidlist_opt ::=",
137849 /* 209 */ "eidlist_opt ::= LP eidlist RP",
137850 /* 210 */ "eidlist ::= eidlist COMMA nm collate sortorder",
137851 /* 211 */ "eidlist ::= nm collate sortorder",
137852 /* 212 */ "collate ::=",
137853 /* 213 */ "collate ::= COLLATE ID|STRING",
137854 /* 214 */ "cmd ::= DROP INDEX ifexists fullname",
137855 /* 215 */ "cmd ::= VACUUM",
137856 /* 216 */ "cmd ::= VACUUM nm",
137857 /* 217 */ "cmd ::= PRAGMA nm dbnm",
137858 /* 218 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
137859 /* 219 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
137860 /* 220 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
137861 /* 221 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
137862 /* 222 */ "plus_num ::= PLUS INTEGER|FLOAT",
137863 /* 223 */ "minus_num ::= MINUS INTEGER|FLOAT",
137864 /* 224 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
137865 /* 225 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
137866 /* 226 */ "trigger_time ::= BEFORE|AFTER",
137867 /* 227 */ "trigger_time ::= INSTEAD OF",
137868 /* 228 */ "trigger_time ::=",
137869 /* 229 */ "trigger_event ::= DELETE|INSERT",
137870 /* 230 */ "trigger_event ::= UPDATE",
137871 /* 231 */ "trigger_event ::= UPDATE OF idlist",
137872 /* 232 */ "when_clause ::=",
137873 /* 233 */ "when_clause ::= WHEN expr",
137874 /* 234 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
137875 /* 235 */ "trigger_cmd_list ::= trigger_cmd SEMI",
137876 /* 236 */ "trnm ::= nm DOT nm",
137877 /* 237 */ "tridxby ::= INDEXED BY nm",
137878 /* 238 */ "tridxby ::= NOT INDEXED",
137879 /* 239 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
137880 /* 240 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
137881 /* 241 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
137882 /* 242 */ "trigger_cmd ::= select",
137883 /* 243 */ "expr ::= RAISE LP IGNORE RP",
137884 /* 244 */ "expr ::= RAISE LP raisetype COMMA nm RP",
137885 /* 245 */ "raisetype ::= ROLLBACK",
137886 /* 246 */ "raisetype ::= ABORT",
137887 /* 247 */ "raisetype ::= FAIL",
137888 /* 248 */ "cmd ::= DROP TRIGGER ifexists fullname",
137889 /* 249 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
137890 /* 250 */ "cmd ::= DETACH database_kw_opt expr",
137891 /* 251 */ "key_opt ::=",
137892 /* 252 */ "key_opt ::= KEY expr",
137893 /* 253 */ "cmd ::= REINDEX",
137894 /* 254 */ "cmd ::= REINDEX nm dbnm",
137895 /* 255 */ "cmd ::= ANALYZE",
137896 /* 256 */ "cmd ::= ANALYZE nm dbnm",
137897 /* 257 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
137898 /* 258 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
137899 /* 259 */ "add_column_fullname ::= fullname",
137900 /* 260 */ "cmd ::= create_vtab",
137901 /* 261 */ "cmd ::= create_vtab LP vtabarglist RP",
137902 /* 262 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
137903 /* 263 */ "vtabarg ::=",
137904 /* 264 */ "vtabargtoken ::= ANY",
137905 /* 265 */ "vtabargtoken ::= lp anylist RP",
137906 /* 266 */ "lp ::= LP",
137907 /* 267 */ "with ::=",
137908 /* 268 */ "with ::= WITH wqlist",
137909 /* 269 */ "with ::= WITH RECURSIVE wqlist",
137910 /* 270 */ "wqlist ::= nm eidlist_opt AS LP select RP",
137911 /* 271 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
137912 /* 272 */ "input ::= cmdlist",
137913 /* 273 */ "cmdlist ::= cmdlist ecmd",
137914 /* 274 */ "cmdlist ::= ecmd",
137915 /* 275 */ "ecmd ::= SEMI",
137916 /* 276 */ "ecmd ::= explain cmdx SEMI",
137917 /* 277 */ "explain ::=",
137918 /* 278 */ "trans_opt ::=",
137919 /* 279 */ "trans_opt ::= TRANSACTION",
137920 /* 280 */ "trans_opt ::= TRANSACTION nm",
137921 /* 281 */ "savepoint_opt ::= SAVEPOINT",
137922 /* 282 */ "savepoint_opt ::=",
137923 /* 283 */ "cmd ::= create_table create_table_args",
137924 /* 284 */ "columnlist ::= columnlist COMMA columnname carglist",
137925 /* 285 */ "columnlist ::= columnname carglist",
137926 /* 286 */ "nm ::= ID|INDEXED",
137927 /* 287 */ "nm ::= STRING",
137928 /* 288 */ "nm ::= JOIN_KW",
137929 /* 289 */ "typetoken ::= typename",
137930 /* 290 */ "typename ::= ID|STRING",
137931 /* 291 */ "signed ::= plus_num",
137932 /* 292 */ "signed ::= minus_num",
137933 /* 293 */ "carglist ::= carglist ccons",
137934 /* 294 */ "carglist ::=",
137935 /* 295 */ "ccons ::= NULL onconf",
137936 /* 296 */ "conslist_opt ::= COMMA conslist",
137937 /* 297 */ "conslist ::= conslist tconscomma tcons",
137938 /* 298 */ "conslist ::= tcons",
137939 /* 299 */ "tconscomma ::=",
137940 /* 300 */ "defer_subclause_opt ::= defer_subclause",
137941 /* 301 */ "resolvetype ::= raisetype",
137942 /* 302 */ "selectnowith ::= oneselect",
137943 /* 303 */ "oneselect ::= values",
137944 /* 304 */ "sclp ::= selcollist COMMA",
137945 /* 305 */ "as ::= ID|STRING",
137946 /* 306 */ "expr ::= term",
137947 /* 307 */ "likeop ::= LIKE_KW|MATCH",
137948 /* 308 */ "exprlist ::= nexprlist",
137949 /* 309 */ "nmnum ::= plus_num",
137950 /* 310 */ "nmnum ::= nm",
137951 /* 311 */ "nmnum ::= ON",
137952 /* 312 */ "nmnum ::= DELETE",
137953 /* 313 */ "nmnum ::= DEFAULT",
137954 /* 314 */ "plus_num ::= INTEGER|FLOAT",
137955 /* 315 */ "foreach_clause ::=",
137956 /* 316 */ "foreach_clause ::= FOR EACH ROW",
137957 /* 317 */ "trnm ::= nm",
137958 /* 318 */ "tridxby ::=",
137959 /* 319 */ "database_kw_opt ::= DATABASE",
137960 /* 320 */ "database_kw_opt ::=",
137961 /* 321 */ "kwcolumn_opt ::=",
137962 /* 322 */ "kwcolumn_opt ::= COLUMNKW",
137963 /* 323 */ "vtabarglist ::= vtabarg",
137964 /* 324 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
137965 /* 325 */ "vtabarg ::= vtabarg vtabargtoken",
137966 /* 326 */ "anylist ::=",
137967 /* 327 */ "anylist ::= anylist LP anylist RP",
137968 /* 328 */ "anylist ::= anylist ANY",
137969};
137970#endif /* NDEBUG */
137971
137972
137973#if YYSTACKDEPTH<=0
137974/*
137975** Try to increase the size of the parser stack.  Return the number
137976** of errors.  Return 0 on success.
137977*/
137978static int yyGrowStack(yyParser *p){
137979  int newSize;
137980  int idx;
137981  yyStackEntry *pNew;
137982
137983  newSize = p->yystksz*2 + 100;
137984  idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
137985  if( p->yystack==&p->yystk0 ){
137986    pNew = malloc(newSize*sizeof(pNew[0]));
137987    if( pNew ) pNew[0] = p->yystk0;
137988  }else{
137989    pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
137990  }
137991  if( pNew ){
137992    p->yystack = pNew;
137993    p->yytos = &p->yystack[idx];
137994#ifndef NDEBUG
137995    if( yyTraceFILE ){
137996      fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
137997              yyTracePrompt, p->yystksz, newSize);
137998    }
137999#endif
138000    p->yystksz = newSize;
138001  }
138002  return pNew==0;
138003}
138004#endif
138005
138006/* Datatype of the argument to the memory allocated passed as the
138007** second argument to sqlite3ParserAlloc() below.  This can be changed by
138008** putting an appropriate #define in the %include section of the input
138009** grammar.
138010*/
138011#ifndef YYMALLOCARGTYPE
138012# define YYMALLOCARGTYPE size_t
138013#endif
138014
138015/* Initialize a new parser that has already been allocated.
138016*/
138017SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
138018  yyParser *pParser = (yyParser*)yypParser;
138019#ifdef YYTRACKMAXSTACKDEPTH
138020  pParser->yyhwm = 0;
138021#endif
138022#if YYSTACKDEPTH<=0
138023  pParser->yytos = NULL;
138024  pParser->yystack = NULL;
138025  pParser->yystksz = 0;
138026  if( yyGrowStack(pParser) ){
138027    pParser->yystack = &pParser->yystk0;
138028    pParser->yystksz = 1;
138029  }
138030#endif
138031#ifndef YYNOERRORRECOVERY
138032  pParser->yyerrcnt = -1;
138033#endif
138034  pParser->yytos = pParser->yystack;
138035  pParser->yystack[0].stateno = 0;
138036  pParser->yystack[0].major = 0;
138037#if YYSTACKDEPTH>0
138038  pParser->yystackEnd = &pParser->yystack[YYSTACKDEPTH-1];
138039#endif
138040}
138041
138042#ifndef sqlite3Parser_ENGINEALWAYSONSTACK
138043/*
138044** This function allocates a new parser.
138045** The only argument is a pointer to a function which works like
138046** malloc.
138047**
138048** Inputs:
138049** A pointer to the function used to allocate memory.
138050**
138051** Outputs:
138052** A pointer to a parser.  This pointer is used in subsequent calls
138053** to sqlite3Parser and sqlite3ParserFree.
138054*/
138055SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
138056  yyParser *pParser;
138057  pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
138058  if( pParser ) sqlite3ParserInit(pParser);
138059  return pParser;
138060}
138061#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
138062
138063
138064/* The following function deletes the "minor type" or semantic value
138065** associated with a symbol.  The symbol can be either a terminal
138066** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
138067** a pointer to the value to be deleted.  The code used to do the
138068** deletions is derived from the %destructor and/or %token_destructor
138069** directives of the input grammar.
138070*/
138071static void yy_destructor(
138072  yyParser *yypParser,    /* The parser */
138073  YYCODETYPE yymajor,     /* Type code for object to destroy */
138074  YYMINORTYPE *yypminor   /* The object to be destroyed */
138075){
138076  sqlite3ParserARG_FETCH;
138077  switch( yymajor ){
138078    /* Here is inserted the actions which take place when a
138079    ** terminal or non-terminal is destroyed.  This can happen
138080    ** when the symbol is popped from the stack during a
138081    ** reduce or during error processing or when a parser is
138082    ** being destroyed before it is finished parsing.
138083    **
138084    ** Note: during a reduce, the only symbols destroyed are those
138085    ** which appear on the RHS of the rule, but which are *not* used
138086    ** inside the C code.
138087    */
138088/********* Begin destructor definitions ***************************************/
138089    case 163: /* select */
138090    case 194: /* selectnowith */
138091    case 195: /* oneselect */
138092    case 206: /* values */
138093{
138094sqlite3SelectDelete(pParse->db, (yypminor->yy243));
138095}
138096      break;
138097    case 172: /* term */
138098    case 173: /* expr */
138099{
138100sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
138101}
138102      break;
138103    case 177: /* eidlist_opt */
138104    case 186: /* sortlist */
138105    case 187: /* eidlist */
138106    case 199: /* selcollist */
138107    case 202: /* groupby_opt */
138108    case 204: /* orderby_opt */
138109    case 207: /* nexprlist */
138110    case 208: /* exprlist */
138111    case 209: /* sclp */
138112    case 218: /* setlist */
138113    case 224: /* paren_exprlist */
138114    case 226: /* case_exprlist */
138115{
138116sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
138117}
138118      break;
138119    case 193: /* fullname */
138120    case 200: /* from */
138121    case 211: /* seltablist */
138122    case 212: /* stl_prefix */
138123{
138124sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
138125}
138126      break;
138127    case 196: /* with */
138128    case 250: /* wqlist */
138129{
138130sqlite3WithDelete(pParse->db, (yypminor->yy285));
138131}
138132      break;
138133    case 201: /* where_opt */
138134    case 203: /* having_opt */
138135    case 215: /* on_opt */
138136    case 225: /* case_operand */
138137    case 227: /* case_else */
138138    case 236: /* when_clause */
138139    case 241: /* key_opt */
138140{
138141sqlite3ExprDelete(pParse->db, (yypminor->yy72));
138142}
138143      break;
138144    case 216: /* using_opt */
138145    case 217: /* idlist */
138146    case 220: /* idlist_opt */
138147{
138148sqlite3IdListDelete(pParse->db, (yypminor->yy254));
138149}
138150      break;
138151    case 232: /* trigger_cmd_list */
138152    case 237: /* trigger_cmd */
138153{
138154sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
138155}
138156      break;
138157    case 234: /* trigger_event */
138158{
138159sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
138160}
138161      break;
138162/********* End destructor definitions *****************************************/
138163    default:  break;   /* If no destructor action specified: do nothing */
138164  }
138165}
138166
138167/*
138168** Pop the parser's stack once.
138169**
138170** If there is a destructor routine associated with the token which
138171** is popped from the stack, then call it.
138172*/
138173static void yy_pop_parser_stack(yyParser *pParser){
138174  yyStackEntry *yytos;
138175  assert( pParser->yytos!=0 );
138176  assert( pParser->yytos > pParser->yystack );
138177  yytos = pParser->yytos--;
138178#ifndef NDEBUG
138179  if( yyTraceFILE ){
138180    fprintf(yyTraceFILE,"%sPopping %s\n",
138181      yyTracePrompt,
138182      yyTokenName[yytos->major]);
138183  }
138184#endif
138185  yy_destructor(pParser, yytos->major, &yytos->minor);
138186}
138187
138188/*
138189** Clear all secondary memory allocations from the parser
138190*/
138191SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
138192  yyParser *pParser = (yyParser*)p;
138193  while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
138194#if YYSTACKDEPTH<=0
138195  if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
138196#endif
138197}
138198
138199#ifndef sqlite3Parser_ENGINEALWAYSONSTACK
138200/*
138201** Deallocate and destroy a parser.  Destructors are called for
138202** all stack elements before shutting the parser down.
138203**
138204** If the YYPARSEFREENEVERNULL macro exists (for example because it
138205** is defined in a %include section of the input grammar) then it is
138206** assumed that the input pointer is never NULL.
138207*/
138208SQLITE_PRIVATE void sqlite3ParserFree(
138209  void *p,                    /* The parser to be deleted */
138210  void (*freeProc)(void*)     /* Function used to reclaim memory */
138211){
138212#ifndef YYPARSEFREENEVERNULL
138213  if( p==0 ) return;
138214#endif
138215  sqlite3ParserFinalize(p);
138216  (*freeProc)(p);
138217}
138218#endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
138219
138220/*
138221** Return the peak depth of the stack for a parser.
138222*/
138223#ifdef YYTRACKMAXSTACKDEPTH
138224SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
138225  yyParser *pParser = (yyParser*)p;
138226  return pParser->yyhwm;
138227}
138228#endif
138229
138230/*
138231** Find the appropriate action for a parser given the terminal
138232** look-ahead token iLookAhead.
138233*/
138234static unsigned int yy_find_shift_action(
138235  yyParser *pParser,        /* The parser */
138236  YYCODETYPE iLookAhead     /* The look-ahead token */
138237){
138238  int i;
138239  int stateno = pParser->yytos->stateno;
138240
138241  if( stateno>=YY_MIN_REDUCE ) return stateno;
138242  assert( stateno <= YY_SHIFT_COUNT );
138243  do{
138244    i = yy_shift_ofst[stateno];
138245    assert( iLookAhead!=YYNOCODE );
138246    i += iLookAhead;
138247    if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
138248#ifdef YYFALLBACK
138249      YYCODETYPE iFallback;            /* Fallback token */
138250      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
138251             && (iFallback = yyFallback[iLookAhead])!=0 ){
138252#ifndef NDEBUG
138253        if( yyTraceFILE ){
138254          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
138255             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
138256        }
138257#endif
138258        assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
138259        iLookAhead = iFallback;
138260        continue;
138261      }
138262#endif
138263#ifdef YYWILDCARD
138264      {
138265        int j = i - iLookAhead + YYWILDCARD;
138266        if(
138267#if YY_SHIFT_MIN+YYWILDCARD<0
138268          j>=0 &&
138269#endif
138270#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
138271          j<YY_ACTTAB_COUNT &&
138272#endif
138273          yy_lookahead[j]==YYWILDCARD && iLookAhead>0
138274        ){
138275#ifndef NDEBUG
138276          if( yyTraceFILE ){
138277            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
138278               yyTracePrompt, yyTokenName[iLookAhead],
138279               yyTokenName[YYWILDCARD]);
138280          }
138281#endif /* NDEBUG */
138282          return yy_action[j];
138283        }
138284      }
138285#endif /* YYWILDCARD */
138286      return yy_default[stateno];
138287    }else{
138288      return yy_action[i];
138289    }
138290  }while(1);
138291}
138292
138293/*
138294** Find the appropriate action for a parser given the non-terminal
138295** look-ahead token iLookAhead.
138296*/
138297static int yy_find_reduce_action(
138298  int stateno,              /* Current state number */
138299  YYCODETYPE iLookAhead     /* The look-ahead token */
138300){
138301  int i;
138302#ifdef YYERRORSYMBOL
138303  if( stateno>YY_REDUCE_COUNT ){
138304    return yy_default[stateno];
138305  }
138306#else
138307  assert( stateno<=YY_REDUCE_COUNT );
138308#endif
138309  i = yy_reduce_ofst[stateno];
138310  assert( i!=YY_REDUCE_USE_DFLT );
138311  assert( iLookAhead!=YYNOCODE );
138312  i += iLookAhead;
138313#ifdef YYERRORSYMBOL
138314  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
138315    return yy_default[stateno];
138316  }
138317#else
138318  assert( i>=0 && i<YY_ACTTAB_COUNT );
138319  assert( yy_lookahead[i]==iLookAhead );
138320#endif
138321  return yy_action[i];
138322}
138323
138324/*
138325** The following routine is called if the stack overflows.
138326*/
138327static void yyStackOverflow(yyParser *yypParser){
138328   sqlite3ParserARG_FETCH;
138329#ifndef NDEBUG
138330   if( yyTraceFILE ){
138331     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
138332   }
138333#endif
138334   while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
138335   /* Here code is inserted which will execute if the parser
138336   ** stack every overflows */
138337/******** Begin %stack_overflow code ******************************************/
138338
138339  sqlite3ErrorMsg(pParse, "parser stack overflow");
138340/******** End %stack_overflow code ********************************************/
138341   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
138342}
138343
138344/*
138345** Print tracing information for a SHIFT action
138346*/
138347#ifndef NDEBUG
138348static void yyTraceShift(yyParser *yypParser, int yyNewState){
138349  if( yyTraceFILE ){
138350    if( yyNewState<YYNSTATE ){
138351      fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
138352         yyTracePrompt,yyTokenName[yypParser->yytos->major],
138353         yyNewState);
138354    }else{
138355      fprintf(yyTraceFILE,"%sShift '%s'\n",
138356         yyTracePrompt,yyTokenName[yypParser->yytos->major]);
138357    }
138358  }
138359}
138360#else
138361# define yyTraceShift(X,Y)
138362#endif
138363
138364/*
138365** Perform a shift action.
138366*/
138367static void yy_shift(
138368  yyParser *yypParser,          /* The parser to be shifted */
138369  int yyNewState,               /* The new state to shift in */
138370  int yyMajor,                  /* The major token to shift in */
138371  sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
138372){
138373  yyStackEntry *yytos;
138374  yypParser->yytos++;
138375#ifdef YYTRACKMAXSTACKDEPTH
138376  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
138377    yypParser->yyhwm++;
138378    assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
138379  }
138380#endif
138381#if YYSTACKDEPTH>0
138382  if( yypParser->yytos>yypParser->yystackEnd ){
138383    yypParser->yytos--;
138384    yyStackOverflow(yypParser);
138385    return;
138386  }
138387#else
138388  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
138389    if( yyGrowStack(yypParser) ){
138390      yypParser->yytos--;
138391      yyStackOverflow(yypParser);
138392      return;
138393    }
138394  }
138395#endif
138396  if( yyNewState > YY_MAX_SHIFT ){
138397    yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
138398  }
138399  yytos = yypParser->yytos;
138400  yytos->stateno = (YYACTIONTYPE)yyNewState;
138401  yytos->major = (YYCODETYPE)yyMajor;
138402  yytos->minor.yy0 = yyMinor;
138403  yyTraceShift(yypParser, yyNewState);
138404}
138405
138406/* The following table contains information about every rule that
138407** is used during the reduce.
138408*/
138409static const struct {
138410  YYCODETYPE lhs;       /* Symbol on the left-hand side of the rule */
138411  signed char nrhs;     /* Negative of the number of RHS symbols in the rule */
138412} yyRuleInfo[] = {
138413  { 147, -1 },
138414  { 147, -3 },
138415  { 148, -1 },
138416  { 149, -3 },
138417  { 150, 0 },
138418  { 150, -1 },
138419  { 150, -1 },
138420  { 150, -1 },
138421  { 149, -2 },
138422  { 149, -2 },
138423  { 149, -2 },
138424  { 149, -3 },
138425  { 149, -5 },
138426  { 154, -6 },
138427  { 156, -1 },
138428  { 158, 0 },
138429  { 158, -3 },
138430  { 157, -1 },
138431  { 157, 0 },
138432  { 155, -5 },
138433  { 155, -2 },
138434  { 162, 0 },
138435  { 162, -2 },
138436  { 164, -2 },
138437  { 166, 0 },
138438  { 166, -4 },
138439  { 166, -6 },
138440  { 167, -2 },
138441  { 171, -2 },
138442  { 171, -2 },
138443  { 171, -4 },
138444  { 171, -3 },
138445  { 171, -3 },
138446  { 171, -2 },
138447  { 171, -3 },
138448  { 171, -5 },
138449  { 171, -2 },
138450  { 171, -4 },
138451  { 171, -4 },
138452  { 171, -1 },
138453  { 171, -2 },
138454  { 176, 0 },
138455  { 176, -1 },
138456  { 178, 0 },
138457  { 178, -2 },
138458  { 180, -2 },
138459  { 180, -3 },
138460  { 180, -3 },
138461  { 180, -3 },
138462  { 181, -2 },
138463  { 181, -2 },
138464  { 181, -1 },
138465  { 181, -1 },
138466  { 181, -2 },
138467  { 179, -3 },
138468  { 179, -2 },
138469  { 182, 0 },
138470  { 182, -2 },
138471  { 182, -2 },
138472  { 161, 0 },
138473  { 184, -1 },
138474  { 185, -2 },
138475  { 185, -7 },
138476  { 185, -5 },
138477  { 185, -5 },
138478  { 185, -10 },
138479  { 188, 0 },
138480  { 174, 0 },
138481  { 174, -3 },
138482  { 189, 0 },
138483  { 189, -2 },
138484  { 190, -1 },
138485  { 190, -1 },
138486  { 149, -4 },
138487  { 192, -2 },
138488  { 192, 0 },
138489  { 149, -9 },
138490  { 149, -4 },
138491  { 149, -1 },
138492  { 163, -2 },
138493  { 194, -3 },
138494  { 197, -1 },
138495  { 197, -2 },
138496  { 197, -1 },
138497  { 195, -9 },
138498  { 206, -4 },
138499  { 206, -5 },
138500  { 198, -1 },
138501  { 198, -1 },
138502  { 198, 0 },
138503  { 209, 0 },
138504  { 199, -3 },
138505  { 199, -2 },
138506  { 199, -4 },
138507  { 210, -2 },
138508  { 210, 0 },
138509  { 200, 0 },
138510  { 200, -2 },
138511  { 212, -2 },
138512  { 212, 0 },
138513  { 211, -7 },
138514  { 211, -9 },
138515  { 211, -7 },
138516  { 211, -7 },
138517  { 159, 0 },
138518  { 159, -2 },
138519  { 193, -2 },
138520  { 213, -1 },
138521  { 213, -2 },
138522  { 213, -3 },
138523  { 213, -4 },
138524  { 215, -2 },
138525  { 215, 0 },
138526  { 214, 0 },
138527  { 214, -3 },
138528  { 214, -2 },
138529  { 216, -4 },
138530  { 216, 0 },
138531  { 204, 0 },
138532  { 204, -3 },
138533  { 186, -4 },
138534  { 186, -2 },
138535  { 175, -1 },
138536  { 175, -1 },
138537  { 175, 0 },
138538  { 202, 0 },
138539  { 202, -3 },
138540  { 203, 0 },
138541  { 203, -2 },
138542  { 205, 0 },
138543  { 205, -2 },
138544  { 205, -4 },
138545  { 205, -4 },
138546  { 149, -6 },
138547  { 201, 0 },
138548  { 201, -2 },
138549  { 149, -8 },
138550  { 218, -5 },
138551  { 218, -7 },
138552  { 218, -3 },
138553  { 218, -5 },
138554  { 149, -6 },
138555  { 149, -7 },
138556  { 219, -2 },
138557  { 219, -1 },
138558  { 220, 0 },
138559  { 220, -3 },
138560  { 217, -3 },
138561  { 217, -1 },
138562  { 173, -3 },
138563  { 173, -1 },
138564  { 173, -1 },
138565  { 173, -3 },
138566  { 173, -5 },
138567  { 172, -1 },
138568  { 172, -1 },
138569  { 172, -1 },
138570  { 173, -1 },
138571  { 173, -3 },
138572  { 173, -6 },
138573  { 173, -5 },
138574  { 173, -4 },
138575  { 172, -1 },
138576  { 173, -5 },
138577  { 173, -3 },
138578  { 173, -3 },
138579  { 173, -3 },
138580  { 173, -3 },
138581  { 173, -3 },
138582  { 173, -3 },
138583  { 173, -3 },
138584  { 173, -3 },
138585  { 221, -2 },
138586  { 173, -3 },
138587  { 173, -5 },
138588  { 173, -2 },
138589  { 173, -3 },
138590  { 173, -3 },
138591  { 173, -4 },
138592  { 173, -2 },
138593  { 173, -2 },
138594  { 173, -2 },
138595  { 173, -2 },
138596  { 222, -1 },
138597  { 222, -2 },
138598  { 173, -5 },
138599  { 223, -1 },
138600  { 223, -2 },
138601  { 173, -5 },
138602  { 173, -3 },
138603  { 173, -5 },
138604  { 173, -5 },
138605  { 173, -4 },
138606  { 173, -5 },
138607  { 226, -5 },
138608  { 226, -4 },
138609  { 227, -2 },
138610  { 227, 0 },
138611  { 225, -1 },
138612  { 225, 0 },
138613  { 208, 0 },
138614  { 207, -3 },
138615  { 207, -1 },
138616  { 224, 0 },
138617  { 224, -3 },
138618  { 149, -12 },
138619  { 228, -1 },
138620  { 228, 0 },
138621  { 177, 0 },
138622  { 177, -3 },
138623  { 187, -5 },
138624  { 187, -3 },
138625  { 229, 0 },
138626  { 229, -2 },
138627  { 149, -4 },
138628  { 149, -1 },
138629  { 149, -2 },
138630  { 149, -3 },
138631  { 149, -5 },
138632  { 149, -6 },
138633  { 149, -5 },
138634  { 149, -6 },
138635  { 169, -2 },
138636  { 170, -2 },
138637  { 149, -5 },
138638  { 231, -11 },
138639  { 233, -1 },
138640  { 233, -2 },
138641  { 233, 0 },
138642  { 234, -1 },
138643  { 234, -1 },
138644  { 234, -3 },
138645  { 236, 0 },
138646  { 236, -2 },
138647  { 232, -3 },
138648  { 232, -2 },
138649  { 238, -3 },
138650  { 239, -3 },
138651  { 239, -2 },
138652  { 237, -7 },
138653  { 237, -5 },
138654  { 237, -5 },
138655  { 237, -1 },
138656  { 173, -4 },
138657  { 173, -6 },
138658  { 191, -1 },
138659  { 191, -1 },
138660  { 191, -1 },
138661  { 149, -4 },
138662  { 149, -6 },
138663  { 149, -3 },
138664  { 241, 0 },
138665  { 241, -2 },
138666  { 149, -1 },
138667  { 149, -3 },
138668  { 149, -1 },
138669  { 149, -3 },
138670  { 149, -6 },
138671  { 149, -7 },
138672  { 242, -1 },
138673  { 149, -1 },
138674  { 149, -4 },
138675  { 244, -8 },
138676  { 246, 0 },
138677  { 247, -1 },
138678  { 247, -3 },
138679  { 248, -1 },
138680  { 196, 0 },
138681  { 196, -2 },
138682  { 196, -3 },
138683  { 250, -6 },
138684  { 250, -8 },
138685  { 144, -1 },
138686  { 145, -2 },
138687  { 145, -1 },
138688  { 146, -1 },
138689  { 146, -3 },
138690  { 147, 0 },
138691  { 151, 0 },
138692  { 151, -1 },
138693  { 151, -2 },
138694  { 153, -1 },
138695  { 153, 0 },
138696  { 149, -2 },
138697  { 160, -4 },
138698  { 160, -2 },
138699  { 152, -1 },
138700  { 152, -1 },
138701  { 152, -1 },
138702  { 166, -1 },
138703  { 167, -1 },
138704  { 168, -1 },
138705  { 168, -1 },
138706  { 165, -2 },
138707  { 165, 0 },
138708  { 171, -2 },
138709  { 161, -2 },
138710  { 183, -3 },
138711  { 183, -1 },
138712  { 184, 0 },
138713  { 188, -1 },
138714  { 190, -1 },
138715  { 194, -1 },
138716  { 195, -1 },
138717  { 209, -2 },
138718  { 210, -1 },
138719  { 173, -1 },
138720  { 221, -1 },
138721  { 208, -1 },
138722  { 230, -1 },
138723  { 230, -1 },
138724  { 230, -1 },
138725  { 230, -1 },
138726  { 230, -1 },
138727  { 169, -1 },
138728  { 235, 0 },
138729  { 235, -3 },
138730  { 238, -1 },
138731  { 239, 0 },
138732  { 240, -1 },
138733  { 240, 0 },
138734  { 243, 0 },
138735  { 243, -1 },
138736  { 245, -1 },
138737  { 245, -3 },
138738  { 246, -2 },
138739  { 249, 0 },
138740  { 249, -4 },
138741  { 249, -2 },
138742};
138743
138744static void yy_accept(yyParser*);  /* Forward Declaration */
138745
138746/*
138747** Perform a reduce action and the shift that must immediately
138748** follow the reduce.
138749*/
138750static void yy_reduce(
138751  yyParser *yypParser,         /* The parser */
138752  unsigned int yyruleno        /* Number of the rule by which to reduce */
138753){
138754  int yygoto;                     /* The next state */
138755  int yyact;                      /* The next action */
138756  yyStackEntry *yymsp;            /* The top of the parser's stack */
138757  int yysize;                     /* Amount to pop the stack */
138758  sqlite3ParserARG_FETCH;
138759  yymsp = yypParser->yytos;
138760#ifndef NDEBUG
138761  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
138762    yysize = yyRuleInfo[yyruleno].nrhs;
138763    fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
138764      yyRuleName[yyruleno], yymsp[yysize].stateno);
138765  }
138766#endif /* NDEBUG */
138767
138768  /* Check that the stack is large enough to grow by a single entry
138769  ** if the RHS of the rule is empty.  This ensures that there is room
138770  ** enough on the stack to push the LHS value */
138771  if( yyRuleInfo[yyruleno].nrhs==0 ){
138772#ifdef YYTRACKMAXSTACKDEPTH
138773    if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
138774      yypParser->yyhwm++;
138775      assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
138776    }
138777#endif
138778#if YYSTACKDEPTH>0
138779    if( yypParser->yytos>=yypParser->yystackEnd ){
138780      yyStackOverflow(yypParser);
138781      return;
138782    }
138783#else
138784    if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
138785      if( yyGrowStack(yypParser) ){
138786        yyStackOverflow(yypParser);
138787        return;
138788      }
138789      yymsp = yypParser->yytos;
138790    }
138791#endif
138792  }
138793
138794  switch( yyruleno ){
138795  /* Beginning here are the reduction cases.  A typical example
138796  ** follows:
138797  **   case 0:
138798  **  #line <lineno> <grammarfile>
138799  **     { ... }           // User supplied code
138800  **  #line <lineno> <thisfile>
138801  **     break;
138802  */
138803/********** Begin reduce actions **********************************************/
138804        YYMINORTYPE yylhsminor;
138805      case 0: /* explain ::= EXPLAIN */
138806{ pParse->explain = 1; }
138807        break;
138808      case 1: /* explain ::= EXPLAIN QUERY PLAN */
138809{ pParse->explain = 2; }
138810        break;
138811      case 2: /* cmdx ::= cmd */
138812{ sqlite3FinishCoding(pParse); }
138813        break;
138814      case 3: /* cmd ::= BEGIN transtype trans_opt */
138815{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
138816        break;
138817      case 4: /* transtype ::= */
138818{yymsp[1].minor.yy194 = TK_DEFERRED;}
138819        break;
138820      case 5: /* transtype ::= DEFERRED */
138821      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
138822      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
138823{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
138824        break;
138825      case 8: /* cmd ::= COMMIT|END trans_opt */
138826      case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
138827{sqlite3EndTransaction(pParse,yymsp[-1].major);}
138828        break;
138829      case 10: /* cmd ::= SAVEPOINT nm */
138830{
138831  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
138832}
138833        break;
138834      case 11: /* cmd ::= RELEASE savepoint_opt nm */
138835{
138836  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
138837}
138838        break;
138839      case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
138840{
138841  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
138842}
138843        break;
138844      case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
138845{
138846   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
138847}
138848        break;
138849      case 14: /* createkw ::= CREATE */
138850{disableLookaside(pParse);}
138851        break;
138852      case 15: /* ifnotexists ::= */
138853      case 18: /* temp ::= */ yytestcase(yyruleno==18);
138854      case 21: /* table_options ::= */ yytestcase(yyruleno==21);
138855      case 41: /* autoinc ::= */ yytestcase(yyruleno==41);
138856      case 56: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==56);
138857      case 66: /* defer_subclause_opt ::= */ yytestcase(yyruleno==66);
138858      case 75: /* ifexists ::= */ yytestcase(yyruleno==75);
138859      case 89: /* distinct ::= */ yytestcase(yyruleno==89);
138860      case 212: /* collate ::= */ yytestcase(yyruleno==212);
138861{yymsp[1].minor.yy194 = 0;}
138862        break;
138863      case 16: /* ifnotexists ::= IF NOT EXISTS */
138864{yymsp[-2].minor.yy194 = 1;}
138865        break;
138866      case 17: /* temp ::= TEMP */
138867      case 42: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==42);
138868{yymsp[0].minor.yy194 = 1;}
138869        break;
138870      case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
138871{
138872  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
138873}
138874        break;
138875      case 20: /* create_table_args ::= AS select */
138876{
138877  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
138878  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
138879}
138880        break;
138881      case 22: /* table_options ::= WITHOUT nm */
138882{
138883  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
138884    yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
138885  }else{
138886    yymsp[-1].minor.yy194 = 0;
138887    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
138888  }
138889}
138890        break;
138891      case 23: /* columnname ::= nm typetoken */
138892{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
138893        break;
138894      case 24: /* typetoken ::= */
138895      case 59: /* conslist_opt ::= */ yytestcase(yyruleno==59);
138896      case 95: /* as ::= */ yytestcase(yyruleno==95);
138897{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
138898        break;
138899      case 25: /* typetoken ::= typename LP signed RP */
138900{
138901  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
138902}
138903        break;
138904      case 26: /* typetoken ::= typename LP signed COMMA signed RP */
138905{
138906  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
138907}
138908        break;
138909      case 27: /* typename ::= typename ID|STRING */
138910{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
138911        break;
138912      case 28: /* ccons ::= CONSTRAINT nm */
138913      case 61: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==61);
138914{pParse->constraintName = yymsp[0].minor.yy0;}
138915        break;
138916      case 29: /* ccons ::= DEFAULT term */
138917      case 31: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==31);
138918{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
138919        break;
138920      case 30: /* ccons ::= DEFAULT LP expr RP */
138921{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
138922        break;
138923      case 32: /* ccons ::= DEFAULT MINUS term */
138924{
138925  ExprSpan v;
138926  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0);
138927  v.zStart = yymsp[-1].minor.yy0.z;
138928  v.zEnd = yymsp[0].minor.yy190.zEnd;
138929  sqlite3AddDefaultValue(pParse,&v);
138930}
138931        break;
138932      case 33: /* ccons ::= DEFAULT ID|INDEXED */
138933{
138934  ExprSpan v;
138935  spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
138936  sqlite3AddDefaultValue(pParse,&v);
138937}
138938        break;
138939      case 34: /* ccons ::= NOT NULL onconf */
138940{sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
138941        break;
138942      case 35: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
138943{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
138944        break;
138945      case 36: /* ccons ::= UNIQUE onconf */
138946{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
138947                                   SQLITE_IDXTYPE_UNIQUE);}
138948        break;
138949      case 37: /* ccons ::= CHECK LP expr RP */
138950{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
138951        break;
138952      case 38: /* ccons ::= REFERENCES nm eidlist_opt refargs */
138953{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
138954        break;
138955      case 39: /* ccons ::= defer_subclause */
138956{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
138957        break;
138958      case 40: /* ccons ::= COLLATE ID|STRING */
138959{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
138960        break;
138961      case 43: /* refargs ::= */
138962{ yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
138963        break;
138964      case 44: /* refargs ::= refargs refarg */
138965{ yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
138966        break;
138967      case 45: /* refarg ::= MATCH nm */
138968{ yymsp[-1].minor.yy497.value = 0;     yymsp[-1].minor.yy497.mask = 0x000000; }
138969        break;
138970      case 46: /* refarg ::= ON INSERT refact */
138971{ yymsp[-2].minor.yy497.value = 0;     yymsp[-2].minor.yy497.mask = 0x000000; }
138972        break;
138973      case 47: /* refarg ::= ON DELETE refact */
138974{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194;     yymsp[-2].minor.yy497.mask = 0x0000ff; }
138975        break;
138976      case 48: /* refarg ::= ON UPDATE refact */
138977{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8;  yymsp[-2].minor.yy497.mask = 0x00ff00; }
138978        break;
138979      case 49: /* refact ::= SET NULL */
138980{ yymsp[-1].minor.yy194 = OE_SetNull;  /* EV: R-33326-45252 */}
138981        break;
138982      case 50: /* refact ::= SET DEFAULT */
138983{ yymsp[-1].minor.yy194 = OE_SetDflt;  /* EV: R-33326-45252 */}
138984        break;
138985      case 51: /* refact ::= CASCADE */
138986{ yymsp[0].minor.yy194 = OE_Cascade;  /* EV: R-33326-45252 */}
138987        break;
138988      case 52: /* refact ::= RESTRICT */
138989{ yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
138990        break;
138991      case 53: /* refact ::= NO ACTION */
138992{ yymsp[-1].minor.yy194 = OE_None;     /* EV: R-33326-45252 */}
138993        break;
138994      case 54: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
138995{yymsp[-2].minor.yy194 = 0;}
138996        break;
138997      case 55: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
138998      case 70: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==70);
138999      case 143: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==143);
139000{yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
139001        break;
139002      case 57: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
139003      case 74: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==74);
139004      case 184: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==184);
139005      case 187: /* in_op ::= NOT IN */ yytestcase(yyruleno==187);
139006      case 213: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==213);
139007{yymsp[-1].minor.yy194 = 1;}
139008        break;
139009      case 58: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
139010{yymsp[-1].minor.yy194 = 0;}
139011        break;
139012      case 60: /* tconscomma ::= COMMA */
139013{pParse->constraintName.n = 0;}
139014        break;
139015      case 62: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
139016{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
139017        break;
139018      case 63: /* tcons ::= UNIQUE LP sortlist RP onconf */
139019{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
139020                                       SQLITE_IDXTYPE_UNIQUE);}
139021        break;
139022      case 64: /* tcons ::= CHECK LP expr RP onconf */
139023{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
139024        break;
139025      case 65: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
139026{
139027    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
139028    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
139029}
139030        break;
139031      case 67: /* onconf ::= */
139032      case 69: /* orconf ::= */ yytestcase(yyruleno==69);
139033{yymsp[1].minor.yy194 = OE_Default;}
139034        break;
139035      case 68: /* onconf ::= ON CONFLICT resolvetype */
139036{yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
139037        break;
139038      case 71: /* resolvetype ::= IGNORE */
139039{yymsp[0].minor.yy194 = OE_Ignore;}
139040        break;
139041      case 72: /* resolvetype ::= REPLACE */
139042      case 144: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==144);
139043{yymsp[0].minor.yy194 = OE_Replace;}
139044        break;
139045      case 73: /* cmd ::= DROP TABLE ifexists fullname */
139046{
139047  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
139048}
139049        break;
139050      case 76: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
139051{
139052  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194);
139053}
139054        break;
139055      case 77: /* cmd ::= DROP VIEW ifexists fullname */
139056{
139057  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
139058}
139059        break;
139060      case 78: /* cmd ::= select */
139061{
139062  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
139063  sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
139064  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
139065}
139066        break;
139067      case 79: /* select ::= with selectnowith */
139068{
139069  Select *p = yymsp[0].minor.yy243;
139070  if( p ){
139071    p->pWith = yymsp[-1].minor.yy285;
139072    parserDoubleLinkSelect(pParse, p);
139073  }else{
139074    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
139075  }
139076  yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
139077}
139078        break;
139079      case 80: /* selectnowith ::= selectnowith multiselect_op oneselect */
139080{
139081  Select *pRhs = yymsp[0].minor.yy243;
139082  Select *pLhs = yymsp[-2].minor.yy243;
139083  if( pRhs && pRhs->pPrior ){
139084    SrcList *pFrom;
139085    Token x;
139086    x.n = 0;
139087    parserDoubleLinkSelect(pParse, pRhs);
139088    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
139089    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
139090  }
139091  if( pRhs ){
139092    pRhs->op = (u8)yymsp[-1].minor.yy194;
139093    pRhs->pPrior = pLhs;
139094    if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
139095    pRhs->selFlags &= ~SF_MultiValue;
139096    if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
139097  }else{
139098    sqlite3SelectDelete(pParse->db, pLhs);
139099  }
139100  yymsp[-2].minor.yy243 = pRhs;
139101}
139102        break;
139103      case 81: /* multiselect_op ::= UNION */
139104      case 83: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==83);
139105{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
139106        break;
139107      case 82: /* multiselect_op ::= UNION ALL */
139108{yymsp[-1].minor.yy194 = TK_ALL;}
139109        break;
139110      case 84: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
139111{
139112#if SELECTTRACE_ENABLED
139113  Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
139114#endif
139115  yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
139116#if SELECTTRACE_ENABLED
139117  /* Populate the Select.zSelName[] string that is used to help with
139118  ** query planner debugging, to differentiate between multiple Select
139119  ** objects in a complex query.
139120  **
139121  ** If the SELECT keyword is immediately followed by a C-style comment
139122  ** then extract the first few alphanumeric characters from within that
139123  ** comment to be the zSelName value.  Otherwise, the label is #N where
139124  ** is an integer that is incremented with each SELECT statement seen.
139125  */
139126  if( yymsp[-8].minor.yy243!=0 ){
139127    const char *z = s.z+6;
139128    int i;
139129    sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
139130                     ++pParse->nSelect);
139131    while( z[0]==' ' ) z++;
139132    if( z[0]=='/' && z[1]=='*' ){
139133      z += 2;
139134      while( z[0]==' ' ) z++;
139135      for(i=0; sqlite3Isalnum(z[i]); i++){}
139136      sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
139137    }
139138  }
139139#endif /* SELECTRACE_ENABLED */
139140}
139141        break;
139142      case 85: /* values ::= VALUES LP nexprlist RP */
139143{
139144  yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
139145}
139146        break;
139147      case 86: /* values ::= values COMMA LP exprlist RP */
139148{
139149  Select *pRight, *pLeft = yymsp[-4].minor.yy243;
139150  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
139151  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
139152  if( pRight ){
139153    pRight->op = TK_ALL;
139154    pRight->pPrior = pLeft;
139155    yymsp[-4].minor.yy243 = pRight;
139156  }else{
139157    yymsp[-4].minor.yy243 = pLeft;
139158  }
139159}
139160        break;
139161      case 87: /* distinct ::= DISTINCT */
139162{yymsp[0].minor.yy194 = SF_Distinct;}
139163        break;
139164      case 88: /* distinct ::= ALL */
139165{yymsp[0].minor.yy194 = SF_All;}
139166        break;
139167      case 90: /* sclp ::= */
139168      case 118: /* orderby_opt ::= */ yytestcase(yyruleno==118);
139169      case 125: /* groupby_opt ::= */ yytestcase(yyruleno==125);
139170      case 200: /* exprlist ::= */ yytestcase(yyruleno==200);
139171      case 203: /* paren_exprlist ::= */ yytestcase(yyruleno==203);
139172      case 208: /* eidlist_opt ::= */ yytestcase(yyruleno==208);
139173{yymsp[1].minor.yy148 = 0;}
139174        break;
139175      case 91: /* selcollist ::= sclp expr as */
139176{
139177   yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
139178   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
139179   sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
139180}
139181        break;
139182      case 92: /* selcollist ::= sclp STAR */
139183{
139184  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
139185  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
139186}
139187        break;
139188      case 93: /* selcollist ::= sclp nm DOT STAR */
139189{
139190  Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
139191  Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139192  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
139193  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
139194}
139195        break;
139196      case 94: /* as ::= AS nm */
139197      case 105: /* dbnm ::= DOT nm */ yytestcase(yyruleno==105);
139198      case 222: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==222);
139199      case 223: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==223);
139200{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
139201        break;
139202      case 96: /* from ::= */
139203{yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
139204        break;
139205      case 97: /* from ::= FROM seltablist */
139206{
139207  yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
139208  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
139209}
139210        break;
139211      case 98: /* stl_prefix ::= seltablist joinop */
139212{
139213   if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194;
139214}
139215        break;
139216      case 99: /* stl_prefix ::= */
139217{yymsp[1].minor.yy185 = 0;}
139218        break;
139219      case 100: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
139220{
139221  yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139222  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
139223}
139224        break;
139225      case 101: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
139226{
139227  yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139228  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
139229}
139230        break;
139231      case 102: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
139232{
139233    yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139234  }
139235        break;
139236      case 103: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
139237{
139238    if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
139239      yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
139240    }else if( yymsp[-4].minor.yy185->nSrc==1 ){
139241      yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139242      if( yymsp[-6].minor.yy185 ){
139243        struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
139244        struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
139245        pNew->zName = pOld->zName;
139246        pNew->zDatabase = pOld->zDatabase;
139247        pNew->pSelect = pOld->pSelect;
139248        pOld->zName = pOld->zDatabase = 0;
139249        pOld->pSelect = 0;
139250      }
139251      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
139252    }else{
139253      Select *pSubquery;
139254      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
139255      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
139256      yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
139257    }
139258  }
139259        break;
139260      case 104: /* dbnm ::= */
139261      case 113: /* indexed_opt ::= */ yytestcase(yyruleno==113);
139262{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
139263        break;
139264      case 106: /* fullname ::= nm dbnm */
139265{yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
139266        break;
139267      case 107: /* joinop ::= COMMA|JOIN */
139268{ yymsp[0].minor.yy194 = JT_INNER; }
139269        break;
139270      case 108: /* joinop ::= JOIN_KW JOIN */
139271{yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
139272        break;
139273      case 109: /* joinop ::= JOIN_KW nm JOIN */
139274{yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
139275        break;
139276      case 110: /* joinop ::= JOIN_KW nm nm JOIN */
139277{yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
139278        break;
139279      case 111: /* on_opt ::= ON expr */
139280      case 128: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==128);
139281      case 135: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==135);
139282      case 196: /* case_else ::= ELSE expr */ yytestcase(yyruleno==196);
139283{yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
139284        break;
139285      case 112: /* on_opt ::= */
139286      case 127: /* having_opt ::= */ yytestcase(yyruleno==127);
139287      case 134: /* where_opt ::= */ yytestcase(yyruleno==134);
139288      case 197: /* case_else ::= */ yytestcase(yyruleno==197);
139289      case 199: /* case_operand ::= */ yytestcase(yyruleno==199);
139290{yymsp[1].minor.yy72 = 0;}
139291        break;
139292      case 114: /* indexed_opt ::= INDEXED BY nm */
139293{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
139294        break;
139295      case 115: /* indexed_opt ::= NOT INDEXED */
139296{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
139297        break;
139298      case 116: /* using_opt ::= USING LP idlist RP */
139299{yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
139300        break;
139301      case 117: /* using_opt ::= */
139302      case 145: /* idlist_opt ::= */ yytestcase(yyruleno==145);
139303{yymsp[1].minor.yy254 = 0;}
139304        break;
139305      case 119: /* orderby_opt ::= ORDER BY sortlist */
139306      case 126: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==126);
139307{yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
139308        break;
139309      case 120: /* sortlist ::= sortlist COMMA expr sortorder */
139310{
139311  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
139312  sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
139313}
139314        break;
139315      case 121: /* sortlist ::= expr sortorder */
139316{
139317  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
139318  sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
139319}
139320        break;
139321      case 122: /* sortorder ::= ASC */
139322{yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
139323        break;
139324      case 123: /* sortorder ::= DESC */
139325{yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
139326        break;
139327      case 124: /* sortorder ::= */
139328{yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
139329        break;
139330      case 129: /* limit_opt ::= */
139331{yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
139332        break;
139333      case 130: /* limit_opt ::= LIMIT expr */
139334{yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
139335        break;
139336      case 131: /* limit_opt ::= LIMIT expr OFFSET expr */
139337{yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
139338        break;
139339      case 132: /* limit_opt ::= LIMIT expr COMMA expr */
139340{yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
139341        break;
139342      case 133: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
139343{
139344  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
139345  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
139346  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
139347}
139348        break;
139349      case 136: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
139350{
139351  sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
139352  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
139353  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
139354  sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
139355}
139356        break;
139357      case 137: /* setlist ::= setlist COMMA nm EQ expr */
139358{
139359  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
139360  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
139361}
139362        break;
139363      case 138: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
139364{
139365  yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
139366}
139367        break;
139368      case 139: /* setlist ::= nm EQ expr */
139369{
139370  yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
139371  sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
139372}
139373  yymsp[-2].minor.yy148 = yylhsminor.yy148;
139374        break;
139375      case 140: /* setlist ::= LP idlist RP EQ expr */
139376{
139377  yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
139378}
139379        break;
139380      case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
139381{
139382  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
139383  sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
139384}
139385        break;
139386      case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
139387{
139388  sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
139389  sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
139390}
139391        break;
139392      case 146: /* idlist_opt ::= LP idlist RP */
139393{yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
139394        break;
139395      case 147: /* idlist ::= idlist COMMA nm */
139396{yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
139397        break;
139398      case 148: /* idlist ::= nm */
139399{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
139400        break;
139401      case 149: /* expr ::= LP expr RP */
139402{spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/  yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;}
139403        break;
139404      case 150: /* expr ::= ID|INDEXED */
139405      case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
139406{spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
139407        break;
139408      case 152: /* expr ::= nm DOT nm */
139409{
139410  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139411  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
139412  spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139413  yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
139414}
139415        break;
139416      case 153: /* expr ::= nm DOT nm DOT nm */
139417{
139418  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
139419  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
139420  Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
139421  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
139422  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139423  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
139424}
139425        break;
139426      case 154: /* term ::= NULL|FLOAT|BLOB */
139427      case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
139428{spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
139429        break;
139430      case 156: /* term ::= INTEGER */
139431{
139432  yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
139433  yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
139434  yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
139435}
139436  yymsp[0].minor.yy190 = yylhsminor.yy190;
139437        break;
139438      case 157: /* expr ::= VARIABLE */
139439{
139440  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
139441    u32 n = yymsp[0].minor.yy0.n;
139442    spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
139443    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
139444  }else{
139445    /* When doing a nested parse, one can include terms in an expression
139446    ** that look like this:   #1 #2 ...  These terms refer to registers
139447    ** in the virtual machine.  #N is the N-th register. */
139448    Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
139449    assert( t.n>=2 );
139450    spanSet(&yymsp[0].minor.yy190, &t, &t);
139451    if( pParse->nested==0 ){
139452      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
139453      yymsp[0].minor.yy190.pExpr = 0;
139454    }else{
139455      yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
139456      if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
139457    }
139458  }
139459}
139460        break;
139461      case 158: /* expr ::= expr COLLATE ID|STRING */
139462{
139463  yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
139464  yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
139465}
139466        break;
139467      case 159: /* expr ::= CAST LP expr AS typetoken RP */
139468{
139469  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
139470  yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
139471  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0);
139472}
139473        break;
139474      case 160: /* expr ::= ID|INDEXED LP distinct exprlist RP */
139475{
139476  if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
139477    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
139478  }
139479  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
139480  spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
139481  if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
139482    yylhsminor.yy190.pExpr->flags |= EP_Distinct;
139483  }
139484}
139485  yymsp[-4].minor.yy190 = yylhsminor.yy190;
139486        break;
139487      case 161: /* expr ::= ID|INDEXED LP STAR RP */
139488{
139489  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
139490  spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
139491}
139492  yymsp[-3].minor.yy190 = yylhsminor.yy190;
139493        break;
139494      case 162: /* term ::= CTIME_KW */
139495{
139496  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
139497  spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
139498}
139499  yymsp[0].minor.yy190 = yylhsminor.yy190;
139500        break;
139501      case 163: /* expr ::= LP nexprlist COMMA expr RP */
139502{
139503  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
139504  yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
139505  if( yylhsminor.yy190.pExpr ){
139506    yylhsminor.yy190.pExpr->x.pList = pList;
139507    spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
139508  }else{
139509    sqlite3ExprListDelete(pParse->db, pList);
139510  }
139511}
139512  yymsp[-4].minor.yy190 = yylhsminor.yy190;
139513        break;
139514      case 164: /* expr ::= expr AND expr */
139515      case 165: /* expr ::= expr OR expr */ yytestcase(yyruleno==165);
139516      case 166: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==166);
139517      case 167: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==167);
139518      case 168: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==168);
139519      case 169: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==169);
139520      case 170: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==170);
139521      case 171: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==171);
139522{spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
139523        break;
139524      case 172: /* likeop ::= NOT LIKE_KW|MATCH */
139525{yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
139526        break;
139527      case 173: /* expr ::= expr likeop expr */
139528{
139529  ExprList *pList;
139530  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
139531  yymsp[-1].minor.yy0.n &= 0x7fffffff;
139532  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
139533  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
139534  yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
139535  exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
139536  yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139537  if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
139538}
139539        break;
139540      case 174: /* expr ::= expr likeop expr ESCAPE expr */
139541{
139542  ExprList *pList;
139543  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
139544  yymsp[-3].minor.yy0.n &= 0x7fffffff;
139545  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
139546  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
139547  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
139548  yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
139549  exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
139550  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139551  if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
139552}
139553        break;
139554      case 175: /* expr ::= expr ISNULL|NOTNULL */
139555{spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
139556        break;
139557      case 176: /* expr ::= expr NOT NULL */
139558{spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
139559        break;
139560      case 177: /* expr ::= expr IS expr */
139561{
139562  spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
139563  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
139564}
139565        break;
139566      case 178: /* expr ::= expr IS NOT expr */
139567{
139568  spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
139569  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
139570}
139571        break;
139572      case 179: /* expr ::= NOT expr */
139573      case 180: /* expr ::= BITNOT expr */ yytestcase(yyruleno==180);
139574{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139575        break;
139576      case 181: /* expr ::= MINUS expr */
139577{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139578        break;
139579      case 182: /* expr ::= PLUS expr */
139580{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
139581        break;
139582      case 183: /* between_op ::= BETWEEN */
139583      case 186: /* in_op ::= IN */ yytestcase(yyruleno==186);
139584{yymsp[0].minor.yy194 = 0;}
139585        break;
139586      case 185: /* expr ::= expr between_op expr AND expr */
139587{
139588  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
139589  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
139590  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0);
139591  if( yymsp[-4].minor.yy190.pExpr ){
139592    yymsp[-4].minor.yy190.pExpr->x.pList = pList;
139593  }else{
139594    sqlite3ExprListDelete(pParse->db, pList);
139595  }
139596  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
139597  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
139598}
139599        break;
139600      case 188: /* expr ::= expr in_op LP exprlist RP */
139601{
139602    if( yymsp[-1].minor.yy148==0 ){
139603      /* Expressions of the form
139604      **
139605      **      expr1 IN ()
139606      **      expr1 NOT IN ()
139607      **
139608      ** simplify to constants 0 (false) and 1 (true), respectively,
139609      ** regardless of the value of expr1.
139610      */
139611      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
139612      yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1);
139613    }else if( yymsp[-1].minor.yy148->nExpr==1 ){
139614      /* Expressions of the form:
139615      **
139616      **      expr1 IN (?1)
139617      **      expr1 NOT IN (?2)
139618      **
139619      ** with exactly one value on the RHS can be simplified to something
139620      ** like this:
139621      **
139622      **      expr1 == ?1
139623      **      expr1 <> ?2
139624      **
139625      ** But, the RHS of the == or <> is marked with the EP_Generic flag
139626      ** so that it may not contribute to the computation of comparison
139627      ** affinity or the collating sequence to use for comparison.  Otherwise,
139628      ** the semantics would be subtly different from IN or NOT IN.
139629      */
139630      Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
139631      yymsp[-1].minor.yy148->a[0].pExpr = 0;
139632      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
139633      /* pRHS cannot be NULL because a malloc error would have been detected
139634      ** before now and control would have never reached this point */
139635      if( ALWAYS(pRHS) ){
139636        pRHS->flags &= ~EP_Collate;
139637        pRHS->flags |= EP_Generic;
139638      }
139639      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS);
139640    }else{
139641      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
139642      if( yymsp[-4].minor.yy190.pExpr ){
139643        yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
139644        sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
139645      }else{
139646        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
139647      }
139648      exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
139649    }
139650    yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
139651  }
139652        break;
139653      case 189: /* expr ::= LP select RP */
139654{
139655    spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
139656    yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
139657    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
139658  }
139659        break;
139660      case 190: /* expr ::= expr in_op LP select RP */
139661{
139662    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
139663    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
139664    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
139665    yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
139666  }
139667        break;
139668      case 191: /* expr ::= expr in_op nm dbnm paren_exprlist */
139669{
139670    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
139671    Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
139672    if( yymsp[0].minor.yy148 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
139673    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
139674    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
139675    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
139676    yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n];
139677  }
139678        break;
139679      case 192: /* expr ::= EXISTS LP select RP */
139680{
139681    Expr *p;
139682    spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
139683    p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
139684    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
139685  }
139686        break;
139687      case 193: /* expr ::= CASE case_operand case_exprlist case_else END */
139688{
139689  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-C*/
139690  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0);
139691  if( yymsp[-4].minor.yy190.pExpr ){
139692    yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148;
139693    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
139694  }else{
139695    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
139696    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
139697  }
139698}
139699        break;
139700      case 194: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
139701{
139702  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
139703  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
139704}
139705        break;
139706      case 195: /* case_exprlist ::= WHEN expr THEN expr */
139707{
139708  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
139709  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
139710}
139711        break;
139712      case 198: /* case_operand ::= expr */
139713{yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
139714        break;
139715      case 201: /* nexprlist ::= nexprlist COMMA expr */
139716{yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
139717        break;
139718      case 202: /* nexprlist ::= expr */
139719{yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
139720        break;
139721      case 204: /* paren_exprlist ::= LP exprlist RP */
139722      case 209: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==209);
139723{yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
139724        break;
139725      case 205: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
139726{
139727  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
139728                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
139729                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
139730}
139731        break;
139732      case 206: /* uniqueflag ::= UNIQUE */
139733      case 246: /* raisetype ::= ABORT */ yytestcase(yyruleno==246);
139734{yymsp[0].minor.yy194 = OE_Abort;}
139735        break;
139736      case 207: /* uniqueflag ::= */
139737{yymsp[1].minor.yy194 = OE_None;}
139738        break;
139739      case 210: /* eidlist ::= eidlist COMMA nm collate sortorder */
139740{
139741  yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
139742}
139743        break;
139744      case 211: /* eidlist ::= nm collate sortorder */
139745{
139746  yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
139747}
139748        break;
139749      case 214: /* cmd ::= DROP INDEX ifexists fullname */
139750{sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
139751        break;
139752      case 215: /* cmd ::= VACUUM */
139753{sqlite3Vacuum(pParse,0);}
139754        break;
139755      case 216: /* cmd ::= VACUUM nm */
139756{sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
139757        break;
139758      case 217: /* cmd ::= PRAGMA nm dbnm */
139759{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
139760        break;
139761      case 218: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
139762{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
139763        break;
139764      case 219: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
139765{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
139766        break;
139767      case 220: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
139768{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
139769        break;
139770      case 221: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
139771{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
139772        break;
139773      case 224: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
139774{
139775  Token all;
139776  all.z = yymsp[-3].minor.yy0.z;
139777  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
139778  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
139779}
139780        break;
139781      case 225: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
139782{
139783  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
139784  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
139785}
139786        break;
139787      case 226: /* trigger_time ::= BEFORE|AFTER */
139788{ yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/ }
139789        break;
139790      case 227: /* trigger_time ::= INSTEAD OF */
139791{ yymsp[-1].minor.yy194 = TK_INSTEAD;}
139792        break;
139793      case 228: /* trigger_time ::= */
139794{ yymsp[1].minor.yy194 = TK_BEFORE; }
139795        break;
139796      case 229: /* trigger_event ::= DELETE|INSERT */
139797      case 230: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==230);
139798{yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
139799        break;
139800      case 231: /* trigger_event ::= UPDATE OF idlist */
139801{yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
139802        break;
139803      case 232: /* when_clause ::= */
139804      case 251: /* key_opt ::= */ yytestcase(yyruleno==251);
139805{ yymsp[1].minor.yy72 = 0; }
139806        break;
139807      case 233: /* when_clause ::= WHEN expr */
139808      case 252: /* key_opt ::= KEY expr */ yytestcase(yyruleno==252);
139809{ yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
139810        break;
139811      case 234: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
139812{
139813  assert( yymsp[-2].minor.yy145!=0 );
139814  yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
139815  yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
139816}
139817        break;
139818      case 235: /* trigger_cmd_list ::= trigger_cmd SEMI */
139819{
139820  assert( yymsp[-1].minor.yy145!=0 );
139821  yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
139822}
139823        break;
139824      case 236: /* trnm ::= nm DOT nm */
139825{
139826  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
139827  sqlite3ErrorMsg(pParse,
139828        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
139829        "statements within triggers");
139830}
139831        break;
139832      case 237: /* tridxby ::= INDEXED BY nm */
139833{
139834  sqlite3ErrorMsg(pParse,
139835        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
139836        "within triggers");
139837}
139838        break;
139839      case 238: /* tridxby ::= NOT INDEXED */
139840{
139841  sqlite3ErrorMsg(pParse,
139842        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
139843        "within triggers");
139844}
139845        break;
139846      case 239: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
139847{yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
139848        break;
139849      case 240: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
139850{yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/}
139851        break;
139852      case 241: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
139853{yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
139854        break;
139855      case 242: /* trigger_cmd ::= select */
139856{yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
139857        break;
139858      case 243: /* expr ::= RAISE LP IGNORE RP */
139859{
139860  spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
139861  yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
139862  if( yymsp[-3].minor.yy190.pExpr ){
139863    yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
139864  }
139865}
139866        break;
139867      case 244: /* expr ::= RAISE LP raisetype COMMA nm RP */
139868{
139869  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
139870  yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
139871  if( yymsp[-5].minor.yy190.pExpr ) {
139872    yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
139873  }
139874}
139875        break;
139876      case 245: /* raisetype ::= ROLLBACK */
139877{yymsp[0].minor.yy194 = OE_Rollback;}
139878        break;
139879      case 247: /* raisetype ::= FAIL */
139880{yymsp[0].minor.yy194 = OE_Fail;}
139881        break;
139882      case 248: /* cmd ::= DROP TRIGGER ifexists fullname */
139883{
139884  sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
139885}
139886        break;
139887      case 249: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
139888{
139889  sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
139890}
139891        break;
139892      case 250: /* cmd ::= DETACH database_kw_opt expr */
139893{
139894  sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
139895}
139896        break;
139897      case 253: /* cmd ::= REINDEX */
139898{sqlite3Reindex(pParse, 0, 0);}
139899        break;
139900      case 254: /* cmd ::= REINDEX nm dbnm */
139901{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
139902        break;
139903      case 255: /* cmd ::= ANALYZE */
139904{sqlite3Analyze(pParse, 0, 0);}
139905        break;
139906      case 256: /* cmd ::= ANALYZE nm dbnm */
139907{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
139908        break;
139909      case 257: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
139910{
139911  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
139912}
139913        break;
139914      case 258: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
139915{
139916  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
139917  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
139918}
139919        break;
139920      case 259: /* add_column_fullname ::= fullname */
139921{
139922  disableLookaside(pParse);
139923  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
139924}
139925        break;
139926      case 260: /* cmd ::= create_vtab */
139927{sqlite3VtabFinishParse(pParse,0);}
139928        break;
139929      case 261: /* cmd ::= create_vtab LP vtabarglist RP */
139930{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
139931        break;
139932      case 262: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
139933{
139934    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
139935}
139936        break;
139937      case 263: /* vtabarg ::= */
139938{sqlite3VtabArgInit(pParse);}
139939        break;
139940      case 264: /* vtabargtoken ::= ANY */
139941      case 265: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==265);
139942      case 266: /* lp ::= LP */ yytestcase(yyruleno==266);
139943{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
139944        break;
139945      case 267: /* with ::= */
139946{yymsp[1].minor.yy285 = 0;}
139947        break;
139948      case 268: /* with ::= WITH wqlist */
139949{ yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
139950        break;
139951      case 269: /* with ::= WITH RECURSIVE wqlist */
139952{ yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
139953        break;
139954      case 270: /* wqlist ::= nm eidlist_opt AS LP select RP */
139955{
139956  yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
139957}
139958        break;
139959      case 271: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
139960{
139961  yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
139962}
139963        break;
139964      default:
139965      /* (272) input ::= cmdlist */ yytestcase(yyruleno==272);
139966      /* (273) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==273);
139967      /* (274) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=274);
139968      /* (275) ecmd ::= SEMI */ yytestcase(yyruleno==275);
139969      /* (276) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==276);
139970      /* (277) explain ::= */ yytestcase(yyruleno==277);
139971      /* (278) trans_opt ::= */ yytestcase(yyruleno==278);
139972      /* (279) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==279);
139973      /* (280) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==280);
139974      /* (281) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==281);
139975      /* (282) savepoint_opt ::= */ yytestcase(yyruleno==282);
139976      /* (283) cmd ::= create_table create_table_args */ yytestcase(yyruleno==283);
139977      /* (284) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==284);
139978      /* (285) columnlist ::= columnname carglist */ yytestcase(yyruleno==285);
139979      /* (286) nm ::= ID|INDEXED */ yytestcase(yyruleno==286);
139980      /* (287) nm ::= STRING */ yytestcase(yyruleno==287);
139981      /* (288) nm ::= JOIN_KW */ yytestcase(yyruleno==288);
139982      /* (289) typetoken ::= typename */ yytestcase(yyruleno==289);
139983      /* (290) typename ::= ID|STRING */ yytestcase(yyruleno==290);
139984      /* (291) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=291);
139985      /* (292) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=292);
139986      /* (293) carglist ::= carglist ccons */ yytestcase(yyruleno==293);
139987      /* (294) carglist ::= */ yytestcase(yyruleno==294);
139988      /* (295) ccons ::= NULL onconf */ yytestcase(yyruleno==295);
139989      /* (296) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==296);
139990      /* (297) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==297);
139991      /* (298) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=298);
139992      /* (299) tconscomma ::= */ yytestcase(yyruleno==299);
139993      /* (300) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=300);
139994      /* (301) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=301);
139995      /* (302) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=302);
139996      /* (303) oneselect ::= values */ yytestcase(yyruleno==303);
139997      /* (304) sclp ::= selcollist COMMA */ yytestcase(yyruleno==304);
139998      /* (305) as ::= ID|STRING */ yytestcase(yyruleno==305);
139999      /* (306) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=306);
140000      /* (307) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==307);
140001      /* (308) exprlist ::= nexprlist */ yytestcase(yyruleno==308);
140002      /* (309) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=309);
140003      /* (310) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=310);
140004      /* (311) nmnum ::= ON */ yytestcase(yyruleno==311);
140005      /* (312) nmnum ::= DELETE */ yytestcase(yyruleno==312);
140006      /* (313) nmnum ::= DEFAULT */ yytestcase(yyruleno==313);
140007      /* (314) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==314);
140008      /* (315) foreach_clause ::= */ yytestcase(yyruleno==315);
140009      /* (316) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==316);
140010      /* (317) trnm ::= nm */ yytestcase(yyruleno==317);
140011      /* (318) tridxby ::= */ yytestcase(yyruleno==318);
140012      /* (319) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==319);
140013      /* (320) database_kw_opt ::= */ yytestcase(yyruleno==320);
140014      /* (321) kwcolumn_opt ::= */ yytestcase(yyruleno==321);
140015      /* (322) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==322);
140016      /* (323) vtabarglist ::= vtabarg */ yytestcase(yyruleno==323);
140017      /* (324) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==324);
140018      /* (325) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==325);
140019      /* (326) anylist ::= */ yytestcase(yyruleno==326);
140020      /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
140021      /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
140022        break;
140023/********** End reduce actions ************************************************/
140024  };
140025  assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
140026  yygoto = yyRuleInfo[yyruleno].lhs;
140027  yysize = yyRuleInfo[yyruleno].nrhs;
140028  yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
140029
140030  /* There are no SHIFTREDUCE actions on nonterminals because the table
140031  ** generator has simplified them to pure REDUCE actions. */
140032  assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
140033
140034  /* It is not possible for a REDUCE to be followed by an error */
140035  assert( yyact!=YY_ERROR_ACTION );
140036
140037  if( yyact==YY_ACCEPT_ACTION ){
140038    yypParser->yytos += yysize;
140039    yy_accept(yypParser);
140040  }else{
140041    yymsp += yysize+1;
140042    yypParser->yytos = yymsp;
140043    yymsp->stateno = (YYACTIONTYPE)yyact;
140044    yymsp->major = (YYCODETYPE)yygoto;
140045    yyTraceShift(yypParser, yyact);
140046  }
140047}
140048
140049/*
140050** The following code executes when the parse fails
140051*/
140052#ifndef YYNOERRORRECOVERY
140053static void yy_parse_failed(
140054  yyParser *yypParser           /* The parser */
140055){
140056  sqlite3ParserARG_FETCH;
140057#ifndef NDEBUG
140058  if( yyTraceFILE ){
140059    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
140060  }
140061#endif
140062  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
140063  /* Here code is inserted which will be executed whenever the
140064  ** parser fails */
140065/************ Begin %parse_failure code ***************************************/
140066/************ End %parse_failure code *****************************************/
140067  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140068}
140069#endif /* YYNOERRORRECOVERY */
140070
140071/*
140072** The following code executes when a syntax error first occurs.
140073*/
140074static void yy_syntax_error(
140075  yyParser *yypParser,           /* The parser */
140076  int yymajor,                   /* The major type of the error token */
140077  sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
140078){
140079  sqlite3ParserARG_FETCH;
140080#define TOKEN yyminor
140081/************ Begin %syntax_error code ****************************************/
140082
140083  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
140084  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
140085  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
140086/************ End %syntax_error code ******************************************/
140087  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140088}
140089
140090/*
140091** The following is executed when the parser accepts
140092*/
140093static void yy_accept(
140094  yyParser *yypParser           /* The parser */
140095){
140096  sqlite3ParserARG_FETCH;
140097#ifndef NDEBUG
140098  if( yyTraceFILE ){
140099    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
140100  }
140101#endif
140102#ifndef YYNOERRORRECOVERY
140103  yypParser->yyerrcnt = -1;
140104#endif
140105  assert( yypParser->yytos==yypParser->yystack );
140106  /* Here code is inserted which will be executed whenever the
140107  ** parser accepts */
140108/*********** Begin %parse_accept code *****************************************/
140109/*********** End %parse_accept code *******************************************/
140110  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
140111}
140112
140113/* The main parser program.
140114** The first argument is a pointer to a structure obtained from
140115** "sqlite3ParserAlloc" which describes the current state of the parser.
140116** The second argument is the major token number.  The third is
140117** the minor token.  The fourth optional argument is whatever the
140118** user wants (and specified in the grammar) and is available for
140119** use by the action routines.
140120**
140121** Inputs:
140122** <ul>
140123** <li> A pointer to the parser (an opaque structure.)
140124** <li> The major token number.
140125** <li> The minor token number.
140126** <li> An option argument of a grammar-specified type.
140127** </ul>
140128**
140129** Outputs:
140130** None.
140131*/
140132SQLITE_PRIVATE void sqlite3Parser(
140133  void *yyp,                   /* The parser */
140134  int yymajor,                 /* The major token code number */
140135  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
140136  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
140137){
140138  YYMINORTYPE yyminorunion;
140139  unsigned int yyact;   /* The parser action. */
140140#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
140141  int yyendofinput;     /* True if we are at the end of input */
140142#endif
140143#ifdef YYERRORSYMBOL
140144  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
140145#endif
140146  yyParser *yypParser;  /* The parser */
140147
140148  yypParser = (yyParser*)yyp;
140149  assert( yypParser->yytos!=0 );
140150#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
140151  yyendofinput = (yymajor==0);
140152#endif
140153  sqlite3ParserARG_STORE;
140154
140155#ifndef NDEBUG
140156  if( yyTraceFILE ){
140157    fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
140158  }
140159#endif
140160
140161  do{
140162    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
140163    if( yyact <= YY_MAX_SHIFTREDUCE ){
140164      yy_shift(yypParser,yyact,yymajor,yyminor);
140165#ifndef YYNOERRORRECOVERY
140166      yypParser->yyerrcnt--;
140167#endif
140168      yymajor = YYNOCODE;
140169    }else if( yyact <= YY_MAX_REDUCE ){
140170      yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
140171    }else{
140172      assert( yyact == YY_ERROR_ACTION );
140173      yyminorunion.yy0 = yyminor;
140174#ifdef YYERRORSYMBOL
140175      int yymx;
140176#endif
140177#ifndef NDEBUG
140178      if( yyTraceFILE ){
140179        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
140180      }
140181#endif
140182#ifdef YYERRORSYMBOL
140183      /* A syntax error has occurred.
140184      ** The response to an error depends upon whether or not the
140185      ** grammar defines an error token "ERROR".
140186      **
140187      ** This is what we do if the grammar does define ERROR:
140188      **
140189      **  * Call the %syntax_error function.
140190      **
140191      **  * Begin popping the stack until we enter a state where
140192      **    it is legal to shift the error symbol, then shift
140193      **    the error symbol.
140194      **
140195      **  * Set the error count to three.
140196      **
140197      **  * Begin accepting and shifting new tokens.  No new error
140198      **    processing will occur until three tokens have been
140199      **    shifted successfully.
140200      **
140201      */
140202      if( yypParser->yyerrcnt<0 ){
140203        yy_syntax_error(yypParser,yymajor,yyminor);
140204      }
140205      yymx = yypParser->yytos->major;
140206      if( yymx==YYERRORSYMBOL || yyerrorhit ){
140207#ifndef NDEBUG
140208        if( yyTraceFILE ){
140209          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
140210             yyTracePrompt,yyTokenName[yymajor]);
140211        }
140212#endif
140213        yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
140214        yymajor = YYNOCODE;
140215      }else{
140216        while( yypParser->yytos >= yypParser->yystack
140217            && yymx != YYERRORSYMBOL
140218            && (yyact = yy_find_reduce_action(
140219                        yypParser->yytos->stateno,
140220                        YYERRORSYMBOL)) >= YY_MIN_REDUCE
140221        ){
140222          yy_pop_parser_stack(yypParser);
140223        }
140224        if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
140225          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140226          yy_parse_failed(yypParser);
140227#ifndef YYNOERRORRECOVERY
140228          yypParser->yyerrcnt = -1;
140229#endif
140230          yymajor = YYNOCODE;
140231        }else if( yymx!=YYERRORSYMBOL ){
140232          yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
140233        }
140234      }
140235      yypParser->yyerrcnt = 3;
140236      yyerrorhit = 1;
140237#elif defined(YYNOERRORRECOVERY)
140238      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
140239      ** do any kind of error recovery.  Instead, simply invoke the syntax
140240      ** error routine and continue going as if nothing had happened.
140241      **
140242      ** Applications can set this macro (for example inside %include) if
140243      ** they intend to abandon the parse upon the first syntax error seen.
140244      */
140245      yy_syntax_error(yypParser,yymajor, yyminor);
140246      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140247      yymajor = YYNOCODE;
140248
140249#else  /* YYERRORSYMBOL is not defined */
140250      /* This is what we do if the grammar does not define ERROR:
140251      **
140252      **  * Report an error message, and throw away the input token.
140253      **
140254      **  * If the input token is $, then fail the parse.
140255      **
140256      ** As before, subsequent error messages are suppressed until
140257      ** three input tokens have been successfully shifted.
140258      */
140259      if( yypParser->yyerrcnt<=0 ){
140260        yy_syntax_error(yypParser,yymajor, yyminor);
140261      }
140262      yypParser->yyerrcnt = 3;
140263      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
140264      if( yyendofinput ){
140265        yy_parse_failed(yypParser);
140266#ifndef YYNOERRORRECOVERY
140267        yypParser->yyerrcnt = -1;
140268#endif
140269      }
140270      yymajor = YYNOCODE;
140271#endif
140272    }
140273  }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
140274#ifndef NDEBUG
140275  if( yyTraceFILE ){
140276    yyStackEntry *i;
140277    char cDiv = '[';
140278    fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
140279    for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
140280      fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
140281      cDiv = ' ';
140282    }
140283    fprintf(yyTraceFILE,"]\n");
140284  }
140285#endif
140286  return;
140287}
140288
140289/************** End of parse.c ***********************************************/
140290/************** Begin file tokenize.c ****************************************/
140291/*
140292** 2001 September 15
140293**
140294** The author disclaims copyright to this source code.  In place of
140295** a legal notice, here is a blessing:
140296**
140297**    May you do good and not evil.
140298**    May you find forgiveness for yourself and forgive others.
140299**    May you share freely, never taking more than you give.
140300**
140301*************************************************************************
140302** An tokenizer for SQL
140303**
140304** This file contains C code that splits an SQL input string up into
140305** individual tokens and sends those tokens one-by-one over to the
140306** parser for analysis.
140307*/
140308/* #include "sqliteInt.h" */
140309/* #include <stdlib.h> */
140310
140311/* Character classes for tokenizing
140312**
140313** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
140314** using a lookup table, whereas a switch() directly on c uses a binary search.
140315** The lookup table is much faster.  To maximize speed, and to ensure that
140316** a lookup table is used, all of the classes need to be small integers and
140317** all of them need to be used within the switch.
140318*/
140319#define CC_X          0    /* The letter 'x', or start of BLOB literal */
140320#define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */
140321#define CC_ID         2    /* unicode characters usable in IDs */
140322#define CC_DIGIT      3    /* Digits */
140323#define CC_DOLLAR     4    /* '$' */
140324#define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
140325#define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
140326#define CC_SPACE      7    /* Space characters */
140327#define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
140328#define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
140329#define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
140330#define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
140331#define CC_LT        12    /* '<'.  Part of < or <= or <> */
140332#define CC_GT        13    /* '>'.  Part of > or >= */
140333#define CC_EQ        14    /* '='.  Part of = or == */
140334#define CC_BANG      15    /* '!'.  Part of != */
140335#define CC_SLASH     16    /* '/'.  / or c-style comment */
140336#define CC_LP        17    /* '(' */
140337#define CC_RP        18    /* ')' */
140338#define CC_SEMI      19    /* ';' */
140339#define CC_PLUS      20    /* '+' */
140340#define CC_STAR      21    /* '*' */
140341#define CC_PERCENT   22    /* '%' */
140342#define CC_COMMA     23    /* ',' */
140343#define CC_AND       24    /* '&' */
140344#define CC_TILDA     25    /* '~' */
140345#define CC_DOT       26    /* '.' */
140346#define CC_ILLEGAL   27    /* Illegal character */
140347
140348static const unsigned char aiClass[] = {
140349#ifdef SQLITE_ASCII
140350/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
140351/* 0x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,
140352/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140353/* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
140354/* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
140355/* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
140356/* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,
140357/* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
140358/* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,
140359/* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140360/* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140361/* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140362/* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140363/* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140364/* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140365/* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
140366/* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
140367#endif
140368#ifdef SQLITE_EBCDIC
140369/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
140370/* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,
140371/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140372/* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140373/* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
140374/* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
140375/* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,
140376/* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  6,
140377/* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,
140378/* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
140379/* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
140380/* Ax */   27, 25,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
140381/* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,
140382/* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
140383/* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
140384/* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
140385/* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,
140386#endif
140387};
140388
140389/*
140390** The charMap() macro maps alphabetic characters (only) into their
140391** lower-case ASCII equivalent.  On ASCII machines, this is just
140392** an upper-to-lower case map.  On EBCDIC machines we also need
140393** to adjust the encoding.  The mapping is only valid for alphabetics
140394** which are the only characters for which this feature is used.
140395**
140396** Used by keywordhash.h
140397*/
140398#ifdef SQLITE_ASCII
140399# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
140400#endif
140401#ifdef SQLITE_EBCDIC
140402# define charMap(X) ebcdicToAscii[(unsigned char)X]
140403const unsigned char ebcdicToAscii[] = {
140404/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
140405   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
140406   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
140407   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
140408   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
140409   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
140410   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
140411   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
140412   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
140413   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
140414   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
140415   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
140416   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
140417   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
140418   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
140419   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
140420   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
140421};
140422#endif
140423
140424/*
140425** The sqlite3KeywordCode function looks up an identifier to determine if
140426** it is a keyword.  If it is a keyword, the token code of that keyword is
140427** returned.  If the input is not a keyword, TK_ID is returned.
140428**
140429** The implementation of this routine was generated by a program,
140430** mkkeywordhash.c, located in the tool subdirectory of the distribution.
140431** The output of the mkkeywordhash.c program is written into a file
140432** named keywordhash.h and then included into this source file by
140433** the #include below.
140434*/
140435/************** Include keywordhash.h in the middle of tokenize.c ************/
140436/************** Begin file keywordhash.h *************************************/
140437/***** This file contains automatically generated code ******
140438**
140439** The code in this file has been automatically generated by
140440**
140441**   sqlite/tool/mkkeywordhash.c
140442**
140443** The code in this file implements a function that determines whether
140444** or not a given identifier is really an SQL keyword.  The same thing
140445** might be implemented more directly using a hand-written hash table.
140446** But by using this automatically generated code, the size of the code
140447** is substantially reduced.  This is important for embedded applications
140448** on platforms with limited memory.
140449*/
140450/* Hash score: 182 */
140451/* zKWText[] encodes 834 bytes of keyword text in 554 bytes */
140452/*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
140453/*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
140454/*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
140455/*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
140456/*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
140457/*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
140458/*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
140459/*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
140460/*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
140461/*   VACUUMVIEWINITIALLY                                                */
140462static const char zKWText[553] = {
140463  'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
140464  'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
140465  'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
140466  'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
140467  'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
140468  'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
140469  'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
140470  'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
140471  'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
140472  'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
140473  'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
140474  'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
140475  'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
140476  'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
140477  'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
140478  'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
140479  'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
140480  'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
140481  'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
140482  'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
140483  'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
140484  'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
140485  'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
140486  'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
140487  'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
140488  'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
140489  'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
140490  'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
140491  'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
140492  'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
140493  'V','I','E','W','I','N','I','T','I','A','L','L','Y',
140494};
140495/* aKWHash[i] is the hash value for the i-th keyword */
140496static const unsigned char aKWHash[127] = {
140497    76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
140498    42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
140499   121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
140500     0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
140501     0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
140502    96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
140503   100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
140504    39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
140505    62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
140506    29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
140507};
140508/* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0
140509** then the i-th keyword has no more hash collisions.  Otherwise,
140510** the next keyword with the same hash is aKWHash[i]-1. */
140511static const unsigned char aKWNext[124] = {
140512     0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
140513     0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
140514     0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
140515     0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
140516     0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
140517     0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
140518     0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
140519    10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
140520     0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
140521    73,  83,   0,  35,  68,   0,   0,
140522};
140523/* aKWLen[i] is the length (in bytes) of the i-th keyword */
140524static const unsigned char aKWLen[124] = {
140525     7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
140526     7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
140527    11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
140528     4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
140529     6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
140530     7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
140531     7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
140532    13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
140533     2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
140534     3,   5,   5,   6,   4,   9,   3,
140535};
140536/* aKWOffset[i] is the index into zKWText[] of the start of
140537** the text for the i-th keyword. */
140538static const unsigned short int aKWOffset[124] = {
140539     0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
140540    36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
140541    86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
140542   159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
140543   199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
140544   250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
140545   320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
140546   387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
140547   460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
140548   521, 524, 529, 534, 540, 544, 549,
140549};
140550/* aKWCode[i] is the parser symbol code for the i-th keyword */
140551static const unsigned char aKWCode[124] = {
140552  TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
140553  TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
140554  TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
140555  TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
140556  TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
140557  TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
140558  TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
140559  TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
140560  TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
140561  TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
140562  TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
140563  TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
140564  TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
140565  TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
140566  TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
140567  TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
140568  TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
140569  TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
140570  TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
140571  TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
140572  TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
140573  TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
140574  TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
140575  TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
140576  TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
140577};
140578/* Check to see if z[0..n-1] is a keyword. If it is, write the
140579** parser symbol code for that keyword into *pType.  Always
140580** return the integer n (the length of the token). */
140581static int keywordCode(const char *z, int n, int *pType){
140582  int i, j;
140583  const char *zKW;
140584  if( n>=2 ){
140585    i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
140586    for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
140587      if( aKWLen[i]!=n ) continue;
140588      j = 0;
140589      zKW = &zKWText[aKWOffset[i]];
140590#ifdef SQLITE_ASCII
140591      while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
140592#endif
140593#ifdef SQLITE_EBCDIC
140594      while( j<n && toupper(z[j])==zKW[j] ){ j++; }
140595#endif
140596      if( j<n ) continue;
140597      testcase( i==0 ); /* REINDEX */
140598      testcase( i==1 ); /* INDEXED */
140599      testcase( i==2 ); /* INDEX */
140600      testcase( i==3 ); /* DESC */
140601      testcase( i==4 ); /* ESCAPE */
140602      testcase( i==5 ); /* EACH */
140603      testcase( i==6 ); /* CHECK */
140604      testcase( i==7 ); /* KEY */
140605      testcase( i==8 ); /* BEFORE */
140606      testcase( i==9 ); /* FOREIGN */
140607      testcase( i==10 ); /* FOR */
140608      testcase( i==11 ); /* IGNORE */
140609      testcase( i==12 ); /* REGEXP */
140610      testcase( i==13 ); /* EXPLAIN */
140611      testcase( i==14 ); /* INSTEAD */
140612      testcase( i==15 ); /* ADD */
140613      testcase( i==16 ); /* DATABASE */
140614      testcase( i==17 ); /* AS */
140615      testcase( i==18 ); /* SELECT */
140616      testcase( i==19 ); /* TABLE */
140617      testcase( i==20 ); /* LEFT */
140618      testcase( i==21 ); /* THEN */
140619      testcase( i==22 ); /* END */
140620      testcase( i==23 ); /* DEFERRABLE */
140621      testcase( i==24 ); /* ELSE */
140622      testcase( i==25 ); /* EXCEPT */
140623      testcase( i==26 ); /* TRANSACTION */
140624      testcase( i==27 ); /* ACTION */
140625      testcase( i==28 ); /* ON */
140626      testcase( i==29 ); /* NATURAL */
140627      testcase( i==30 ); /* ALTER */
140628      testcase( i==31 ); /* RAISE */
140629      testcase( i==32 ); /* EXCLUSIVE */
140630      testcase( i==33 ); /* EXISTS */
140631      testcase( i==34 ); /* SAVEPOINT */
140632      testcase( i==35 ); /* INTERSECT */
140633      testcase( i==36 ); /* TRIGGER */
140634      testcase( i==37 ); /* REFERENCES */
140635      testcase( i==38 ); /* CONSTRAINT */
140636      testcase( i==39 ); /* INTO */
140637      testcase( i==40 ); /* OFFSET */
140638      testcase( i==41 ); /* OF */
140639      testcase( i==42 ); /* SET */
140640      testcase( i==43 ); /* TEMPORARY */
140641      testcase( i==44 ); /* TEMP */
140642      testcase( i==45 ); /* OR */
140643      testcase( i==46 ); /* UNIQUE */
140644      testcase( i==47 ); /* QUERY */
140645      testcase( i==48 ); /* WITHOUT */
140646      testcase( i==49 ); /* WITH */
140647      testcase( i==50 ); /* OUTER */
140648      testcase( i==51 ); /* RELEASE */
140649      testcase( i==52 ); /* ATTACH */
140650      testcase( i==53 ); /* HAVING */
140651      testcase( i==54 ); /* GROUP */
140652      testcase( i==55 ); /* UPDATE */
140653      testcase( i==56 ); /* BEGIN */
140654      testcase( i==57 ); /* INNER */
140655      testcase( i==58 ); /* RECURSIVE */
140656      testcase( i==59 ); /* BETWEEN */
140657      testcase( i==60 ); /* NOTNULL */
140658      testcase( i==61 ); /* NOT */
140659      testcase( i==62 ); /* NO */
140660      testcase( i==63 ); /* NULL */
140661      testcase( i==64 ); /* LIKE */
140662      testcase( i==65 ); /* CASCADE */
140663      testcase( i==66 ); /* ASC */
140664      testcase( i==67 ); /* DELETE */
140665      testcase( i==68 ); /* CASE */
140666      testcase( i==69 ); /* COLLATE */
140667      testcase( i==70 ); /* CREATE */
140668      testcase( i==71 ); /* CURRENT_DATE */
140669      testcase( i==72 ); /* DETACH */
140670      testcase( i==73 ); /* IMMEDIATE */
140671      testcase( i==74 ); /* JOIN */
140672      testcase( i==75 ); /* INSERT */
140673      testcase( i==76 ); /* MATCH */
140674      testcase( i==77 ); /* PLAN */
140675      testcase( i==78 ); /* ANALYZE */
140676      testcase( i==79 ); /* PRAGMA */
140677      testcase( i==80 ); /* ABORT */
140678      testcase( i==81 ); /* VALUES */
140679      testcase( i==82 ); /* VIRTUAL */
140680      testcase( i==83 ); /* LIMIT */
140681      testcase( i==84 ); /* WHEN */
140682      testcase( i==85 ); /* WHERE */
140683      testcase( i==86 ); /* RENAME */
140684      testcase( i==87 ); /* AFTER */
140685      testcase( i==88 ); /* REPLACE */
140686      testcase( i==89 ); /* AND */
140687      testcase( i==90 ); /* DEFAULT */
140688      testcase( i==91 ); /* AUTOINCREMENT */
140689      testcase( i==92 ); /* TO */
140690      testcase( i==93 ); /* IN */
140691      testcase( i==94 ); /* CAST */
140692      testcase( i==95 ); /* COLUMN */
140693      testcase( i==96 ); /* COMMIT */
140694      testcase( i==97 ); /* CONFLICT */
140695      testcase( i==98 ); /* CROSS */
140696      testcase( i==99 ); /* CURRENT_TIMESTAMP */
140697      testcase( i==100 ); /* CURRENT_TIME */
140698      testcase( i==101 ); /* PRIMARY */
140699      testcase( i==102 ); /* DEFERRED */
140700      testcase( i==103 ); /* DISTINCT */
140701      testcase( i==104 ); /* IS */
140702      testcase( i==105 ); /* DROP */
140703      testcase( i==106 ); /* FAIL */
140704      testcase( i==107 ); /* FROM */
140705      testcase( i==108 ); /* FULL */
140706      testcase( i==109 ); /* GLOB */
140707      testcase( i==110 ); /* BY */
140708      testcase( i==111 ); /* IF */
140709      testcase( i==112 ); /* ISNULL */
140710      testcase( i==113 ); /* ORDER */
140711      testcase( i==114 ); /* RESTRICT */
140712      testcase( i==115 ); /* RIGHT */
140713      testcase( i==116 ); /* ROLLBACK */
140714      testcase( i==117 ); /* ROW */
140715      testcase( i==118 ); /* UNION */
140716      testcase( i==119 ); /* USING */
140717      testcase( i==120 ); /* VACUUM */
140718      testcase( i==121 ); /* VIEW */
140719      testcase( i==122 ); /* INITIALLY */
140720      testcase( i==123 ); /* ALL */
140721      *pType = aKWCode[i];
140722      break;
140723    }
140724  }
140725  return n;
140726}
140727SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
140728  int id = TK_ID;
140729  keywordCode((char*)z, n, &id);
140730  return id;
140731}
140732#define SQLITE_N_KEYWORD 124
140733
140734/************** End of keywordhash.h *****************************************/
140735/************** Continuing where we left off in tokenize.c *******************/
140736
140737
140738/*
140739** If X is a character that can be used in an identifier then
140740** IdChar(X) will be true.  Otherwise it is false.
140741**
140742** For ASCII, any character with the high-order bit set is
140743** allowed in an identifier.  For 7-bit characters,
140744** sqlite3IsIdChar[X] must be 1.
140745**
140746** For EBCDIC, the rules are more complex but have the same
140747** end result.
140748**
140749** Ticket #1066.  the SQL standard does not allow '$' in the
140750** middle of identifiers.  But many SQL implementations do.
140751** SQLite will allow '$' in identifiers for compatibility.
140752** But the feature is undocumented.
140753*/
140754#ifdef SQLITE_ASCII
140755#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
140756#endif
140757#ifdef SQLITE_EBCDIC
140758SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
140759/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
140760    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
140761    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
140762    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
140763    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
140764    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
140765    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
140766    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
140767    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
140768    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
140769    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
140770    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
140771    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
140772};
140773#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
140774#endif
140775
140776/* Make the IdChar function accessible from ctime.c */
140777#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
140778SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
140779#endif
140780
140781
140782/*
140783** Return the length (in bytes) of the token that begins at z[0].
140784** Store the token type in *tokenType before returning.
140785*/
140786SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
140787  int i, c;
140788  switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
140789                          ** of the token. See the comment on the CC_ defines
140790                          ** above. */
140791    case CC_SPACE: {
140792      testcase( z[0]==' ' );
140793      testcase( z[0]=='\t' );
140794      testcase( z[0]=='\n' );
140795      testcase( z[0]=='\f' );
140796      testcase( z[0]=='\r' );
140797      for(i=1; sqlite3Isspace(z[i]); i++){}
140798      *tokenType = TK_SPACE;
140799      return i;
140800    }
140801    case CC_MINUS: {
140802      if( z[1]=='-' ){
140803        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
140804        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
140805        return i;
140806      }
140807      *tokenType = TK_MINUS;
140808      return 1;
140809    }
140810    case CC_LP: {
140811      *tokenType = TK_LP;
140812      return 1;
140813    }
140814    case CC_RP: {
140815      *tokenType = TK_RP;
140816      return 1;
140817    }
140818    case CC_SEMI: {
140819      *tokenType = TK_SEMI;
140820      return 1;
140821    }
140822    case CC_PLUS: {
140823      *tokenType = TK_PLUS;
140824      return 1;
140825    }
140826    case CC_STAR: {
140827      *tokenType = TK_STAR;
140828      return 1;
140829    }
140830    case CC_SLASH: {
140831      if( z[1]!='*' || z[2]==0 ){
140832        *tokenType = TK_SLASH;
140833        return 1;
140834      }
140835      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
140836      if( c ) i++;
140837      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
140838      return i;
140839    }
140840    case CC_PERCENT: {
140841      *tokenType = TK_REM;
140842      return 1;
140843    }
140844    case CC_EQ: {
140845      *tokenType = TK_EQ;
140846      return 1 + (z[1]=='=');
140847    }
140848    case CC_LT: {
140849      if( (c=z[1])=='=' ){
140850        *tokenType = TK_LE;
140851        return 2;
140852      }else if( c=='>' ){
140853        *tokenType = TK_NE;
140854        return 2;
140855      }else if( c=='<' ){
140856        *tokenType = TK_LSHIFT;
140857        return 2;
140858      }else{
140859        *tokenType = TK_LT;
140860        return 1;
140861      }
140862    }
140863    case CC_GT: {
140864      if( (c=z[1])=='=' ){
140865        *tokenType = TK_GE;
140866        return 2;
140867      }else if( c=='>' ){
140868        *tokenType = TK_RSHIFT;
140869        return 2;
140870      }else{
140871        *tokenType = TK_GT;
140872        return 1;
140873      }
140874    }
140875    case CC_BANG: {
140876      if( z[1]!='=' ){
140877        *tokenType = TK_ILLEGAL;
140878        return 1;
140879      }else{
140880        *tokenType = TK_NE;
140881        return 2;
140882      }
140883    }
140884    case CC_PIPE: {
140885      if( z[1]!='|' ){
140886        *tokenType = TK_BITOR;
140887        return 1;
140888      }else{
140889        *tokenType = TK_CONCAT;
140890        return 2;
140891      }
140892    }
140893    case CC_COMMA: {
140894      *tokenType = TK_COMMA;
140895      return 1;
140896    }
140897    case CC_AND: {
140898      *tokenType = TK_BITAND;
140899      return 1;
140900    }
140901    case CC_TILDA: {
140902      *tokenType = TK_BITNOT;
140903      return 1;
140904    }
140905    case CC_QUOTE: {
140906      int delim = z[0];
140907      testcase( delim=='`' );
140908      testcase( delim=='\'' );
140909      testcase( delim=='"' );
140910      for(i=1; (c=z[i])!=0; i++){
140911        if( c==delim ){
140912          if( z[i+1]==delim ){
140913            i++;
140914          }else{
140915            break;
140916          }
140917        }
140918      }
140919      if( c=='\'' ){
140920        *tokenType = TK_STRING;
140921        return i+1;
140922      }else if( c!=0 ){
140923        *tokenType = TK_ID;
140924        return i+1;
140925      }else{
140926        *tokenType = TK_ILLEGAL;
140927        return i;
140928      }
140929    }
140930    case CC_DOT: {
140931#ifndef SQLITE_OMIT_FLOATING_POINT
140932      if( !sqlite3Isdigit(z[1]) )
140933#endif
140934      {
140935        *tokenType = TK_DOT;
140936        return 1;
140937      }
140938      /* If the next character is a digit, this is a floating point
140939      ** number that begins with ".".  Fall thru into the next case */
140940    }
140941    case CC_DIGIT: {
140942      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
140943      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
140944      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
140945      testcase( z[0]=='9' );
140946      *tokenType = TK_INTEGER;
140947#ifndef SQLITE_OMIT_HEX_INTEGER
140948      if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
140949        for(i=3; sqlite3Isxdigit(z[i]); i++){}
140950        return i;
140951      }
140952#endif
140953      for(i=0; sqlite3Isdigit(z[i]); i++){}
140954#ifndef SQLITE_OMIT_FLOATING_POINT
140955      if( z[i]=='.' ){
140956        i++;
140957        while( sqlite3Isdigit(z[i]) ){ i++; }
140958        *tokenType = TK_FLOAT;
140959      }
140960      if( (z[i]=='e' || z[i]=='E') &&
140961           ( sqlite3Isdigit(z[i+1])
140962            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
140963           )
140964      ){
140965        i += 2;
140966        while( sqlite3Isdigit(z[i]) ){ i++; }
140967        *tokenType = TK_FLOAT;
140968      }
140969#endif
140970      while( IdChar(z[i]) ){
140971        *tokenType = TK_ILLEGAL;
140972        i++;
140973      }
140974      return i;
140975    }
140976    case CC_QUOTE2: {
140977      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
140978      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
140979      return i;
140980    }
140981    case CC_VARNUM: {
140982      *tokenType = TK_VARIABLE;
140983      for(i=1; sqlite3Isdigit(z[i]); i++){}
140984      return i;
140985    }
140986    case CC_DOLLAR:
140987    case CC_VARALPHA: {
140988      int n = 0;
140989      testcase( z[0]=='$' );  testcase( z[0]=='@' );
140990      testcase( z[0]==':' );  testcase( z[0]=='#' );
140991      *tokenType = TK_VARIABLE;
140992      for(i=1; (c=z[i])!=0; i++){
140993        if( IdChar(c) ){
140994          n++;
140995#ifndef SQLITE_OMIT_TCL_VARIABLE
140996        }else if( c=='(' && n>0 ){
140997          do{
140998            i++;
140999          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
141000          if( c==')' ){
141001            i++;
141002          }else{
141003            *tokenType = TK_ILLEGAL;
141004          }
141005          break;
141006        }else if( c==':' && z[i+1]==':' ){
141007          i++;
141008#endif
141009        }else{
141010          break;
141011        }
141012      }
141013      if( n==0 ) *tokenType = TK_ILLEGAL;
141014      return i;
141015    }
141016    case CC_KYWD: {
141017      for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
141018      if( IdChar(z[i]) ){
141019        /* This token started out using characters that can appear in keywords,
141020        ** but z[i] is a character not allowed within keywords, so this must
141021        ** be an identifier instead */
141022        i++;
141023        break;
141024      }
141025      *tokenType = TK_ID;
141026      return keywordCode((char*)z, i, tokenType);
141027    }
141028    case CC_X: {
141029#ifndef SQLITE_OMIT_BLOB_LITERAL
141030      testcase( z[0]=='x' ); testcase( z[0]=='X' );
141031      if( z[1]=='\'' ){
141032        *tokenType = TK_BLOB;
141033        for(i=2; sqlite3Isxdigit(z[i]); i++){}
141034        if( z[i]!='\'' || i%2 ){
141035          *tokenType = TK_ILLEGAL;
141036          while( z[i] && z[i]!='\'' ){ i++; }
141037        }
141038        if( z[i] ) i++;
141039        return i;
141040      }
141041#endif
141042      /* If it is not a BLOB literal, then it must be an ID, since no
141043      ** SQL keywords start with the letter 'x'.  Fall through */
141044    }
141045    case CC_ID: {
141046      i = 1;
141047      break;
141048    }
141049    default: {
141050      *tokenType = TK_ILLEGAL;
141051      return 1;
141052    }
141053  }
141054  while( IdChar(z[i]) ){ i++; }
141055  *tokenType = TK_ID;
141056  return i;
141057}
141058
141059/*
141060** Run the parser on the given SQL string.  The parser structure is
141061** passed in.  An SQLITE_ status code is returned.  If an error occurs
141062** then an and attempt is made to write an error message into
141063** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
141064** error message.
141065*/
141066SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
141067  int nErr = 0;                   /* Number of errors encountered */
141068  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
141069  int n = 0;                      /* Length of the next token token */
141070  int tokenType;                  /* type of the next token */
141071  int lastTokenParsed = -1;       /* type of the previous token */
141072  sqlite3 *db = pParse->db;       /* The database connection */
141073  int mxSqlLen;                   /* Max length of an SQL string */
141074#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141075  yyParser sEngine;    /* Space to hold the Lemon-generated Parser object */
141076#endif
141077
141078  assert( zSql!=0 );
141079  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
141080  if( db->nVdbeActive==0 ){
141081    db->u1.isInterrupted = 0;
141082  }
141083  pParse->rc = SQLITE_OK;
141084  pParse->zTail = zSql;
141085  assert( pzErrMsg!=0 );
141086  /* sqlite3ParserTrace(stdout, "parser: "); */
141087#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141088  pEngine = &sEngine;
141089  sqlite3ParserInit(pEngine);
141090#else
141091  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
141092  if( pEngine==0 ){
141093    sqlite3OomFault(db);
141094    return SQLITE_NOMEM_BKPT;
141095  }
141096#endif
141097  assert( pParse->pNewTable==0 );
141098  assert( pParse->pNewTrigger==0 );
141099  assert( pParse->nVar==0 );
141100  assert( pParse->pVList==0 );
141101  while( 1 ){
141102    if( zSql[0]!=0 ){
141103      n = sqlite3GetToken((u8*)zSql, &tokenType);
141104      mxSqlLen -= n;
141105      if( mxSqlLen<0 ){
141106        pParse->rc = SQLITE_TOOBIG;
141107        break;
141108      }
141109    }else{
141110      /* Upon reaching the end of input, call the parser two more times
141111      ** with tokens TK_SEMI and 0, in that order. */
141112      if( lastTokenParsed==TK_SEMI ){
141113        tokenType = 0;
141114      }else if( lastTokenParsed==0 ){
141115        break;
141116      }else{
141117        tokenType = TK_SEMI;
141118      }
141119      zSql -= n;
141120    }
141121    if( tokenType>=TK_SPACE ){
141122      assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
141123      if( db->u1.isInterrupted ){
141124        pParse->rc = SQLITE_INTERRUPT;
141125        break;
141126      }
141127      if( tokenType==TK_ILLEGAL ){
141128        sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
141129        break;
141130      }
141131      zSql += n;
141132    }else{
141133      pParse->sLastToken.z = zSql;
141134      pParse->sLastToken.n = n;
141135      sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
141136      lastTokenParsed = tokenType;
141137      zSql += n;
141138      if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
141139    }
141140  }
141141  assert( nErr==0 );
141142  pParse->zTail = zSql;
141143#ifdef YYTRACKMAXSTACKDEPTH
141144  sqlite3_mutex_enter(sqlite3MallocMutex());
141145  sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
141146      sqlite3ParserStackPeak(pEngine)
141147  );
141148  sqlite3_mutex_leave(sqlite3MallocMutex());
141149#endif /* YYDEBUG */
141150#ifdef sqlite3Parser_ENGINEALWAYSONSTACK
141151  sqlite3ParserFinalize(pEngine);
141152#else
141153  sqlite3ParserFree(pEngine, sqlite3_free);
141154#endif
141155  if( db->mallocFailed ){
141156    pParse->rc = SQLITE_NOMEM_BKPT;
141157  }
141158  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
141159    pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
141160  }
141161  assert( pzErrMsg!=0 );
141162  if( pParse->zErrMsg ){
141163    *pzErrMsg = pParse->zErrMsg;
141164    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
141165    pParse->zErrMsg = 0;
141166    nErr++;
141167  }
141168  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
141169    sqlite3VdbeDelete(pParse->pVdbe);
141170    pParse->pVdbe = 0;
141171  }
141172#ifndef SQLITE_OMIT_SHARED_CACHE
141173  if( pParse->nested==0 ){
141174    sqlite3DbFree(db, pParse->aTableLock);
141175    pParse->aTableLock = 0;
141176    pParse->nTableLock = 0;
141177  }
141178#endif
141179#ifndef SQLITE_OMIT_VIRTUALTABLE
141180  sqlite3_free(pParse->apVtabLock);
141181#endif
141182
141183  if( !IN_DECLARE_VTAB ){
141184    /* If the pParse->declareVtab flag is set, do not delete any table
141185    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
141186    ** will take responsibility for freeing the Table structure.
141187    */
141188    sqlite3DeleteTable(db, pParse->pNewTable);
141189  }
141190
141191  if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
141192  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
141193  sqlite3DbFree(db, pParse->pVList);
141194  while( pParse->pAinc ){
141195    AutoincInfo *p = pParse->pAinc;
141196    pParse->pAinc = p->pNext;
141197    sqlite3DbFreeNN(db, p);
141198  }
141199  while( pParse->pZombieTab ){
141200    Table *p = pParse->pZombieTab;
141201    pParse->pZombieTab = p->pNextZombie;
141202    sqlite3DeleteTable(db, p);
141203  }
141204  assert( nErr==0 || pParse->rc!=SQLITE_OK );
141205  return nErr;
141206}
141207
141208/************** End of tokenize.c ********************************************/
141209/************** Begin file complete.c ****************************************/
141210/*
141211** 2001 September 15
141212**
141213** The author disclaims copyright to this source code.  In place of
141214** a legal notice, here is a blessing:
141215**
141216**    May you do good and not evil.
141217**    May you find forgiveness for yourself and forgive others.
141218**    May you share freely, never taking more than you give.
141219**
141220*************************************************************************
141221** An tokenizer for SQL
141222**
141223** This file contains C code that implements the sqlite3_complete() API.
141224** This code used to be part of the tokenizer.c source file.  But by
141225** separating it out, the code will be automatically omitted from
141226** static links that do not use it.
141227*/
141228/* #include "sqliteInt.h" */
141229#ifndef SQLITE_OMIT_COMPLETE
141230
141231/*
141232** This is defined in tokenize.c.  We just have to import the definition.
141233*/
141234#ifndef SQLITE_AMALGAMATION
141235#ifdef SQLITE_ASCII
141236#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
141237#endif
141238#ifdef SQLITE_EBCDIC
141239SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
141240#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
141241#endif
141242#endif /* SQLITE_AMALGAMATION */
141243
141244
141245/*
141246** Token types used by the sqlite3_complete() routine.  See the header
141247** comments on that procedure for additional information.
141248*/
141249#define tkSEMI    0
141250#define tkWS      1
141251#define tkOTHER   2
141252#ifndef SQLITE_OMIT_TRIGGER
141253#define tkEXPLAIN 3
141254#define tkCREATE  4
141255#define tkTEMP    5
141256#define tkTRIGGER 6
141257#define tkEND     7
141258#endif
141259
141260/*
141261** Return TRUE if the given SQL string ends in a semicolon.
141262**
141263** Special handling is require for CREATE TRIGGER statements.
141264** Whenever the CREATE TRIGGER keywords are seen, the statement
141265** must end with ";END;".
141266**
141267** This implementation uses a state machine with 8 states:
141268**
141269**   (0) INVALID   We have not yet seen a non-whitespace character.
141270**
141271**   (1) START     At the beginning or end of an SQL statement.  This routine
141272**                 returns 1 if it ends in the START state and 0 if it ends
141273**                 in any other state.
141274**
141275**   (2) NORMAL    We are in the middle of statement which ends with a single
141276**                 semicolon.
141277**
141278**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
141279**                 a statement.
141280**
141281**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
141282**                 statement, possibly preceded by EXPLAIN and/or followed by
141283**                 TEMP or TEMPORARY
141284**
141285**   (5) TRIGGER   We are in the middle of a trigger definition that must be
141286**                 ended by a semicolon, the keyword END, and another semicolon.
141287**
141288**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
141289**                 the end of a trigger definition.
141290**
141291**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
141292**                 of a trigger definition.
141293**
141294** Transitions between states above are determined by tokens extracted
141295** from the input.  The following tokens are significant:
141296**
141297**   (0) tkSEMI      A semicolon.
141298**   (1) tkWS        Whitespace.
141299**   (2) tkOTHER     Any other SQL token.
141300**   (3) tkEXPLAIN   The "explain" keyword.
141301**   (4) tkCREATE    The "create" keyword.
141302**   (5) tkTEMP      The "temp" or "temporary" keyword.
141303**   (6) tkTRIGGER   The "trigger" keyword.
141304**   (7) tkEND       The "end" keyword.
141305**
141306** Whitespace never causes a state transition and is always ignored.
141307** This means that a SQL string of all whitespace is invalid.
141308**
141309** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
141310** to recognize the end of a trigger can be omitted.  All we have to do
141311** is look for a semicolon that is not part of an string or comment.
141312*/
141313SQLITE_API int sqlite3_complete(const char *zSql){
141314  u8 state = 0;   /* Current state, using numbers defined in header comment */
141315  u8 token;       /* Value of the next token */
141316
141317#ifndef SQLITE_OMIT_TRIGGER
141318  /* A complex statement machine used to detect the end of a CREATE TRIGGER
141319  ** statement.  This is the normal case.
141320  */
141321  static const u8 trans[8][8] = {
141322                     /* Token:                                                */
141323     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
141324     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
141325     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
141326     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
141327     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
141328     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
141329     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
141330     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
141331     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
141332  };
141333#else
141334  /* If triggers are not supported by this compile then the statement machine
141335  ** used to detect the end of a statement is much simpler
141336  */
141337  static const u8 trans[3][3] = {
141338                     /* Token:           */
141339     /* State:       **  SEMI  WS  OTHER */
141340     /* 0 INVALID: */ {    1,  0,     2, },
141341     /* 1   START: */ {    1,  1,     2, },
141342     /* 2  NORMAL: */ {    1,  2,     2, },
141343  };
141344#endif /* SQLITE_OMIT_TRIGGER */
141345
141346#ifdef SQLITE_ENABLE_API_ARMOR
141347  if( zSql==0 ){
141348    (void)SQLITE_MISUSE_BKPT;
141349    return 0;
141350  }
141351#endif
141352
141353  while( *zSql ){
141354    switch( *zSql ){
141355      case ';': {  /* A semicolon */
141356        token = tkSEMI;
141357        break;
141358      }
141359      case ' ':
141360      case '\r':
141361      case '\t':
141362      case '\n':
141363      case '\f': {  /* White space is ignored */
141364        token = tkWS;
141365        break;
141366      }
141367      case '/': {   /* C-style comments */
141368        if( zSql[1]!='*' ){
141369          token = tkOTHER;
141370          break;
141371        }
141372        zSql += 2;
141373        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
141374        if( zSql[0]==0 ) return 0;
141375        zSql++;
141376        token = tkWS;
141377        break;
141378      }
141379      case '-': {   /* SQL-style comments from "--" to end of line */
141380        if( zSql[1]!='-' ){
141381          token = tkOTHER;
141382          break;
141383        }
141384        while( *zSql && *zSql!='\n' ){ zSql++; }
141385        if( *zSql==0 ) return state==1;
141386        token = tkWS;
141387        break;
141388      }
141389      case '[': {   /* Microsoft-style identifiers in [...] */
141390        zSql++;
141391        while( *zSql && *zSql!=']' ){ zSql++; }
141392        if( *zSql==0 ) return 0;
141393        token = tkOTHER;
141394        break;
141395      }
141396      case '`':     /* Grave-accent quoted symbols used by MySQL */
141397      case '"':     /* single- and double-quoted strings */
141398      case '\'': {
141399        int c = *zSql;
141400        zSql++;
141401        while( *zSql && *zSql!=c ){ zSql++; }
141402        if( *zSql==0 ) return 0;
141403        token = tkOTHER;
141404        break;
141405      }
141406      default: {
141407#ifdef SQLITE_EBCDIC
141408        unsigned char c;
141409#endif
141410        if( IdChar((u8)*zSql) ){
141411          /* Keywords and unquoted identifiers */
141412          int nId;
141413          for(nId=1; IdChar(zSql[nId]); nId++){}
141414#ifdef SQLITE_OMIT_TRIGGER
141415          token = tkOTHER;
141416#else
141417          switch( *zSql ){
141418            case 'c': case 'C': {
141419              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
141420                token = tkCREATE;
141421              }else{
141422                token = tkOTHER;
141423              }
141424              break;
141425            }
141426            case 't': case 'T': {
141427              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
141428                token = tkTRIGGER;
141429              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
141430                token = tkTEMP;
141431              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
141432                token = tkTEMP;
141433              }else{
141434                token = tkOTHER;
141435              }
141436              break;
141437            }
141438            case 'e':  case 'E': {
141439              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
141440                token = tkEND;
141441              }else
141442#ifndef SQLITE_OMIT_EXPLAIN
141443              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
141444                token = tkEXPLAIN;
141445              }else
141446#endif
141447              {
141448                token = tkOTHER;
141449              }
141450              break;
141451            }
141452            default: {
141453              token = tkOTHER;
141454              break;
141455            }
141456          }
141457#endif /* SQLITE_OMIT_TRIGGER */
141458          zSql += nId-1;
141459        }else{
141460          /* Operators and special symbols */
141461          token = tkOTHER;
141462        }
141463        break;
141464      }
141465    }
141466    state = trans[state][token];
141467    zSql++;
141468  }
141469  return state==1;
141470}
141471
141472#ifndef SQLITE_OMIT_UTF16
141473/*
141474** This routine is the same as the sqlite3_complete() routine described
141475** above, except that the parameter is required to be UTF-16 encoded, not
141476** UTF-8.
141477*/
141478SQLITE_API int sqlite3_complete16(const void *zSql){
141479  sqlite3_value *pVal;
141480  char const *zSql8;
141481  int rc;
141482
141483#ifndef SQLITE_OMIT_AUTOINIT
141484  rc = sqlite3_initialize();
141485  if( rc ) return rc;
141486#endif
141487  pVal = sqlite3ValueNew(0);
141488  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
141489  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
141490  if( zSql8 ){
141491    rc = sqlite3_complete(zSql8);
141492  }else{
141493    rc = SQLITE_NOMEM_BKPT;
141494  }
141495  sqlite3ValueFree(pVal);
141496  return rc & 0xff;
141497}
141498#endif /* SQLITE_OMIT_UTF16 */
141499#endif /* SQLITE_OMIT_COMPLETE */
141500
141501/************** End of complete.c ********************************************/
141502/************** Begin file main.c ********************************************/
141503/*
141504** 2001 September 15
141505**
141506** The author disclaims copyright to this source code.  In place of
141507** a legal notice, here is a blessing:
141508**
141509**    May you do good and not evil.
141510**    May you find forgiveness for yourself and forgive others.
141511**    May you share freely, never taking more than you give.
141512**
141513*************************************************************************
141514** Main file for the SQLite library.  The routines in this file
141515** implement the programmer interface to the library.  Routines in
141516** other files are for internal use by SQLite and should not be
141517** accessed by users of the library.
141518*/
141519/* #include "sqliteInt.h" */
141520
141521#ifdef SQLITE_ENABLE_FTS3
141522/************** Include fts3.h in the middle of main.c ***********************/
141523/************** Begin file fts3.h ********************************************/
141524/*
141525** 2006 Oct 10
141526**
141527** The author disclaims copyright to this source code.  In place of
141528** a legal notice, here is a blessing:
141529**
141530**    May you do good and not evil.
141531**    May you find forgiveness for yourself and forgive others.
141532**    May you share freely, never taking more than you give.
141533**
141534******************************************************************************
141535**
141536** This header file is used by programs that want to link against the
141537** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
141538*/
141539/* #include "sqlite3.h" */
141540
141541#if 0
141542extern "C" {
141543#endif  /* __cplusplus */
141544
141545SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
141546
141547#if 0
141548}  /* extern "C" */
141549#endif  /* __cplusplus */
141550
141551/************** End of fts3.h ************************************************/
141552/************** Continuing where we left off in main.c ***********************/
141553#endif
141554#ifdef SQLITE_ENABLE_RTREE
141555/************** Include rtree.h in the middle of main.c **********************/
141556/************** Begin file rtree.h *******************************************/
141557/*
141558** 2008 May 26
141559**
141560** The author disclaims copyright to this source code.  In place of
141561** a legal notice, here is a blessing:
141562**
141563**    May you do good and not evil.
141564**    May you find forgiveness for yourself and forgive others.
141565**    May you share freely, never taking more than you give.
141566**
141567******************************************************************************
141568**
141569** This header file is used by programs that want to link against the
141570** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
141571*/
141572/* #include "sqlite3.h" */
141573
141574#if 0
141575extern "C" {
141576#endif  /* __cplusplus */
141577
141578SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
141579
141580#if 0
141581}  /* extern "C" */
141582#endif  /* __cplusplus */
141583
141584/************** End of rtree.h ***********************************************/
141585/************** Continuing where we left off in main.c ***********************/
141586#endif
141587#ifdef SQLITE_ENABLE_ICU
141588/************** Include sqliteicu.h in the middle of main.c ******************/
141589/************** Begin file sqliteicu.h ***************************************/
141590/*
141591** 2008 May 26
141592**
141593** The author disclaims copyright to this source code.  In place of
141594** a legal notice, here is a blessing:
141595**
141596**    May you do good and not evil.
141597**    May you find forgiveness for yourself and forgive others.
141598**    May you share freely, never taking more than you give.
141599**
141600******************************************************************************
141601**
141602** This header file is used by programs that want to link against the
141603** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
141604*/
141605/* #include "sqlite3.h" */
141606
141607#if 0
141608extern "C" {
141609#endif  /* __cplusplus */
141610
141611SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
141612
141613#if 0
141614}  /* extern "C" */
141615#endif  /* __cplusplus */
141616
141617
141618/************** End of sqliteicu.h *******************************************/
141619/************** Continuing where we left off in main.c ***********************/
141620#endif
141621#ifdef SQLITE_ENABLE_JSON1
141622SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
141623#endif
141624#ifdef SQLITE_ENABLE_STMTVTAB
141625SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
141626#endif
141627#ifdef SQLITE_ENABLE_FTS5
141628SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
141629#endif
141630
141631#ifndef SQLITE_AMALGAMATION
141632/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
141633** contains the text of SQLITE_VERSION macro.
141634*/
141635SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
141636#endif
141637
141638/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
141639** a pointer to the to the sqlite3_version[] string constant.
141640*/
141641SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
141642
141643/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
141644** pointer to a string constant whose value is the same as the
141645** SQLITE_SOURCE_ID C preprocessor macro.
141646*/
141647SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
141648
141649/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
141650** returns an integer equal to SQLITE_VERSION_NUMBER.
141651*/
141652SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
141653
141654/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
141655** zero if and only if SQLite was compiled with mutexing code omitted due to
141656** the SQLITE_THREADSAFE compile-time option being set to 0.
141657*/
141658SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
141659
141660/*
141661** When compiling the test fixture or with debugging enabled (on Win32),
141662** this variable being set to non-zero will cause OSTRACE macros to emit
141663** extra diagnostic information.
141664*/
141665#ifdef SQLITE_HAVE_OS_TRACE
141666# ifndef SQLITE_DEBUG_OS_TRACE
141667#   define SQLITE_DEBUG_OS_TRACE 0
141668# endif
141669  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
141670#endif
141671
141672#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
141673/*
141674** If the following function pointer is not NULL and if
141675** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
141676** I/O active are written using this function.  These messages
141677** are intended for debugging activity only.
141678*/
141679SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
141680#endif
141681
141682/*
141683** If the following global variable points to a string which is the
141684** name of a directory, then that directory will be used to store
141685** temporary files.
141686**
141687** See also the "PRAGMA temp_store_directory" SQL command.
141688*/
141689SQLITE_API char *sqlite3_temp_directory = 0;
141690
141691/*
141692** If the following global variable points to a string which is the
141693** name of a directory, then that directory will be used to store
141694** all database files specified with a relative pathname.
141695**
141696** See also the "PRAGMA data_store_directory" SQL command.
141697*/
141698SQLITE_API char *sqlite3_data_directory = 0;
141699
141700/*
141701** Initialize SQLite.
141702**
141703** This routine must be called to initialize the memory allocation,
141704** VFS, and mutex subsystems prior to doing any serious work with
141705** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
141706** this routine will be called automatically by key routines such as
141707** sqlite3_open().
141708**
141709** This routine is a no-op except on its very first call for the process,
141710** or for the first call after a call to sqlite3_shutdown.
141711**
141712** The first thread to call this routine runs the initialization to
141713** completion.  If subsequent threads call this routine before the first
141714** thread has finished the initialization process, then the subsequent
141715** threads must block until the first thread finishes with the initialization.
141716**
141717** The first thread might call this routine recursively.  Recursive
141718** calls to this routine should not block, of course.  Otherwise the
141719** initialization process would never complete.
141720**
141721** Let X be the first thread to enter this routine.  Let Y be some other
141722** thread.  Then while the initial invocation of this routine by X is
141723** incomplete, it is required that:
141724**
141725**    *  Calls to this routine from Y must block until the outer-most
141726**       call by X completes.
141727**
141728**    *  Recursive calls to this routine from thread X return immediately
141729**       without blocking.
141730*/
141731SQLITE_API int sqlite3_initialize(void){
141732  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
141733  int rc;                                      /* Result code */
141734#ifdef SQLITE_EXTRA_INIT
141735  int bRunExtraInit = 0;                       /* Extra initialization needed */
141736#endif
141737
141738#ifdef SQLITE_OMIT_WSD
141739  rc = sqlite3_wsd_init(4096, 24);
141740  if( rc!=SQLITE_OK ){
141741    return rc;
141742  }
141743#endif
141744
141745  /* If the following assert() fails on some obscure processor/compiler
141746  ** combination, the work-around is to set the correct pointer
141747  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
141748  assert( SQLITE_PTRSIZE==sizeof(char*) );
141749
141750  /* If SQLite is already completely initialized, then this call
141751  ** to sqlite3_initialize() should be a no-op.  But the initialization
141752  ** must be complete.  So isInit must not be set until the very end
141753  ** of this routine.
141754  */
141755  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
141756
141757  /* Make sure the mutex subsystem is initialized.  If unable to
141758  ** initialize the mutex subsystem, return early with the error.
141759  ** If the system is so sick that we are unable to allocate a mutex,
141760  ** there is not much SQLite is going to be able to do.
141761  **
141762  ** The mutex subsystem must take care of serializing its own
141763  ** initialization.
141764  */
141765  rc = sqlite3MutexInit();
141766  if( rc ) return rc;
141767
141768  /* Initialize the malloc() system and the recursive pInitMutex mutex.
141769  ** This operation is protected by the STATIC_MASTER mutex.  Note that
141770  ** MutexAlloc() is called for a static mutex prior to initializing the
141771  ** malloc subsystem - this implies that the allocation of a static
141772  ** mutex must not require support from the malloc subsystem.
141773  */
141774  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
141775  sqlite3_mutex_enter(pMaster);
141776  sqlite3GlobalConfig.isMutexInit = 1;
141777  if( !sqlite3GlobalConfig.isMallocInit ){
141778    rc = sqlite3MallocInit();
141779  }
141780  if( rc==SQLITE_OK ){
141781    sqlite3GlobalConfig.isMallocInit = 1;
141782    if( !sqlite3GlobalConfig.pInitMutex ){
141783      sqlite3GlobalConfig.pInitMutex =
141784           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
141785      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
141786        rc = SQLITE_NOMEM_BKPT;
141787      }
141788    }
141789  }
141790  if( rc==SQLITE_OK ){
141791    sqlite3GlobalConfig.nRefInitMutex++;
141792  }
141793  sqlite3_mutex_leave(pMaster);
141794
141795  /* If rc is not SQLITE_OK at this point, then either the malloc
141796  ** subsystem could not be initialized or the system failed to allocate
141797  ** the pInitMutex mutex. Return an error in either case.  */
141798  if( rc!=SQLITE_OK ){
141799    return rc;
141800  }
141801
141802  /* Do the rest of the initialization under the recursive mutex so
141803  ** that we will be able to handle recursive calls into
141804  ** sqlite3_initialize().  The recursive calls normally come through
141805  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
141806  ** recursive calls might also be possible.
141807  **
141808  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
141809  ** to the xInit method, so the xInit method need not be threadsafe.
141810  **
141811  ** The following mutex is what serializes access to the appdef pcache xInit
141812  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
141813  ** call to sqlite3PcacheInitialize().
141814  */
141815  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
141816  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
141817    sqlite3GlobalConfig.inProgress = 1;
141818#ifdef SQLITE_ENABLE_SQLLOG
141819    {
141820      extern void sqlite3_init_sqllog(void);
141821      sqlite3_init_sqllog();
141822    }
141823#endif
141824    memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
141825    sqlite3RegisterBuiltinFunctions();
141826    if( sqlite3GlobalConfig.isPCacheInit==0 ){
141827      rc = sqlite3PcacheInitialize();
141828    }
141829    if( rc==SQLITE_OK ){
141830      sqlite3GlobalConfig.isPCacheInit = 1;
141831      rc = sqlite3OsInit();
141832    }
141833    if( rc==SQLITE_OK ){
141834      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
141835          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
141836      sqlite3GlobalConfig.isInit = 1;
141837#ifdef SQLITE_EXTRA_INIT
141838      bRunExtraInit = 1;
141839#endif
141840    }
141841    sqlite3GlobalConfig.inProgress = 0;
141842  }
141843  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
141844
141845  /* Go back under the static mutex and clean up the recursive
141846  ** mutex to prevent a resource leak.
141847  */
141848  sqlite3_mutex_enter(pMaster);
141849  sqlite3GlobalConfig.nRefInitMutex--;
141850  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
141851    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
141852    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
141853    sqlite3GlobalConfig.pInitMutex = 0;
141854  }
141855  sqlite3_mutex_leave(pMaster);
141856
141857  /* The following is just a sanity check to make sure SQLite has
141858  ** been compiled correctly.  It is important to run this code, but
141859  ** we don't want to run it too often and soak up CPU cycles for no
141860  ** reason.  So we run it once during initialization.
141861  */
141862#ifndef NDEBUG
141863#ifndef SQLITE_OMIT_FLOATING_POINT
141864  /* This section of code's only "output" is via assert() statements. */
141865  if ( rc==SQLITE_OK ){
141866    u64 x = (((u64)1)<<63)-1;
141867    double y;
141868    assert(sizeof(x)==8);
141869    assert(sizeof(x)==sizeof(y));
141870    memcpy(&y, &x, 8);
141871    assert( sqlite3IsNaN(y) );
141872  }
141873#endif
141874#endif
141875
141876  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
141877  ** compile-time option.
141878  */
141879#ifdef SQLITE_EXTRA_INIT
141880  if( bRunExtraInit ){
141881    int SQLITE_EXTRA_INIT(const char*);
141882    rc = SQLITE_EXTRA_INIT(0);
141883  }
141884#endif
141885
141886  return rc;
141887}
141888
141889/*
141890** Undo the effects of sqlite3_initialize().  Must not be called while
141891** there are outstanding database connections or memory allocations or
141892** while any part of SQLite is otherwise in use in any thread.  This
141893** routine is not threadsafe.  But it is safe to invoke this routine
141894** on when SQLite is already shut down.  If SQLite is already shut down
141895** when this routine is invoked, then this routine is a harmless no-op.
141896*/
141897SQLITE_API int sqlite3_shutdown(void){
141898#ifdef SQLITE_OMIT_WSD
141899  int rc = sqlite3_wsd_init(4096, 24);
141900  if( rc!=SQLITE_OK ){
141901    return rc;
141902  }
141903#endif
141904
141905  if( sqlite3GlobalConfig.isInit ){
141906#ifdef SQLITE_EXTRA_SHUTDOWN
141907    void SQLITE_EXTRA_SHUTDOWN(void);
141908    SQLITE_EXTRA_SHUTDOWN();
141909#endif
141910    sqlite3_os_end();
141911    sqlite3_reset_auto_extension();
141912    sqlite3GlobalConfig.isInit = 0;
141913  }
141914  if( sqlite3GlobalConfig.isPCacheInit ){
141915    sqlite3PcacheShutdown();
141916    sqlite3GlobalConfig.isPCacheInit = 0;
141917  }
141918  if( sqlite3GlobalConfig.isMallocInit ){
141919    sqlite3MallocEnd();
141920    sqlite3GlobalConfig.isMallocInit = 0;
141921
141922#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
141923    /* The heap subsystem has now been shutdown and these values are supposed
141924    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
141925    ** which would rely on that heap subsystem; therefore, make sure these
141926    ** values cannot refer to heap memory that was just invalidated when the
141927    ** heap subsystem was shutdown.  This is only done if the current call to
141928    ** this function resulted in the heap subsystem actually being shutdown.
141929    */
141930    sqlite3_data_directory = 0;
141931    sqlite3_temp_directory = 0;
141932#endif
141933  }
141934  if( sqlite3GlobalConfig.isMutexInit ){
141935    sqlite3MutexEnd();
141936    sqlite3GlobalConfig.isMutexInit = 0;
141937  }
141938
141939  return SQLITE_OK;
141940}
141941
141942/*
141943** This API allows applications to modify the global configuration of
141944** the SQLite library at run-time.
141945**
141946** This routine should only be called when there are no outstanding
141947** database connections or memory allocations.  This routine is not
141948** threadsafe.  Failure to heed these warnings can lead to unpredictable
141949** behavior.
141950*/
141951SQLITE_API int sqlite3_config(int op, ...){
141952  va_list ap;
141953  int rc = SQLITE_OK;
141954
141955  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
141956  ** the SQLite library is in use. */
141957  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
141958
141959  va_start(ap, op);
141960  switch( op ){
141961
141962    /* Mutex configuration options are only available in a threadsafe
141963    ** compile.
141964    */
141965#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
141966    case SQLITE_CONFIG_SINGLETHREAD: {
141967      /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
141968      ** Single-thread. */
141969      sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
141970      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
141971      break;
141972    }
141973#endif
141974#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
141975    case SQLITE_CONFIG_MULTITHREAD: {
141976      /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
141977      ** Multi-thread. */
141978      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
141979      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
141980      break;
141981    }
141982#endif
141983#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
141984    case SQLITE_CONFIG_SERIALIZED: {
141985      /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
141986      ** Serialized. */
141987      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
141988      sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
141989      break;
141990    }
141991#endif
141992#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
141993    case SQLITE_CONFIG_MUTEX: {
141994      /* Specify an alternative mutex implementation */
141995      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
141996      break;
141997    }
141998#endif
141999#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
142000    case SQLITE_CONFIG_GETMUTEX: {
142001      /* Retrieve the current mutex implementation */
142002      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
142003      break;
142004    }
142005#endif
142006
142007    case SQLITE_CONFIG_MALLOC: {
142008      /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
142009      ** single argument which is a pointer to an instance of the
142010      ** sqlite3_mem_methods structure. The argument specifies alternative
142011      ** low-level memory allocation routines to be used in place of the memory
142012      ** allocation routines built into SQLite. */
142013      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
142014      break;
142015    }
142016    case SQLITE_CONFIG_GETMALLOC: {
142017      /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
142018      ** single argument which is a pointer to an instance of the
142019      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
142020      ** filled with the currently defined memory allocation routines. */
142021      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
142022      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
142023      break;
142024    }
142025    case SQLITE_CONFIG_MEMSTATUS: {
142026      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
142027      ** single argument of type int, interpreted as a boolean, which enables
142028      ** or disables the collection of memory allocation statistics. */
142029      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
142030      break;
142031    }
142032    case SQLITE_CONFIG_SCRATCH: {
142033      /* EVIDENCE-OF: R-08404-60887 There are three arguments to
142034      ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
142035      ** which the scratch allocations will be drawn, the size of each scratch
142036      ** allocation (sz), and the maximum number of scratch allocations (N). */
142037      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
142038      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
142039      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
142040      break;
142041    }
142042    case SQLITE_CONFIG_PAGECACHE: {
142043      /* EVIDENCE-OF: R-18761-36601 There are three arguments to
142044      ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
142045      ** the size of each page cache line (sz), and the number of cache lines
142046      ** (N). */
142047      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
142048      sqlite3GlobalConfig.szPage = va_arg(ap, int);
142049      sqlite3GlobalConfig.nPage = va_arg(ap, int);
142050      break;
142051    }
142052    case SQLITE_CONFIG_PCACHE_HDRSZ: {
142053      /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
142054      ** a single parameter which is a pointer to an integer and writes into
142055      ** that integer the number of extra bytes per page required for each page
142056      ** in SQLITE_CONFIG_PAGECACHE. */
142057      *va_arg(ap, int*) =
142058          sqlite3HeaderSizeBtree() +
142059          sqlite3HeaderSizePcache() +
142060          sqlite3HeaderSizePcache1();
142061      break;
142062    }
142063
142064    case SQLITE_CONFIG_PCACHE: {
142065      /* no-op */
142066      break;
142067    }
142068    case SQLITE_CONFIG_GETPCACHE: {
142069      /* now an error */
142070      rc = SQLITE_ERROR;
142071      break;
142072    }
142073
142074    case SQLITE_CONFIG_PCACHE2: {
142075      /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
142076      ** single argument which is a pointer to an sqlite3_pcache_methods2
142077      ** object. This object specifies the interface to a custom page cache
142078      ** implementation. */
142079      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
142080      break;
142081    }
142082    case SQLITE_CONFIG_GETPCACHE2: {
142083      /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
142084      ** single argument which is a pointer to an sqlite3_pcache_methods2
142085      ** object. SQLite copies of the current page cache implementation into
142086      ** that object. */
142087      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
142088        sqlite3PCacheSetDefault();
142089      }
142090      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
142091      break;
142092    }
142093
142094/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
142095** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
142096** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
142097#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
142098    case SQLITE_CONFIG_HEAP: {
142099      /* EVIDENCE-OF: R-19854-42126 There are three arguments to
142100      ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
142101      ** number of bytes in the memory buffer, and the minimum allocation size.
142102      */
142103      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
142104      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
142105      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
142106
142107      if( sqlite3GlobalConfig.mnReq<1 ){
142108        sqlite3GlobalConfig.mnReq = 1;
142109      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
142110        /* cap min request size at 2^12 */
142111        sqlite3GlobalConfig.mnReq = (1<<12);
142112      }
142113
142114      if( sqlite3GlobalConfig.pHeap==0 ){
142115        /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
142116        ** is NULL, then SQLite reverts to using its default memory allocator
142117        ** (the system malloc() implementation), undoing any prior invocation of
142118        ** SQLITE_CONFIG_MALLOC.
142119        **
142120        ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
142121        ** revert to its default implementation when sqlite3_initialize() is run
142122        */
142123        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
142124      }else{
142125        /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
142126        ** alternative memory allocator is engaged to handle all of SQLites
142127        ** memory allocation needs. */
142128#ifdef SQLITE_ENABLE_MEMSYS3
142129        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
142130#endif
142131#ifdef SQLITE_ENABLE_MEMSYS5
142132        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
142133#endif
142134      }
142135      break;
142136    }
142137#endif
142138
142139    case SQLITE_CONFIG_LOOKASIDE: {
142140      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
142141      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
142142      break;
142143    }
142144
142145    /* Record a pointer to the logger function and its first argument.
142146    ** The default is NULL.  Logging is disabled if the function pointer is
142147    ** NULL.
142148    */
142149    case SQLITE_CONFIG_LOG: {
142150      /* MSVC is picky about pulling func ptrs from va lists.
142151      ** http://support.microsoft.com/kb/47961
142152      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
142153      */
142154      typedef void(*LOGFUNC_t)(void*,int,const char*);
142155      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
142156      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
142157      break;
142158    }
142159
142160    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
142161    ** can be changed at start-time using the
142162    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
142163    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
142164    */
142165    case SQLITE_CONFIG_URI: {
142166      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
142167      ** argument of type int. If non-zero, then URI handling is globally
142168      ** enabled. If the parameter is zero, then URI handling is globally
142169      ** disabled. */
142170      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
142171      break;
142172    }
142173
142174    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
142175      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
142176      ** option takes a single integer argument which is interpreted as a
142177      ** boolean in order to enable or disable the use of covering indices for
142178      ** full table scans in the query optimizer. */
142179      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
142180      break;
142181    }
142182
142183#ifdef SQLITE_ENABLE_SQLLOG
142184    case SQLITE_CONFIG_SQLLOG: {
142185      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
142186      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
142187      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
142188      break;
142189    }
142190#endif
142191
142192    case SQLITE_CONFIG_MMAP_SIZE: {
142193      /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
142194      ** integer (sqlite3_int64) values that are the default mmap size limit
142195      ** (the default setting for PRAGMA mmap_size) and the maximum allowed
142196      ** mmap size limit. */
142197      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
142198      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
142199      /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
142200      ** negative, then that argument is changed to its compile-time default.
142201      **
142202      ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
142203      ** silently truncated if necessary so that it does not exceed the
142204      ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
142205      ** compile-time option.
142206      */
142207      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
142208        mxMmap = SQLITE_MAX_MMAP_SIZE;
142209      }
142210      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
142211      if( szMmap>mxMmap) szMmap = mxMmap;
142212      sqlite3GlobalConfig.mxMmap = mxMmap;
142213      sqlite3GlobalConfig.szMmap = szMmap;
142214      break;
142215    }
142216
142217#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
142218    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
142219      /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
142220      ** unsigned integer value that specifies the maximum size of the created
142221      ** heap. */
142222      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
142223      break;
142224    }
142225#endif
142226
142227    case SQLITE_CONFIG_PMASZ: {
142228      sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
142229      break;
142230    }
142231
142232    case SQLITE_CONFIG_STMTJRNL_SPILL: {
142233      sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
142234      break;
142235    }
142236
142237    default: {
142238      rc = SQLITE_ERROR;
142239      break;
142240    }
142241  }
142242  va_end(ap);
142243  return rc;
142244}
142245
142246/*
142247** Set up the lookaside buffers for a database connection.
142248** Return SQLITE_OK on success.
142249** If lookaside is already active, return SQLITE_BUSY.
142250**
142251** The sz parameter is the number of bytes in each lookaside slot.
142252** The cnt parameter is the number of slots.  If pStart is NULL the
142253** space for the lookaside memory is obtained from sqlite3_malloc().
142254** If pStart is not NULL then it is sz*cnt bytes of memory to use for
142255** the lookaside memory.
142256*/
142257static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
142258#ifndef SQLITE_OMIT_LOOKASIDE
142259  void *pStart;
142260  if( db->lookaside.nOut ){
142261    return SQLITE_BUSY;
142262  }
142263  /* Free any existing lookaside buffer for this handle before
142264  ** allocating a new one so we don't have to have space for
142265  ** both at the same time.
142266  */
142267  if( db->lookaside.bMalloced ){
142268    sqlite3_free(db->lookaside.pStart);
142269  }
142270  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
142271  ** than a pointer to be useful.
142272  */
142273  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
142274  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
142275  if( cnt<0 ) cnt = 0;
142276  if( sz==0 || cnt==0 ){
142277    sz = 0;
142278    pStart = 0;
142279  }else if( pBuf==0 ){
142280    sqlite3BeginBenignMalloc();
142281    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
142282    sqlite3EndBenignMalloc();
142283    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
142284  }else{
142285    pStart = pBuf;
142286  }
142287  db->lookaside.pStart = pStart;
142288  db->lookaside.pFree = 0;
142289  db->lookaside.sz = (u16)sz;
142290  if( pStart ){
142291    int i;
142292    LookasideSlot *p;
142293    assert( sz > (int)sizeof(LookasideSlot*) );
142294    p = (LookasideSlot*)pStart;
142295    for(i=cnt-1; i>=0; i--){
142296      p->pNext = db->lookaside.pFree;
142297      db->lookaside.pFree = p;
142298      p = (LookasideSlot*)&((u8*)p)[sz];
142299    }
142300    db->lookaside.pEnd = p;
142301    db->lookaside.bDisable = 0;
142302    db->lookaside.bMalloced = pBuf==0 ?1:0;
142303  }else{
142304    db->lookaside.pStart = db;
142305    db->lookaside.pEnd = db;
142306    db->lookaside.bDisable = 1;
142307    db->lookaside.bMalloced = 0;
142308  }
142309#endif /* SQLITE_OMIT_LOOKASIDE */
142310  return SQLITE_OK;
142311}
142312
142313/*
142314** Return the mutex associated with a database connection.
142315*/
142316SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
142317#ifdef SQLITE_ENABLE_API_ARMOR
142318  if( !sqlite3SafetyCheckOk(db) ){
142319    (void)SQLITE_MISUSE_BKPT;
142320    return 0;
142321  }
142322#endif
142323  return db->mutex;
142324}
142325
142326/*
142327** Free up as much memory as we can from the given database
142328** connection.
142329*/
142330SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
142331  int i;
142332
142333#ifdef SQLITE_ENABLE_API_ARMOR
142334  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
142335#endif
142336  sqlite3_mutex_enter(db->mutex);
142337  sqlite3BtreeEnterAll(db);
142338  for(i=0; i<db->nDb; i++){
142339    Btree *pBt = db->aDb[i].pBt;
142340    if( pBt ){
142341      Pager *pPager = sqlite3BtreePager(pBt);
142342      sqlite3PagerShrink(pPager);
142343    }
142344  }
142345  sqlite3BtreeLeaveAll(db);
142346  sqlite3_mutex_leave(db->mutex);
142347  return SQLITE_OK;
142348}
142349
142350/*
142351** Flush any dirty pages in the pager-cache for any attached database
142352** to disk.
142353*/
142354SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
142355  int i;
142356  int rc = SQLITE_OK;
142357  int bSeenBusy = 0;
142358
142359#ifdef SQLITE_ENABLE_API_ARMOR
142360  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
142361#endif
142362  sqlite3_mutex_enter(db->mutex);
142363  sqlite3BtreeEnterAll(db);
142364  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
142365    Btree *pBt = db->aDb[i].pBt;
142366    if( pBt && sqlite3BtreeIsInTrans(pBt) ){
142367      Pager *pPager = sqlite3BtreePager(pBt);
142368      rc = sqlite3PagerFlush(pPager);
142369      if( rc==SQLITE_BUSY ){
142370        bSeenBusy = 1;
142371        rc = SQLITE_OK;
142372      }
142373    }
142374  }
142375  sqlite3BtreeLeaveAll(db);
142376  sqlite3_mutex_leave(db->mutex);
142377  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
142378}
142379
142380/*
142381** Configuration settings for an individual database connection
142382*/
142383SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
142384  va_list ap;
142385  int rc;
142386  va_start(ap, op);
142387  switch( op ){
142388    case SQLITE_DBCONFIG_MAINDBNAME: {
142389      /* IMP: R-06824-28531 */
142390      /* IMP: R-36257-52125 */
142391      db->aDb[0].zDbSName = va_arg(ap,char*);
142392      rc = SQLITE_OK;
142393      break;
142394    }
142395    case SQLITE_DBCONFIG_LOOKASIDE: {
142396      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
142397      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
142398      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
142399      rc = setupLookaside(db, pBuf, sz, cnt);
142400      break;
142401    }
142402    default: {
142403      static const struct {
142404        int op;      /* The opcode */
142405        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
142406      } aFlagOp[] = {
142407        { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
142408        { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
142409        { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
142410        { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
142411        { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,      SQLITE_NoCkptOnClose  },
142412        { SQLITE_DBCONFIG_ENABLE_QPSG,           SQLITE_EnableQPSG     },
142413      };
142414      unsigned int i;
142415      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
142416      for(i=0; i<ArraySize(aFlagOp); i++){
142417        if( aFlagOp[i].op==op ){
142418          int onoff = va_arg(ap, int);
142419          int *pRes = va_arg(ap, int*);
142420          int oldFlags = db->flags;
142421          if( onoff>0 ){
142422            db->flags |= aFlagOp[i].mask;
142423          }else if( onoff==0 ){
142424            db->flags &= ~aFlagOp[i].mask;
142425          }
142426          if( oldFlags!=db->flags ){
142427            sqlite3ExpirePreparedStatements(db);
142428          }
142429          if( pRes ){
142430            *pRes = (db->flags & aFlagOp[i].mask)!=0;
142431          }
142432          rc = SQLITE_OK;
142433          break;
142434        }
142435      }
142436      break;
142437    }
142438  }
142439  va_end(ap);
142440  return rc;
142441}
142442
142443
142444/*
142445** Return true if the buffer z[0..n-1] contains all spaces.
142446*/
142447static int allSpaces(const char *z, int n){
142448  while( n>0 && z[n-1]==' ' ){ n--; }
142449  return n==0;
142450}
142451
142452/*
142453** This is the default collating function named "BINARY" which is always
142454** available.
142455**
142456** If the padFlag argument is not NULL then space padding at the end
142457** of strings is ignored.  This implements the RTRIM collation.
142458*/
142459static int binCollFunc(
142460  void *padFlag,
142461  int nKey1, const void *pKey1,
142462  int nKey2, const void *pKey2
142463){
142464  int rc, n;
142465  n = nKey1<nKey2 ? nKey1 : nKey2;
142466  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
142467  ** strings byte by byte using the memcmp() function from the standard C
142468  ** library. */
142469  assert( pKey1 && pKey2 );
142470  rc = memcmp(pKey1, pKey2, n);
142471  if( rc==0 ){
142472    if( padFlag
142473     && allSpaces(((char*)pKey1)+n, nKey1-n)
142474     && allSpaces(((char*)pKey2)+n, nKey2-n)
142475    ){
142476      /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
142477      ** spaces at the end of either string do not change the result. In other
142478      ** words, strings will compare equal to one another as long as they
142479      ** differ only in the number of spaces at the end.
142480      */
142481    }else{
142482      rc = nKey1 - nKey2;
142483    }
142484  }
142485  return rc;
142486}
142487
142488/*
142489** Another built-in collating sequence: NOCASE.
142490**
142491** This collating sequence is intended to be used for "case independent
142492** comparison". SQLite's knowledge of upper and lower case equivalents
142493** extends only to the 26 characters used in the English language.
142494**
142495** At the moment there is only a UTF-8 implementation.
142496*/
142497static int nocaseCollatingFunc(
142498  void *NotUsed,
142499  int nKey1, const void *pKey1,
142500  int nKey2, const void *pKey2
142501){
142502  int r = sqlite3StrNICmp(
142503      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
142504  UNUSED_PARAMETER(NotUsed);
142505  if( 0==r ){
142506    r = nKey1-nKey2;
142507  }
142508  return r;
142509}
142510
142511/*
142512** Return the ROWID of the most recent insert
142513*/
142514SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
142515#ifdef SQLITE_ENABLE_API_ARMOR
142516  if( !sqlite3SafetyCheckOk(db) ){
142517    (void)SQLITE_MISUSE_BKPT;
142518    return 0;
142519  }
142520#endif
142521  return db->lastRowid;
142522}
142523
142524/*
142525** Set the value returned by the sqlite3_last_insert_rowid() API function.
142526*/
142527SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
142528#ifdef SQLITE_ENABLE_API_ARMOR
142529  if( !sqlite3SafetyCheckOk(db) ){
142530    (void)SQLITE_MISUSE_BKPT;
142531    return;
142532  }
142533#endif
142534  sqlite3_mutex_enter(db->mutex);
142535  db->lastRowid = iRowid;
142536  sqlite3_mutex_leave(db->mutex);
142537}
142538
142539/*
142540** Return the number of changes in the most recent call to sqlite3_exec().
142541*/
142542SQLITE_API int sqlite3_changes(sqlite3 *db){
142543#ifdef SQLITE_ENABLE_API_ARMOR
142544  if( !sqlite3SafetyCheckOk(db) ){
142545    (void)SQLITE_MISUSE_BKPT;
142546    return 0;
142547  }
142548#endif
142549  return db->nChange;
142550}
142551
142552/*
142553** Return the number of changes since the database handle was opened.
142554*/
142555SQLITE_API int sqlite3_total_changes(sqlite3 *db){
142556#ifdef SQLITE_ENABLE_API_ARMOR
142557  if( !sqlite3SafetyCheckOk(db) ){
142558    (void)SQLITE_MISUSE_BKPT;
142559    return 0;
142560  }
142561#endif
142562  return db->nTotalChange;
142563}
142564
142565/*
142566** Close all open savepoints. This function only manipulates fields of the
142567** database handle object, it does not close any savepoints that may be open
142568** at the b-tree/pager level.
142569*/
142570SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
142571  while( db->pSavepoint ){
142572    Savepoint *pTmp = db->pSavepoint;
142573    db->pSavepoint = pTmp->pNext;
142574    sqlite3DbFree(db, pTmp);
142575  }
142576  db->nSavepoint = 0;
142577  db->nStatement = 0;
142578  db->isTransactionSavepoint = 0;
142579}
142580
142581/*
142582** Invoke the destructor function associated with FuncDef p, if any. Except,
142583** if this is not the last copy of the function, do not invoke it. Multiple
142584** copies of a single function are created when create_function() is called
142585** with SQLITE_ANY as the encoding.
142586*/
142587static void functionDestroy(sqlite3 *db, FuncDef *p){
142588  FuncDestructor *pDestructor = p->u.pDestructor;
142589  if( pDestructor ){
142590    pDestructor->nRef--;
142591    if( pDestructor->nRef==0 ){
142592      pDestructor->xDestroy(pDestructor->pUserData);
142593      sqlite3DbFree(db, pDestructor);
142594    }
142595  }
142596}
142597
142598/*
142599** Disconnect all sqlite3_vtab objects that belong to database connection
142600** db. This is called when db is being closed.
142601*/
142602static void disconnectAllVtab(sqlite3 *db){
142603#ifndef SQLITE_OMIT_VIRTUALTABLE
142604  int i;
142605  HashElem *p;
142606  sqlite3BtreeEnterAll(db);
142607  for(i=0; i<db->nDb; i++){
142608    Schema *pSchema = db->aDb[i].pSchema;
142609    if( db->aDb[i].pSchema ){
142610      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
142611        Table *pTab = (Table *)sqliteHashData(p);
142612        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
142613      }
142614    }
142615  }
142616  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
142617    Module *pMod = (Module *)sqliteHashData(p);
142618    if( pMod->pEpoTab ){
142619      sqlite3VtabDisconnect(db, pMod->pEpoTab);
142620    }
142621  }
142622  sqlite3VtabUnlockList(db);
142623  sqlite3BtreeLeaveAll(db);
142624#else
142625  UNUSED_PARAMETER(db);
142626#endif
142627}
142628
142629/*
142630** Return TRUE if database connection db has unfinalized prepared
142631** statements or unfinished sqlite3_backup objects.
142632*/
142633static int connectionIsBusy(sqlite3 *db){
142634  int j;
142635  assert( sqlite3_mutex_held(db->mutex) );
142636  if( db->pVdbe ) return 1;
142637  for(j=0; j<db->nDb; j++){
142638    Btree *pBt = db->aDb[j].pBt;
142639    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
142640  }
142641  return 0;
142642}
142643
142644/*
142645** Close an existing SQLite database
142646*/
142647static int sqlite3Close(sqlite3 *db, int forceZombie){
142648  if( !db ){
142649    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
142650    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
142651    return SQLITE_OK;
142652  }
142653  if( !sqlite3SafetyCheckSickOrOk(db) ){
142654    return SQLITE_MISUSE_BKPT;
142655  }
142656  sqlite3_mutex_enter(db->mutex);
142657  if( db->mTrace & SQLITE_TRACE_CLOSE ){
142658    db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
142659  }
142660
142661  /* Force xDisconnect calls on all virtual tables */
142662  disconnectAllVtab(db);
142663
142664  /* If a transaction is open, the disconnectAllVtab() call above
142665  ** will not have called the xDisconnect() method on any virtual
142666  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
142667  ** call will do so. We need to do this before the check for active
142668  ** SQL statements below, as the v-table implementation may be storing
142669  ** some prepared statements internally.
142670  */
142671  sqlite3VtabRollback(db);
142672
142673  /* Legacy behavior (sqlite3_close() behavior) is to return
142674  ** SQLITE_BUSY if the connection can not be closed immediately.
142675  */
142676  if( !forceZombie && connectionIsBusy(db) ){
142677    sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
142678       "statements or unfinished backups");
142679    sqlite3_mutex_leave(db->mutex);
142680    return SQLITE_BUSY;
142681  }
142682
142683#ifdef SQLITE_ENABLE_SQLLOG
142684  if( sqlite3GlobalConfig.xSqllog ){
142685    /* Closing the handle. Fourth parameter is passed the value 2. */
142686    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
142687  }
142688#endif
142689
142690  /* Convert the connection into a zombie and then close it.
142691  */
142692  db->magic = SQLITE_MAGIC_ZOMBIE;
142693  sqlite3LeaveMutexAndCloseZombie(db);
142694  return SQLITE_OK;
142695}
142696
142697/*
142698** Two variations on the public interface for closing a database
142699** connection. The sqlite3_close() version returns SQLITE_BUSY and
142700** leaves the connection option if there are unfinalized prepared
142701** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
142702** version forces the connection to become a zombie if there are
142703** unclosed resources, and arranges for deallocation when the last
142704** prepare statement or sqlite3_backup closes.
142705*/
142706SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
142707SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
142708
142709
142710/*
142711** Close the mutex on database connection db.
142712**
142713** Furthermore, if database connection db is a zombie (meaning that there
142714** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
142715** every sqlite3_stmt has now been finalized and every sqlite3_backup has
142716** finished, then free all resources.
142717*/
142718SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
142719  HashElem *i;                    /* Hash table iterator */
142720  int j;
142721
142722  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
142723  ** or if the connection has not yet been closed by sqlite3_close_v2(),
142724  ** then just leave the mutex and return.
142725  */
142726  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
142727    sqlite3_mutex_leave(db->mutex);
142728    return;
142729  }
142730
142731  /* If we reach this point, it means that the database connection has
142732  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
142733  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
142734  ** go ahead and free all resources.
142735  */
142736
142737  /* If a transaction is open, roll it back. This also ensures that if
142738  ** any database schemas have been modified by an uncommitted transaction
142739  ** they are reset. And that the required b-tree mutex is held to make
142740  ** the pager rollback and schema reset an atomic operation. */
142741  sqlite3RollbackAll(db, SQLITE_OK);
142742
142743  /* Free any outstanding Savepoint structures. */
142744  sqlite3CloseSavepoints(db);
142745
142746  /* Close all database connections */
142747  for(j=0; j<db->nDb; j++){
142748    struct Db *pDb = &db->aDb[j];
142749    if( pDb->pBt ){
142750      sqlite3BtreeClose(pDb->pBt);
142751      pDb->pBt = 0;
142752      if( j!=1 ){
142753        pDb->pSchema = 0;
142754      }
142755    }
142756  }
142757  /* Clear the TEMP schema separately and last */
142758  if( db->aDb[1].pSchema ){
142759    sqlite3SchemaClear(db->aDb[1].pSchema);
142760  }
142761  sqlite3VtabUnlockList(db);
142762
142763  /* Free up the array of auxiliary databases */
142764  sqlite3CollapseDatabaseArray(db);
142765  assert( db->nDb<=2 );
142766  assert( db->aDb==db->aDbStatic );
142767
142768  /* Tell the code in notify.c that the connection no longer holds any
142769  ** locks and does not require any further unlock-notify callbacks.
142770  */
142771  sqlite3ConnectionClosed(db);
142772
142773  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
142774    FuncDef *pNext, *p;
142775    p = sqliteHashData(i);
142776    do{
142777      functionDestroy(db, p);
142778      pNext = p->pNext;
142779      sqlite3DbFree(db, p);
142780      p = pNext;
142781    }while( p );
142782  }
142783  sqlite3HashClear(&db->aFunc);
142784  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
142785    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
142786    /* Invoke any destructors registered for collation sequence user data. */
142787    for(j=0; j<3; j++){
142788      if( pColl[j].xDel ){
142789        pColl[j].xDel(pColl[j].pUser);
142790      }
142791    }
142792    sqlite3DbFree(db, pColl);
142793  }
142794  sqlite3HashClear(&db->aCollSeq);
142795#ifndef SQLITE_OMIT_VIRTUALTABLE
142796  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
142797    Module *pMod = (Module *)sqliteHashData(i);
142798    if( pMod->xDestroy ){
142799      pMod->xDestroy(pMod->pAux);
142800    }
142801    sqlite3VtabEponymousTableClear(db, pMod);
142802    sqlite3DbFree(db, pMod);
142803  }
142804  sqlite3HashClear(&db->aModule);
142805#endif
142806
142807  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
142808  sqlite3ValueFree(db->pErr);
142809  sqlite3CloseExtensions(db);
142810#if SQLITE_USER_AUTHENTICATION
142811  sqlite3_free(db->auth.zAuthUser);
142812  sqlite3_free(db->auth.zAuthPW);
142813#endif
142814
142815  db->magic = SQLITE_MAGIC_ERROR;
142816
142817  /* The temp-database schema is allocated differently from the other schema
142818  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
142819  ** So it needs to be freed here. Todo: Why not roll the temp schema into
142820  ** the same sqliteMalloc() as the one that allocates the database
142821  ** structure?
142822  */
142823  sqlite3DbFree(db, db->aDb[1].pSchema);
142824  sqlite3_mutex_leave(db->mutex);
142825  db->magic = SQLITE_MAGIC_CLOSED;
142826  sqlite3_mutex_free(db->mutex);
142827  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
142828  if( db->lookaside.bMalloced ){
142829    sqlite3_free(db->lookaside.pStart);
142830  }
142831  sqlite3_free(db);
142832}
142833
142834/*
142835** Rollback all database files.  If tripCode is not SQLITE_OK, then
142836** any write cursors are invalidated ("tripped" - as in "tripping a circuit
142837** breaker") and made to return tripCode if there are any further
142838** attempts to use that cursor.  Read cursors remain open and valid
142839** but are "saved" in case the table pages are moved around.
142840*/
142841SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
142842  int i;
142843  int inTrans = 0;
142844  int schemaChange;
142845  assert( sqlite3_mutex_held(db->mutex) );
142846  sqlite3BeginBenignMalloc();
142847
142848  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
142849  ** This is important in case the transaction being rolled back has
142850  ** modified the database schema. If the b-tree mutexes are not taken
142851  ** here, then another shared-cache connection might sneak in between
142852  ** the database rollback and schema reset, which can cause false
142853  ** corruption reports in some cases.  */
142854  sqlite3BtreeEnterAll(db);
142855  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
142856
142857  for(i=0; i<db->nDb; i++){
142858    Btree *p = db->aDb[i].pBt;
142859    if( p ){
142860      if( sqlite3BtreeIsInTrans(p) ){
142861        inTrans = 1;
142862      }
142863      sqlite3BtreeRollback(p, tripCode, !schemaChange);
142864    }
142865  }
142866  sqlite3VtabRollback(db);
142867  sqlite3EndBenignMalloc();
142868
142869  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
142870    sqlite3ExpirePreparedStatements(db);
142871    sqlite3ResetAllSchemasOfConnection(db);
142872  }
142873  sqlite3BtreeLeaveAll(db);
142874
142875  /* Any deferred constraint violations have now been resolved. */
142876  db->nDeferredCons = 0;
142877  db->nDeferredImmCons = 0;
142878  db->flags &= ~SQLITE_DeferFKs;
142879
142880  /* If one has been configured, invoke the rollback-hook callback */
142881  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
142882    db->xRollbackCallback(db->pRollbackArg);
142883  }
142884}
142885
142886/*
142887** Return a static string containing the name corresponding to the error code
142888** specified in the argument.
142889*/
142890#if defined(SQLITE_NEED_ERR_NAME)
142891SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
142892  const char *zName = 0;
142893  int i, origRc = rc;
142894  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
142895    switch( rc ){
142896      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
142897      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
142898      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
142899      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
142900      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
142901      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
142902      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
142903      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
142904      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
142905      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
142906      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
142907      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
142908      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
142909      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
142910      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
142911      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
142912      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
142913      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
142914      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
142915      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
142916      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
142917      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
142918      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
142919      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
142920      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
142921      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
142922      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
142923      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
142924      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
142925      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
142926      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
142927      case SQLITE_IOERR_CHECKRESERVEDLOCK:
142928                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
142929      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
142930      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
142931      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
142932      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
142933      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
142934      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
142935      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
142936      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
142937      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
142938      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
142939      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
142940      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
142941      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
142942      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
142943      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
142944      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
142945      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
142946      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
142947      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
142948      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
142949      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
142950      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
142951      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
142952      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
142953      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
142954      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
142955      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
142956      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
142957      case SQLITE_CONSTRAINT_FOREIGNKEY:
142958                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
142959      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
142960      case SQLITE_CONSTRAINT_PRIMARYKEY:
142961                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
142962      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
142963      case SQLITE_CONSTRAINT_COMMITHOOK:
142964                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
142965      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
142966      case SQLITE_CONSTRAINT_FUNCTION:
142967                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
142968      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
142969      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
142970      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
142971      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
142972      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
142973      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
142974      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
142975      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
142976      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
142977      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
142978      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
142979      case SQLITE_NOTICE_RECOVER_ROLLBACK:
142980                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
142981      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
142982      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
142983      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
142984    }
142985  }
142986  if( zName==0 ){
142987    static char zBuf[50];
142988    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
142989    zName = zBuf;
142990  }
142991  return zName;
142992}
142993#endif
142994
142995/*
142996** Return a static string that describes the kind of error specified in the
142997** argument.
142998*/
142999SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
143000  static const char* const aMsg[] = {
143001    /* SQLITE_OK          */ "not an error",
143002    /* SQLITE_ERROR       */ "SQL logic error",
143003    /* SQLITE_INTERNAL    */ 0,
143004    /* SQLITE_PERM        */ "access permission denied",
143005    /* SQLITE_ABORT       */ "query aborted",
143006    /* SQLITE_BUSY        */ "database is locked",
143007    /* SQLITE_LOCKED      */ "database table is locked",
143008    /* SQLITE_NOMEM       */ "out of memory",
143009    /* SQLITE_READONLY    */ "attempt to write a readonly database",
143010    /* SQLITE_INTERRUPT   */ "interrupted",
143011    /* SQLITE_IOERR       */ "disk I/O error",
143012    /* SQLITE_CORRUPT     */ "database disk image is malformed",
143013    /* SQLITE_NOTFOUND    */ "unknown operation",
143014    /* SQLITE_FULL        */ "database or disk is full",
143015    /* SQLITE_CANTOPEN    */ "unable to open database file",
143016    /* SQLITE_PROTOCOL    */ "locking protocol",
143017    /* SQLITE_EMPTY       */ 0,
143018    /* SQLITE_SCHEMA      */ "database schema has changed",
143019    /* SQLITE_TOOBIG      */ "string or blob too big",
143020    /* SQLITE_CONSTRAINT  */ "constraint failed",
143021    /* SQLITE_MISMATCH    */ "datatype mismatch",
143022    /* SQLITE_MISUSE      */ "bad parameter or other API misuse",
143023#ifdef SQLITE_DISABLE_LFS
143024    /* SQLITE_NOLFS       */ "large file support is disabled",
143025#else
143026    /* SQLITE_NOLFS       */ 0,
143027#endif
143028    /* SQLITE_AUTH        */ "authorization denied",
143029    /* SQLITE_FORMAT      */ 0,
143030    /* SQLITE_RANGE       */ "column index out of range",
143031    /* SQLITE_NOTADB      */ "file is not a database",
143032  };
143033  const char *zErr = "unknown error";
143034  switch( rc ){
143035    case SQLITE_ABORT_ROLLBACK: {
143036      zErr = "abort due to ROLLBACK";
143037      break;
143038    }
143039    default: {
143040      rc &= 0xff;
143041      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
143042        zErr = aMsg[rc];
143043      }
143044      break;
143045    }
143046  }
143047  return zErr;
143048}
143049
143050/*
143051** This routine implements a busy callback that sleeps and tries
143052** again until a timeout value is reached.  The timeout value is
143053** an integer number of milliseconds passed in as the first
143054** argument.
143055*/
143056static int sqliteDefaultBusyCallback(
143057 void *ptr,               /* Database connection */
143058 int count                /* Number of times table has been busy */
143059){
143060#if SQLITE_OS_WIN || HAVE_USLEEP
143061  static const u8 delays[] =
143062     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
143063  static const u8 totals[] =
143064     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
143065# define NDELAY ArraySize(delays)
143066  sqlite3 *db = (sqlite3 *)ptr;
143067  int timeout = db->busyTimeout;
143068  int delay, prior;
143069
143070  assert( count>=0 );
143071  if( count < NDELAY ){
143072    delay = delays[count];
143073    prior = totals[count];
143074  }else{
143075    delay = delays[NDELAY-1];
143076    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
143077  }
143078  if( prior + delay > timeout ){
143079    delay = timeout - prior;
143080    if( delay<=0 ) return 0;
143081  }
143082  sqlite3OsSleep(db->pVfs, delay*1000);
143083  return 1;
143084#else
143085  sqlite3 *db = (sqlite3 *)ptr;
143086  int timeout = ((sqlite3 *)ptr)->busyTimeout;
143087  if( (count+1)*1000 > timeout ){
143088    return 0;
143089  }
143090  sqlite3OsSleep(db->pVfs, 1000000);
143091  return 1;
143092#endif
143093}
143094
143095/*
143096** Invoke the given busy handler.
143097**
143098** This routine is called when an operation failed with a lock.
143099** If this routine returns non-zero, the lock is retried.  If it
143100** returns 0, the operation aborts with an SQLITE_BUSY error.
143101*/
143102SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
143103  int rc;
143104  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
143105  rc = p->xFunc(p->pArg, p->nBusy);
143106  if( rc==0 ){
143107    p->nBusy = -1;
143108  }else{
143109    p->nBusy++;
143110  }
143111  return rc;
143112}
143113
143114/*
143115** This routine sets the busy callback for an Sqlite database to the
143116** given callback function with the given argument.
143117*/
143118SQLITE_API int sqlite3_busy_handler(
143119  sqlite3 *db,
143120  int (*xBusy)(void*,int),
143121  void *pArg
143122){
143123#ifdef SQLITE_ENABLE_API_ARMOR
143124  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143125#endif
143126  sqlite3_mutex_enter(db->mutex);
143127  db->busyHandler.xFunc = xBusy;
143128  db->busyHandler.pArg = pArg;
143129  db->busyHandler.nBusy = 0;
143130  db->busyTimeout = 0;
143131  sqlite3_mutex_leave(db->mutex);
143132  return SQLITE_OK;
143133}
143134
143135#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
143136/*
143137** This routine sets the progress callback for an Sqlite database to the
143138** given callback function with the given argument. The progress callback will
143139** be invoked every nOps opcodes.
143140*/
143141SQLITE_API void sqlite3_progress_handler(
143142  sqlite3 *db,
143143  int nOps,
143144  int (*xProgress)(void*),
143145  void *pArg
143146){
143147#ifdef SQLITE_ENABLE_API_ARMOR
143148  if( !sqlite3SafetyCheckOk(db) ){
143149    (void)SQLITE_MISUSE_BKPT;
143150    return;
143151  }
143152#endif
143153  sqlite3_mutex_enter(db->mutex);
143154  if( nOps>0 ){
143155    db->xProgress = xProgress;
143156    db->nProgressOps = (unsigned)nOps;
143157    db->pProgressArg = pArg;
143158  }else{
143159    db->xProgress = 0;
143160    db->nProgressOps = 0;
143161    db->pProgressArg = 0;
143162  }
143163  sqlite3_mutex_leave(db->mutex);
143164}
143165#endif
143166
143167
143168/*
143169** This routine installs a default busy handler that waits for the
143170** specified number of milliseconds before returning 0.
143171*/
143172SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
143173#ifdef SQLITE_ENABLE_API_ARMOR
143174  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143175#endif
143176  if( ms>0 ){
143177    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
143178    db->busyTimeout = ms;
143179  }else{
143180    sqlite3_busy_handler(db, 0, 0);
143181  }
143182  return SQLITE_OK;
143183}
143184
143185/*
143186** Cause any pending operation to stop at its earliest opportunity.
143187*/
143188SQLITE_API void sqlite3_interrupt(sqlite3 *db){
143189#ifdef SQLITE_ENABLE_API_ARMOR
143190  if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
143191    (void)SQLITE_MISUSE_BKPT;
143192    return;
143193  }
143194#endif
143195  db->u1.isInterrupted = 1;
143196}
143197
143198
143199/*
143200** This function is exactly the same as sqlite3_create_function(), except
143201** that it is designed to be called by internal code. The difference is
143202** that if a malloc() fails in sqlite3_create_function(), an error code
143203** is returned and the mallocFailed flag cleared.
143204*/
143205SQLITE_PRIVATE int sqlite3CreateFunc(
143206  sqlite3 *db,
143207  const char *zFunctionName,
143208  int nArg,
143209  int enc,
143210  void *pUserData,
143211  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143212  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143213  void (*xFinal)(sqlite3_context*),
143214  FuncDestructor *pDestructor
143215){
143216  FuncDef *p;
143217  int nName;
143218  int extraFlags;
143219
143220  assert( sqlite3_mutex_held(db->mutex) );
143221  if( zFunctionName==0 ||
143222      (xSFunc && (xFinal || xStep)) ||
143223      (!xSFunc && (xFinal && !xStep)) ||
143224      (!xSFunc && (!xFinal && xStep)) ||
143225      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
143226      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
143227    return SQLITE_MISUSE_BKPT;
143228  }
143229
143230  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
143231  extraFlags = enc &  SQLITE_DETERMINISTIC;
143232  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
143233
143234#ifndef SQLITE_OMIT_UTF16
143235  /* If SQLITE_UTF16 is specified as the encoding type, transform this
143236  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
143237  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
143238  **
143239  ** If SQLITE_ANY is specified, add three versions of the function
143240  ** to the hash table.
143241  */
143242  if( enc==SQLITE_UTF16 ){
143243    enc = SQLITE_UTF16NATIVE;
143244  }else if( enc==SQLITE_ANY ){
143245    int rc;
143246    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
143247         pUserData, xSFunc, xStep, xFinal, pDestructor);
143248    if( rc==SQLITE_OK ){
143249      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
143250          pUserData, xSFunc, xStep, xFinal, pDestructor);
143251    }
143252    if( rc!=SQLITE_OK ){
143253      return rc;
143254    }
143255    enc = SQLITE_UTF16BE;
143256  }
143257#else
143258  enc = SQLITE_UTF8;
143259#endif
143260
143261  /* Check if an existing function is being overridden or deleted. If so,
143262  ** and there are active VMs, then return SQLITE_BUSY. If a function
143263  ** is being overridden/deleted but there are no active VMs, allow the
143264  ** operation to continue but invalidate all precompiled statements.
143265  */
143266  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
143267  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
143268    if( db->nVdbeActive ){
143269      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
143270        "unable to delete/modify user-function due to active statements");
143271      assert( !db->mallocFailed );
143272      return SQLITE_BUSY;
143273    }else{
143274      sqlite3ExpirePreparedStatements(db);
143275    }
143276  }
143277
143278  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
143279  assert(p || db->mallocFailed);
143280  if( !p ){
143281    return SQLITE_NOMEM_BKPT;
143282  }
143283
143284  /* If an older version of the function with a configured destructor is
143285  ** being replaced invoke the destructor function here. */
143286  functionDestroy(db, p);
143287
143288  if( pDestructor ){
143289    pDestructor->nRef++;
143290  }
143291  p->u.pDestructor = pDestructor;
143292  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
143293  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
143294  p->xSFunc = xSFunc ? xSFunc : xStep;
143295  p->xFinalize = xFinal;
143296  p->pUserData = pUserData;
143297  p->nArg = (u16)nArg;
143298  return SQLITE_OK;
143299}
143300
143301/*
143302** Create new user functions.
143303*/
143304SQLITE_API int sqlite3_create_function(
143305  sqlite3 *db,
143306  const char *zFunc,
143307  int nArg,
143308  int enc,
143309  void *p,
143310  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143311  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143312  void (*xFinal)(sqlite3_context*)
143313){
143314  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
143315                                    xFinal, 0);
143316}
143317
143318SQLITE_API int sqlite3_create_function_v2(
143319  sqlite3 *db,
143320  const char *zFunc,
143321  int nArg,
143322  int enc,
143323  void *p,
143324  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
143325  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
143326  void (*xFinal)(sqlite3_context*),
143327  void (*xDestroy)(void *)
143328){
143329  int rc = SQLITE_ERROR;
143330  FuncDestructor *pArg = 0;
143331
143332#ifdef SQLITE_ENABLE_API_ARMOR
143333  if( !sqlite3SafetyCheckOk(db) ){
143334    return SQLITE_MISUSE_BKPT;
143335  }
143336#endif
143337  sqlite3_mutex_enter(db->mutex);
143338  if( xDestroy ){
143339    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
143340    if( !pArg ){
143341      xDestroy(p);
143342      goto out;
143343    }
143344    pArg->xDestroy = xDestroy;
143345    pArg->pUserData = p;
143346  }
143347  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
143348  if( pArg && pArg->nRef==0 ){
143349    assert( rc!=SQLITE_OK );
143350    xDestroy(p);
143351    sqlite3DbFree(db, pArg);
143352  }
143353
143354 out:
143355  rc = sqlite3ApiExit(db, rc);
143356  sqlite3_mutex_leave(db->mutex);
143357  return rc;
143358}
143359
143360#ifndef SQLITE_OMIT_UTF16
143361SQLITE_API int sqlite3_create_function16(
143362  sqlite3 *db,
143363  const void *zFunctionName,
143364  int nArg,
143365  int eTextRep,
143366  void *p,
143367  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
143368  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
143369  void (*xFinal)(sqlite3_context*)
143370){
143371  int rc;
143372  char *zFunc8;
143373
143374#ifdef SQLITE_ENABLE_API_ARMOR
143375  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
143376#endif
143377  sqlite3_mutex_enter(db->mutex);
143378  assert( !db->mallocFailed );
143379  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
143380  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
143381  sqlite3DbFree(db, zFunc8);
143382  rc = sqlite3ApiExit(db, rc);
143383  sqlite3_mutex_leave(db->mutex);
143384  return rc;
143385}
143386#endif
143387
143388
143389/*
143390** Declare that a function has been overloaded by a virtual table.
143391**
143392** If the function already exists as a regular global function, then
143393** this routine is a no-op.  If the function does not exist, then create
143394** a new one that always throws a run-time error.
143395**
143396** When virtual tables intend to provide an overloaded function, they
143397** should call this routine to make sure the global function exists.
143398** A global function must exist in order for name resolution to work
143399** properly.
143400*/
143401SQLITE_API int sqlite3_overload_function(
143402  sqlite3 *db,
143403  const char *zName,
143404  int nArg
143405){
143406  int rc = SQLITE_OK;
143407
143408#ifdef SQLITE_ENABLE_API_ARMOR
143409  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
143410    return SQLITE_MISUSE_BKPT;
143411  }
143412#endif
143413  sqlite3_mutex_enter(db->mutex);
143414  if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
143415    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
143416                           0, sqlite3InvalidFunction, 0, 0, 0);
143417  }
143418  rc = sqlite3ApiExit(db, rc);
143419  sqlite3_mutex_leave(db->mutex);
143420  return rc;
143421}
143422
143423#ifndef SQLITE_OMIT_TRACE
143424/*
143425** Register a trace function.  The pArg from the previously registered trace
143426** is returned.
143427**
143428** A NULL trace function means that no tracing is executes.  A non-NULL
143429** trace is a pointer to a function that is invoked at the start of each
143430** SQL statement.
143431*/
143432#ifndef SQLITE_OMIT_DEPRECATED
143433SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
143434  void *pOld;
143435
143436#ifdef SQLITE_ENABLE_API_ARMOR
143437  if( !sqlite3SafetyCheckOk(db) ){
143438    (void)SQLITE_MISUSE_BKPT;
143439    return 0;
143440  }
143441#endif
143442  sqlite3_mutex_enter(db->mutex);
143443  pOld = db->pTraceArg;
143444  db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
143445  db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
143446  db->pTraceArg = pArg;
143447  sqlite3_mutex_leave(db->mutex);
143448  return pOld;
143449}
143450#endif /* SQLITE_OMIT_DEPRECATED */
143451
143452/* Register a trace callback using the version-2 interface.
143453*/
143454SQLITE_API int sqlite3_trace_v2(
143455  sqlite3 *db,                               /* Trace this connection */
143456  unsigned mTrace,                           /* Mask of events to be traced */
143457  int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
143458  void *pArg                                 /* Context */
143459){
143460#ifdef SQLITE_ENABLE_API_ARMOR
143461  if( !sqlite3SafetyCheckOk(db) ){
143462    return SQLITE_MISUSE_BKPT;
143463  }
143464#endif
143465  sqlite3_mutex_enter(db->mutex);
143466  if( mTrace==0 ) xTrace = 0;
143467  if( xTrace==0 ) mTrace = 0;
143468  db->mTrace = mTrace;
143469  db->xTrace = xTrace;
143470  db->pTraceArg = pArg;
143471  sqlite3_mutex_leave(db->mutex);
143472  return SQLITE_OK;
143473}
143474
143475#ifndef SQLITE_OMIT_DEPRECATED
143476/*
143477** Register a profile function.  The pArg from the previously registered
143478** profile function is returned.
143479**
143480** A NULL profile function means that no profiling is executes.  A non-NULL
143481** profile is a pointer to a function that is invoked at the conclusion of
143482** each SQL statement that is run.
143483*/
143484SQLITE_API void *sqlite3_profile(
143485  sqlite3 *db,
143486  void (*xProfile)(void*,const char*,sqlite_uint64),
143487  void *pArg
143488){
143489  void *pOld;
143490
143491#ifdef SQLITE_ENABLE_API_ARMOR
143492  if( !sqlite3SafetyCheckOk(db) ){
143493    (void)SQLITE_MISUSE_BKPT;
143494    return 0;
143495  }
143496#endif
143497  sqlite3_mutex_enter(db->mutex);
143498  pOld = db->pProfileArg;
143499  db->xProfile = xProfile;
143500  db->pProfileArg = pArg;
143501  sqlite3_mutex_leave(db->mutex);
143502  return pOld;
143503}
143504#endif /* SQLITE_OMIT_DEPRECATED */
143505#endif /* SQLITE_OMIT_TRACE */
143506
143507/*
143508** Register a function to be invoked when a transaction commits.
143509** If the invoked function returns non-zero, then the commit becomes a
143510** rollback.
143511*/
143512SQLITE_API void *sqlite3_commit_hook(
143513  sqlite3 *db,              /* Attach the hook to this database */
143514  int (*xCallback)(void*),  /* Function to invoke on each commit */
143515  void *pArg                /* Argument to the function */
143516){
143517  void *pOld;
143518
143519#ifdef SQLITE_ENABLE_API_ARMOR
143520  if( !sqlite3SafetyCheckOk(db) ){
143521    (void)SQLITE_MISUSE_BKPT;
143522    return 0;
143523  }
143524#endif
143525  sqlite3_mutex_enter(db->mutex);
143526  pOld = db->pCommitArg;
143527  db->xCommitCallback = xCallback;
143528  db->pCommitArg = pArg;
143529  sqlite3_mutex_leave(db->mutex);
143530  return pOld;
143531}
143532
143533/*
143534** Register a callback to be invoked each time a row is updated,
143535** inserted or deleted using this database connection.
143536*/
143537SQLITE_API void *sqlite3_update_hook(
143538  sqlite3 *db,              /* Attach the hook to this database */
143539  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
143540  void *pArg                /* Argument to the function */
143541){
143542  void *pRet;
143543
143544#ifdef SQLITE_ENABLE_API_ARMOR
143545  if( !sqlite3SafetyCheckOk(db) ){
143546    (void)SQLITE_MISUSE_BKPT;
143547    return 0;
143548  }
143549#endif
143550  sqlite3_mutex_enter(db->mutex);
143551  pRet = db->pUpdateArg;
143552  db->xUpdateCallback = xCallback;
143553  db->pUpdateArg = pArg;
143554  sqlite3_mutex_leave(db->mutex);
143555  return pRet;
143556}
143557
143558/*
143559** Register a callback to be invoked each time a transaction is rolled
143560** back by this database connection.
143561*/
143562SQLITE_API void *sqlite3_rollback_hook(
143563  sqlite3 *db,              /* Attach the hook to this database */
143564  void (*xCallback)(void*), /* Callback function */
143565  void *pArg                /* Argument to the function */
143566){
143567  void *pRet;
143568
143569#ifdef SQLITE_ENABLE_API_ARMOR
143570  if( !sqlite3SafetyCheckOk(db) ){
143571    (void)SQLITE_MISUSE_BKPT;
143572    return 0;
143573  }
143574#endif
143575  sqlite3_mutex_enter(db->mutex);
143576  pRet = db->pRollbackArg;
143577  db->xRollbackCallback = xCallback;
143578  db->pRollbackArg = pArg;
143579  sqlite3_mutex_leave(db->mutex);
143580  return pRet;
143581}
143582
143583#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
143584/*
143585** Register a callback to be invoked each time a row is updated,
143586** inserted or deleted using this database connection.
143587*/
143588SQLITE_API void *sqlite3_preupdate_hook(
143589  sqlite3 *db,              /* Attach the hook to this database */
143590  void(*xCallback)(         /* Callback function */
143591    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
143592  void *pArg                /* First callback argument */
143593){
143594  void *pRet;
143595  sqlite3_mutex_enter(db->mutex);
143596  pRet = db->pPreUpdateArg;
143597  db->xPreUpdateCallback = xCallback;
143598  db->pPreUpdateArg = pArg;
143599  sqlite3_mutex_leave(db->mutex);
143600  return pRet;
143601}
143602#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
143603
143604#ifndef SQLITE_OMIT_WAL
143605/*
143606** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
143607** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
143608** is greater than sqlite3.pWalArg cast to an integer (the value configured by
143609** wal_autocheckpoint()).
143610*/
143611SQLITE_PRIVATE int sqlite3WalDefaultHook(
143612  void *pClientData,     /* Argument */
143613  sqlite3 *db,           /* Connection */
143614  const char *zDb,       /* Database */
143615  int nFrame             /* Size of WAL */
143616){
143617  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
143618    sqlite3BeginBenignMalloc();
143619    sqlite3_wal_checkpoint(db, zDb);
143620    sqlite3EndBenignMalloc();
143621  }
143622  return SQLITE_OK;
143623}
143624#endif /* SQLITE_OMIT_WAL */
143625
143626/*
143627** Configure an sqlite3_wal_hook() callback to automatically checkpoint
143628** a database after committing a transaction if there are nFrame or
143629** more frames in the log file. Passing zero or a negative value as the
143630** nFrame parameter disables automatic checkpoints entirely.
143631**
143632** The callback registered by this function replaces any existing callback
143633** registered using sqlite3_wal_hook(). Likewise, registering a callback
143634** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
143635** configured by this function.
143636*/
143637SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
143638#ifdef SQLITE_OMIT_WAL
143639  UNUSED_PARAMETER(db);
143640  UNUSED_PARAMETER(nFrame);
143641#else
143642#ifdef SQLITE_ENABLE_API_ARMOR
143643  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143644#endif
143645  if( nFrame>0 ){
143646    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
143647  }else{
143648    sqlite3_wal_hook(db, 0, 0);
143649  }
143650#endif
143651  return SQLITE_OK;
143652}
143653
143654/*
143655** Register a callback to be invoked each time a transaction is written
143656** into the write-ahead-log by this database connection.
143657*/
143658SQLITE_API void *sqlite3_wal_hook(
143659  sqlite3 *db,                    /* Attach the hook to this db handle */
143660  int(*xCallback)(void *, sqlite3*, const char*, int),
143661  void *pArg                      /* First argument passed to xCallback() */
143662){
143663#ifndef SQLITE_OMIT_WAL
143664  void *pRet;
143665#ifdef SQLITE_ENABLE_API_ARMOR
143666  if( !sqlite3SafetyCheckOk(db) ){
143667    (void)SQLITE_MISUSE_BKPT;
143668    return 0;
143669  }
143670#endif
143671  sqlite3_mutex_enter(db->mutex);
143672  pRet = db->pWalArg;
143673  db->xWalCallback = xCallback;
143674  db->pWalArg = pArg;
143675  sqlite3_mutex_leave(db->mutex);
143676  return pRet;
143677#else
143678  return 0;
143679#endif
143680}
143681
143682/*
143683** Checkpoint database zDb.
143684*/
143685SQLITE_API int sqlite3_wal_checkpoint_v2(
143686  sqlite3 *db,                    /* Database handle */
143687  const char *zDb,                /* Name of attached database (or NULL) */
143688  int eMode,                      /* SQLITE_CHECKPOINT_* value */
143689  int *pnLog,                     /* OUT: Size of WAL log in frames */
143690  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
143691){
143692#ifdef SQLITE_OMIT_WAL
143693  return SQLITE_OK;
143694#else
143695  int rc;                         /* Return code */
143696  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
143697
143698#ifdef SQLITE_ENABLE_API_ARMOR
143699  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
143700#endif
143701
143702  /* Initialize the output variables to -1 in case an error occurs. */
143703  if( pnLog ) *pnLog = -1;
143704  if( pnCkpt ) *pnCkpt = -1;
143705
143706  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
143707  assert( SQLITE_CHECKPOINT_FULL==1 );
143708  assert( SQLITE_CHECKPOINT_RESTART==2 );
143709  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
143710  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
143711    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
143712    ** mode: */
143713    return SQLITE_MISUSE;
143714  }
143715
143716  sqlite3_mutex_enter(db->mutex);
143717  if( zDb && zDb[0] ){
143718    iDb = sqlite3FindDbName(db, zDb);
143719  }
143720  if( iDb<0 ){
143721    rc = SQLITE_ERROR;
143722    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
143723  }else{
143724    db->busyHandler.nBusy = 0;
143725    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
143726    sqlite3Error(db, rc);
143727  }
143728  rc = sqlite3ApiExit(db, rc);
143729
143730  /* If there are no active statements, clear the interrupt flag at this
143731  ** point.  */
143732  if( db->nVdbeActive==0 ){
143733    db->u1.isInterrupted = 0;
143734  }
143735
143736  sqlite3_mutex_leave(db->mutex);
143737  return rc;
143738#endif
143739}
143740
143741
143742/*
143743** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
143744** to contains a zero-length string, all attached databases are
143745** checkpointed.
143746*/
143747SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
143748  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
143749  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
143750  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
143751}
143752
143753#ifndef SQLITE_OMIT_WAL
143754/*
143755** Run a checkpoint on database iDb. This is a no-op if database iDb is
143756** not currently open in WAL mode.
143757**
143758** If a transaction is open on the database being checkpointed, this
143759** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
143760** an error occurs while running the checkpoint, an SQLite error code is
143761** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
143762**
143763** The mutex on database handle db should be held by the caller. The mutex
143764** associated with the specific b-tree being checkpointed is taken by
143765** this function while the checkpoint is running.
143766**
143767** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
143768** checkpointed. If an error is encountered it is returned immediately -
143769** no attempt is made to checkpoint any remaining databases.
143770**
143771** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
143772*/
143773SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
143774  int rc = SQLITE_OK;             /* Return code */
143775  int i;                          /* Used to iterate through attached dbs */
143776  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
143777
143778  assert( sqlite3_mutex_held(db->mutex) );
143779  assert( !pnLog || *pnLog==-1 );
143780  assert( !pnCkpt || *pnCkpt==-1 );
143781
143782  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
143783    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
143784      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
143785      pnLog = 0;
143786      pnCkpt = 0;
143787      if( rc==SQLITE_BUSY ){
143788        bBusy = 1;
143789        rc = SQLITE_OK;
143790      }
143791    }
143792  }
143793
143794  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
143795}
143796#endif /* SQLITE_OMIT_WAL */
143797
143798/*
143799** This function returns true if main-memory should be used instead of
143800** a temporary file for transient pager files and statement journals.
143801** The value returned depends on the value of db->temp_store (runtime
143802** parameter) and the compile time value of SQLITE_TEMP_STORE. The
143803** following table describes the relationship between these two values
143804** and this functions return value.
143805**
143806**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
143807**   -----------------     --------------     ------------------------------
143808**   0                     any                file      (return 0)
143809**   1                     1                  file      (return 0)
143810**   1                     2                  memory    (return 1)
143811**   1                     0                  file      (return 0)
143812**   2                     1                  file      (return 0)
143813**   2                     2                  memory    (return 1)
143814**   2                     0                  memory    (return 1)
143815**   3                     any                memory    (return 1)
143816*/
143817SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
143818#if SQLITE_TEMP_STORE==1
143819  return ( db->temp_store==2 );
143820#endif
143821#if SQLITE_TEMP_STORE==2
143822  return ( db->temp_store!=1 );
143823#endif
143824#if SQLITE_TEMP_STORE==3
143825  UNUSED_PARAMETER(db);
143826  return 1;
143827#endif
143828#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
143829  UNUSED_PARAMETER(db);
143830  return 0;
143831#endif
143832}
143833
143834/*
143835** Return UTF-8 encoded English language explanation of the most recent
143836** error.
143837*/
143838SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
143839  const char *z;
143840  if( !db ){
143841    return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
143842  }
143843  if( !sqlite3SafetyCheckSickOrOk(db) ){
143844    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
143845  }
143846  sqlite3_mutex_enter(db->mutex);
143847  if( db->mallocFailed ){
143848    z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
143849  }else{
143850    testcase( db->pErr==0 );
143851    z = (char*)sqlite3_value_text(db->pErr);
143852    assert( !db->mallocFailed );
143853    if( z==0 ){
143854      z = sqlite3ErrStr(db->errCode);
143855    }
143856  }
143857  sqlite3_mutex_leave(db->mutex);
143858  return z;
143859}
143860
143861#ifndef SQLITE_OMIT_UTF16
143862/*
143863** Return UTF-16 encoded English language explanation of the most recent
143864** error.
143865*/
143866SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
143867  static const u16 outOfMem[] = {
143868    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
143869  };
143870  static const u16 misuse[] = {
143871    'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
143872    'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
143873    'm', 'i', 's', 'u', 's', 'e', 0
143874  };
143875
143876  const void *z;
143877  if( !db ){
143878    return (void *)outOfMem;
143879  }
143880  if( !sqlite3SafetyCheckSickOrOk(db) ){
143881    return (void *)misuse;
143882  }
143883  sqlite3_mutex_enter(db->mutex);
143884  if( db->mallocFailed ){
143885    z = (void *)outOfMem;
143886  }else{
143887    z = sqlite3_value_text16(db->pErr);
143888    if( z==0 ){
143889      sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
143890      z = sqlite3_value_text16(db->pErr);
143891    }
143892    /* A malloc() may have failed within the call to sqlite3_value_text16()
143893    ** above. If this is the case, then the db->mallocFailed flag needs to
143894    ** be cleared before returning. Do this directly, instead of via
143895    ** sqlite3ApiExit(), to avoid setting the database handle error message.
143896    */
143897    sqlite3OomClear(db);
143898  }
143899  sqlite3_mutex_leave(db->mutex);
143900  return z;
143901}
143902#endif /* SQLITE_OMIT_UTF16 */
143903
143904/*
143905** Return the most recent error code generated by an SQLite routine. If NULL is
143906** passed to this function, we assume a malloc() failed during sqlite3_open().
143907*/
143908SQLITE_API int sqlite3_errcode(sqlite3 *db){
143909  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
143910    return SQLITE_MISUSE_BKPT;
143911  }
143912  if( !db || db->mallocFailed ){
143913    return SQLITE_NOMEM_BKPT;
143914  }
143915  return db->errCode & db->errMask;
143916}
143917SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
143918  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
143919    return SQLITE_MISUSE_BKPT;
143920  }
143921  if( !db || db->mallocFailed ){
143922    return SQLITE_NOMEM_BKPT;
143923  }
143924  return db->errCode;
143925}
143926SQLITE_API int sqlite3_system_errno(sqlite3 *db){
143927  return db ? db->iSysErrno : 0;
143928}
143929
143930/*
143931** Return a string that describes the kind of error specified in the
143932** argument.  For now, this simply calls the internal sqlite3ErrStr()
143933** function.
143934*/
143935SQLITE_API const char *sqlite3_errstr(int rc){
143936  return sqlite3ErrStr(rc);
143937}
143938
143939/*
143940** Create a new collating function for database "db".  The name is zName
143941** and the encoding is enc.
143942*/
143943static int createCollation(
143944  sqlite3* db,
143945  const char *zName,
143946  u8 enc,
143947  void* pCtx,
143948  int(*xCompare)(void*,int,const void*,int,const void*),
143949  void(*xDel)(void*)
143950){
143951  CollSeq *pColl;
143952  int enc2;
143953
143954  assert( sqlite3_mutex_held(db->mutex) );
143955
143956  /* If SQLITE_UTF16 is specified as the encoding type, transform this
143957  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
143958  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
143959  */
143960  enc2 = enc;
143961  testcase( enc2==SQLITE_UTF16 );
143962  testcase( enc2==SQLITE_UTF16_ALIGNED );
143963  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
143964    enc2 = SQLITE_UTF16NATIVE;
143965  }
143966  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
143967    return SQLITE_MISUSE_BKPT;
143968  }
143969
143970  /* Check if this call is removing or replacing an existing collation
143971  ** sequence. If so, and there are active VMs, return busy. If there
143972  ** are no active VMs, invalidate any pre-compiled statements.
143973  */
143974  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
143975  if( pColl && pColl->xCmp ){
143976    if( db->nVdbeActive ){
143977      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
143978        "unable to delete/modify collation sequence due to active statements");
143979      return SQLITE_BUSY;
143980    }
143981    sqlite3ExpirePreparedStatements(db);
143982
143983    /* If collation sequence pColl was created directly by a call to
143984    ** sqlite3_create_collation, and not generated by synthCollSeq(),
143985    ** then any copies made by synthCollSeq() need to be invalidated.
143986    ** Also, collation destructor - CollSeq.xDel() - function may need
143987    ** to be called.
143988    */
143989    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
143990      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
143991      int j;
143992      for(j=0; j<3; j++){
143993        CollSeq *p = &aColl[j];
143994        if( p->enc==pColl->enc ){
143995          if( p->xDel ){
143996            p->xDel(p->pUser);
143997          }
143998          p->xCmp = 0;
143999        }
144000      }
144001    }
144002  }
144003
144004  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
144005  if( pColl==0 ) return SQLITE_NOMEM_BKPT;
144006  pColl->xCmp = xCompare;
144007  pColl->pUser = pCtx;
144008  pColl->xDel = xDel;
144009  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
144010  sqlite3Error(db, SQLITE_OK);
144011  return SQLITE_OK;
144012}
144013
144014
144015/*
144016** This array defines hard upper bounds on limit values.  The
144017** initializer must be kept in sync with the SQLITE_LIMIT_*
144018** #defines in sqlite3.h.
144019*/
144020static const int aHardLimit[] = {
144021  SQLITE_MAX_LENGTH,
144022  SQLITE_MAX_SQL_LENGTH,
144023  SQLITE_MAX_COLUMN,
144024  SQLITE_MAX_EXPR_DEPTH,
144025  SQLITE_MAX_COMPOUND_SELECT,
144026  SQLITE_MAX_VDBE_OP,
144027  SQLITE_MAX_FUNCTION_ARG,
144028  SQLITE_MAX_ATTACHED,
144029  SQLITE_MAX_LIKE_PATTERN_LENGTH,
144030  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
144031  SQLITE_MAX_TRIGGER_DEPTH,
144032  SQLITE_MAX_WORKER_THREADS,
144033};
144034
144035/*
144036** Make sure the hard limits are set to reasonable values
144037*/
144038#if SQLITE_MAX_LENGTH<100
144039# error SQLITE_MAX_LENGTH must be at least 100
144040#endif
144041#if SQLITE_MAX_SQL_LENGTH<100
144042# error SQLITE_MAX_SQL_LENGTH must be at least 100
144043#endif
144044#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
144045# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
144046#endif
144047#if SQLITE_MAX_COMPOUND_SELECT<2
144048# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
144049#endif
144050#if SQLITE_MAX_VDBE_OP<40
144051# error SQLITE_MAX_VDBE_OP must be at least 40
144052#endif
144053#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
144054# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
144055#endif
144056#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
144057# error SQLITE_MAX_ATTACHED must be between 0 and 125
144058#endif
144059#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
144060# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
144061#endif
144062#if SQLITE_MAX_COLUMN>32767
144063# error SQLITE_MAX_COLUMN must not exceed 32767
144064#endif
144065#if SQLITE_MAX_TRIGGER_DEPTH<1
144066# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
144067#endif
144068#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
144069# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
144070#endif
144071
144072
144073/*
144074** Change the value of a limit.  Report the old value.
144075** If an invalid limit index is supplied, report -1.
144076** Make no changes but still report the old value if the
144077** new limit is negative.
144078**
144079** A new lower limit does not shrink existing constructs.
144080** It merely prevents new constructs that exceed the limit
144081** from forming.
144082*/
144083SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
144084  int oldLimit;
144085
144086#ifdef SQLITE_ENABLE_API_ARMOR
144087  if( !sqlite3SafetyCheckOk(db) ){
144088    (void)SQLITE_MISUSE_BKPT;
144089    return -1;
144090  }
144091#endif
144092
144093  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
144094  ** there is a hard upper bound set at compile-time by a C preprocessor
144095  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
144096  ** "_MAX_".)
144097  */
144098  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
144099  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
144100  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
144101  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
144102  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
144103  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
144104  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
144105  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
144106  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
144107                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
144108  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
144109  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
144110  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
144111  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
144112
144113
144114  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
144115    return -1;
144116  }
144117  oldLimit = db->aLimit[limitId];
144118  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
144119    if( newLimit>aHardLimit[limitId] ){
144120      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
144121    }
144122    db->aLimit[limitId] = newLimit;
144123  }
144124  return oldLimit;                     /* IMP: R-53341-35419 */
144125}
144126
144127/*
144128** This function is used to parse both URIs and non-URI filenames passed by the
144129** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
144130** URIs specified as part of ATTACH statements.
144131**
144132** The first argument to this function is the name of the VFS to use (or
144133** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
144134** query parameter. The second argument contains the URI (or non-URI filename)
144135** itself. When this function is called the *pFlags variable should contain
144136** the default flags to open the database handle with. The value stored in
144137** *pFlags may be updated before returning if the URI filename contains
144138** "cache=xxx" or "mode=xxx" query parameters.
144139**
144140** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
144141** the VFS that should be used to open the database file. *pzFile is set to
144142** point to a buffer containing the name of the file to open. It is the
144143** responsibility of the caller to eventually call sqlite3_free() to release
144144** this buffer.
144145**
144146** If an error occurs, then an SQLite error code is returned and *pzErrMsg
144147** may be set to point to a buffer containing an English language error
144148** message. It is the responsibility of the caller to eventually release
144149** this buffer by calling sqlite3_free().
144150*/
144151SQLITE_PRIVATE int sqlite3ParseUri(
144152  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
144153  const char *zUri,               /* Nul-terminated URI to parse */
144154  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
144155  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
144156  char **pzFile,                  /* OUT: Filename component of URI */
144157  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
144158){
144159  int rc = SQLITE_OK;
144160  unsigned int flags = *pFlags;
144161  const char *zVfs = zDefaultVfs;
144162  char *zFile;
144163  char c;
144164  int nUri = sqlite3Strlen30(zUri);
144165
144166  assert( *pzErrMsg==0 );
144167
144168  if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
144169            || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
144170   && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
144171  ){
144172    char *zOpt;
144173    int eState;                   /* Parser state when parsing URI */
144174    int iIn;                      /* Input character index */
144175    int iOut = 0;                 /* Output character index */
144176    u64 nByte = nUri+2;           /* Bytes of space to allocate */
144177
144178    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
144179    ** method that there may be extra parameters following the file-name.  */
144180    flags |= SQLITE_OPEN_URI;
144181
144182    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
144183    zFile = sqlite3_malloc64(nByte);
144184    if( !zFile ) return SQLITE_NOMEM_BKPT;
144185
144186    iIn = 5;
144187#ifdef SQLITE_ALLOW_URI_AUTHORITY
144188    if( strncmp(zUri+5, "///", 3)==0 ){
144189      iIn = 7;
144190      /* The following condition causes URIs with five leading / characters
144191      ** like file://///host/path to be converted into UNCs like //host/path.
144192      ** The correct URI for that UNC has only two or four leading / characters
144193      ** file://host/path or file:////host/path.  But 5 leading slashes is a
144194      ** common error, we are told, so we handle it as a special case. */
144195      if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
144196    }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
144197      iIn = 16;
144198    }
144199#else
144200    /* Discard the scheme and authority segments of the URI. */
144201    if( zUri[5]=='/' && zUri[6]=='/' ){
144202      iIn = 7;
144203      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
144204      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
144205        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
144206            iIn-7, &zUri[7]);
144207        rc = SQLITE_ERROR;
144208        goto parse_uri_out;
144209      }
144210    }
144211#endif
144212
144213    /* Copy the filename and any query parameters into the zFile buffer.
144214    ** Decode %HH escape codes along the way.
144215    **
144216    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
144217    ** on the parsing context. As follows:
144218    **
144219    **   0: Parsing file-name.
144220    **   1: Parsing name section of a name=value query parameter.
144221    **   2: Parsing value section of a name=value query parameter.
144222    */
144223    eState = 0;
144224    while( (c = zUri[iIn])!=0 && c!='#' ){
144225      iIn++;
144226      if( c=='%'
144227       && sqlite3Isxdigit(zUri[iIn])
144228       && sqlite3Isxdigit(zUri[iIn+1])
144229      ){
144230        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
144231        octet += sqlite3HexToInt(zUri[iIn++]);
144232
144233        assert( octet>=0 && octet<256 );
144234        if( octet==0 ){
144235#ifndef SQLITE_ENABLE_URI_00_ERROR
144236          /* This branch is taken when "%00" appears within the URI. In this
144237          ** case we ignore all text in the remainder of the path, name or
144238          ** value currently being parsed. So ignore the current character
144239          ** and skip to the next "?", "=" or "&", as appropriate. */
144240          while( (c = zUri[iIn])!=0 && c!='#'
144241              && (eState!=0 || c!='?')
144242              && (eState!=1 || (c!='=' && c!='&'))
144243              && (eState!=2 || c!='&')
144244          ){
144245            iIn++;
144246          }
144247          continue;
144248#else
144249          /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
144250          *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
144251          rc = SQLITE_ERROR;
144252          goto parse_uri_out;
144253#endif
144254        }
144255        c = octet;
144256      }else if( eState==1 && (c=='&' || c=='=') ){
144257        if( zFile[iOut-1]==0 ){
144258          /* An empty option name. Ignore this option altogether. */
144259          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
144260          continue;
144261        }
144262        if( c=='&' ){
144263          zFile[iOut++] = '\0';
144264        }else{
144265          eState = 2;
144266        }
144267        c = 0;
144268      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
144269        c = 0;
144270        eState = 1;
144271      }
144272      zFile[iOut++] = c;
144273    }
144274    if( eState==1 ) zFile[iOut++] = '\0';
144275    zFile[iOut++] = '\0';
144276    zFile[iOut++] = '\0';
144277
144278    /* Check if there were any options specified that should be interpreted
144279    ** here. Options that are interpreted here include "vfs" and those that
144280    ** correspond to flags that may be passed to the sqlite3_open_v2()
144281    ** method. */
144282    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
144283    while( zOpt[0] ){
144284      int nOpt = sqlite3Strlen30(zOpt);
144285      char *zVal = &zOpt[nOpt+1];
144286      int nVal = sqlite3Strlen30(zVal);
144287
144288      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
144289        zVfs = zVal;
144290      }else{
144291        struct OpenMode {
144292          const char *z;
144293          int mode;
144294        } *aMode = 0;
144295        char *zModeType = 0;
144296        int mask = 0;
144297        int limit = 0;
144298
144299        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
144300          static struct OpenMode aCacheMode[] = {
144301            { "shared",  SQLITE_OPEN_SHAREDCACHE },
144302            { "private", SQLITE_OPEN_PRIVATECACHE },
144303            { 0, 0 }
144304          };
144305
144306          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
144307          aMode = aCacheMode;
144308          limit = mask;
144309          zModeType = "cache";
144310        }
144311        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
144312          static struct OpenMode aOpenMode[] = {
144313            { "ro",  SQLITE_OPEN_READONLY },
144314            { "rw",  SQLITE_OPEN_READWRITE },
144315            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
144316            { "memory", SQLITE_OPEN_MEMORY },
144317            { 0, 0 }
144318          };
144319
144320          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
144321                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
144322          aMode = aOpenMode;
144323          limit = mask & flags;
144324          zModeType = "access";
144325        }
144326
144327        if( aMode ){
144328          int i;
144329          int mode = 0;
144330          for(i=0; aMode[i].z; i++){
144331            const char *z = aMode[i].z;
144332            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
144333              mode = aMode[i].mode;
144334              break;
144335            }
144336          }
144337          if( mode==0 ){
144338            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
144339            rc = SQLITE_ERROR;
144340            goto parse_uri_out;
144341          }
144342          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
144343            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
144344                                        zModeType, zVal);
144345            rc = SQLITE_PERM;
144346            goto parse_uri_out;
144347          }
144348          flags = (flags & ~mask) | mode;
144349        }
144350      }
144351
144352      zOpt = &zVal[nVal+1];
144353    }
144354
144355  }else{
144356    zFile = sqlite3_malloc64(nUri+2);
144357    if( !zFile ) return SQLITE_NOMEM_BKPT;
144358    if( nUri ){
144359      memcpy(zFile, zUri, nUri);
144360    }
144361    zFile[nUri] = '\0';
144362    zFile[nUri+1] = '\0';
144363    flags &= ~SQLITE_OPEN_URI;
144364  }
144365
144366  *ppVfs = sqlite3_vfs_find(zVfs);
144367  if( *ppVfs==0 ){
144368    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
144369    rc = SQLITE_ERROR;
144370  }
144371 parse_uri_out:
144372  if( rc!=SQLITE_OK ){
144373    sqlite3_free(zFile);
144374    zFile = 0;
144375  }
144376  *pFlags = flags;
144377  *pzFile = zFile;
144378  return rc;
144379}
144380
144381
144382/*
144383** This routine does the work of opening a database on behalf of
144384** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
144385** is UTF-8 encoded.
144386*/
144387static int openDatabase(
144388  const char *zFilename, /* Database filename UTF-8 encoded */
144389  sqlite3 **ppDb,        /* OUT: Returned database handle */
144390  unsigned int flags,    /* Operational flags */
144391  const char *zVfs       /* Name of the VFS to use */
144392){
144393  sqlite3 *db;                    /* Store allocated handle here */
144394  int rc;                         /* Return code */
144395  int isThreadsafe;               /* True for threadsafe connections */
144396  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
144397  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
144398
144399#ifdef SQLITE_ENABLE_API_ARMOR
144400  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
144401#endif
144402  *ppDb = 0;
144403#ifndef SQLITE_OMIT_AUTOINIT
144404  rc = sqlite3_initialize();
144405  if( rc ) return rc;
144406#endif
144407
144408  if( sqlite3GlobalConfig.bCoreMutex==0 ){
144409    isThreadsafe = 0;
144410  }else if( flags & SQLITE_OPEN_NOMUTEX ){
144411    isThreadsafe = 0;
144412  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
144413    isThreadsafe = 1;
144414  }else{
144415    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
144416  }
144417  if( flags & SQLITE_OPEN_PRIVATECACHE ){
144418    flags &= ~SQLITE_OPEN_SHAREDCACHE;
144419  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
144420    flags |= SQLITE_OPEN_SHAREDCACHE;
144421  }
144422
144423  /* Remove harmful bits from the flags parameter
144424  **
144425  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
144426  ** dealt with in the previous code block.  Besides these, the only
144427  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
144428  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
144429  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
144430  ** off all other flags.
144431  */
144432  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
144433               SQLITE_OPEN_EXCLUSIVE |
144434               SQLITE_OPEN_MAIN_DB |
144435               SQLITE_OPEN_TEMP_DB |
144436               SQLITE_OPEN_TRANSIENT_DB |
144437               SQLITE_OPEN_MAIN_JOURNAL |
144438               SQLITE_OPEN_TEMP_JOURNAL |
144439               SQLITE_OPEN_SUBJOURNAL |
144440               SQLITE_OPEN_MASTER_JOURNAL |
144441               SQLITE_OPEN_NOMUTEX |
144442               SQLITE_OPEN_FULLMUTEX |
144443               SQLITE_OPEN_WAL
144444             );
144445
144446  /* Allocate the sqlite data structure */
144447  db = sqlite3MallocZero( sizeof(sqlite3) );
144448  if( db==0 ) goto opendb_out;
144449  if( isThreadsafe ){
144450    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
144451    if( db->mutex==0 ){
144452      sqlite3_free(db);
144453      db = 0;
144454      goto opendb_out;
144455    }
144456  }
144457  sqlite3_mutex_enter(db->mutex);
144458  db->errMask = 0xff;
144459  db->nDb = 2;
144460  db->magic = SQLITE_MAGIC_BUSY;
144461  db->aDb = db->aDbStatic;
144462
144463  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
144464  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
144465  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
144466  db->autoCommit = 1;
144467  db->nextAutovac = -1;
144468  db->szMmap = sqlite3GlobalConfig.szMmap;
144469  db->nextPagesize = 0;
144470  db->nMaxSorterMmap = 0x7FFFFFFF;
144471  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
144472#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
144473                 | SQLITE_AutoIndex
144474#endif
144475#if SQLITE_DEFAULT_CKPTFULLFSYNC
144476                 | SQLITE_CkptFullFSync
144477#endif
144478#if SQLITE_DEFAULT_FILE_FORMAT<4
144479                 | SQLITE_LegacyFileFmt
144480#endif
144481#ifdef SQLITE_ENABLE_LOAD_EXTENSION
144482                 | SQLITE_LoadExtension
144483#endif
144484#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
144485                 | SQLITE_RecTriggers
144486#endif
144487#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
144488                 | SQLITE_ForeignKeys
144489#endif
144490#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
144491                 | SQLITE_ReverseOrder
144492#endif
144493#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
144494                 | SQLITE_CellSizeCk
144495#endif
144496#if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
144497                 | SQLITE_Fts3Tokenizer
144498#endif
144499#if defined(SQLITE_ENABLE_QPSG)
144500                 | SQLITE_EnableQPSG
144501#endif
144502      ;
144503  sqlite3HashInit(&db->aCollSeq);
144504#ifndef SQLITE_OMIT_VIRTUALTABLE
144505  sqlite3HashInit(&db->aModule);
144506#endif
144507
144508  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
144509  ** and UTF-16, so add a version for each to avoid any unnecessary
144510  ** conversions. The only error that can occur here is a malloc() failure.
144511  **
144512  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
144513  ** functions:
144514  */
144515  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
144516  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
144517  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
144518  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
144519  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
144520  if( db->mallocFailed ){
144521    goto opendb_out;
144522  }
144523  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
144524  ** strings is BINARY.
144525  */
144526  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
144527  assert( db->pDfltColl!=0 );
144528
144529  /* Parse the filename/URI argument
144530  **
144531  ** Only allow sensible combinations of bits in the flags argument.
144532  ** Throw an error if any non-sense combination is used.  If we
144533  ** do not block illegal combinations here, it could trigger
144534  ** assert() statements in deeper layers.  Sensible combinations
144535  ** are:
144536  **
144537  **  1:  SQLITE_OPEN_READONLY
144538  **  2:  SQLITE_OPEN_READWRITE
144539  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
144540  */
144541  db->openFlags = flags;
144542  assert( SQLITE_OPEN_READONLY  == 0x01 );
144543  assert( SQLITE_OPEN_READWRITE == 0x02 );
144544  assert( SQLITE_OPEN_CREATE    == 0x04 );
144545  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
144546  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
144547  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
144548  if( ((1<<(flags&7)) & 0x46)==0 ){
144549    rc = SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
144550  }else{
144551    rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
144552  }
144553  if( rc!=SQLITE_OK ){
144554    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
144555    sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
144556    sqlite3_free(zErrMsg);
144557    goto opendb_out;
144558  }
144559
144560  /* Open the backend database driver */
144561  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
144562                        flags | SQLITE_OPEN_MAIN_DB);
144563  if( rc!=SQLITE_OK ){
144564    if( rc==SQLITE_IOERR_NOMEM ){
144565      rc = SQLITE_NOMEM_BKPT;
144566    }
144567    sqlite3Error(db, rc);
144568    goto opendb_out;
144569  }
144570  sqlite3BtreeEnter(db->aDb[0].pBt);
144571  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
144572  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
144573  sqlite3BtreeLeave(db->aDb[0].pBt);
144574  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
144575
144576  /* The default safety_level for the main database is FULL; for the temp
144577  ** database it is OFF. This matches the pager layer defaults.
144578  */
144579  db->aDb[0].zDbSName = "main";
144580  db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
144581  db->aDb[1].zDbSName = "temp";
144582  db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
144583
144584  db->magic = SQLITE_MAGIC_OPEN;
144585  if( db->mallocFailed ){
144586    goto opendb_out;
144587  }
144588
144589  /* Register all built-in functions, but do not attempt to read the
144590  ** database schema yet. This is delayed until the first time the database
144591  ** is accessed.
144592  */
144593  sqlite3Error(db, SQLITE_OK);
144594  sqlite3RegisterPerConnectionBuiltinFunctions(db);
144595  rc = sqlite3_errcode(db);
144596
144597#ifdef SQLITE_ENABLE_FTS5
144598  /* Register any built-in FTS5 module before loading the automatic
144599  ** extensions. This allows automatic extensions to register FTS5
144600  ** tokenizers and auxiliary functions.  */
144601  if( !db->mallocFailed && rc==SQLITE_OK ){
144602    rc = sqlite3Fts5Init(db);
144603  }
144604#endif
144605
144606  /* Load automatic extensions - extensions that have been registered
144607  ** using the sqlite3_automatic_extension() API.
144608  */
144609  if( rc==SQLITE_OK ){
144610    sqlite3AutoLoadExtensions(db);
144611    rc = sqlite3_errcode(db);
144612    if( rc!=SQLITE_OK ){
144613      goto opendb_out;
144614    }
144615  }
144616
144617#ifdef SQLITE_ENABLE_FTS1
144618  if( !db->mallocFailed ){
144619    extern int sqlite3Fts1Init(sqlite3*);
144620    rc = sqlite3Fts1Init(db);
144621  }
144622#endif
144623
144624#ifdef SQLITE_ENABLE_FTS2
144625  if( !db->mallocFailed && rc==SQLITE_OK ){
144626    extern int sqlite3Fts2Init(sqlite3*);
144627    rc = sqlite3Fts2Init(db);
144628  }
144629#endif
144630
144631#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
144632  if( !db->mallocFailed && rc==SQLITE_OK ){
144633    rc = sqlite3Fts3Init(db);
144634  }
144635#endif
144636
144637#ifdef SQLITE_ENABLE_ICU
144638  if( !db->mallocFailed && rc==SQLITE_OK ){
144639    rc = sqlite3IcuInit(db);
144640  }
144641#endif
144642
144643#ifdef SQLITE_ENABLE_RTREE
144644  if( !db->mallocFailed && rc==SQLITE_OK){
144645    rc = sqlite3RtreeInit(db);
144646  }
144647#endif
144648
144649#ifdef SQLITE_ENABLE_DBSTAT_VTAB
144650  if( !db->mallocFailed && rc==SQLITE_OK){
144651    rc = sqlite3DbstatRegister(db);
144652  }
144653#endif
144654
144655#ifdef SQLITE_ENABLE_JSON1
144656  if( !db->mallocFailed && rc==SQLITE_OK){
144657    rc = sqlite3Json1Init(db);
144658  }
144659#endif
144660
144661#ifdef SQLITE_ENABLE_STMTVTAB
144662  if( !db->mallocFailed && rc==SQLITE_OK){
144663    rc = sqlite3StmtVtabInit(db);
144664  }
144665#endif
144666
144667  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
144668  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
144669  ** mode.  Doing nothing at all also makes NORMAL the default.
144670  */
144671#ifdef SQLITE_DEFAULT_LOCKING_MODE
144672  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
144673  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
144674                          SQLITE_DEFAULT_LOCKING_MODE);
144675#endif
144676
144677  if( rc ) sqlite3Error(db, rc);
144678
144679  /* Enable the lookaside-malloc subsystem */
144680  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
144681                        sqlite3GlobalConfig.nLookaside);
144682
144683  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
144684
144685opendb_out:
144686  if( db ){
144687    assert( db->mutex!=0 || isThreadsafe==0
144688           || sqlite3GlobalConfig.bFullMutex==0 );
144689    sqlite3_mutex_leave(db->mutex);
144690  }
144691  rc = sqlite3_errcode(db);
144692  assert( db!=0 || rc==SQLITE_NOMEM );
144693  if( rc==SQLITE_NOMEM ){
144694    sqlite3_close(db);
144695    db = 0;
144696  }else if( rc!=SQLITE_OK ){
144697    db->magic = SQLITE_MAGIC_SICK;
144698  }
144699  *ppDb = db;
144700#ifdef SQLITE_ENABLE_SQLLOG
144701  if( sqlite3GlobalConfig.xSqllog ){
144702    /* Opening a db handle. Fourth parameter is passed 0. */
144703    void *pArg = sqlite3GlobalConfig.pSqllogArg;
144704    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
144705  }
144706#endif
144707#if defined(SQLITE_HAS_CODEC)
144708  if( rc==SQLITE_OK ){
144709    const char *zKey;
144710    if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
144711      u8 iByte;
144712      int i;
144713      char zDecoded[40];
144714      for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
144715        iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
144716        if( (i&1)!=0 ) zDecoded[i/2] = iByte;
144717      }
144718      sqlite3_key_v2(db, 0, zDecoded, i/2);
144719    }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
144720      sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
144721    }
144722  }
144723#endif
144724  sqlite3_free(zOpen);
144725  return rc & 0xff;
144726}
144727
144728/*
144729** Open a new database handle.
144730*/
144731SQLITE_API int sqlite3_open(
144732  const char *zFilename,
144733  sqlite3 **ppDb
144734){
144735  return openDatabase(zFilename, ppDb,
144736                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
144737}
144738SQLITE_API int sqlite3_open_v2(
144739  const char *filename,   /* Database filename (UTF-8) */
144740  sqlite3 **ppDb,         /* OUT: SQLite db handle */
144741  int flags,              /* Flags */
144742  const char *zVfs        /* Name of VFS module to use */
144743){
144744  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
144745}
144746
144747#ifndef SQLITE_OMIT_UTF16
144748/*
144749** Open a new database handle.
144750*/
144751SQLITE_API int sqlite3_open16(
144752  const void *zFilename,
144753  sqlite3 **ppDb
144754){
144755  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
144756  sqlite3_value *pVal;
144757  int rc;
144758
144759#ifdef SQLITE_ENABLE_API_ARMOR
144760  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
144761#endif
144762  *ppDb = 0;
144763#ifndef SQLITE_OMIT_AUTOINIT
144764  rc = sqlite3_initialize();
144765  if( rc ) return rc;
144766#endif
144767  if( zFilename==0 ) zFilename = "\000\000";
144768  pVal = sqlite3ValueNew(0);
144769  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
144770  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
144771  if( zFilename8 ){
144772    rc = openDatabase(zFilename8, ppDb,
144773                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
144774    assert( *ppDb || rc==SQLITE_NOMEM );
144775    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
144776      SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
144777    }
144778  }else{
144779    rc = SQLITE_NOMEM_BKPT;
144780  }
144781  sqlite3ValueFree(pVal);
144782
144783  return rc & 0xff;
144784}
144785#endif /* SQLITE_OMIT_UTF16 */
144786
144787/*
144788** Register a new collation sequence with the database handle db.
144789*/
144790SQLITE_API int sqlite3_create_collation(
144791  sqlite3* db,
144792  const char *zName,
144793  int enc,
144794  void* pCtx,
144795  int(*xCompare)(void*,int,const void*,int,const void*)
144796){
144797  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
144798}
144799
144800/*
144801** Register a new collation sequence with the database handle db.
144802*/
144803SQLITE_API int sqlite3_create_collation_v2(
144804  sqlite3* db,
144805  const char *zName,
144806  int enc,
144807  void* pCtx,
144808  int(*xCompare)(void*,int,const void*,int,const void*),
144809  void(*xDel)(void*)
144810){
144811  int rc;
144812
144813#ifdef SQLITE_ENABLE_API_ARMOR
144814  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
144815#endif
144816  sqlite3_mutex_enter(db->mutex);
144817  assert( !db->mallocFailed );
144818  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
144819  rc = sqlite3ApiExit(db, rc);
144820  sqlite3_mutex_leave(db->mutex);
144821  return rc;
144822}
144823
144824#ifndef SQLITE_OMIT_UTF16
144825/*
144826** Register a new collation sequence with the database handle db.
144827*/
144828SQLITE_API int sqlite3_create_collation16(
144829  sqlite3* db,
144830  const void *zName,
144831  int enc,
144832  void* pCtx,
144833  int(*xCompare)(void*,int,const void*,int,const void*)
144834){
144835  int rc = SQLITE_OK;
144836  char *zName8;
144837
144838#ifdef SQLITE_ENABLE_API_ARMOR
144839  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
144840#endif
144841  sqlite3_mutex_enter(db->mutex);
144842  assert( !db->mallocFailed );
144843  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
144844  if( zName8 ){
144845    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
144846    sqlite3DbFree(db, zName8);
144847  }
144848  rc = sqlite3ApiExit(db, rc);
144849  sqlite3_mutex_leave(db->mutex);
144850  return rc;
144851}
144852#endif /* SQLITE_OMIT_UTF16 */
144853
144854/*
144855** Register a collation sequence factory callback with the database handle
144856** db. Replace any previously installed collation sequence factory.
144857*/
144858SQLITE_API int sqlite3_collation_needed(
144859  sqlite3 *db,
144860  void *pCollNeededArg,
144861  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
144862){
144863#ifdef SQLITE_ENABLE_API_ARMOR
144864  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
144865#endif
144866  sqlite3_mutex_enter(db->mutex);
144867  db->xCollNeeded = xCollNeeded;
144868  db->xCollNeeded16 = 0;
144869  db->pCollNeededArg = pCollNeededArg;
144870  sqlite3_mutex_leave(db->mutex);
144871  return SQLITE_OK;
144872}
144873
144874#ifndef SQLITE_OMIT_UTF16
144875/*
144876** Register a collation sequence factory callback with the database handle
144877** db. Replace any previously installed collation sequence factory.
144878*/
144879SQLITE_API int sqlite3_collation_needed16(
144880  sqlite3 *db,
144881  void *pCollNeededArg,
144882  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
144883){
144884#ifdef SQLITE_ENABLE_API_ARMOR
144885  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
144886#endif
144887  sqlite3_mutex_enter(db->mutex);
144888  db->xCollNeeded = 0;
144889  db->xCollNeeded16 = xCollNeeded16;
144890  db->pCollNeededArg = pCollNeededArg;
144891  sqlite3_mutex_leave(db->mutex);
144892  return SQLITE_OK;
144893}
144894#endif /* SQLITE_OMIT_UTF16 */
144895
144896#ifndef SQLITE_OMIT_DEPRECATED
144897/*
144898** This function is now an anachronism. It used to be used to recover from a
144899** malloc() failure, but SQLite now does this automatically.
144900*/
144901SQLITE_API int sqlite3_global_recover(void){
144902  return SQLITE_OK;
144903}
144904#endif
144905
144906/*
144907** Test to see whether or not the database connection is in autocommit
144908** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
144909** by default.  Autocommit is disabled by a BEGIN statement and reenabled
144910** by the next COMMIT or ROLLBACK.
144911*/
144912SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
144913#ifdef SQLITE_ENABLE_API_ARMOR
144914  if( !sqlite3SafetyCheckOk(db) ){
144915    (void)SQLITE_MISUSE_BKPT;
144916    return 0;
144917  }
144918#endif
144919  return db->autoCommit;
144920}
144921
144922/*
144923** The following routines are substitutes for constants SQLITE_CORRUPT,
144924** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
144925** constants.  They serve two purposes:
144926**
144927**   1.  Serve as a convenient place to set a breakpoint in a debugger
144928**       to detect when version error conditions occurs.
144929**
144930**   2.  Invoke sqlite3_log() to provide the source code location where
144931**       a low-level error is first detected.
144932*/
144933static int reportError(int iErr, int lineno, const char *zType){
144934  sqlite3_log(iErr, "%s at line %d of [%.10s]",
144935              zType, lineno, 20+sqlite3_sourceid());
144936  return iErr;
144937}
144938SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
144939  testcase( sqlite3GlobalConfig.xLog!=0 );
144940  return reportError(SQLITE_CORRUPT, lineno, "database corruption");
144941}
144942SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
144943  testcase( sqlite3GlobalConfig.xLog!=0 );
144944  return reportError(SQLITE_MISUSE, lineno, "misuse");
144945}
144946SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
144947  testcase( sqlite3GlobalConfig.xLog!=0 );
144948  return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
144949}
144950#ifdef SQLITE_DEBUG
144951SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
144952  char zMsg[100];
144953  sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
144954  testcase( sqlite3GlobalConfig.xLog!=0 );
144955  return reportError(SQLITE_CORRUPT, lineno, zMsg);
144956}
144957SQLITE_PRIVATE int sqlite3NomemError(int lineno){
144958  testcase( sqlite3GlobalConfig.xLog!=0 );
144959  return reportError(SQLITE_NOMEM, lineno, "OOM");
144960}
144961SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
144962  testcase( sqlite3GlobalConfig.xLog!=0 );
144963  return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
144964}
144965#endif
144966
144967#ifndef SQLITE_OMIT_DEPRECATED
144968/*
144969** This is a convenience routine that makes sure that all thread-specific
144970** data for this thread has been deallocated.
144971**
144972** SQLite no longer uses thread-specific data so this routine is now a
144973** no-op.  It is retained for historical compatibility.
144974*/
144975SQLITE_API void sqlite3_thread_cleanup(void){
144976}
144977#endif
144978
144979/*
144980** Return meta information about a specific column of a database table.
144981** See comment in sqlite3.h (sqlite.h.in) for details.
144982*/
144983SQLITE_API int sqlite3_table_column_metadata(
144984  sqlite3 *db,                /* Connection handle */
144985  const char *zDbName,        /* Database name or NULL */
144986  const char *zTableName,     /* Table name */
144987  const char *zColumnName,    /* Column name */
144988  char const **pzDataType,    /* OUTPUT: Declared data type */
144989  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
144990  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
144991  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
144992  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
144993){
144994  int rc;
144995  char *zErrMsg = 0;
144996  Table *pTab = 0;
144997  Column *pCol = 0;
144998  int iCol = 0;
144999  char const *zDataType = 0;
145000  char const *zCollSeq = 0;
145001  int notnull = 0;
145002  int primarykey = 0;
145003  int autoinc = 0;
145004
145005
145006#ifdef SQLITE_ENABLE_API_ARMOR
145007  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
145008    return SQLITE_MISUSE_BKPT;
145009  }
145010#endif
145011
145012  /* Ensure the database schema has been loaded */
145013  sqlite3_mutex_enter(db->mutex);
145014  sqlite3BtreeEnterAll(db);
145015  rc = sqlite3Init(db, &zErrMsg);
145016  if( SQLITE_OK!=rc ){
145017    goto error_out;
145018  }
145019
145020  /* Locate the table in question */
145021  pTab = sqlite3FindTable(db, zTableName, zDbName);
145022  if( !pTab || pTab->pSelect ){
145023    pTab = 0;
145024    goto error_out;
145025  }
145026
145027  /* Find the column for which info is requested */
145028  if( zColumnName==0 ){
145029    /* Query for existance of table only */
145030  }else{
145031    for(iCol=0; iCol<pTab->nCol; iCol++){
145032      pCol = &pTab->aCol[iCol];
145033      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
145034        break;
145035      }
145036    }
145037    if( iCol==pTab->nCol ){
145038      if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
145039        iCol = pTab->iPKey;
145040        pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
145041      }else{
145042        pTab = 0;
145043        goto error_out;
145044      }
145045    }
145046  }
145047
145048  /* The following block stores the meta information that will be returned
145049  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
145050  ** and autoinc. At this point there are two possibilities:
145051  **
145052  **     1. The specified column name was rowid", "oid" or "_rowid_"
145053  **        and there is no explicitly declared IPK column.
145054  **
145055  **     2. The table is not a view and the column name identified an
145056  **        explicitly declared column. Copy meta information from *pCol.
145057  */
145058  if( pCol ){
145059    zDataType = sqlite3ColumnType(pCol,0);
145060    zCollSeq = pCol->zColl;
145061    notnull = pCol->notNull!=0;
145062    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
145063    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
145064  }else{
145065    zDataType = "INTEGER";
145066    primarykey = 1;
145067  }
145068  if( !zCollSeq ){
145069    zCollSeq = sqlite3StrBINARY;
145070  }
145071
145072error_out:
145073  sqlite3BtreeLeaveAll(db);
145074
145075  /* Whether the function call succeeded or failed, set the output parameters
145076  ** to whatever their local counterparts contain. If an error did occur,
145077  ** this has the effect of zeroing all output parameters.
145078  */
145079  if( pzDataType ) *pzDataType = zDataType;
145080  if( pzCollSeq ) *pzCollSeq = zCollSeq;
145081  if( pNotNull ) *pNotNull = notnull;
145082  if( pPrimaryKey ) *pPrimaryKey = primarykey;
145083  if( pAutoinc ) *pAutoinc = autoinc;
145084
145085  if( SQLITE_OK==rc && !pTab ){
145086    sqlite3DbFree(db, zErrMsg);
145087    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
145088        zColumnName);
145089    rc = SQLITE_ERROR;
145090  }
145091  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
145092  sqlite3DbFree(db, zErrMsg);
145093  rc = sqlite3ApiExit(db, rc);
145094  sqlite3_mutex_leave(db->mutex);
145095  return rc;
145096}
145097
145098/*
145099** Sleep for a little while.  Return the amount of time slept.
145100*/
145101SQLITE_API int sqlite3_sleep(int ms){
145102  sqlite3_vfs *pVfs;
145103  int rc;
145104  pVfs = sqlite3_vfs_find(0);
145105  if( pVfs==0 ) return 0;
145106
145107  /* This function works in milliseconds, but the underlying OsSleep()
145108  ** API uses microseconds. Hence the 1000's.
145109  */
145110  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
145111  return rc;
145112}
145113
145114/*
145115** Enable or disable the extended result codes.
145116*/
145117SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
145118#ifdef SQLITE_ENABLE_API_ARMOR
145119  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145120#endif
145121  sqlite3_mutex_enter(db->mutex);
145122  db->errMask = onoff ? 0xffffffff : 0xff;
145123  sqlite3_mutex_leave(db->mutex);
145124  return SQLITE_OK;
145125}
145126
145127/*
145128** Invoke the xFileControl method on a particular database.
145129*/
145130SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
145131  int rc = SQLITE_ERROR;
145132  Btree *pBtree;
145133
145134#ifdef SQLITE_ENABLE_API_ARMOR
145135  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
145136#endif
145137  sqlite3_mutex_enter(db->mutex);
145138  pBtree = sqlite3DbNameToBtree(db, zDbName);
145139  if( pBtree ){
145140    Pager *pPager;
145141    sqlite3_file *fd;
145142    sqlite3BtreeEnter(pBtree);
145143    pPager = sqlite3BtreePager(pBtree);
145144    assert( pPager!=0 );
145145    fd = sqlite3PagerFile(pPager);
145146    assert( fd!=0 );
145147    if( op==SQLITE_FCNTL_FILE_POINTER ){
145148      *(sqlite3_file**)pArg = fd;
145149      rc = SQLITE_OK;
145150    }else if( op==SQLITE_FCNTL_VFS_POINTER ){
145151      *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
145152      rc = SQLITE_OK;
145153    }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
145154      *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
145155      rc = SQLITE_OK;
145156    }else if( fd->pMethods ){
145157      rc = sqlite3OsFileControl(fd, op, pArg);
145158    }else{
145159      rc = SQLITE_NOTFOUND;
145160    }
145161    sqlite3BtreeLeave(pBtree);
145162  }
145163  sqlite3_mutex_leave(db->mutex);
145164  return rc;
145165}
145166
145167/*
145168** Interface to the testing logic.
145169*/
145170SQLITE_API int sqlite3_test_control(int op, ...){
145171  int rc = 0;
145172#ifdef SQLITE_UNTESTABLE
145173  UNUSED_PARAMETER(op);
145174#else
145175  va_list ap;
145176  va_start(ap, op);
145177  switch( op ){
145178
145179    /*
145180    ** Save the current state of the PRNG.
145181    */
145182    case SQLITE_TESTCTRL_PRNG_SAVE: {
145183      sqlite3PrngSaveState();
145184      break;
145185    }
145186
145187    /*
145188    ** Restore the state of the PRNG to the last state saved using
145189    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
145190    ** this verb acts like PRNG_RESET.
145191    */
145192    case SQLITE_TESTCTRL_PRNG_RESTORE: {
145193      sqlite3PrngRestoreState();
145194      break;
145195    }
145196
145197    /*
145198    ** Reset the PRNG back to its uninitialized state.  The next call
145199    ** to sqlite3_randomness() will reseed the PRNG using a single call
145200    ** to the xRandomness method of the default VFS.
145201    */
145202    case SQLITE_TESTCTRL_PRNG_RESET: {
145203      sqlite3_randomness(0,0);
145204      break;
145205    }
145206
145207    /*
145208    **  sqlite3_test_control(BITVEC_TEST, size, program)
145209    **
145210    ** Run a test against a Bitvec object of size.  The program argument
145211    ** is an array of integers that defines the test.  Return -1 on a
145212    ** memory allocation error, 0 on success, or non-zero for an error.
145213    ** See the sqlite3BitvecBuiltinTest() for additional information.
145214    */
145215    case SQLITE_TESTCTRL_BITVEC_TEST: {
145216      int sz = va_arg(ap, int);
145217      int *aProg = va_arg(ap, int*);
145218      rc = sqlite3BitvecBuiltinTest(sz, aProg);
145219      break;
145220    }
145221
145222    /*
145223    **  sqlite3_test_control(FAULT_INSTALL, xCallback)
145224    **
145225    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
145226    ** if xCallback is not NULL.
145227    **
145228    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
145229    ** is called immediately after installing the new callback and the return
145230    ** value from sqlite3FaultSim(0) becomes the return from
145231    ** sqlite3_test_control().
145232    */
145233    case SQLITE_TESTCTRL_FAULT_INSTALL: {
145234      /* MSVC is picky about pulling func ptrs from va lists.
145235      ** http://support.microsoft.com/kb/47961
145236      ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
145237      */
145238      typedef int(*TESTCALLBACKFUNC_t)(int);
145239      sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
145240      rc = sqlite3FaultSim(0);
145241      break;
145242    }
145243
145244    /*
145245    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
145246    **
145247    ** Register hooks to call to indicate which malloc() failures
145248    ** are benign.
145249    */
145250    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
145251      typedef void (*void_function)(void);
145252      void_function xBenignBegin;
145253      void_function xBenignEnd;
145254      xBenignBegin = va_arg(ap, void_function);
145255      xBenignEnd = va_arg(ap, void_function);
145256      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
145257      break;
145258    }
145259
145260    /*
145261    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
145262    **
145263    ** Set the PENDING byte to the value in the argument, if X>0.
145264    ** Make no changes if X==0.  Return the value of the pending byte
145265    ** as it existing before this routine was called.
145266    **
145267    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
145268    ** an incompatible database file format.  Changing the PENDING byte
145269    ** while any database connection is open results in undefined and
145270    ** deleterious behavior.
145271    */
145272    case SQLITE_TESTCTRL_PENDING_BYTE: {
145273      rc = PENDING_BYTE;
145274#ifndef SQLITE_OMIT_WSD
145275      {
145276        unsigned int newVal = va_arg(ap, unsigned int);
145277        if( newVal ) sqlite3PendingByte = newVal;
145278      }
145279#endif
145280      break;
145281    }
145282
145283    /*
145284    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
145285    **
145286    ** This action provides a run-time test to see whether or not
145287    ** assert() was enabled at compile-time.  If X is true and assert()
145288    ** is enabled, then the return value is true.  If X is true and
145289    ** assert() is disabled, then the return value is zero.  If X is
145290    ** false and assert() is enabled, then the assertion fires and the
145291    ** process aborts.  If X is false and assert() is disabled, then the
145292    ** return value is zero.
145293    */
145294    case SQLITE_TESTCTRL_ASSERT: {
145295      volatile int x = 0;
145296      assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
145297      rc = x;
145298      break;
145299    }
145300
145301
145302    /*
145303    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
145304    **
145305    ** This action provides a run-time test to see how the ALWAYS and
145306    ** NEVER macros were defined at compile-time.
145307    **
145308    ** The return value is ALWAYS(X).
145309    **
145310    ** The recommended test is X==2.  If the return value is 2, that means
145311    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
145312    ** default setting.  If the return value is 1, then ALWAYS() is either
145313    ** hard-coded to true or else it asserts if its argument is false.
145314    ** The first behavior (hard-coded to true) is the case if
145315    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
145316    ** behavior (assert if the argument to ALWAYS() is false) is the case if
145317    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
145318    **
145319    ** The run-time test procedure might look something like this:
145320    **
145321    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
145322    **      // ALWAYS() and NEVER() are no-op pass-through macros
145323    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
145324    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
145325    **    }else{
145326    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
145327    **    }
145328    */
145329    case SQLITE_TESTCTRL_ALWAYS: {
145330      int x = va_arg(ap,int);
145331      rc = ALWAYS(x);
145332      break;
145333    }
145334
145335    /*
145336    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
145337    **
145338    ** The integer returned reveals the byte-order of the computer on which
145339    ** SQLite is running:
145340    **
145341    **       1     big-endian,    determined at run-time
145342    **      10     little-endian, determined at run-time
145343    **  432101     big-endian,    determined at compile-time
145344    **  123410     little-endian, determined at compile-time
145345    */
145346    case SQLITE_TESTCTRL_BYTEORDER: {
145347      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
145348      break;
145349    }
145350
145351    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
145352    **
145353    ** Set the nReserve size to N for the main database on the database
145354    ** connection db.
145355    */
145356    case SQLITE_TESTCTRL_RESERVE: {
145357      sqlite3 *db = va_arg(ap, sqlite3*);
145358      int x = va_arg(ap,int);
145359      sqlite3_mutex_enter(db->mutex);
145360      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
145361      sqlite3_mutex_leave(db->mutex);
145362      break;
145363    }
145364
145365    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
145366    **
145367    ** Enable or disable various optimizations for testing purposes.  The
145368    ** argument N is a bitmask of optimizations to be disabled.  For normal
145369    ** operation N should be 0.  The idea is that a test program (like the
145370    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
145371    ** with various optimizations disabled to verify that the same answer
145372    ** is obtained in every case.
145373    */
145374    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
145375      sqlite3 *db = va_arg(ap, sqlite3*);
145376      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
145377      break;
145378    }
145379
145380#ifdef SQLITE_N_KEYWORD
145381    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
145382    **
145383    ** If zWord is a keyword recognized by the parser, then return the
145384    ** number of keywords.  Or if zWord is not a keyword, return 0.
145385    **
145386    ** This test feature is only available in the amalgamation since
145387    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
145388    ** is built using separate source files.
145389    */
145390    case SQLITE_TESTCTRL_ISKEYWORD: {
145391      const char *zWord = va_arg(ap, const char*);
145392      int n = sqlite3Strlen30(zWord);
145393      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
145394      break;
145395    }
145396#endif
145397
145398    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
145399    **
145400    ** Pass pFree into sqlite3ScratchFree().
145401    ** If sz>0 then allocate a scratch buffer into pNew.
145402    */
145403    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
145404      void *pFree, **ppNew;
145405      int sz;
145406      sz = va_arg(ap, int);
145407      ppNew = va_arg(ap, void**);
145408      pFree = va_arg(ap, void*);
145409      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
145410      sqlite3ScratchFree(pFree);
145411      break;
145412    }
145413
145414    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
145415    **
145416    ** If parameter onoff is non-zero, configure the wrappers so that all
145417    ** subsequent calls to localtime() and variants fail. If onoff is zero,
145418    ** undo this setting.
145419    */
145420    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
145421      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
145422      break;
145423    }
145424
145425    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
145426    **
145427    ** Set or clear a flag that indicates that the database file is always well-
145428    ** formed and never corrupt.  This flag is clear by default, indicating that
145429    ** database files might have arbitrary corruption.  Setting the flag during
145430    ** testing causes certain assert() statements in the code to be activated
145431    ** that demonstrat invariants on well-formed database files.
145432    */
145433    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
145434      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
145435      break;
145436    }
145437
145438    /* Set the threshold at which OP_Once counters reset back to zero.
145439    ** By default this is 0x7ffffffe (over 2 billion), but that value is
145440    ** too big to test in a reasonable amount of time, so this control is
145441    ** provided to set a small and easily reachable reset value.
145442    */
145443    case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
145444      sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
145445      break;
145446    }
145447
145448    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
145449    **
145450    ** Set the VDBE coverage callback function to xCallback with context
145451    ** pointer ptr.
145452    */
145453    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
145454#ifdef SQLITE_VDBE_COVERAGE
145455      typedef void (*branch_callback)(void*,int,u8,u8);
145456      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
145457      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
145458#endif
145459      break;
145460    }
145461
145462    /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
145463    case SQLITE_TESTCTRL_SORTER_MMAP: {
145464      sqlite3 *db = va_arg(ap, sqlite3*);
145465      db->nMaxSorterMmap = va_arg(ap, int);
145466      break;
145467    }
145468
145469    /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
145470    **
145471    ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
145472    ** not.
145473    */
145474    case SQLITE_TESTCTRL_ISINIT: {
145475      if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
145476      break;
145477    }
145478
145479    /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
145480    **
145481    ** This test control is used to create imposter tables.  "db" is a pointer
145482    ** to the database connection.  dbName is the database name (ex: "main" or
145483    ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
145484    ** or off.  "tnum" is the root page of the b-tree to which the imposter
145485    ** table should connect.
145486    **
145487    ** Enable imposter mode only when the schema has already been parsed.  Then
145488    ** run a single CREATE TABLE statement to construct the imposter table in
145489    ** the parsed schema.  Then turn imposter mode back off again.
145490    **
145491    ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
145492    ** the schema to be reparsed the next time it is needed.  This has the
145493    ** effect of erasing all imposter tables.
145494    */
145495    case SQLITE_TESTCTRL_IMPOSTER: {
145496      sqlite3 *db = va_arg(ap, sqlite3*);
145497      sqlite3_mutex_enter(db->mutex);
145498      db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
145499      db->init.busy = db->init.imposterTable = va_arg(ap,int);
145500      db->init.newTnum = va_arg(ap,int);
145501      if( db->init.busy==0 && db->init.newTnum>0 ){
145502        sqlite3ResetAllSchemasOfConnection(db);
145503      }
145504      sqlite3_mutex_leave(db->mutex);
145505      break;
145506    }
145507  }
145508  va_end(ap);
145509#endif /* SQLITE_UNTESTABLE */
145510  return rc;
145511}
145512
145513/*
145514** This is a utility routine, useful to VFS implementations, that checks
145515** to see if a database file was a URI that contained a specific query
145516** parameter, and if so obtains the value of the query parameter.
145517**
145518** The zFilename argument is the filename pointer passed into the xOpen()
145519** method of a VFS implementation.  The zParam argument is the name of the
145520** query parameter we seek.  This routine returns the value of the zParam
145521** parameter if it exists.  If the parameter does not exist, this routine
145522** returns a NULL pointer.
145523*/
145524SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
145525  if( zFilename==0 || zParam==0 ) return 0;
145526  zFilename += sqlite3Strlen30(zFilename) + 1;
145527  while( zFilename[0] ){
145528    int x = strcmp(zFilename, zParam);
145529    zFilename += sqlite3Strlen30(zFilename) + 1;
145530    if( x==0 ) return zFilename;
145531    zFilename += sqlite3Strlen30(zFilename) + 1;
145532  }
145533  return 0;
145534}
145535
145536/*
145537** Return a boolean value for a query parameter.
145538*/
145539SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
145540  const char *z = sqlite3_uri_parameter(zFilename, zParam);
145541  bDflt = bDflt!=0;
145542  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
145543}
145544
145545/*
145546** Return a 64-bit integer value for a query parameter.
145547*/
145548SQLITE_API sqlite3_int64 sqlite3_uri_int64(
145549  const char *zFilename,    /* Filename as passed to xOpen */
145550  const char *zParam,       /* URI parameter sought */
145551  sqlite3_int64 bDflt       /* return if parameter is missing */
145552){
145553  const char *z = sqlite3_uri_parameter(zFilename, zParam);
145554  sqlite3_int64 v;
145555  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
145556    bDflt = v;
145557  }
145558  return bDflt;
145559}
145560
145561/*
145562** Return the Btree pointer identified by zDbName.  Return NULL if not found.
145563*/
145564SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
145565  int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
145566  return iDb<0 ? 0 : db->aDb[iDb].pBt;
145567}
145568
145569/*
145570** Return the filename of the database associated with a database
145571** connection.
145572*/
145573SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
145574  Btree *pBt;
145575#ifdef SQLITE_ENABLE_API_ARMOR
145576  if( !sqlite3SafetyCheckOk(db) ){
145577    (void)SQLITE_MISUSE_BKPT;
145578    return 0;
145579  }
145580#endif
145581  pBt = sqlite3DbNameToBtree(db, zDbName);
145582  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
145583}
145584
145585/*
145586** Return 1 if database is read-only or 0 if read/write.  Return -1 if
145587** no such database exists.
145588*/
145589SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
145590  Btree *pBt;
145591#ifdef SQLITE_ENABLE_API_ARMOR
145592  if( !sqlite3SafetyCheckOk(db) ){
145593    (void)SQLITE_MISUSE_BKPT;
145594    return -1;
145595  }
145596#endif
145597  pBt = sqlite3DbNameToBtree(db, zDbName);
145598  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
145599}
145600
145601#ifdef SQLITE_ENABLE_SNAPSHOT
145602/*
145603** Obtain a snapshot handle for the snapshot of database zDb currently
145604** being read by handle db.
145605*/
145606SQLITE_API int sqlite3_snapshot_get(
145607  sqlite3 *db,
145608  const char *zDb,
145609  sqlite3_snapshot **ppSnapshot
145610){
145611  int rc = SQLITE_ERROR;
145612#ifndef SQLITE_OMIT_WAL
145613
145614#ifdef SQLITE_ENABLE_API_ARMOR
145615  if( !sqlite3SafetyCheckOk(db) ){
145616    return SQLITE_MISUSE_BKPT;
145617  }
145618#endif
145619  sqlite3_mutex_enter(db->mutex);
145620
145621  if( db->autoCommit==0 ){
145622    int iDb = sqlite3FindDbName(db, zDb);
145623    if( iDb==0 || iDb>1 ){
145624      Btree *pBt = db->aDb[iDb].pBt;
145625      if( 0==sqlite3BtreeIsInTrans(pBt) ){
145626        rc = sqlite3BtreeBeginTrans(pBt, 0);
145627        if( rc==SQLITE_OK ){
145628          rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
145629        }
145630      }
145631    }
145632  }
145633
145634  sqlite3_mutex_leave(db->mutex);
145635#endif   /* SQLITE_OMIT_WAL */
145636  return rc;
145637}
145638
145639/*
145640** Open a read-transaction on the snapshot idendified by pSnapshot.
145641*/
145642SQLITE_API int sqlite3_snapshot_open(
145643  sqlite3 *db,
145644  const char *zDb,
145645  sqlite3_snapshot *pSnapshot
145646){
145647  int rc = SQLITE_ERROR;
145648#ifndef SQLITE_OMIT_WAL
145649
145650#ifdef SQLITE_ENABLE_API_ARMOR
145651  if( !sqlite3SafetyCheckOk(db) ){
145652    return SQLITE_MISUSE_BKPT;
145653  }
145654#endif
145655  sqlite3_mutex_enter(db->mutex);
145656  if( db->autoCommit==0 ){
145657    int iDb;
145658    iDb = sqlite3FindDbName(db, zDb);
145659    if( iDb==0 || iDb>1 ){
145660      Btree *pBt = db->aDb[iDb].pBt;
145661      if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
145662        rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
145663        if( rc==SQLITE_OK ){
145664          rc = sqlite3BtreeBeginTrans(pBt, 0);
145665          sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
145666        }
145667      }
145668    }
145669  }
145670
145671  sqlite3_mutex_leave(db->mutex);
145672#endif   /* SQLITE_OMIT_WAL */
145673  return rc;
145674}
145675
145676/*
145677** Recover as many snapshots as possible from the wal file associated with
145678** schema zDb of database db.
145679*/
145680SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
145681  int rc = SQLITE_ERROR;
145682  int iDb;
145683#ifndef SQLITE_OMIT_WAL
145684
145685#ifdef SQLITE_ENABLE_API_ARMOR
145686  if( !sqlite3SafetyCheckOk(db) ){
145687    return SQLITE_MISUSE_BKPT;
145688  }
145689#endif
145690
145691  sqlite3_mutex_enter(db->mutex);
145692  iDb = sqlite3FindDbName(db, zDb);
145693  if( iDb==0 || iDb>1 ){
145694    Btree *pBt = db->aDb[iDb].pBt;
145695    if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
145696      rc = sqlite3BtreeBeginTrans(pBt, 0);
145697      if( rc==SQLITE_OK ){
145698        rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
145699        sqlite3BtreeCommit(pBt);
145700      }
145701    }
145702  }
145703  sqlite3_mutex_leave(db->mutex);
145704#endif   /* SQLITE_OMIT_WAL */
145705  return rc;
145706}
145707
145708/*
145709** Free a snapshot handle obtained from sqlite3_snapshot_get().
145710*/
145711SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
145712  sqlite3_free(pSnapshot);
145713}
145714#endif /* SQLITE_ENABLE_SNAPSHOT */
145715
145716#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
145717/*
145718** Given the name of a compile-time option, return true if that option
145719** was used and false if not.
145720**
145721** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
145722** is not required for a match.
145723*/
145724SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
145725  int i, n;
145726  int nOpt;
145727  const char **azCompileOpt;
145728
145729#if SQLITE_ENABLE_API_ARMOR
145730  if( zOptName==0 ){
145731    (void)SQLITE_MISUSE_BKPT;
145732    return 0;
145733  }
145734#endif
145735
145736  azCompileOpt = sqlite3CompileOptions(&nOpt);
145737
145738  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
145739  n = sqlite3Strlen30(zOptName);
145740
145741  /* Since nOpt is normally in single digits, a linear search is
145742  ** adequate. No need for a binary search. */
145743  for(i=0; i<nOpt; i++){
145744    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
145745     && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
145746    ){
145747      return 1;
145748    }
145749  }
145750  return 0;
145751}
145752
145753/*
145754** Return the N-th compile-time option string.  If N is out of range,
145755** return a NULL pointer.
145756*/
145757SQLITE_API const char *sqlite3_compileoption_get(int N){
145758  int nOpt;
145759  const char **azCompileOpt;
145760  azCompileOpt = sqlite3CompileOptions(&nOpt);
145761  if( N>=0 && N<nOpt ){
145762    return azCompileOpt[N];
145763  }
145764  return 0;
145765}
145766#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
145767
145768/************** End of main.c ************************************************/
145769/************** Begin file notify.c ******************************************/
145770/*
145771** 2009 March 3
145772**
145773** The author disclaims copyright to this source code.  In place of
145774** a legal notice, here is a blessing:
145775**
145776**    May you do good and not evil.
145777**    May you find forgiveness for yourself and forgive others.
145778**    May you share freely, never taking more than you give.
145779**
145780*************************************************************************
145781**
145782** This file contains the implementation of the sqlite3_unlock_notify()
145783** API method and its associated functionality.
145784*/
145785/* #include "sqliteInt.h" */
145786/* #include "btreeInt.h" */
145787
145788/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
145789#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
145790
145791/*
145792** Public interfaces:
145793**
145794**   sqlite3ConnectionBlocked()
145795**   sqlite3ConnectionUnlocked()
145796**   sqlite3ConnectionClosed()
145797**   sqlite3_unlock_notify()
145798*/
145799
145800#define assertMutexHeld() \
145801  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
145802
145803/*
145804** Head of a linked list of all sqlite3 objects created by this process
145805** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
145806** is not NULL. This variable may only accessed while the STATIC_MASTER
145807** mutex is held.
145808*/
145809static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
145810
145811#ifndef NDEBUG
145812/*
145813** This function is a complex assert() that verifies the following
145814** properties of the blocked connections list:
145815**
145816**   1) Each entry in the list has a non-NULL value for either
145817**      pUnlockConnection or pBlockingConnection, or both.
145818**
145819**   2) All entries in the list that share a common value for
145820**      xUnlockNotify are grouped together.
145821**
145822**   3) If the argument db is not NULL, then none of the entries in the
145823**      blocked connections list have pUnlockConnection or pBlockingConnection
145824**      set to db. This is used when closing connection db.
145825*/
145826static void checkListProperties(sqlite3 *db){
145827  sqlite3 *p;
145828  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
145829    int seen = 0;
145830    sqlite3 *p2;
145831
145832    /* Verify property (1) */
145833    assert( p->pUnlockConnection || p->pBlockingConnection );
145834
145835    /* Verify property (2) */
145836    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
145837      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
145838      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
145839      assert( db==0 || p->pUnlockConnection!=db );
145840      assert( db==0 || p->pBlockingConnection!=db );
145841    }
145842  }
145843}
145844#else
145845# define checkListProperties(x)
145846#endif
145847
145848/*
145849** Remove connection db from the blocked connections list. If connection
145850** db is not currently a part of the list, this function is a no-op.
145851*/
145852static void removeFromBlockedList(sqlite3 *db){
145853  sqlite3 **pp;
145854  assertMutexHeld();
145855  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
145856    if( *pp==db ){
145857      *pp = (*pp)->pNextBlocked;
145858      break;
145859    }
145860  }
145861}
145862
145863/*
145864** Add connection db to the blocked connections list. It is assumed
145865** that it is not already a part of the list.
145866*/
145867static void addToBlockedList(sqlite3 *db){
145868  sqlite3 **pp;
145869  assertMutexHeld();
145870  for(
145871    pp=&sqlite3BlockedList;
145872    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
145873    pp=&(*pp)->pNextBlocked
145874  );
145875  db->pNextBlocked = *pp;
145876  *pp = db;
145877}
145878
145879/*
145880** Obtain the STATIC_MASTER mutex.
145881*/
145882static void enterMutex(void){
145883  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
145884  checkListProperties(0);
145885}
145886
145887/*
145888** Release the STATIC_MASTER mutex.
145889*/
145890static void leaveMutex(void){
145891  assertMutexHeld();
145892  checkListProperties(0);
145893  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
145894}
145895
145896/*
145897** Register an unlock-notify callback.
145898**
145899** This is called after connection "db" has attempted some operation
145900** but has received an SQLITE_LOCKED error because another connection
145901** (call it pOther) in the same process was busy using the same shared
145902** cache.  pOther is found by looking at db->pBlockingConnection.
145903**
145904** If there is no blocking connection, the callback is invoked immediately,
145905** before this routine returns.
145906**
145907** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
145908** a deadlock.
145909**
145910** Otherwise, make arrangements to invoke xNotify when pOther drops
145911** its locks.
145912**
145913** Each call to this routine overrides any prior callbacks registered
145914** on the same "db".  If xNotify==0 then any prior callbacks are immediately
145915** cancelled.
145916*/
145917SQLITE_API int sqlite3_unlock_notify(
145918  sqlite3 *db,
145919  void (*xNotify)(void **, int),
145920  void *pArg
145921){
145922  int rc = SQLITE_OK;
145923
145924  sqlite3_mutex_enter(db->mutex);
145925  enterMutex();
145926
145927  if( xNotify==0 ){
145928    removeFromBlockedList(db);
145929    db->pBlockingConnection = 0;
145930    db->pUnlockConnection = 0;
145931    db->xUnlockNotify = 0;
145932    db->pUnlockArg = 0;
145933  }else if( 0==db->pBlockingConnection ){
145934    /* The blocking transaction has been concluded. Or there never was a
145935    ** blocking transaction. In either case, invoke the notify callback
145936    ** immediately.
145937    */
145938    xNotify(&pArg, 1);
145939  }else{
145940    sqlite3 *p;
145941
145942    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
145943    if( p ){
145944      rc = SQLITE_LOCKED;              /* Deadlock detected. */
145945    }else{
145946      db->pUnlockConnection = db->pBlockingConnection;
145947      db->xUnlockNotify = xNotify;
145948      db->pUnlockArg = pArg;
145949      removeFromBlockedList(db);
145950      addToBlockedList(db);
145951    }
145952  }
145953
145954  leaveMutex();
145955  assert( !db->mallocFailed );
145956  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
145957  sqlite3_mutex_leave(db->mutex);
145958  return rc;
145959}
145960
145961/*
145962** This function is called while stepping or preparing a statement
145963** associated with connection db. The operation will return SQLITE_LOCKED
145964** to the user because it requires a lock that will not be available
145965** until connection pBlocker concludes its current transaction.
145966*/
145967SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
145968  enterMutex();
145969  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
145970    addToBlockedList(db);
145971  }
145972  db->pBlockingConnection = pBlocker;
145973  leaveMutex();
145974}
145975
145976/*
145977** This function is called when
145978** the transaction opened by database db has just finished. Locks held
145979** by database connection db have been released.
145980**
145981** This function loops through each entry in the blocked connections
145982** list and does the following:
145983**
145984**   1) If the sqlite3.pBlockingConnection member of a list entry is
145985**      set to db, then set pBlockingConnection=0.
145986**
145987**   2) If the sqlite3.pUnlockConnection member of a list entry is
145988**      set to db, then invoke the configured unlock-notify callback and
145989**      set pUnlockConnection=0.
145990**
145991**   3) If the two steps above mean that pBlockingConnection==0 and
145992**      pUnlockConnection==0, remove the entry from the blocked connections
145993**      list.
145994*/
145995SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
145996  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
145997  int nArg = 0;                            /* Number of entries in aArg[] */
145998  sqlite3 **pp;                            /* Iterator variable */
145999  void **aArg;               /* Arguments to the unlock callback */
146000  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
146001  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
146002
146003  aArg = aStatic;
146004  enterMutex();         /* Enter STATIC_MASTER mutex */
146005
146006  /* This loop runs once for each entry in the blocked-connections list. */
146007  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
146008    sqlite3 *p = *pp;
146009
146010    /* Step 1. */
146011    if( p->pBlockingConnection==db ){
146012      p->pBlockingConnection = 0;
146013    }
146014
146015    /* Step 2. */
146016    if( p->pUnlockConnection==db ){
146017      assert( p->xUnlockNotify );
146018      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
146019        xUnlockNotify(aArg, nArg);
146020        nArg = 0;
146021      }
146022
146023      sqlite3BeginBenignMalloc();
146024      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
146025      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
146026      if( (!aDyn && nArg==(int)ArraySize(aStatic))
146027       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
146028      ){
146029        /* The aArg[] array needs to grow. */
146030        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
146031        if( pNew ){
146032          memcpy(pNew, aArg, nArg*sizeof(void *));
146033          sqlite3_free(aDyn);
146034          aDyn = aArg = pNew;
146035        }else{
146036          /* This occurs when the array of context pointers that need to
146037          ** be passed to the unlock-notify callback is larger than the
146038          ** aStatic[] array allocated on the stack and the attempt to
146039          ** allocate a larger array from the heap has failed.
146040          **
146041          ** This is a difficult situation to handle. Returning an error
146042          ** code to the caller is insufficient, as even if an error code
146043          ** is returned the transaction on connection db will still be
146044          ** closed and the unlock-notify callbacks on blocked connections
146045          ** will go unissued. This might cause the application to wait
146046          ** indefinitely for an unlock-notify callback that will never
146047          ** arrive.
146048          **
146049          ** Instead, invoke the unlock-notify callback with the context
146050          ** array already accumulated. We can then clear the array and
146051          ** begin accumulating any further context pointers without
146052          ** requiring any dynamic allocation. This is sub-optimal because
146053          ** it means that instead of one callback with a large array of
146054          ** context pointers the application will receive two or more
146055          ** callbacks with smaller arrays of context pointers, which will
146056          ** reduce the applications ability to prioritize multiple
146057          ** connections. But it is the best that can be done under the
146058          ** circumstances.
146059          */
146060          xUnlockNotify(aArg, nArg);
146061          nArg = 0;
146062        }
146063      }
146064      sqlite3EndBenignMalloc();
146065
146066      aArg[nArg++] = p->pUnlockArg;
146067      xUnlockNotify = p->xUnlockNotify;
146068      p->pUnlockConnection = 0;
146069      p->xUnlockNotify = 0;
146070      p->pUnlockArg = 0;
146071    }
146072
146073    /* Step 3. */
146074    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
146075      /* Remove connection p from the blocked connections list. */
146076      *pp = p->pNextBlocked;
146077      p->pNextBlocked = 0;
146078    }else{
146079      pp = &p->pNextBlocked;
146080    }
146081  }
146082
146083  if( nArg!=0 ){
146084    xUnlockNotify(aArg, nArg);
146085  }
146086  sqlite3_free(aDyn);
146087  leaveMutex();         /* Leave STATIC_MASTER mutex */
146088}
146089
146090/*
146091** This is called when the database connection passed as an argument is
146092** being closed. The connection is removed from the blocked list.
146093*/
146094SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
146095  sqlite3ConnectionUnlocked(db);
146096  enterMutex();
146097  removeFromBlockedList(db);
146098  checkListProperties(db);
146099  leaveMutex();
146100}
146101#endif
146102
146103/************** End of notify.c **********************************************/
146104/************** Begin file fts3.c ********************************************/
146105/*
146106** 2006 Oct 10
146107**
146108** The author disclaims copyright to this source code.  In place of
146109** a legal notice, here is a blessing:
146110**
146111**    May you do good and not evil.
146112**    May you find forgiveness for yourself and forgive others.
146113**    May you share freely, never taking more than you give.
146114**
146115******************************************************************************
146116**
146117** This is an SQLite module implementing full-text search.
146118*/
146119
146120/*
146121** The code in this file is only compiled if:
146122**
146123**     * The FTS3 module is being built as an extension
146124**       (in which case SQLITE_CORE is not defined), or
146125**
146126**     * The FTS3 module is being built into the core of
146127**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
146128*/
146129
146130/* The full-text index is stored in a series of b+tree (-like)
146131** structures called segments which map terms to doclists.  The
146132** structures are like b+trees in layout, but are constructed from the
146133** bottom up in optimal fashion and are not updatable.  Since trees
146134** are built from the bottom up, things will be described from the
146135** bottom up.
146136**
146137**
146138**** Varints ****
146139** The basic unit of encoding is a variable-length integer called a
146140** varint.  We encode variable-length integers in little-endian order
146141** using seven bits * per byte as follows:
146142**
146143** KEY:
146144**         A = 0xxxxxxx    7 bits of data and one flag bit
146145**         B = 1xxxxxxx    7 bits of data and one flag bit
146146**
146147**  7 bits - A
146148** 14 bits - BA
146149** 21 bits - BBA
146150** and so on.
146151**
146152** This is similar in concept to how sqlite encodes "varints" but
146153** the encoding is not the same.  SQLite varints are big-endian
146154** are are limited to 9 bytes in length whereas FTS3 varints are
146155** little-endian and can be up to 10 bytes in length (in theory).
146156**
146157** Example encodings:
146158**
146159**     1:    0x01
146160**   127:    0x7f
146161**   128:    0x81 0x00
146162**
146163**
146164**** Document lists ****
146165** A doclist (document list) holds a docid-sorted list of hits for a
146166** given term.  Doclists hold docids and associated token positions.
146167** A docid is the unique integer identifier for a single document.
146168** A position is the index of a word within the document.  The first
146169** word of the document has a position of 0.
146170**
146171** FTS3 used to optionally store character offsets using a compile-time
146172** option.  But that functionality is no longer supported.
146173**
146174** A doclist is stored like this:
146175**
146176** array {
146177**   varint docid;          (delta from previous doclist)
146178**   array {                (position list for column 0)
146179**     varint position;     (2 more than the delta from previous position)
146180**   }
146181**   array {
146182**     varint POS_COLUMN;   (marks start of position list for new column)
146183**     varint column;       (index of new column)
146184**     array {
146185**       varint position;   (2 more than the delta from previous position)
146186**     }
146187**   }
146188**   varint POS_END;        (marks end of positions for this document.
146189** }
146190**
146191** Here, array { X } means zero or more occurrences of X, adjacent in
146192** memory.  A "position" is an index of a token in the token stream
146193** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
146194** in the same logical place as the position element, and act as sentinals
146195** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
146196** The positions numbers are not stored literally but rather as two more
146197** than the difference from the prior position, or the just the position plus
146198** 2 for the first position.  Example:
146199**
146200**   label:       A B C D E  F  G H   I  J K
146201**   value:     123 5 9 1 1 14 35 0 234 72 0
146202**
146203** The 123 value is the first docid.  For column zero in this document
146204** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
146205** at D signals the start of a new column; the 1 at E indicates that the
146206** new column is column number 1.  There are two positions at 12 and 45
146207** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
146208** 234 at I is the delta to next docid (357).  It has one position 70
146209** (72-2) and then terminates with the 0 at K.
146210**
146211** A "position-list" is the list of positions for multiple columns for
146212** a single docid.  A "column-list" is the set of positions for a single
146213** column.  Hence, a position-list consists of one or more column-lists,
146214** a document record consists of a docid followed by a position-list and
146215** a doclist consists of one or more document records.
146216**
146217** A bare doclist omits the position information, becoming an
146218** array of varint-encoded docids.
146219**
146220**** Segment leaf nodes ****
146221** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
146222** nodes are written using LeafWriter, and read using LeafReader (to
146223** iterate through a single leaf node's data) and LeavesReader (to
146224** iterate through a segment's entire leaf layer).  Leaf nodes have
146225** the format:
146226**
146227** varint iHeight;             (height from leaf level, always 0)
146228** varint nTerm;               (length of first term)
146229** char pTerm[nTerm];          (content of first term)
146230** varint nDoclist;            (length of term's associated doclist)
146231** char pDoclist[nDoclist];    (content of doclist)
146232** array {
146233**                             (further terms are delta-encoded)
146234**   varint nPrefix;           (length of prefix shared with previous term)
146235**   varint nSuffix;           (length of unshared suffix)
146236**   char pTermSuffix[nSuffix];(unshared suffix of next term)
146237**   varint nDoclist;          (length of term's associated doclist)
146238**   char pDoclist[nDoclist];  (content of doclist)
146239** }
146240**
146241** Here, array { X } means zero or more occurrences of X, adjacent in
146242** memory.
146243**
146244** Leaf nodes are broken into blocks which are stored contiguously in
146245** the %_segments table in sorted order.  This means that when the end
146246** of a node is reached, the next term is in the node with the next
146247** greater node id.
146248**
146249** New data is spilled to a new leaf node when the current node
146250** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
146251** larger than STANDALONE_MIN (default 1024) is placed in a standalone
146252** node (a leaf node with a single term and doclist).  The goal of
146253** these settings is to pack together groups of small doclists while
146254** making it efficient to directly access large doclists.  The
146255** assumption is that large doclists represent terms which are more
146256** likely to be query targets.
146257**
146258** TODO(shess) It may be useful for blocking decisions to be more
146259** dynamic.  For instance, it may make more sense to have a 2.5k leaf
146260** node rather than splitting into 2k and .5k nodes.  My intuition is
146261** that this might extend through 2x or 4x the pagesize.
146262**
146263**
146264**** Segment interior nodes ****
146265** Segment interior nodes store blockids for subtree nodes and terms
146266** to describe what data is stored by the each subtree.  Interior
146267** nodes are written using InteriorWriter, and read using
146268** InteriorReader.  InteriorWriters are created as needed when
146269** SegmentWriter creates new leaf nodes, or when an interior node
146270** itself grows too big and must be split.  The format of interior
146271** nodes:
146272**
146273** varint iHeight;           (height from leaf level, always >0)
146274** varint iBlockid;          (block id of node's leftmost subtree)
146275** optional {
146276**   varint nTerm;           (length of first term)
146277**   char pTerm[nTerm];      (content of first term)
146278**   array {
146279**                                (further terms are delta-encoded)
146280**     varint nPrefix;            (length of shared prefix with previous term)
146281**     varint nSuffix;            (length of unshared suffix)
146282**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
146283**   }
146284** }
146285**
146286** Here, optional { X } means an optional element, while array { X }
146287** means zero or more occurrences of X, adjacent in memory.
146288**
146289** An interior node encodes n terms separating n+1 subtrees.  The
146290** subtree blocks are contiguous, so only the first subtree's blockid
146291** is encoded.  The subtree at iBlockid will contain all terms less
146292** than the first term encoded (or all terms if no term is encoded).
146293** Otherwise, for terms greater than or equal to pTerm[i] but less
146294** than pTerm[i+1], the subtree for that term will be rooted at
146295** iBlockid+i.  Interior nodes only store enough term data to
146296** distinguish adjacent children (if the rightmost term of the left
146297** child is "something", and the leftmost term of the right child is
146298** "wicked", only "w" is stored).
146299**
146300** New data is spilled to a new interior node at the same height when
146301** the current node exceeds INTERIOR_MAX bytes (default 2048).
146302** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
146303** interior nodes and making the tree too skinny.  The interior nodes
146304** at a given height are naturally tracked by interior nodes at
146305** height+1, and so on.
146306**
146307**
146308**** Segment directory ****
146309** The segment directory in table %_segdir stores meta-information for
146310** merging and deleting segments, and also the root node of the
146311** segment's tree.
146312**
146313** The root node is the top node of the segment's tree after encoding
146314** the entire segment, restricted to ROOT_MAX bytes (default 1024).
146315** This could be either a leaf node or an interior node.  If the top
146316** node requires more than ROOT_MAX bytes, it is flushed to %_segments
146317** and a new root interior node is generated (which should always fit
146318** within ROOT_MAX because it only needs space for 2 varints, the
146319** height and the blockid of the previous root).
146320**
146321** The meta-information in the segment directory is:
146322**   level               - segment level (see below)
146323**   idx                 - index within level
146324**                       - (level,idx uniquely identify a segment)
146325**   start_block         - first leaf node
146326**   leaves_end_block    - last leaf node
146327**   end_block           - last block (including interior nodes)
146328**   root                - contents of root node
146329**
146330** If the root node is a leaf node, then start_block,
146331** leaves_end_block, and end_block are all 0.
146332**
146333**
146334**** Segment merging ****
146335** To amortize update costs, segments are grouped into levels and
146336** merged in batches.  Each increase in level represents exponentially
146337** more documents.
146338**
146339** New documents (actually, document updates) are tokenized and
146340** written individually (using LeafWriter) to a level 0 segment, with
146341** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
146342** level 0 segments are merged into a single level 1 segment.  Level 1
146343** is populated like level 0, and eventually MERGE_COUNT level 1
146344** segments are merged to a single level 2 segment (representing
146345** MERGE_COUNT^2 updates), and so on.
146346**
146347** A segment merge traverses all segments at a given level in
146348** parallel, performing a straightforward sorted merge.  Since segment
146349** leaf nodes are written in to the %_segments table in order, this
146350** merge traverses the underlying sqlite disk structures efficiently.
146351** After the merge, all segment blocks from the merged level are
146352** deleted.
146353**
146354** MERGE_COUNT controls how often we merge segments.  16 seems to be
146355** somewhat of a sweet spot for insertion performance.  32 and 64 show
146356** very similar performance numbers to 16 on insertion, though they're
146357** a tiny bit slower (perhaps due to more overhead in merge-time
146358** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
146359** 16, 2 about 66% slower than 16.
146360**
146361** At query time, high MERGE_COUNT increases the number of segments
146362** which need to be scanned and merged.  For instance, with 100k docs
146363** inserted:
146364**
146365**    MERGE_COUNT   segments
146366**       16           25
146367**        8           12
146368**        4           10
146369**        2            6
146370**
146371** This appears to have only a moderate impact on queries for very
146372** frequent terms (which are somewhat dominated by segment merge
146373** costs), and infrequent and non-existent terms still seem to be fast
146374** even with many segments.
146375**
146376** TODO(shess) That said, it would be nice to have a better query-side
146377** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
146378** optimizations to things like doclist merging will swing the sweet
146379** spot around.
146380**
146381**
146382**
146383**** Handling of deletions and updates ****
146384** Since we're using a segmented structure, with no docid-oriented
146385** index into the term index, we clearly cannot simply update the term
146386** index when a document is deleted or updated.  For deletions, we
146387** write an empty doclist (varint(docid) varint(POS_END)), for updates
146388** we simply write the new doclist.  Segment merges overwrite older
146389** data for a particular docid with newer data, so deletes or updates
146390** will eventually overtake the earlier data and knock it out.  The
146391** query logic likewise merges doclists so that newer data knocks out
146392** older data.
146393*/
146394
146395/************** Include fts3Int.h in the middle of fts3.c ********************/
146396/************** Begin file fts3Int.h *****************************************/
146397/*
146398** 2009 Nov 12
146399**
146400** The author disclaims copyright to this source code.  In place of
146401** a legal notice, here is a blessing:
146402**
146403**    May you do good and not evil.
146404**    May you find forgiveness for yourself and forgive others.
146405**    May you share freely, never taking more than you give.
146406**
146407******************************************************************************
146408**
146409*/
146410#ifndef _FTSINT_H
146411#define _FTSINT_H
146412
146413#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
146414# define NDEBUG 1
146415#endif
146416
146417/* FTS3/FTS4 require virtual tables */
146418#ifdef SQLITE_OMIT_VIRTUALTABLE
146419# undef SQLITE_ENABLE_FTS3
146420# undef SQLITE_ENABLE_FTS4
146421#endif
146422
146423/*
146424** FTS4 is really an extension for FTS3.  It is enabled using the
146425** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
146426** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
146427*/
146428#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
146429# define SQLITE_ENABLE_FTS3
146430#endif
146431
146432#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
146433
146434/* If not building as part of the core, include sqlite3ext.h. */
146435#ifndef SQLITE_CORE
146436/* # include "sqlite3ext.h"  */
146437SQLITE_EXTENSION_INIT3
146438#endif
146439
146440/* #include "sqlite3.h" */
146441/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
146442/************** Begin file fts3_tokenizer.h **********************************/
146443/*
146444** 2006 July 10
146445**
146446** The author disclaims copyright to this source code.
146447**
146448*************************************************************************
146449** Defines the interface to tokenizers used by fulltext-search.  There
146450** are three basic components:
146451**
146452** sqlite3_tokenizer_module is a singleton defining the tokenizer
146453** interface functions.  This is essentially the class structure for
146454** tokenizers.
146455**
146456** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
146457** including customization information defined at creation time.
146458**
146459** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
146460** tokens from a particular input.
146461*/
146462#ifndef _FTS3_TOKENIZER_H_
146463#define _FTS3_TOKENIZER_H_
146464
146465/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
146466** If tokenizers are to be allowed to call sqlite3_*() functions, then
146467** we will need a way to register the API consistently.
146468*/
146469/* #include "sqlite3.h" */
146470
146471/*
146472** Structures used by the tokenizer interface. When a new tokenizer
146473** implementation is registered, the caller provides a pointer to
146474** an sqlite3_tokenizer_module containing pointers to the callback
146475** functions that make up an implementation.
146476**
146477** When an fts3 table is created, it passes any arguments passed to
146478** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
146479** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
146480** implementation. The xCreate() function in turn returns an
146481** sqlite3_tokenizer structure representing the specific tokenizer to
146482** be used for the fts3 table (customized by the tokenizer clause arguments).
146483**
146484** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
146485** method is called. It returns an sqlite3_tokenizer_cursor object
146486** that may be used to tokenize a specific input buffer based on
146487** the tokenization rules supplied by a specific sqlite3_tokenizer
146488** object.
146489*/
146490typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
146491typedef struct sqlite3_tokenizer sqlite3_tokenizer;
146492typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
146493
146494struct sqlite3_tokenizer_module {
146495
146496  /*
146497  ** Structure version. Should always be set to 0 or 1.
146498  */
146499  int iVersion;
146500
146501  /*
146502  ** Create a new tokenizer. The values in the argv[] array are the
146503  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
146504  ** TABLE statement that created the fts3 table. For example, if
146505  ** the following SQL is executed:
146506  **
146507  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
146508  **
146509  ** then argc is set to 2, and the argv[] array contains pointers
146510  ** to the strings "arg1" and "arg2".
146511  **
146512  ** This method should return either SQLITE_OK (0), or an SQLite error
146513  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
146514  ** to point at the newly created tokenizer structure. The generic
146515  ** sqlite3_tokenizer.pModule variable should not be initialized by
146516  ** this callback. The caller will do so.
146517  */
146518  int (*xCreate)(
146519    int argc,                           /* Size of argv array */
146520    const char *const*argv,             /* Tokenizer argument strings */
146521    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
146522  );
146523
146524  /*
146525  ** Destroy an existing tokenizer. The fts3 module calls this method
146526  ** exactly once for each successful call to xCreate().
146527  */
146528  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
146529
146530  /*
146531  ** Create a tokenizer cursor to tokenize an input buffer. The caller
146532  ** is responsible for ensuring that the input buffer remains valid
146533  ** until the cursor is closed (using the xClose() method).
146534  */
146535  int (*xOpen)(
146536    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
146537    const char *pInput, int nBytes,      /* Input buffer */
146538    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
146539  );
146540
146541  /*
146542  ** Destroy an existing tokenizer cursor. The fts3 module calls this
146543  ** method exactly once for each successful call to xOpen().
146544  */
146545  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
146546
146547  /*
146548  ** Retrieve the next token from the tokenizer cursor pCursor. This
146549  ** method should either return SQLITE_OK and set the values of the
146550  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
146551  ** the end of the buffer has been reached, or an SQLite error code.
146552  **
146553  ** *ppToken should be set to point at a buffer containing the
146554  ** normalized version of the token (i.e. after any case-folding and/or
146555  ** stemming has been performed). *pnBytes should be set to the length
146556  ** of this buffer in bytes. The input text that generated the token is
146557  ** identified by the byte offsets returned in *piStartOffset and
146558  ** *piEndOffset. *piStartOffset should be set to the index of the first
146559  ** byte of the token in the input buffer. *piEndOffset should be set
146560  ** to the index of the first byte just past the end of the token in
146561  ** the input buffer.
146562  **
146563  ** The buffer *ppToken is set to point at is managed by the tokenizer
146564  ** implementation. It is only required to be valid until the next call
146565  ** to xNext() or xClose().
146566  */
146567  /* TODO(shess) current implementation requires pInput to be
146568  ** nul-terminated.  This should either be fixed, or pInput/nBytes
146569  ** should be converted to zInput.
146570  */
146571  int (*xNext)(
146572    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
146573    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
146574    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
146575    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
146576    int *piPosition      /* OUT: Number of tokens returned before this one */
146577  );
146578
146579  /***********************************************************************
146580  ** Methods below this point are only available if iVersion>=1.
146581  */
146582
146583  /*
146584  ** Configure the language id of a tokenizer cursor.
146585  */
146586  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
146587};
146588
146589struct sqlite3_tokenizer {
146590  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
146591  /* Tokenizer implementations will typically add additional fields */
146592};
146593
146594struct sqlite3_tokenizer_cursor {
146595  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
146596  /* Tokenizer implementations will typically add additional fields */
146597};
146598
146599int fts3_global_term_cnt(int iTerm, int iCol);
146600int fts3_term_cnt(int iTerm, int iCol);
146601
146602
146603#endif /* _FTS3_TOKENIZER_H_ */
146604
146605/************** End of fts3_tokenizer.h **************************************/
146606/************** Continuing where we left off in fts3Int.h ********************/
146607/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
146608/************** Begin file fts3_hash.h ***************************************/
146609/*
146610** 2001 September 22
146611**
146612** The author disclaims copyright to this source code.  In place of
146613** a legal notice, here is a blessing:
146614**
146615**    May you do good and not evil.
146616**    May you find forgiveness for yourself and forgive others.
146617**    May you share freely, never taking more than you give.
146618**
146619*************************************************************************
146620** This is the header file for the generic hash-table implementation
146621** used in SQLite.  We've modified it slightly to serve as a standalone
146622** hash table implementation for the full-text indexing module.
146623**
146624*/
146625#ifndef _FTS3_HASH_H_
146626#define _FTS3_HASH_H_
146627
146628/* Forward declarations of structures. */
146629typedef struct Fts3Hash Fts3Hash;
146630typedef struct Fts3HashElem Fts3HashElem;
146631
146632/* A complete hash table is an instance of the following structure.
146633** The internals of this structure are intended to be opaque -- client
146634** code should not attempt to access or modify the fields of this structure
146635** directly.  Change this structure only by using the routines below.
146636** However, many of the "procedures" and "functions" for modifying and
146637** accessing this structure are really macros, so we can't really make
146638** this structure opaque.
146639*/
146640struct Fts3Hash {
146641  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
146642  char copyKey;           /* True if copy of key made on insert */
146643  int count;              /* Number of entries in this table */
146644  Fts3HashElem *first;    /* The first element of the array */
146645  int htsize;             /* Number of buckets in the hash table */
146646  struct _fts3ht {        /* the hash table */
146647    int count;               /* Number of entries with this hash */
146648    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
146649  } *ht;
146650};
146651
146652/* Each element in the hash table is an instance of the following
146653** structure.  All elements are stored on a single doubly-linked list.
146654**
146655** Again, this structure is intended to be opaque, but it can't really
146656** be opaque because it is used by macros.
146657*/
146658struct Fts3HashElem {
146659  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
146660  void *data;                /* Data associated with this element */
146661  void *pKey; int nKey;      /* Key associated with this element */
146662};
146663
146664/*
146665** There are 2 different modes of operation for a hash table:
146666**
146667**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
146668**                           (including the null-terminator, if any).  Case
146669**                           is respected in comparisons.
146670**
146671**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
146672**                           memcmp() is used to compare keys.
146673**
146674** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
146675*/
146676#define FTS3_HASH_STRING    1
146677#define FTS3_HASH_BINARY    2
146678
146679/*
146680** Access routines.  To delete, insert a NULL pointer.
146681*/
146682SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
146683SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
146684SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
146685SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
146686SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
146687
146688/*
146689** Shorthand for the functions above
146690*/
146691#define fts3HashInit     sqlite3Fts3HashInit
146692#define fts3HashInsert   sqlite3Fts3HashInsert
146693#define fts3HashFind     sqlite3Fts3HashFind
146694#define fts3HashClear    sqlite3Fts3HashClear
146695#define fts3HashFindElem sqlite3Fts3HashFindElem
146696
146697/*
146698** Macros for looping over all elements of a hash table.  The idiom is
146699** like this:
146700**
146701**   Fts3Hash h;
146702**   Fts3HashElem *p;
146703**   ...
146704**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
146705**     SomeStructure *pData = fts3HashData(p);
146706**     // do something with pData
146707**   }
146708*/
146709#define fts3HashFirst(H)  ((H)->first)
146710#define fts3HashNext(E)   ((E)->next)
146711#define fts3HashData(E)   ((E)->data)
146712#define fts3HashKey(E)    ((E)->pKey)
146713#define fts3HashKeysize(E) ((E)->nKey)
146714
146715/*
146716** Number of entries in a hash table
146717*/
146718#define fts3HashCount(H)  ((H)->count)
146719
146720#endif /* _FTS3_HASH_H_ */
146721
146722/************** End of fts3_hash.h *******************************************/
146723/************** Continuing where we left off in fts3Int.h ********************/
146724
146725/*
146726** This constant determines the maximum depth of an FTS expression tree
146727** that the library will create and use. FTS uses recursion to perform
146728** various operations on the query tree, so the disadvantage of a large
146729** limit is that it may allow very large queries to use large amounts
146730** of stack space (perhaps causing a stack overflow).
146731*/
146732#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
146733# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
146734#endif
146735
146736
146737/*
146738** This constant controls how often segments are merged. Once there are
146739** FTS3_MERGE_COUNT segments of level N, they are merged into a single
146740** segment of level N+1.
146741*/
146742#define FTS3_MERGE_COUNT 16
146743
146744/*
146745** This is the maximum amount of data (in bytes) to store in the
146746** Fts3Table.pendingTerms hash table. Normally, the hash table is
146747** populated as documents are inserted/updated/deleted in a transaction
146748** and used to create a new segment when the transaction is committed.
146749** However if this limit is reached midway through a transaction, a new
146750** segment is created and the hash table cleared immediately.
146751*/
146752#define FTS3_MAX_PENDING_DATA (1*1024*1024)
146753
146754/*
146755** Macro to return the number of elements in an array. SQLite has a
146756** similar macro called ArraySize(). Use a different name to avoid
146757** a collision when building an amalgamation with built-in FTS3.
146758*/
146759#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
146760
146761
146762#ifndef MIN
146763# define MIN(x,y) ((x)<(y)?(x):(y))
146764#endif
146765#ifndef MAX
146766# define MAX(x,y) ((x)>(y)?(x):(y))
146767#endif
146768
146769/*
146770** Maximum length of a varint encoded integer. The varint format is different
146771** from that used by SQLite, so the maximum length is 10, not 9.
146772*/
146773#define FTS3_VARINT_MAX 10
146774
146775/*
146776** FTS4 virtual tables may maintain multiple indexes - one index of all terms
146777** in the document set and zero or more prefix indexes. All indexes are stored
146778** as one or more b+-trees in the %_segments and %_segdir tables.
146779**
146780** It is possible to determine which index a b+-tree belongs to based on the
146781** value stored in the "%_segdir.level" column. Given this value L, the index
146782** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
146783** level values between 0 and 1023 (inclusive) belong to index 0, all levels
146784** between 1024 and 2047 to index 1, and so on.
146785**
146786** It is considered impossible for an index to use more than 1024 levels. In
146787** theory though this may happen, but only after at least
146788** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
146789*/
146790#define FTS3_SEGDIR_MAXLEVEL      1024
146791#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
146792
146793/*
146794** The testcase() macro is only used by the amalgamation.  If undefined,
146795** make it a no-op.
146796*/
146797#ifndef testcase
146798# define testcase(X)
146799#endif
146800
146801/*
146802** Terminator values for position-lists and column-lists.
146803*/
146804#define POS_COLUMN  (1)     /* Column-list terminator */
146805#define POS_END     (0)     /* Position-list terminator */
146806
146807/*
146808** This section provides definitions to allow the
146809** FTS3 extension to be compiled outside of the
146810** amalgamation.
146811*/
146812#ifndef SQLITE_AMALGAMATION
146813/*
146814** Macros indicating that conditional expressions are always true or
146815** false.
146816*/
146817#ifdef SQLITE_COVERAGE_TEST
146818# define ALWAYS(x) (1)
146819# define NEVER(X)  (0)
146820#elif defined(SQLITE_DEBUG)
146821# define ALWAYS(x) sqlite3Fts3Always((x)!=0)
146822# define NEVER(x) sqlite3Fts3Never((x)!=0)
146823SQLITE_PRIVATE int sqlite3Fts3Always(int b);
146824SQLITE_PRIVATE int sqlite3Fts3Never(int b);
146825#else
146826# define ALWAYS(x) (x)
146827# define NEVER(x)  (x)
146828#endif
146829
146830/*
146831** Internal types used by SQLite.
146832*/
146833typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
146834typedef short int i16;            /* 2-byte (or larger) signed integer */
146835typedef unsigned int u32;         /* 4-byte unsigned integer */
146836typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
146837typedef sqlite3_int64 i64;        /* 8-byte signed integer */
146838
146839/*
146840** Macro used to suppress compiler warnings for unused parameters.
146841*/
146842#define UNUSED_PARAMETER(x) (void)(x)
146843
146844/*
146845** Activate assert() only if SQLITE_TEST is enabled.
146846*/
146847#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
146848# define NDEBUG 1
146849#endif
146850
146851/*
146852** The TESTONLY macro is used to enclose variable declarations or
146853** other bits of code that are needed to support the arguments
146854** within testcase() and assert() macros.
146855*/
146856#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
146857# define TESTONLY(X)  X
146858#else
146859# define TESTONLY(X)
146860#endif
146861
146862#endif /* SQLITE_AMALGAMATION */
146863
146864#ifdef SQLITE_DEBUG
146865SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
146866# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
146867#else
146868# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
146869#endif
146870
146871typedef struct Fts3Table Fts3Table;
146872typedef struct Fts3Cursor Fts3Cursor;
146873typedef struct Fts3Expr Fts3Expr;
146874typedef struct Fts3Phrase Fts3Phrase;
146875typedef struct Fts3PhraseToken Fts3PhraseToken;
146876
146877typedef struct Fts3Doclist Fts3Doclist;
146878typedef struct Fts3SegFilter Fts3SegFilter;
146879typedef struct Fts3DeferredToken Fts3DeferredToken;
146880typedef struct Fts3SegReader Fts3SegReader;
146881typedef struct Fts3MultiSegReader Fts3MultiSegReader;
146882
146883typedef struct MatchinfoBuffer MatchinfoBuffer;
146884
146885/*
146886** A connection to a fulltext index is an instance of the following
146887** structure. The xCreate and xConnect methods create an instance
146888** of this structure and xDestroy and xDisconnect free that instance.
146889** All other methods receive a pointer to the structure as one of their
146890** arguments.
146891*/
146892struct Fts3Table {
146893  sqlite3_vtab base;              /* Base class used by SQLite core */
146894  sqlite3 *db;                    /* The database connection */
146895  const char *zDb;                /* logical database name */
146896  const char *zName;              /* virtual table name */
146897  int nColumn;                    /* number of named columns in virtual table */
146898  char **azColumn;                /* column names.  malloced */
146899  u8 *abNotindexed;               /* True for 'notindexed' columns */
146900  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
146901  char *zContentTbl;              /* content=xxx option, or NULL */
146902  char *zLanguageid;              /* languageid=xxx option, or NULL */
146903  int nAutoincrmerge;             /* Value configured by 'automerge' */
146904  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
146905
146906  /* Precompiled statements used by the implementation. Each of these
146907  ** statements is run and reset within a single virtual table API call.
146908  */
146909  sqlite3_stmt *aStmt[40];
146910  sqlite3_stmt *pSeekStmt;        /* Cache for fts3CursorSeekStmt() */
146911
146912  char *zReadExprlist;
146913  char *zWriteExprlist;
146914
146915  int nNodeSize;                  /* Soft limit for node size */
146916  u8 bFts4;                       /* True for FTS4, false for FTS3 */
146917  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
146918  u8 bHasDocsize;                 /* True if %_docsize table exists */
146919  u8 bDescIdx;                    /* True if doclists are in reverse order */
146920  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
146921  int nPgsz;                      /* Page size for host database */
146922  char *zSegmentsTbl;             /* Name of %_segments table */
146923  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
146924
146925  /*
146926  ** The following array of hash tables is used to buffer pending index
146927  ** updates during transactions. All pending updates buffered at any one
146928  ** time must share a common language-id (see the FTS4 langid= feature).
146929  ** The current language id is stored in variable iPrevLangid.
146930  **
146931  ** A single FTS4 table may have multiple full-text indexes. For each index
146932  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
146933  ** terms that appear in the document set. Each subsequent index in aIndex[]
146934  ** is an index of prefixes of a specific length.
146935  **
146936  ** Variable nPendingData contains an estimate the memory consumed by the
146937  ** pending data structures, including hash table overhead, but not including
146938  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
146939  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
146940  ** recently inserted record.
146941  */
146942  int nIndex;                     /* Size of aIndex[] */
146943  struct Fts3Index {
146944    int nPrefix;                  /* Prefix length (0 for main terms index) */
146945    Fts3Hash hPending;            /* Pending terms table for this index */
146946  } *aIndex;
146947  int nMaxPendingData;            /* Max pending data before flush to disk */
146948  int nPendingData;               /* Current bytes of pending data */
146949  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
146950  int iPrevLangid;                /* Langid of recently inserted document */
146951  int bPrevDelete;                /* True if last operation was a delete */
146952
146953#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
146954  /* State variables used for validating that the transaction control
146955  ** methods of the virtual table are called at appropriate times.  These
146956  ** values do not contribute to FTS functionality; they are used for
146957  ** verifying the operation of the SQLite core.
146958  */
146959  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
146960  int mxSavepoint;       /* Largest valid xSavepoint integer */
146961#endif
146962
146963#ifdef SQLITE_TEST
146964  /* True to disable the incremental doclist optimization. This is controled
146965  ** by special insert command 'test-no-incr-doclist'.  */
146966  int bNoIncrDoclist;
146967#endif
146968};
146969
146970/*
146971** When the core wants to read from the virtual table, it creates a
146972** virtual table cursor (an instance of the following structure) using
146973** the xOpen method. Cursors are destroyed using the xClose method.
146974*/
146975struct Fts3Cursor {
146976  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
146977  i16 eSearch;                    /* Search strategy (see below) */
146978  u8 isEof;                       /* True if at End Of Results */
146979  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
146980  u8 bSeekStmt;                   /* True if pStmt is a seek */
146981  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
146982  Fts3Expr *pExpr;                /* Parsed MATCH query string */
146983  int iLangid;                    /* Language being queried for */
146984  int nPhrase;                    /* Number of matchable phrases in query */
146985  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
146986  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
146987  char *pNextId;                  /* Pointer into the body of aDoclist */
146988  char *aDoclist;                 /* List of docids for full-text queries */
146989  int nDoclist;                   /* Size of buffer at aDoclist */
146990  u8 bDesc;                       /* True to sort in descending order */
146991  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
146992  int nRowAvg;                    /* Average size of database rows, in pages */
146993  sqlite3_int64 nDoc;             /* Documents in table */
146994  i64 iMinDocid;                  /* Minimum docid to return */
146995  i64 iMaxDocid;                  /* Maximum docid to return */
146996  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
146997  MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
146998};
146999
147000#define FTS3_EVAL_FILTER    0
147001#define FTS3_EVAL_NEXT      1
147002#define FTS3_EVAL_MATCHINFO 2
147003
147004/*
147005** The Fts3Cursor.eSearch member is always set to one of the following.
147006** Actualy, Fts3Cursor.eSearch can be greater than or equal to
147007** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
147008** of the column to be searched.  For example, in
147009**
147010**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
147011**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
147012**
147013** Because the LHS of the MATCH operator is 2nd column "b",
147014** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
147015** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
147016** indicating that all columns should be searched,
147017** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
147018*/
147019#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
147020#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
147021#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
147022
147023/*
147024** The lower 16-bits of the sqlite3_index_info.idxNum value set by
147025** the xBestIndex() method contains the Fts3Cursor.eSearch value described
147026** above. The upper 16-bits contain a combination of the following
147027** bits, used to describe extra constraints on full-text searches.
147028*/
147029#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
147030#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
147031#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
147032
147033struct Fts3Doclist {
147034  char *aAll;                    /* Array containing doclist (or NULL) */
147035  int nAll;                      /* Size of a[] in bytes */
147036  char *pNextDocid;              /* Pointer to next docid */
147037
147038  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
147039  int bFreeList;                 /* True if pList should be sqlite3_free()d */
147040  char *pList;                   /* Pointer to position list following iDocid */
147041  int nList;                     /* Length of position list */
147042};
147043
147044/*
147045** A "phrase" is a sequence of one or more tokens that must match in
147046** sequence.  A single token is the base case and the most common case.
147047** For a sequence of tokens contained in double-quotes (i.e. "one two three")
147048** nToken will be the number of tokens in the string.
147049*/
147050struct Fts3PhraseToken {
147051  char *z;                        /* Text of the token */
147052  int n;                          /* Number of bytes in buffer z */
147053  int isPrefix;                   /* True if token ends with a "*" character */
147054  int bFirst;                     /* True if token must appear at position 0 */
147055
147056  /* Variables above this point are populated when the expression is
147057  ** parsed (by code in fts3_expr.c). Below this point the variables are
147058  ** used when evaluating the expression. */
147059  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
147060  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
147061};
147062
147063struct Fts3Phrase {
147064  /* Cache of doclist for this phrase. */
147065  Fts3Doclist doclist;
147066  int bIncr;                 /* True if doclist is loaded incrementally */
147067  int iDoclistToken;
147068
147069  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
147070  ** OR condition.  */
147071  char *pOrPoslist;
147072  i64 iOrDocid;
147073
147074  /* Variables below this point are populated by fts3_expr.c when parsing
147075  ** a MATCH expression. Everything above is part of the evaluation phase.
147076  */
147077  int nToken;                /* Number of tokens in the phrase */
147078  int iColumn;               /* Index of column this phrase must match */
147079  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
147080};
147081
147082/*
147083** A tree of these objects forms the RHS of a MATCH operator.
147084**
147085** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
147086** points to a malloced buffer, size nDoclist bytes, containing the results
147087** of this phrase query in FTS3 doclist format. As usual, the initial
147088** "Length" field found in doclists stored on disk is omitted from this
147089** buffer.
147090**
147091** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
147092** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
147093** where nCol is the number of columns in the queried FTS table. The array
147094** is populated as follows:
147095**
147096**   aMI[iCol*3 + 0] = Undefined
147097**   aMI[iCol*3 + 1] = Number of occurrences
147098**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
147099**
147100** The aMI array is allocated using sqlite3_malloc(). It should be freed
147101** when the expression node is.
147102*/
147103struct Fts3Expr {
147104  int eType;                 /* One of the FTSQUERY_XXX values defined below */
147105  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
147106  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
147107  Fts3Expr *pLeft;           /* Left operand */
147108  Fts3Expr *pRight;          /* Right operand */
147109  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
147110
147111  /* The following are used by the fts3_eval.c module. */
147112  sqlite3_int64 iDocid;      /* Current docid */
147113  u8 bEof;                   /* True this expression is at EOF already */
147114  u8 bStart;                 /* True if iDocid is valid */
147115  u8 bDeferred;              /* True if this expression is entirely deferred */
147116
147117  /* The following are used by the fts3_snippet.c module. */
147118  int iPhrase;               /* Index of this phrase in matchinfo() results */
147119  u32 *aMI;                  /* See above */
147120};
147121
147122/*
147123** Candidate values for Fts3Query.eType. Note that the order of the first
147124** four values is in order of precedence when parsing expressions. For
147125** example, the following:
147126**
147127**   "a OR b AND c NOT d NEAR e"
147128**
147129** is equivalent to:
147130**
147131**   "a OR (b AND (c NOT (d NEAR e)))"
147132*/
147133#define FTSQUERY_NEAR   1
147134#define FTSQUERY_NOT    2
147135#define FTSQUERY_AND    3
147136#define FTSQUERY_OR     4
147137#define FTSQUERY_PHRASE 5
147138
147139
147140/* fts3_write.c */
147141SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
147142SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
147143SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
147144SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
147145SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
147146  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
147147SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
147148  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
147149SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
147150SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
147151SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
147152
147153SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
147154SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
147155
147156#ifndef SQLITE_DISABLE_FTS4_DEFERRED
147157SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
147158SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
147159SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
147160SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
147161SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
147162#else
147163# define sqlite3Fts3FreeDeferredTokens(x)
147164# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
147165# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
147166# define sqlite3Fts3FreeDeferredDoclists(x)
147167# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
147168#endif
147169
147170SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
147171SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
147172
147173/* Special values interpreted by sqlite3SegReaderCursor() */
147174#define FTS3_SEGCURSOR_PENDING        -1
147175#define FTS3_SEGCURSOR_ALL            -2
147176
147177SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
147178SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
147179SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
147180
147181SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
147182    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
147183
147184/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
147185#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
147186#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
147187#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
147188#define FTS3_SEGMENT_PREFIX        0x00000008
147189#define FTS3_SEGMENT_SCAN          0x00000010
147190#define FTS3_SEGMENT_FIRST         0x00000020
147191
147192/* Type passed as 4th argument to SegmentReaderIterate() */
147193struct Fts3SegFilter {
147194  const char *zTerm;
147195  int nTerm;
147196  int iCol;
147197  int flags;
147198};
147199
147200struct Fts3MultiSegReader {
147201  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
147202  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
147203  int nSegment;                   /* Size of apSegment array */
147204  int nAdvance;                   /* How many seg-readers to advance */
147205  Fts3SegFilter *pFilter;         /* Pointer to filter object */
147206  char *aBuffer;                  /* Buffer to merge doclists in */
147207  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
147208
147209  int iColFilter;                 /* If >=0, filter for this column */
147210  int bRestart;
147211
147212  /* Used by fts3.c only. */
147213  int nCost;                      /* Cost of running iterator */
147214  int bLookup;                    /* True if a lookup of a single entry. */
147215
147216  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
147217  char *zTerm;                    /* Pointer to term buffer */
147218  int nTerm;                      /* Size of zTerm in bytes */
147219  char *aDoclist;                 /* Pointer to doclist buffer */
147220  int nDoclist;                   /* Size of aDoclist[] in bytes */
147221};
147222
147223SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
147224
147225#define fts3GetVarint32(p, piVal) (                                           \
147226  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
147227)
147228
147229/* fts3.c */
147230SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
147231SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
147232SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
147233SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
147234SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
147235SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
147236SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
147237SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
147238SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
147239SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
147240SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
147241
147242/* fts3_tokenizer.c */
147243SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
147244SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
147245SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
147246    sqlite3_tokenizer **, char **
147247);
147248SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
147249
147250/* fts3_snippet.c */
147251SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
147252SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
147253  const char *, const char *, int, int
147254);
147255SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
147256SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
147257
147258/* fts3_expr.c */
147259SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
147260  char **, int, int, int, const char *, int, Fts3Expr **, char **
147261);
147262SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
147263#ifdef SQLITE_TEST
147264SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
147265SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
147266#endif
147267
147268SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
147269  sqlite3_tokenizer_cursor **
147270);
147271
147272/* fts3_aux.c */
147273SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
147274
147275SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
147276
147277SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
147278    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
147279SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
147280    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
147281SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
147282SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
147283SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
147284
147285/* fts3_tokenize_vtab.c */
147286SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
147287
147288/* fts3_unicode2.c (functions generated by parsing unicode text files) */
147289#ifndef SQLITE_DISABLE_FTS3_UNICODE
147290SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
147291SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
147292SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
147293#endif
147294
147295#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
147296#endif /* _FTSINT_H */
147297
147298/************** End of fts3Int.h *********************************************/
147299/************** Continuing where we left off in fts3.c ***********************/
147300#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147301
147302#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
147303# define SQLITE_CORE 1
147304#endif
147305
147306/* #include <assert.h> */
147307/* #include <stdlib.h> */
147308/* #include <stddef.h> */
147309/* #include <stdio.h> */
147310/* #include <string.h> */
147311/* #include <stdarg.h> */
147312
147313/* #include "fts3.h" */
147314#ifndef SQLITE_CORE
147315/* # include "sqlite3ext.h" */
147316  SQLITE_EXTENSION_INIT1
147317#endif
147318
147319static int fts3EvalNext(Fts3Cursor *pCsr);
147320static int fts3EvalStart(Fts3Cursor *pCsr);
147321static int fts3TermSegReaderCursor(
147322    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
147323
147324#ifndef SQLITE_AMALGAMATION
147325# if defined(SQLITE_DEBUG)
147326SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
147327SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
147328# endif
147329#endif
147330
147331/*
147332** Write a 64-bit variable-length integer to memory starting at p[0].
147333** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
147334** The number of bytes written is returned.
147335*/
147336SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
147337  unsigned char *q = (unsigned char *) p;
147338  sqlite_uint64 vu = v;
147339  do{
147340    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
147341    vu >>= 7;
147342  }while( vu!=0 );
147343  q[-1] &= 0x7f;  /* turn off high bit in final byte */
147344  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
147345  return (int) (q - (unsigned char *)p);
147346}
147347
147348#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
147349  v = (v & mask1) | ( (*ptr++) << shift );                    \
147350  if( (v & mask2)==0 ){ var = v; return ret; }
147351#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
147352  v = (*ptr++);                                               \
147353  if( (v & mask2)==0 ){ var = v; return ret; }
147354
147355/*
147356** Read a 64-bit variable-length integer from memory starting at p[0].
147357** Return the number of bytes read, or 0 on error.
147358** The value is stored in *v.
147359*/
147360SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
147361  const unsigned char *p = (const unsigned char*)pBuf;
147362  const unsigned char *pStart = p;
147363  u32 a;
147364  u64 b;
147365  int shift;
147366
147367  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
147368  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
147369  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
147370  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
147371  b = (a & 0x0FFFFFFF );
147372
147373  for(shift=28; shift<=63; shift+=7){
147374    u64 c = *p++;
147375    b += (c&0x7F) << shift;
147376    if( (c & 0x80)==0 ) break;
147377  }
147378  *v = b;
147379  return (int)(p - pStart);
147380}
147381
147382/*
147383** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
147384** a non-negative 32-bit integer before it is returned.
147385*/
147386SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
147387  u32 a;
147388
147389#ifndef fts3GetVarint32
147390  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
147391#else
147392  a = (*p++);
147393  assert( a & 0x80 );
147394#endif
147395
147396  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
147397  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
147398  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
147399  a = (a & 0x0FFFFFFF );
147400  *pi = (int)(a | ((u32)(*p & 0x07) << 28));
147401  assert( 0==(a & 0x80000000) );
147402  assert( *pi>=0 );
147403  return 5;
147404}
147405
147406/*
147407** Return the number of bytes required to encode v as a varint
147408*/
147409SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
147410  int i = 0;
147411  do{
147412    i++;
147413    v >>= 7;
147414  }while( v!=0 );
147415  return i;
147416}
147417
147418/*
147419** Convert an SQL-style quoted string into a normal string by removing
147420** the quote characters.  The conversion is done in-place.  If the
147421** input does not begin with a quote character, then this routine
147422** is a no-op.
147423**
147424** Examples:
147425**
147426**     "abc"   becomes   abc
147427**     'xyz'   becomes   xyz
147428**     [pqr]   becomes   pqr
147429**     `mno`   becomes   mno
147430**
147431*/
147432SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
147433  char quote;                     /* Quote character (if any ) */
147434
147435  quote = z[0];
147436  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
147437    int iIn = 1;                  /* Index of next byte to read from input */
147438    int iOut = 0;                 /* Index of next byte to write to output */
147439
147440    /* If the first byte was a '[', then the close-quote character is a ']' */
147441    if( quote=='[' ) quote = ']';
147442
147443    while( z[iIn] ){
147444      if( z[iIn]==quote ){
147445        if( z[iIn+1]!=quote ) break;
147446        z[iOut++] = quote;
147447        iIn += 2;
147448      }else{
147449        z[iOut++] = z[iIn++];
147450      }
147451    }
147452    z[iOut] = '\0';
147453  }
147454}
147455
147456/*
147457** Read a single varint from the doclist at *pp and advance *pp to point
147458** to the first byte past the end of the varint.  Add the value of the varint
147459** to *pVal.
147460*/
147461static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
147462  sqlite3_int64 iVal;
147463  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
147464  *pVal += iVal;
147465}
147466
147467/*
147468** When this function is called, *pp points to the first byte following a
147469** varint that is part of a doclist (or position-list, or any other list
147470** of varints). This function moves *pp to point to the start of that varint,
147471** and sets *pVal by the varint value.
147472**
147473** Argument pStart points to the first byte of the doclist that the
147474** varint is part of.
147475*/
147476static void fts3GetReverseVarint(
147477  char **pp,
147478  char *pStart,
147479  sqlite3_int64 *pVal
147480){
147481  sqlite3_int64 iVal;
147482  char *p;
147483
147484  /* Pointer p now points at the first byte past the varint we are
147485  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
147486  ** clear on character p[-1]. */
147487  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
147488  p++;
147489  *pp = p;
147490
147491  sqlite3Fts3GetVarint(p, &iVal);
147492  *pVal = iVal;
147493}
147494
147495/*
147496** The xDisconnect() virtual table method.
147497*/
147498static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
147499  Fts3Table *p = (Fts3Table *)pVtab;
147500  int i;
147501
147502  assert( p->nPendingData==0 );
147503  assert( p->pSegments==0 );
147504
147505  /* Free any prepared statements held */
147506  sqlite3_finalize(p->pSeekStmt);
147507  for(i=0; i<SizeofArray(p->aStmt); i++){
147508    sqlite3_finalize(p->aStmt[i]);
147509  }
147510  sqlite3_free(p->zSegmentsTbl);
147511  sqlite3_free(p->zReadExprlist);
147512  sqlite3_free(p->zWriteExprlist);
147513  sqlite3_free(p->zContentTbl);
147514  sqlite3_free(p->zLanguageid);
147515
147516  /* Invoke the tokenizer destructor to free the tokenizer. */
147517  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
147518
147519  sqlite3_free(p);
147520  return SQLITE_OK;
147521}
147522
147523/*
147524** Write an error message into *pzErr
147525*/
147526SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
147527  va_list ap;
147528  sqlite3_free(*pzErr);
147529  va_start(ap, zFormat);
147530  *pzErr = sqlite3_vmprintf(zFormat, ap);
147531  va_end(ap);
147532}
147533
147534/*
147535** Construct one or more SQL statements from the format string given
147536** and then evaluate those statements. The success code is written
147537** into *pRc.
147538**
147539** If *pRc is initially non-zero then this routine is a no-op.
147540*/
147541static void fts3DbExec(
147542  int *pRc,              /* Success code */
147543  sqlite3 *db,           /* Database in which to run SQL */
147544  const char *zFormat,   /* Format string for SQL */
147545  ...                    /* Arguments to the format string */
147546){
147547  va_list ap;
147548  char *zSql;
147549  if( *pRc ) return;
147550  va_start(ap, zFormat);
147551  zSql = sqlite3_vmprintf(zFormat, ap);
147552  va_end(ap);
147553  if( zSql==0 ){
147554    *pRc = SQLITE_NOMEM;
147555  }else{
147556    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
147557    sqlite3_free(zSql);
147558  }
147559}
147560
147561/*
147562** The xDestroy() virtual table method.
147563*/
147564static int fts3DestroyMethod(sqlite3_vtab *pVtab){
147565  Fts3Table *p = (Fts3Table *)pVtab;
147566  int rc = SQLITE_OK;              /* Return code */
147567  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
147568  sqlite3 *db = p->db;             /* Database handle */
147569
147570  /* Drop the shadow tables */
147571  if( p->zContentTbl==0 ){
147572    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
147573  }
147574  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
147575  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
147576  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
147577  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
147578
147579  /* If everything has worked, invoke fts3DisconnectMethod() to free the
147580  ** memory associated with the Fts3Table structure and return SQLITE_OK.
147581  ** Otherwise, return an SQLite error code.
147582  */
147583  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
147584}
147585
147586
147587/*
147588** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
147589** passed as the first argument. This is done as part of the xConnect()
147590** and xCreate() methods.
147591**
147592** If *pRc is non-zero when this function is called, it is a no-op.
147593** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
147594** before returning.
147595*/
147596static void fts3DeclareVtab(int *pRc, Fts3Table *p){
147597  if( *pRc==SQLITE_OK ){
147598    int i;                        /* Iterator variable */
147599    int rc;                       /* Return code */
147600    char *zSql;                   /* SQL statement passed to declare_vtab() */
147601    char *zCols;                  /* List of user defined columns */
147602    const char *zLanguageid;
147603
147604    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
147605    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
147606
147607    /* Create a list of user columns for the virtual table */
147608    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
147609    for(i=1; zCols && i<p->nColumn; i++){
147610      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
147611    }
147612
147613    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
147614    zSql = sqlite3_mprintf(
147615        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
147616        zCols, p->zName, zLanguageid
147617    );
147618    if( !zCols || !zSql ){
147619      rc = SQLITE_NOMEM;
147620    }else{
147621      rc = sqlite3_declare_vtab(p->db, zSql);
147622    }
147623
147624    sqlite3_free(zSql);
147625    sqlite3_free(zCols);
147626    *pRc = rc;
147627  }
147628}
147629
147630/*
147631** Create the %_stat table if it does not already exist.
147632*/
147633SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
147634  fts3DbExec(pRc, p->db,
147635      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
147636          "(id INTEGER PRIMARY KEY, value BLOB);",
147637      p->zDb, p->zName
147638  );
147639  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
147640}
147641
147642/*
147643** Create the backing store tables (%_content, %_segments and %_segdir)
147644** required by the FTS3 table passed as the only argument. This is done
147645** as part of the vtab xCreate() method.
147646**
147647** If the p->bHasDocsize boolean is true (indicating that this is an
147648** FTS4 table, not an FTS3 table) then also create the %_docsize and
147649** %_stat tables required by FTS4.
147650*/
147651static int fts3CreateTables(Fts3Table *p){
147652  int rc = SQLITE_OK;             /* Return code */
147653  int i;                          /* Iterator variable */
147654  sqlite3 *db = p->db;            /* The database connection */
147655
147656  if( p->zContentTbl==0 ){
147657    const char *zLanguageid = p->zLanguageid;
147658    char *zContentCols;           /* Columns of %_content table */
147659
147660    /* Create a list of user columns for the content table */
147661    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
147662    for(i=0; zContentCols && i<p->nColumn; i++){
147663      char *z = p->azColumn[i];
147664      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
147665    }
147666    if( zLanguageid && zContentCols ){
147667      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
147668    }
147669    if( zContentCols==0 ) rc = SQLITE_NOMEM;
147670
147671    /* Create the content table */
147672    fts3DbExec(&rc, db,
147673       "CREATE TABLE %Q.'%q_content'(%s)",
147674       p->zDb, p->zName, zContentCols
147675    );
147676    sqlite3_free(zContentCols);
147677  }
147678
147679  /* Create other tables */
147680  fts3DbExec(&rc, db,
147681      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
147682      p->zDb, p->zName
147683  );
147684  fts3DbExec(&rc, db,
147685      "CREATE TABLE %Q.'%q_segdir'("
147686        "level INTEGER,"
147687        "idx INTEGER,"
147688        "start_block INTEGER,"
147689        "leaves_end_block INTEGER,"
147690        "end_block INTEGER,"
147691        "root BLOB,"
147692        "PRIMARY KEY(level, idx)"
147693      ");",
147694      p->zDb, p->zName
147695  );
147696  if( p->bHasDocsize ){
147697    fts3DbExec(&rc, db,
147698        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
147699        p->zDb, p->zName
147700    );
147701  }
147702  assert( p->bHasStat==p->bFts4 );
147703  if( p->bHasStat ){
147704    sqlite3Fts3CreateStatTable(&rc, p);
147705  }
147706  return rc;
147707}
147708
147709/*
147710** Store the current database page-size in bytes in p->nPgsz.
147711**
147712** If *pRc is non-zero when this function is called, it is a no-op.
147713** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
147714** before returning.
147715*/
147716static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
147717  if( *pRc==SQLITE_OK ){
147718    int rc;                       /* Return code */
147719    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
147720    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
147721
147722    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
147723    if( !zSql ){
147724      rc = SQLITE_NOMEM;
147725    }else{
147726      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
147727      if( rc==SQLITE_OK ){
147728        sqlite3_step(pStmt);
147729        p->nPgsz = sqlite3_column_int(pStmt, 0);
147730        rc = sqlite3_finalize(pStmt);
147731      }else if( rc==SQLITE_AUTH ){
147732        p->nPgsz = 1024;
147733        rc = SQLITE_OK;
147734      }
147735    }
147736    assert( p->nPgsz>0 || rc!=SQLITE_OK );
147737    sqlite3_free(zSql);
147738    *pRc = rc;
147739  }
147740}
147741
147742/*
147743** "Special" FTS4 arguments are column specifications of the following form:
147744**
147745**   <key> = <value>
147746**
147747** There may not be whitespace surrounding the "=" character. The <value>
147748** term may be quoted, but the <key> may not.
147749*/
147750static int fts3IsSpecialColumn(
147751  const char *z,
147752  int *pnKey,
147753  char **pzValue
147754){
147755  char *zValue;
147756  const char *zCsr = z;
147757
147758  while( *zCsr!='=' ){
147759    if( *zCsr=='\0' ) return 0;
147760    zCsr++;
147761  }
147762
147763  *pnKey = (int)(zCsr-z);
147764  zValue = sqlite3_mprintf("%s", &zCsr[1]);
147765  if( zValue ){
147766    sqlite3Fts3Dequote(zValue);
147767  }
147768  *pzValue = zValue;
147769  return 1;
147770}
147771
147772/*
147773** Append the output of a printf() style formatting to an existing string.
147774*/
147775static void fts3Appendf(
147776  int *pRc,                       /* IN/OUT: Error code */
147777  char **pz,                      /* IN/OUT: Pointer to string buffer */
147778  const char *zFormat,            /* Printf format string to append */
147779  ...                             /* Arguments for printf format string */
147780){
147781  if( *pRc==SQLITE_OK ){
147782    va_list ap;
147783    char *z;
147784    va_start(ap, zFormat);
147785    z = sqlite3_vmprintf(zFormat, ap);
147786    va_end(ap);
147787    if( z && *pz ){
147788      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
147789      sqlite3_free(z);
147790      z = z2;
147791    }
147792    if( z==0 ) *pRc = SQLITE_NOMEM;
147793    sqlite3_free(*pz);
147794    *pz = z;
147795  }
147796}
147797
147798/*
147799** Return a copy of input string zInput enclosed in double-quotes (") and
147800** with all double quote characters escaped. For example:
147801**
147802**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
147803**
147804** The pointer returned points to memory obtained from sqlite3_malloc(). It
147805** is the callers responsibility to call sqlite3_free() to release this
147806** memory.
147807*/
147808static char *fts3QuoteId(char const *zInput){
147809  int nRet;
147810  char *zRet;
147811  nRet = 2 + (int)strlen(zInput)*2 + 1;
147812  zRet = sqlite3_malloc(nRet);
147813  if( zRet ){
147814    int i;
147815    char *z = zRet;
147816    *(z++) = '"';
147817    for(i=0; zInput[i]; i++){
147818      if( zInput[i]=='"' ) *(z++) = '"';
147819      *(z++) = zInput[i];
147820    }
147821    *(z++) = '"';
147822    *(z++) = '\0';
147823  }
147824  return zRet;
147825}
147826
147827/*
147828** Return a list of comma separated SQL expressions and a FROM clause that
147829** could be used in a SELECT statement such as the following:
147830**
147831**     SELECT <list of expressions> FROM %_content AS x ...
147832**
147833** to return the docid, followed by each column of text data in order
147834** from left to write. If parameter zFunc is not NULL, then instead of
147835** being returned directly each column of text data is passed to an SQL
147836** function named zFunc first. For example, if zFunc is "unzip" and the
147837** table has the three user-defined columns "a", "b", and "c", the following
147838** string is returned:
147839**
147840**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
147841**
147842** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
147843** is the responsibility of the caller to eventually free it.
147844**
147845** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
147846** a NULL pointer is returned). Otherwise, if an OOM error is encountered
147847** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
147848** no error occurs, *pRc is left unmodified.
147849*/
147850static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
147851  char *zRet = 0;
147852  char *zFree = 0;
147853  char *zFunction;
147854  int i;
147855
147856  if( p->zContentTbl==0 ){
147857    if( !zFunc ){
147858      zFunction = "";
147859    }else{
147860      zFree = zFunction = fts3QuoteId(zFunc);
147861    }
147862    fts3Appendf(pRc, &zRet, "docid");
147863    for(i=0; i<p->nColumn; i++){
147864      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
147865    }
147866    if( p->zLanguageid ){
147867      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
147868    }
147869    sqlite3_free(zFree);
147870  }else{
147871    fts3Appendf(pRc, &zRet, "rowid");
147872    for(i=0; i<p->nColumn; i++){
147873      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
147874    }
147875    if( p->zLanguageid ){
147876      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
147877    }
147878  }
147879  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
147880      p->zDb,
147881      (p->zContentTbl ? p->zContentTbl : p->zName),
147882      (p->zContentTbl ? "" : "_content")
147883  );
147884  return zRet;
147885}
147886
147887/*
147888** Return a list of N comma separated question marks, where N is the number
147889** of columns in the %_content table (one for the docid plus one for each
147890** user-defined text column).
147891**
147892** If argument zFunc is not NULL, then all but the first question mark
147893** is preceded by zFunc and an open bracket, and followed by a closed
147894** bracket. For example, if zFunc is "zip" and the FTS3 table has three
147895** user-defined text columns, the following string is returned:
147896**
147897**     "?, zip(?), zip(?), zip(?)"
147898**
147899** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
147900** is the responsibility of the caller to eventually free it.
147901**
147902** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
147903** a NULL pointer is returned). Otherwise, if an OOM error is encountered
147904** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
147905** no error occurs, *pRc is left unmodified.
147906*/
147907static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
147908  char *zRet = 0;
147909  char *zFree = 0;
147910  char *zFunction;
147911  int i;
147912
147913  if( !zFunc ){
147914    zFunction = "";
147915  }else{
147916    zFree = zFunction = fts3QuoteId(zFunc);
147917  }
147918  fts3Appendf(pRc, &zRet, "?");
147919  for(i=0; i<p->nColumn; i++){
147920    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
147921  }
147922  if( p->zLanguageid ){
147923    fts3Appendf(pRc, &zRet, ", ?");
147924  }
147925  sqlite3_free(zFree);
147926  return zRet;
147927}
147928
147929/*
147930** This function interprets the string at (*pp) as a non-negative integer
147931** value. It reads the integer and sets *pnOut to the value read, then
147932** sets *pp to point to the byte immediately following the last byte of
147933** the integer value.
147934**
147935** Only decimal digits ('0'..'9') may be part of an integer value.
147936**
147937** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
147938** the output value undefined. Otherwise SQLITE_OK is returned.
147939**
147940** This function is used when parsing the "prefix=" FTS4 parameter.
147941*/
147942static int fts3GobbleInt(const char **pp, int *pnOut){
147943  const int MAX_NPREFIX = 10000000;
147944  const char *p;                  /* Iterator pointer */
147945  int nInt = 0;                   /* Output value */
147946
147947  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
147948    nInt = nInt * 10 + (p[0] - '0');
147949    if( nInt>MAX_NPREFIX ){
147950      nInt = 0;
147951      break;
147952    }
147953  }
147954  if( p==*pp ) return SQLITE_ERROR;
147955  *pnOut = nInt;
147956  *pp = p;
147957  return SQLITE_OK;
147958}
147959
147960/*
147961** This function is called to allocate an array of Fts3Index structures
147962** representing the indexes maintained by the current FTS table. FTS tables
147963** always maintain the main "terms" index, but may also maintain one or
147964** more "prefix" indexes, depending on the value of the "prefix=" parameter
147965** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
147966**
147967** Argument zParam is passed the value of the "prefix=" option if one was
147968** specified, or NULL otherwise.
147969**
147970** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
147971** the allocated array. *pnIndex is set to the number of elements in the
147972** array. If an error does occur, an SQLite error code is returned.
147973**
147974** Regardless of whether or not an error is returned, it is the responsibility
147975** of the caller to call sqlite3_free() on the output array to free it.
147976*/
147977static int fts3PrefixParameter(
147978  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
147979  int *pnIndex,                   /* OUT: size of *apIndex[] array */
147980  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
147981){
147982  struct Fts3Index *aIndex;       /* Allocated array */
147983  int nIndex = 1;                 /* Number of entries in array */
147984
147985  if( zParam && zParam[0] ){
147986    const char *p;
147987    nIndex++;
147988    for(p=zParam; *p; p++){
147989      if( *p==',' ) nIndex++;
147990    }
147991  }
147992
147993  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
147994  *apIndex = aIndex;
147995  if( !aIndex ){
147996    return SQLITE_NOMEM;
147997  }
147998
147999  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
148000  if( zParam ){
148001    const char *p = zParam;
148002    int i;
148003    for(i=1; i<nIndex; i++){
148004      int nPrefix = 0;
148005      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
148006      assert( nPrefix>=0 );
148007      if( nPrefix==0 ){
148008        nIndex--;
148009        i--;
148010      }else{
148011        aIndex[i].nPrefix = nPrefix;
148012      }
148013      p++;
148014    }
148015  }
148016
148017  *pnIndex = nIndex;
148018  return SQLITE_OK;
148019}
148020
148021/*
148022** This function is called when initializing an FTS4 table that uses the
148023** content=xxx option. It determines the number of and names of the columns
148024** of the new FTS4 table.
148025**
148026** The third argument passed to this function is the value passed to the
148027** config=xxx option (i.e. "xxx"). This function queries the database for
148028** a table of that name. If found, the output variables are populated
148029** as follows:
148030**
148031**   *pnCol:   Set to the number of columns table xxx has,
148032**
148033**   *pnStr:   Set to the total amount of space required to store a copy
148034**             of each columns name, including the nul-terminator.
148035**
148036**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
148037**             the name of the corresponding column in table xxx. The array
148038**             and its contents are allocated using a single allocation. It
148039**             is the responsibility of the caller to free this allocation
148040**             by eventually passing the *pazCol value to sqlite3_free().
148041**
148042** If the table cannot be found, an error code is returned and the output
148043** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
148044** returned (and the output variables are undefined).
148045*/
148046static int fts3ContentColumns(
148047  sqlite3 *db,                    /* Database handle */
148048  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
148049  const char *zTbl,               /* Name of content table */
148050  const char ***pazCol,           /* OUT: Malloc'd array of column names */
148051  int *pnCol,                     /* OUT: Size of array *pazCol */
148052  int *pnStr,                     /* OUT: Bytes of string content */
148053  char **pzErr                    /* OUT: error message */
148054){
148055  int rc = SQLITE_OK;             /* Return code */
148056  char *zSql;                     /* "SELECT *" statement on zTbl */
148057  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
148058
148059  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
148060  if( !zSql ){
148061    rc = SQLITE_NOMEM;
148062  }else{
148063    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
148064    if( rc!=SQLITE_OK ){
148065      sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
148066    }
148067  }
148068  sqlite3_free(zSql);
148069
148070  if( rc==SQLITE_OK ){
148071    const char **azCol;           /* Output array */
148072    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
148073    int nCol;                     /* Number of table columns */
148074    int i;                        /* Used to iterate through columns */
148075
148076    /* Loop through the returned columns. Set nStr to the number of bytes of
148077    ** space required to store a copy of each column name, including the
148078    ** nul-terminator byte.  */
148079    nCol = sqlite3_column_count(pStmt);
148080    for(i=0; i<nCol; i++){
148081      const char *zCol = sqlite3_column_name(pStmt, i);
148082      nStr += (int)strlen(zCol) + 1;
148083    }
148084
148085    /* Allocate and populate the array to return. */
148086    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
148087    if( azCol==0 ){
148088      rc = SQLITE_NOMEM;
148089    }else{
148090      char *p = (char *)&azCol[nCol];
148091      for(i=0; i<nCol; i++){
148092        const char *zCol = sqlite3_column_name(pStmt, i);
148093        int n = (int)strlen(zCol)+1;
148094        memcpy(p, zCol, n);
148095        azCol[i] = p;
148096        p += n;
148097      }
148098    }
148099    sqlite3_finalize(pStmt);
148100
148101    /* Set the output variables. */
148102    *pnCol = nCol;
148103    *pnStr = nStr;
148104    *pazCol = azCol;
148105  }
148106
148107  return rc;
148108}
148109
148110/*
148111** This function is the implementation of both the xConnect and xCreate
148112** methods of the FTS3 virtual table.
148113**
148114** The argv[] array contains the following:
148115**
148116**   argv[0]   -> module name  ("fts3" or "fts4")
148117**   argv[1]   -> database name
148118**   argv[2]   -> table name
148119**   argv[...] -> "column name" and other module argument fields.
148120*/
148121static int fts3InitVtab(
148122  int isCreate,                   /* True for xCreate, false for xConnect */
148123  sqlite3 *db,                    /* The SQLite database connection */
148124  void *pAux,                     /* Hash table containing tokenizers */
148125  int argc,                       /* Number of elements in argv array */
148126  const char * const *argv,       /* xCreate/xConnect argument array */
148127  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
148128  char **pzErr                    /* Write any error message here */
148129){
148130  Fts3Hash *pHash = (Fts3Hash *)pAux;
148131  Fts3Table *p = 0;               /* Pointer to allocated vtab */
148132  int rc = SQLITE_OK;             /* Return code */
148133  int i;                          /* Iterator variable */
148134  int nByte;                      /* Size of allocation used for *p */
148135  int iCol;                       /* Column index */
148136  int nString = 0;                /* Bytes required to hold all column names */
148137  int nCol = 0;                   /* Number of columns in the FTS table */
148138  char *zCsr;                     /* Space for holding column names */
148139  int nDb;                        /* Bytes required to hold database name */
148140  int nName;                      /* Bytes required to hold table name */
148141  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
148142  const char **aCol;              /* Array of column names */
148143  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
148144
148145  int nIndex = 0;                 /* Size of aIndex[] array */
148146  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
148147
148148  /* The results of parsing supported FTS4 key=value options: */
148149  int bNoDocsize = 0;             /* True to omit %_docsize table */
148150  int bDescIdx = 0;               /* True to store descending indexes */
148151  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
148152  char *zCompress = 0;            /* compress=? parameter (or NULL) */
148153  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
148154  char *zContent = 0;             /* content=? parameter (or NULL) */
148155  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
148156  char **azNotindexed = 0;        /* The set of notindexed= columns */
148157  int nNotindexed = 0;            /* Size of azNotindexed[] array */
148158
148159  assert( strlen(argv[0])==4 );
148160  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
148161       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
148162  );
148163
148164  nDb = (int)strlen(argv[1]) + 1;
148165  nName = (int)strlen(argv[2]) + 1;
148166
148167  nByte = sizeof(const char *) * (argc-2);
148168  aCol = (const char **)sqlite3_malloc(nByte);
148169  if( aCol ){
148170    memset((void*)aCol, 0, nByte);
148171    azNotindexed = (char **)sqlite3_malloc(nByte);
148172  }
148173  if( azNotindexed ){
148174    memset(azNotindexed, 0, nByte);
148175  }
148176  if( !aCol || !azNotindexed ){
148177    rc = SQLITE_NOMEM;
148178    goto fts3_init_out;
148179  }
148180
148181  /* Loop through all of the arguments passed by the user to the FTS3/4
148182  ** module (i.e. all the column names and special arguments). This loop
148183  ** does the following:
148184  **
148185  **   + Figures out the number of columns the FTSX table will have, and
148186  **     the number of bytes of space that must be allocated to store copies
148187  **     of the column names.
148188  **
148189  **   + If there is a tokenizer specification included in the arguments,
148190  **     initializes the tokenizer pTokenizer.
148191  */
148192  for(i=3; rc==SQLITE_OK && i<argc; i++){
148193    char const *z = argv[i];
148194    int nKey;
148195    char *zVal;
148196
148197    /* Check if this is a tokenizer specification */
148198    if( !pTokenizer
148199     && strlen(z)>8
148200     && 0==sqlite3_strnicmp(z, "tokenize", 8)
148201     && 0==sqlite3Fts3IsIdChar(z[8])
148202    ){
148203      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
148204    }
148205
148206    /* Check if it is an FTS4 special argument. */
148207    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
148208      struct Fts4Option {
148209        const char *zOpt;
148210        int nOpt;
148211      } aFts4Opt[] = {
148212        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
148213        { "prefix",      6 },     /* 1 -> PREFIX */
148214        { "compress",    8 },     /* 2 -> COMPRESS */
148215        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
148216        { "order",       5 },     /* 4 -> ORDER */
148217        { "content",     7 },     /* 5 -> CONTENT */
148218        { "languageid", 10 },     /* 6 -> LANGUAGEID */
148219        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
148220      };
148221
148222      int iOpt;
148223      if( !zVal ){
148224        rc = SQLITE_NOMEM;
148225      }else{
148226        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
148227          struct Fts4Option *pOp = &aFts4Opt[iOpt];
148228          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
148229            break;
148230          }
148231        }
148232        switch( iOpt ){
148233          case 0:               /* MATCHINFO */
148234            if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
148235              sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
148236              rc = SQLITE_ERROR;
148237            }
148238            bNoDocsize = 1;
148239            break;
148240
148241          case 1:               /* PREFIX */
148242            sqlite3_free(zPrefix);
148243            zPrefix = zVal;
148244            zVal = 0;
148245            break;
148246
148247          case 2:               /* COMPRESS */
148248            sqlite3_free(zCompress);
148249            zCompress = zVal;
148250            zVal = 0;
148251            break;
148252
148253          case 3:               /* UNCOMPRESS */
148254            sqlite3_free(zUncompress);
148255            zUncompress = zVal;
148256            zVal = 0;
148257            break;
148258
148259          case 4:               /* ORDER */
148260            if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
148261             && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
148262            ){
148263              sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
148264              rc = SQLITE_ERROR;
148265            }
148266            bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
148267            break;
148268
148269          case 5:              /* CONTENT */
148270            sqlite3_free(zContent);
148271            zContent = zVal;
148272            zVal = 0;
148273            break;
148274
148275          case 6:              /* LANGUAGEID */
148276            assert( iOpt==6 );
148277            sqlite3_free(zLanguageid);
148278            zLanguageid = zVal;
148279            zVal = 0;
148280            break;
148281
148282          case 7:              /* NOTINDEXED */
148283            azNotindexed[nNotindexed++] = zVal;
148284            zVal = 0;
148285            break;
148286
148287          default:
148288            assert( iOpt==SizeofArray(aFts4Opt) );
148289            sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
148290            rc = SQLITE_ERROR;
148291            break;
148292        }
148293        sqlite3_free(zVal);
148294      }
148295    }
148296
148297    /* Otherwise, the argument is a column name. */
148298    else {
148299      nString += (int)(strlen(z) + 1);
148300      aCol[nCol++] = z;
148301    }
148302  }
148303
148304  /* If a content=xxx option was specified, the following:
148305  **
148306  **   1. Ignore any compress= and uncompress= options.
148307  **
148308  **   2. If no column names were specified as part of the CREATE VIRTUAL
148309  **      TABLE statement, use all columns from the content table.
148310  */
148311  if( rc==SQLITE_OK && zContent ){
148312    sqlite3_free(zCompress);
148313    sqlite3_free(zUncompress);
148314    zCompress = 0;
148315    zUncompress = 0;
148316    if( nCol==0 ){
148317      sqlite3_free((void*)aCol);
148318      aCol = 0;
148319      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
148320
148321      /* If a languageid= option was specified, remove the language id
148322      ** column from the aCol[] array. */
148323      if( rc==SQLITE_OK && zLanguageid ){
148324        int j;
148325        for(j=0; j<nCol; j++){
148326          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
148327            int k;
148328            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
148329            nCol--;
148330            break;
148331          }
148332        }
148333      }
148334    }
148335  }
148336  if( rc!=SQLITE_OK ) goto fts3_init_out;
148337
148338  if( nCol==0 ){
148339    assert( nString==0 );
148340    aCol[0] = "content";
148341    nString = 8;
148342    nCol = 1;
148343  }
148344
148345  if( pTokenizer==0 ){
148346    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
148347    if( rc!=SQLITE_OK ) goto fts3_init_out;
148348  }
148349  assert( pTokenizer );
148350
148351  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
148352  if( rc==SQLITE_ERROR ){
148353    assert( zPrefix );
148354    sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
148355  }
148356  if( rc!=SQLITE_OK ) goto fts3_init_out;
148357
148358  /* Allocate and populate the Fts3Table structure. */
148359  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
148360          nCol * sizeof(char *) +              /* azColumn */
148361          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
148362          nCol * sizeof(u8) +                  /* abNotindexed */
148363          nName +                              /* zName */
148364          nDb +                                /* zDb */
148365          nString;                             /* Space for azColumn strings */
148366  p = (Fts3Table*)sqlite3_malloc(nByte);
148367  if( p==0 ){
148368    rc = SQLITE_NOMEM;
148369    goto fts3_init_out;
148370  }
148371  memset(p, 0, nByte);
148372  p->db = db;
148373  p->nColumn = nCol;
148374  p->nPendingData = 0;
148375  p->azColumn = (char **)&p[1];
148376  p->pTokenizer = pTokenizer;
148377  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
148378  p->bHasDocsize = (isFts4 && bNoDocsize==0);
148379  p->bHasStat = (u8)isFts4;
148380  p->bFts4 = (u8)isFts4;
148381  p->bDescIdx = (u8)bDescIdx;
148382  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
148383  p->zContentTbl = zContent;
148384  p->zLanguageid = zLanguageid;
148385  zContent = 0;
148386  zLanguageid = 0;
148387  TESTONLY( p->inTransaction = -1 );
148388  TESTONLY( p->mxSavepoint = -1 );
148389
148390  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
148391  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
148392  p->nIndex = nIndex;
148393  for(i=0; i<nIndex; i++){
148394    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
148395  }
148396  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
148397
148398  /* Fill in the zName and zDb fields of the vtab structure. */
148399  zCsr = (char *)&p->abNotindexed[nCol];
148400  p->zName = zCsr;
148401  memcpy(zCsr, argv[2], nName);
148402  zCsr += nName;
148403  p->zDb = zCsr;
148404  memcpy(zCsr, argv[1], nDb);
148405  zCsr += nDb;
148406
148407  /* Fill in the azColumn array */
148408  for(iCol=0; iCol<nCol; iCol++){
148409    char *z;
148410    int n = 0;
148411    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
148412    if( n>0 ){
148413      memcpy(zCsr, z, n);
148414    }
148415    zCsr[n] = '\0';
148416    sqlite3Fts3Dequote(zCsr);
148417    p->azColumn[iCol] = zCsr;
148418    zCsr += n+1;
148419    assert( zCsr <= &((char *)p)[nByte] );
148420  }
148421
148422  /* Fill in the abNotindexed array */
148423  for(iCol=0; iCol<nCol; iCol++){
148424    int n = (int)strlen(p->azColumn[iCol]);
148425    for(i=0; i<nNotindexed; i++){
148426      char *zNot = azNotindexed[i];
148427      if( zNot && n==(int)strlen(zNot)
148428       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
148429      ){
148430        p->abNotindexed[iCol] = 1;
148431        sqlite3_free(zNot);
148432        azNotindexed[i] = 0;
148433      }
148434    }
148435  }
148436  for(i=0; i<nNotindexed; i++){
148437    if( azNotindexed[i] ){
148438      sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
148439      rc = SQLITE_ERROR;
148440    }
148441  }
148442
148443  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
148444    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
148445    rc = SQLITE_ERROR;
148446    sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
148447  }
148448  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
148449  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
148450  if( rc!=SQLITE_OK ) goto fts3_init_out;
148451
148452  /* If this is an xCreate call, create the underlying tables in the
148453  ** database. TODO: For xConnect(), it could verify that said tables exist.
148454  */
148455  if( isCreate ){
148456    rc = fts3CreateTables(p);
148457  }
148458
148459  /* Check to see if a legacy fts3 table has been "upgraded" by the
148460  ** addition of a %_stat table so that it can use incremental merge.
148461  */
148462  if( !isFts4 && !isCreate ){
148463    p->bHasStat = 2;
148464  }
148465
148466  /* Figure out the page-size for the database. This is required in order to
148467  ** estimate the cost of loading large doclists from the database.  */
148468  fts3DatabasePageSize(&rc, p);
148469  p->nNodeSize = p->nPgsz-35;
148470
148471  /* Declare the table schema to SQLite. */
148472  fts3DeclareVtab(&rc, p);
148473
148474fts3_init_out:
148475  sqlite3_free(zPrefix);
148476  sqlite3_free(aIndex);
148477  sqlite3_free(zCompress);
148478  sqlite3_free(zUncompress);
148479  sqlite3_free(zContent);
148480  sqlite3_free(zLanguageid);
148481  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
148482  sqlite3_free((void *)aCol);
148483  sqlite3_free((void *)azNotindexed);
148484  if( rc!=SQLITE_OK ){
148485    if( p ){
148486      fts3DisconnectMethod((sqlite3_vtab *)p);
148487    }else if( pTokenizer ){
148488      pTokenizer->pModule->xDestroy(pTokenizer);
148489    }
148490  }else{
148491    assert( p->pSegments==0 );
148492    *ppVTab = &p->base;
148493  }
148494  return rc;
148495}
148496
148497/*
148498** The xConnect() and xCreate() methods for the virtual table. All the
148499** work is done in function fts3InitVtab().
148500*/
148501static int fts3ConnectMethod(
148502  sqlite3 *db,                    /* Database connection */
148503  void *pAux,                     /* Pointer to tokenizer hash table */
148504  int argc,                       /* Number of elements in argv array */
148505  const char * const *argv,       /* xCreate/xConnect argument array */
148506  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
148507  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
148508){
148509  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
148510}
148511static int fts3CreateMethod(
148512  sqlite3 *db,                    /* Database connection */
148513  void *pAux,                     /* Pointer to tokenizer hash table */
148514  int argc,                       /* Number of elements in argv array */
148515  const char * const *argv,       /* xCreate/xConnect argument array */
148516  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
148517  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
148518){
148519  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
148520}
148521
148522/*
148523** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
148524** extension is currently being used by a version of SQLite too old to
148525** support estimatedRows. In that case this function is a no-op.
148526*/
148527static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
148528#if SQLITE_VERSION_NUMBER>=3008002
148529  if( sqlite3_libversion_number()>=3008002 ){
148530    pIdxInfo->estimatedRows = nRow;
148531  }
148532#endif
148533}
148534
148535/*
148536** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
148537** extension is currently being used by a version of SQLite too old to
148538** support index-info flags. In that case this function is a no-op.
148539*/
148540static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
148541#if SQLITE_VERSION_NUMBER>=3008012
148542  if( sqlite3_libversion_number()>=3008012 ){
148543    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
148544  }
148545#endif
148546}
148547
148548/*
148549** Implementation of the xBestIndex method for FTS3 tables. There
148550** are three possible strategies, in order of preference:
148551**
148552**   1. Direct lookup by rowid or docid.
148553**   2. Full-text search using a MATCH operator on a non-docid column.
148554**   3. Linear scan of %_content table.
148555*/
148556static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
148557  Fts3Table *p = (Fts3Table *)pVTab;
148558  int i;                          /* Iterator variable */
148559  int iCons = -1;                 /* Index of constraint to use */
148560
148561  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
148562  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
148563  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
148564  int iIdx;
148565
148566  /* By default use a full table scan. This is an expensive option,
148567  ** so search through the constraints to see if a more efficient
148568  ** strategy is possible.
148569  */
148570  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
148571  pInfo->estimatedCost = 5000000;
148572  for(i=0; i<pInfo->nConstraint; i++){
148573    int bDocid;                 /* True if this constraint is on docid */
148574    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
148575    if( pCons->usable==0 ){
148576      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
148577        /* There exists an unusable MATCH constraint. This means that if
148578        ** the planner does elect to use the results of this call as part
148579        ** of the overall query plan the user will see an "unable to use
148580        ** function MATCH in the requested context" error. To discourage
148581        ** this, return a very high cost here.  */
148582        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
148583        pInfo->estimatedCost = 1e50;
148584        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
148585        return SQLITE_OK;
148586      }
148587      continue;
148588    }
148589
148590    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
148591
148592    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
148593    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
148594      pInfo->idxNum = FTS3_DOCID_SEARCH;
148595      pInfo->estimatedCost = 1.0;
148596      iCons = i;
148597    }
148598
148599    /* A MATCH constraint. Use a full-text search.
148600    **
148601    ** If there is more than one MATCH constraint available, use the first
148602    ** one encountered. If there is both a MATCH constraint and a direct
148603    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
148604    ** though the rowid/docid lookup is faster than a MATCH query, selecting
148605    ** it would lead to an "unable to use function MATCH in the requested
148606    ** context" error.
148607    */
148608    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
148609     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
148610    ){
148611      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
148612      pInfo->estimatedCost = 2.0;
148613      iCons = i;
148614    }
148615
148616    /* Equality constraint on the langid column */
148617    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
148618     && pCons->iColumn==p->nColumn + 2
148619    ){
148620      iLangidCons = i;
148621    }
148622
148623    if( bDocid ){
148624      switch( pCons->op ){
148625        case SQLITE_INDEX_CONSTRAINT_GE:
148626        case SQLITE_INDEX_CONSTRAINT_GT:
148627          iDocidGe = i;
148628          break;
148629
148630        case SQLITE_INDEX_CONSTRAINT_LE:
148631        case SQLITE_INDEX_CONSTRAINT_LT:
148632          iDocidLe = i;
148633          break;
148634      }
148635    }
148636  }
148637
148638  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
148639  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
148640
148641  iIdx = 1;
148642  if( iCons>=0 ){
148643    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
148644    pInfo->aConstraintUsage[iCons].omit = 1;
148645  }
148646  if( iLangidCons>=0 ){
148647    pInfo->idxNum |= FTS3_HAVE_LANGID;
148648    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
148649  }
148650  if( iDocidGe>=0 ){
148651    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
148652    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
148653  }
148654  if( iDocidLe>=0 ){
148655    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
148656    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
148657  }
148658
148659  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
148660  ** docid) order. Both ascending and descending are possible.
148661  */
148662  if( pInfo->nOrderBy==1 ){
148663    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
148664    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
148665      if( pOrder->desc ){
148666        pInfo->idxStr = "DESC";
148667      }else{
148668        pInfo->idxStr = "ASC";
148669      }
148670      pInfo->orderByConsumed = 1;
148671    }
148672  }
148673
148674  assert( p->pSegments==0 );
148675  return SQLITE_OK;
148676}
148677
148678/*
148679** Implementation of xOpen method.
148680*/
148681static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
148682  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
148683
148684  UNUSED_PARAMETER(pVTab);
148685
148686  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
148687  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
148688  ** if the allocation fails, return SQLITE_NOMEM.
148689  */
148690  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
148691  if( !pCsr ){
148692    return SQLITE_NOMEM;
148693  }
148694  memset(pCsr, 0, sizeof(Fts3Cursor));
148695  return SQLITE_OK;
148696}
148697
148698/*
148699** Finalize the statement handle at pCsr->pStmt.
148700**
148701** Or, if that statement handle is one created by fts3CursorSeekStmt(),
148702** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
148703** pointer there instead of finalizing it.
148704*/
148705static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
148706  if( pCsr->bSeekStmt ){
148707    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
148708    if( p->pSeekStmt==0 ){
148709      p->pSeekStmt = pCsr->pStmt;
148710      sqlite3_reset(pCsr->pStmt);
148711      pCsr->pStmt = 0;
148712    }
148713    pCsr->bSeekStmt = 0;
148714  }
148715  sqlite3_finalize(pCsr->pStmt);
148716}
148717
148718/*
148719** Free all resources currently held by the cursor passed as the only
148720** argument.
148721*/
148722static void fts3ClearCursor(Fts3Cursor *pCsr){
148723  fts3CursorFinalizeStmt(pCsr);
148724  sqlite3Fts3FreeDeferredTokens(pCsr);
148725  sqlite3_free(pCsr->aDoclist);
148726  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
148727  sqlite3Fts3ExprFree(pCsr->pExpr);
148728  memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
148729}
148730
148731/*
148732** Close the cursor.  For additional information see the documentation
148733** on the xClose method of the virtual table interface.
148734*/
148735static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
148736  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
148737  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
148738  fts3ClearCursor(pCsr);
148739  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
148740  sqlite3_free(pCsr);
148741  return SQLITE_OK;
148742}
148743
148744/*
148745** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
148746** compose and prepare an SQL statement of the form:
148747**
148748**    "SELECT <columns> FROM %_content WHERE rowid = ?"
148749**
148750** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
148751** it. If an error occurs, return an SQLite error code.
148752*/
148753static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
148754  int rc = SQLITE_OK;
148755  if( pCsr->pStmt==0 ){
148756    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
148757    char *zSql;
148758    if( p->pSeekStmt ){
148759      pCsr->pStmt = p->pSeekStmt;
148760      p->pSeekStmt = 0;
148761    }else{
148762      zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
148763      if( !zSql ) return SQLITE_NOMEM;
148764      rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
148765      sqlite3_free(zSql);
148766    }
148767    if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
148768  }
148769  return rc;
148770}
148771
148772/*
148773** Position the pCsr->pStmt statement so that it is on the row
148774** of the %_content table that contains the last match.  Return
148775** SQLITE_OK on success.
148776*/
148777static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
148778  int rc = SQLITE_OK;
148779  if( pCsr->isRequireSeek ){
148780    rc = fts3CursorSeekStmt(pCsr);
148781    if( rc==SQLITE_OK ){
148782      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
148783      pCsr->isRequireSeek = 0;
148784      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
148785        return SQLITE_OK;
148786      }else{
148787        rc = sqlite3_reset(pCsr->pStmt);
148788        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
148789          /* If no row was found and no error has occurred, then the %_content
148790          ** table is missing a row that is present in the full-text index.
148791          ** The data structures are corrupt.  */
148792          rc = FTS_CORRUPT_VTAB;
148793          pCsr->isEof = 1;
148794        }
148795      }
148796    }
148797  }
148798
148799  if( rc!=SQLITE_OK && pContext ){
148800    sqlite3_result_error_code(pContext, rc);
148801  }
148802  return rc;
148803}
148804
148805/*
148806** This function is used to process a single interior node when searching
148807** a b-tree for a term or term prefix. The node data is passed to this
148808** function via the zNode/nNode parameters. The term to search for is
148809** passed in zTerm/nTerm.
148810**
148811** If piFirst is not NULL, then this function sets *piFirst to the blockid
148812** of the child node that heads the sub-tree that may contain the term.
148813**
148814** If piLast is not NULL, then *piLast is set to the right-most child node
148815** that heads a sub-tree that may contain a term for which zTerm/nTerm is
148816** a prefix.
148817**
148818** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
148819*/
148820static int fts3ScanInteriorNode(
148821  const char *zTerm,              /* Term to select leaves for */
148822  int nTerm,                      /* Size of term zTerm in bytes */
148823  const char *zNode,              /* Buffer containing segment interior node */
148824  int nNode,                      /* Size of buffer at zNode */
148825  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
148826  sqlite3_int64 *piLast           /* OUT: Selected child node */
148827){
148828  int rc = SQLITE_OK;             /* Return code */
148829  const char *zCsr = zNode;       /* Cursor to iterate through node */
148830  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
148831  char *zBuffer = 0;              /* Buffer to load terms into */
148832  int nAlloc = 0;                 /* Size of allocated buffer */
148833  int isFirstTerm = 1;            /* True when processing first term on page */
148834  sqlite3_int64 iChild;           /* Block id of child node to descend to */
148835
148836  /* Skip over the 'height' varint that occurs at the start of every
148837  ** interior node. Then load the blockid of the left-child of the b-tree
148838  ** node into variable iChild.
148839  **
148840  ** Even if the data structure on disk is corrupted, this (reading two
148841  ** varints from the buffer) does not risk an overread. If zNode is a
148842  ** root node, then the buffer comes from a SELECT statement. SQLite does
148843  ** not make this guarantee explicitly, but in practice there are always
148844  ** either more than 20 bytes of allocated space following the nNode bytes of
148845  ** contents, or two zero bytes. Or, if the node is read from the %_segments
148846  ** table, then there are always 20 bytes of zeroed padding following the
148847  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
148848  */
148849  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
148850  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
148851  if( zCsr>zEnd ){
148852    return FTS_CORRUPT_VTAB;
148853  }
148854
148855  while( zCsr<zEnd && (piFirst || piLast) ){
148856    int cmp;                      /* memcmp() result */
148857    int nSuffix;                  /* Size of term suffix */
148858    int nPrefix = 0;              /* Size of term prefix */
148859    int nBuffer;                  /* Total term size */
148860
148861    /* Load the next term on the node into zBuffer. Use realloc() to expand
148862    ** the size of zBuffer if required.  */
148863    if( !isFirstTerm ){
148864      zCsr += fts3GetVarint32(zCsr, &nPrefix);
148865    }
148866    isFirstTerm = 0;
148867    zCsr += fts3GetVarint32(zCsr, &nSuffix);
148868
148869    assert( nPrefix>=0 && nSuffix>=0 );
148870    if( &zCsr[nSuffix]>zEnd ){
148871      rc = FTS_CORRUPT_VTAB;
148872      goto finish_scan;
148873    }
148874    if( nPrefix+nSuffix>nAlloc ){
148875      char *zNew;
148876      nAlloc = (nPrefix+nSuffix) * 2;
148877      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
148878      if( !zNew ){
148879        rc = SQLITE_NOMEM;
148880        goto finish_scan;
148881      }
148882      zBuffer = zNew;
148883    }
148884    assert( zBuffer );
148885    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
148886    nBuffer = nPrefix + nSuffix;
148887    zCsr += nSuffix;
148888
148889    /* Compare the term we are searching for with the term just loaded from
148890    ** the interior node. If the specified term is greater than or equal
148891    ** to the term from the interior node, then all terms on the sub-tree
148892    ** headed by node iChild are smaller than zTerm. No need to search
148893    ** iChild.
148894    **
148895    ** If the interior node term is larger than the specified term, then
148896    ** the tree headed by iChild may contain the specified term.
148897    */
148898    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
148899    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
148900      *piFirst = iChild;
148901      piFirst = 0;
148902    }
148903
148904    if( piLast && cmp<0 ){
148905      *piLast = iChild;
148906      piLast = 0;
148907    }
148908
148909    iChild++;
148910  };
148911
148912  if( piFirst ) *piFirst = iChild;
148913  if( piLast ) *piLast = iChild;
148914
148915 finish_scan:
148916  sqlite3_free(zBuffer);
148917  return rc;
148918}
148919
148920
148921/*
148922** The buffer pointed to by argument zNode (size nNode bytes) contains an
148923** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
148924** contains a term. This function searches the sub-tree headed by the zNode
148925** node for the range of leaf nodes that may contain the specified term
148926** or terms for which the specified term is a prefix.
148927**
148928** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
148929** left-most leaf node in the tree that may contain the specified term.
148930** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
148931** right-most leaf node that may contain a term for which the specified
148932** term is a prefix.
148933**
148934** It is possible that the range of returned leaf nodes does not contain
148935** the specified term or any terms for which it is a prefix. However, if the
148936** segment does contain any such terms, they are stored within the identified
148937** range. Because this function only inspects interior segment nodes (and
148938** never loads leaf nodes into memory), it is not possible to be sure.
148939**
148940** If an error occurs, an error code other than SQLITE_OK is returned.
148941*/
148942static int fts3SelectLeaf(
148943  Fts3Table *p,                   /* Virtual table handle */
148944  const char *zTerm,              /* Term to select leaves for */
148945  int nTerm,                      /* Size of term zTerm in bytes */
148946  const char *zNode,              /* Buffer containing segment interior node */
148947  int nNode,                      /* Size of buffer at zNode */
148948  sqlite3_int64 *piLeaf,          /* Selected leaf node */
148949  sqlite3_int64 *piLeaf2          /* Selected leaf node */
148950){
148951  int rc = SQLITE_OK;             /* Return code */
148952  int iHeight;                    /* Height of this node in tree */
148953
148954  assert( piLeaf || piLeaf2 );
148955
148956  fts3GetVarint32(zNode, &iHeight);
148957  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
148958  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
148959
148960  if( rc==SQLITE_OK && iHeight>1 ){
148961    char *zBlob = 0;              /* Blob read from %_segments table */
148962    int nBlob = 0;                /* Size of zBlob in bytes */
148963
148964    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
148965      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
148966      if( rc==SQLITE_OK ){
148967        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
148968      }
148969      sqlite3_free(zBlob);
148970      piLeaf = 0;
148971      zBlob = 0;
148972    }
148973
148974    if( rc==SQLITE_OK ){
148975      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
148976    }
148977    if( rc==SQLITE_OK ){
148978      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
148979    }
148980    sqlite3_free(zBlob);
148981  }
148982
148983  return rc;
148984}
148985
148986/*
148987** This function is used to create delta-encoded serialized lists of FTS3
148988** varints. Each call to this function appends a single varint to a list.
148989*/
148990static void fts3PutDeltaVarint(
148991  char **pp,                      /* IN/OUT: Output pointer */
148992  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
148993  sqlite3_int64 iVal              /* Write this value to the list */
148994){
148995  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
148996  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
148997  *piPrev = iVal;
148998}
148999
149000/*
149001** When this function is called, *ppPoslist is assumed to point to the
149002** start of a position-list. After it returns, *ppPoslist points to the
149003** first byte after the position-list.
149004**
149005** A position list is list of positions (delta encoded) and columns for
149006** a single document record of a doclist.  So, in other words, this
149007** routine advances *ppPoslist so that it points to the next docid in
149008** the doclist, or to the first byte past the end of the doclist.
149009**
149010** If pp is not NULL, then the contents of the position list are copied
149011** to *pp. *pp is set to point to the first byte past the last byte copied
149012** before this function returns.
149013*/
149014static void fts3PoslistCopy(char **pp, char **ppPoslist){
149015  char *pEnd = *ppPoslist;
149016  char c = 0;
149017
149018  /* The end of a position list is marked by a zero encoded as an FTS3
149019  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
149020  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
149021  ** of some other, multi-byte, value.
149022  **
149023  ** The following while-loop moves pEnd to point to the first byte that is not
149024  ** immediately preceded by a byte with the 0x80 bit set. Then increments
149025  ** pEnd once more so that it points to the byte immediately following the
149026  ** last byte in the position-list.
149027  */
149028  while( *pEnd | c ){
149029    c = *pEnd++ & 0x80;
149030    testcase( c!=0 && (*pEnd)==0 );
149031  }
149032  pEnd++;  /* Advance past the POS_END terminator byte */
149033
149034  if( pp ){
149035    int n = (int)(pEnd - *ppPoslist);
149036    char *p = *pp;
149037    memcpy(p, *ppPoslist, n);
149038    p += n;
149039    *pp = p;
149040  }
149041  *ppPoslist = pEnd;
149042}
149043
149044/*
149045** When this function is called, *ppPoslist is assumed to point to the
149046** start of a column-list. After it returns, *ppPoslist points to the
149047** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
149048**
149049** A column-list is list of delta-encoded positions for a single column
149050** within a single document within a doclist.
149051**
149052** The column-list is terminated either by a POS_COLUMN varint (1) or
149053** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
149054** the POS_COLUMN or POS_END that terminates the column-list.
149055**
149056** If pp is not NULL, then the contents of the column-list are copied
149057** to *pp. *pp is set to point to the first byte past the last byte copied
149058** before this function returns.  The POS_COLUMN or POS_END terminator
149059** is not copied into *pp.
149060*/
149061static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
149062  char *pEnd = *ppPoslist;
149063  char c = 0;
149064
149065  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
149066  ** not part of a multi-byte varint.
149067  */
149068  while( 0xFE & (*pEnd | c) ){
149069    c = *pEnd++ & 0x80;
149070    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
149071  }
149072  if( pp ){
149073    int n = (int)(pEnd - *ppPoslist);
149074    char *p = *pp;
149075    memcpy(p, *ppPoslist, n);
149076    p += n;
149077    *pp = p;
149078  }
149079  *ppPoslist = pEnd;
149080}
149081
149082/*
149083** Value used to signify the end of an position-list. This is safe because
149084** it is not possible to have a document with 2^31 terms.
149085*/
149086#define POSITION_LIST_END 0x7fffffff
149087
149088/*
149089** This function is used to help parse position-lists. When this function is
149090** called, *pp may point to the start of the next varint in the position-list
149091** being parsed, or it may point to 1 byte past the end of the position-list
149092** (in which case **pp will be a terminator bytes POS_END (0) or
149093** (1)).
149094**
149095** If *pp points past the end of the current position-list, set *pi to
149096** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
149097** increment the current value of *pi by the value read, and set *pp to
149098** point to the next value before returning.
149099**
149100** Before calling this routine *pi must be initialized to the value of
149101** the previous position, or zero if we are reading the first position
149102** in the position-list.  Because positions are delta-encoded, the value
149103** of the previous position is needed in order to compute the value of
149104** the next position.
149105*/
149106static void fts3ReadNextPos(
149107  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
149108  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
149109){
149110  if( (**pp)&0xFE ){
149111    fts3GetDeltaVarint(pp, pi);
149112    *pi -= 2;
149113  }else{
149114    *pi = POSITION_LIST_END;
149115  }
149116}
149117
149118/*
149119** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
149120** the value of iCol encoded as a varint to *pp.   This will start a new
149121** column list.
149122**
149123** Set *pp to point to the byte just after the last byte written before
149124** returning (do not modify it if iCol==0). Return the total number of bytes
149125** written (0 if iCol==0).
149126*/
149127static int fts3PutColNumber(char **pp, int iCol){
149128  int n = 0;                      /* Number of bytes written */
149129  if( iCol ){
149130    char *p = *pp;                /* Output pointer */
149131    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
149132    *p = 0x01;
149133    *pp = &p[n];
149134  }
149135  return n;
149136}
149137
149138/*
149139** Compute the union of two position lists.  The output written
149140** into *pp contains all positions of both *pp1 and *pp2 in sorted
149141** order and with any duplicates removed.  All pointers are
149142** updated appropriately.   The caller is responsible for insuring
149143** that there is enough space in *pp to hold the complete output.
149144*/
149145static void fts3PoslistMerge(
149146  char **pp,                      /* Output buffer */
149147  char **pp1,                     /* Left input list */
149148  char **pp2                      /* Right input list */
149149){
149150  char *p = *pp;
149151  char *p1 = *pp1;
149152  char *p2 = *pp2;
149153
149154  while( *p1 || *p2 ){
149155    int iCol1;         /* The current column index in pp1 */
149156    int iCol2;         /* The current column index in pp2 */
149157
149158    if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
149159    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
149160    else iCol1 = 0;
149161
149162    if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
149163    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
149164    else iCol2 = 0;
149165
149166    if( iCol1==iCol2 ){
149167      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
149168      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
149169      sqlite3_int64 iPrev = 0;
149170      int n = fts3PutColNumber(&p, iCol1);
149171      p1 += n;
149172      p2 += n;
149173
149174      /* At this point, both p1 and p2 point to the start of column-lists
149175      ** for the same column (the column with index iCol1 and iCol2).
149176      ** A column-list is a list of non-negative delta-encoded varints, each
149177      ** incremented by 2 before being stored. Each list is terminated by a
149178      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
149179      ** and writes the results to buffer p. p is left pointing to the byte
149180      ** after the list written. No terminator (POS_END or POS_COLUMN) is
149181      ** written to the output.
149182      */
149183      fts3GetDeltaVarint(&p1, &i1);
149184      fts3GetDeltaVarint(&p2, &i2);
149185      do {
149186        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
149187        iPrev -= 2;
149188        if( i1==i2 ){
149189          fts3ReadNextPos(&p1, &i1);
149190          fts3ReadNextPos(&p2, &i2);
149191        }else if( i1<i2 ){
149192          fts3ReadNextPos(&p1, &i1);
149193        }else{
149194          fts3ReadNextPos(&p2, &i2);
149195        }
149196      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
149197    }else if( iCol1<iCol2 ){
149198      p1 += fts3PutColNumber(&p, iCol1);
149199      fts3ColumnlistCopy(&p, &p1);
149200    }else{
149201      p2 += fts3PutColNumber(&p, iCol2);
149202      fts3ColumnlistCopy(&p, &p2);
149203    }
149204  }
149205
149206  *p++ = POS_END;
149207  *pp = p;
149208  *pp1 = p1 + 1;
149209  *pp2 = p2 + 1;
149210}
149211
149212/*
149213** This function is used to merge two position lists into one. When it is
149214** called, *pp1 and *pp2 must both point to position lists. A position-list is
149215** the part of a doclist that follows each document id. For example, if a row
149216** contains:
149217**
149218**     'a b c'|'x y z'|'a b b a'
149219**
149220** Then the position list for this row for token 'b' would consist of:
149221**
149222**     0x02 0x01 0x02 0x03 0x03 0x00
149223**
149224** When this function returns, both *pp1 and *pp2 are left pointing to the
149225** byte following the 0x00 terminator of their respective position lists.
149226**
149227** If isSaveLeft is 0, an entry is added to the output position list for
149228** each position in *pp2 for which there exists one or more positions in
149229** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
149230** when the *pp1 token appears before the *pp2 token, but not more than nToken
149231** slots before it.
149232**
149233** e.g. nToken==1 searches for adjacent positions.
149234*/
149235static int fts3PoslistPhraseMerge(
149236  char **pp,                      /* IN/OUT: Preallocated output buffer */
149237  int nToken,                     /* Maximum difference in token positions */
149238  int isSaveLeft,                 /* Save the left position */
149239  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
149240  char **pp1,                     /* IN/OUT: Left input list */
149241  char **pp2                      /* IN/OUT: Right input list */
149242){
149243  char *p = *pp;
149244  char *p1 = *pp1;
149245  char *p2 = *pp2;
149246  int iCol1 = 0;
149247  int iCol2 = 0;
149248
149249  /* Never set both isSaveLeft and isExact for the same invocation. */
149250  assert( isSaveLeft==0 || isExact==0 );
149251
149252  assert( p!=0 && *p1!=0 && *p2!=0 );
149253  if( *p1==POS_COLUMN ){
149254    p1++;
149255    p1 += fts3GetVarint32(p1, &iCol1);
149256  }
149257  if( *p2==POS_COLUMN ){
149258    p2++;
149259    p2 += fts3GetVarint32(p2, &iCol2);
149260  }
149261
149262  while( 1 ){
149263    if( iCol1==iCol2 ){
149264      char *pSave = p;
149265      sqlite3_int64 iPrev = 0;
149266      sqlite3_int64 iPos1 = 0;
149267      sqlite3_int64 iPos2 = 0;
149268
149269      if( iCol1 ){
149270        *p++ = POS_COLUMN;
149271        p += sqlite3Fts3PutVarint(p, iCol1);
149272      }
149273
149274      assert( *p1!=POS_END && *p1!=POS_COLUMN );
149275      assert( *p2!=POS_END && *p2!=POS_COLUMN );
149276      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
149277      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
149278
149279      while( 1 ){
149280        if( iPos2==iPos1+nToken
149281         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
149282        ){
149283          sqlite3_int64 iSave;
149284          iSave = isSaveLeft ? iPos1 : iPos2;
149285          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
149286          pSave = 0;
149287          assert( p );
149288        }
149289        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
149290          if( (*p2&0xFE)==0 ) break;
149291          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
149292        }else{
149293          if( (*p1&0xFE)==0 ) break;
149294          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
149295        }
149296      }
149297
149298      if( pSave ){
149299        assert( pp && p );
149300        p = pSave;
149301      }
149302
149303      fts3ColumnlistCopy(0, &p1);
149304      fts3ColumnlistCopy(0, &p2);
149305      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
149306      if( 0==*p1 || 0==*p2 ) break;
149307
149308      p1++;
149309      p1 += fts3GetVarint32(p1, &iCol1);
149310      p2++;
149311      p2 += fts3GetVarint32(p2, &iCol2);
149312    }
149313
149314    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
149315    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
149316    ** end of the position list, or the 0x01 that precedes the next
149317    ** column-number in the position list.
149318    */
149319    else if( iCol1<iCol2 ){
149320      fts3ColumnlistCopy(0, &p1);
149321      if( 0==*p1 ) break;
149322      p1++;
149323      p1 += fts3GetVarint32(p1, &iCol1);
149324    }else{
149325      fts3ColumnlistCopy(0, &p2);
149326      if( 0==*p2 ) break;
149327      p2++;
149328      p2 += fts3GetVarint32(p2, &iCol2);
149329    }
149330  }
149331
149332  fts3PoslistCopy(0, &p2);
149333  fts3PoslistCopy(0, &p1);
149334  *pp1 = p1;
149335  *pp2 = p2;
149336  if( *pp==p ){
149337    return 0;
149338  }
149339  *p++ = 0x00;
149340  *pp = p;
149341  return 1;
149342}
149343
149344/*
149345** Merge two position-lists as required by the NEAR operator. The argument
149346** position lists correspond to the left and right phrases of an expression
149347** like:
149348**
149349**     "phrase 1" NEAR "phrase number 2"
149350**
149351** Position list *pp1 corresponds to the left-hand side of the NEAR
149352** expression and *pp2 to the right. As usual, the indexes in the position
149353** lists are the offsets of the last token in each phrase (tokens "1" and "2"
149354** in the example above).
149355**
149356** The output position list - written to *pp - is a copy of *pp2 with those
149357** entries that are not sufficiently NEAR entries in *pp1 removed.
149358*/
149359static int fts3PoslistNearMerge(
149360  char **pp,                      /* Output buffer */
149361  char *aTmp,                     /* Temporary buffer space */
149362  int nRight,                     /* Maximum difference in token positions */
149363  int nLeft,                      /* Maximum difference in token positions */
149364  char **pp1,                     /* IN/OUT: Left input list */
149365  char **pp2                      /* IN/OUT: Right input list */
149366){
149367  char *p1 = *pp1;
149368  char *p2 = *pp2;
149369
149370  char *pTmp1 = aTmp;
149371  char *pTmp2;
149372  char *aTmp2;
149373  int res = 1;
149374
149375  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
149376  aTmp2 = pTmp2 = pTmp1;
149377  *pp1 = p1;
149378  *pp2 = p2;
149379  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
149380  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
149381    fts3PoslistMerge(pp, &aTmp, &aTmp2);
149382  }else if( pTmp1!=aTmp ){
149383    fts3PoslistCopy(pp, &aTmp);
149384  }else if( pTmp2!=aTmp2 ){
149385    fts3PoslistCopy(pp, &aTmp2);
149386  }else{
149387    res = 0;
149388  }
149389
149390  return res;
149391}
149392
149393/*
149394** An instance of this function is used to merge together the (potentially
149395** large number of) doclists for each term that matches a prefix query.
149396** See function fts3TermSelectMerge() for details.
149397*/
149398typedef struct TermSelect TermSelect;
149399struct TermSelect {
149400  char *aaOutput[16];             /* Malloc'd output buffers */
149401  int anOutput[16];               /* Size each output buffer in bytes */
149402};
149403
149404/*
149405** This function is used to read a single varint from a buffer. Parameter
149406** pEnd points 1 byte past the end of the buffer. When this function is
149407** called, if *pp points to pEnd or greater, then the end of the buffer
149408** has been reached. In this case *pp is set to 0 and the function returns.
149409**
149410** If *pp does not point to or past pEnd, then a single varint is read
149411** from *pp. *pp is then set to point 1 byte past the end of the read varint.
149412**
149413** If bDescIdx is false, the value read is added to *pVal before returning.
149414** If it is true, the value read is subtracted from *pVal before this
149415** function returns.
149416*/
149417static void fts3GetDeltaVarint3(
149418  char **pp,                      /* IN/OUT: Point to read varint from */
149419  char *pEnd,                     /* End of buffer */
149420  int bDescIdx,                   /* True if docids are descending */
149421  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
149422){
149423  if( *pp>=pEnd ){
149424    *pp = 0;
149425  }else{
149426    sqlite3_int64 iVal;
149427    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
149428    if( bDescIdx ){
149429      *pVal -= iVal;
149430    }else{
149431      *pVal += iVal;
149432    }
149433  }
149434}
149435
149436/*
149437** This function is used to write a single varint to a buffer. The varint
149438** is written to *pp. Before returning, *pp is set to point 1 byte past the
149439** end of the value written.
149440**
149441** If *pbFirst is zero when this function is called, the value written to
149442** the buffer is that of parameter iVal.
149443**
149444** If *pbFirst is non-zero when this function is called, then the value
149445** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
149446** (if bDescIdx is non-zero).
149447**
149448** Before returning, this function always sets *pbFirst to 1 and *piPrev
149449** to the value of parameter iVal.
149450*/
149451static void fts3PutDeltaVarint3(
149452  char **pp,                      /* IN/OUT: Output pointer */
149453  int bDescIdx,                   /* True for descending docids */
149454  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
149455  int *pbFirst,                   /* IN/OUT: True after first int written */
149456  sqlite3_int64 iVal              /* Write this value to the list */
149457){
149458  sqlite3_int64 iWrite;
149459  if( bDescIdx==0 || *pbFirst==0 ){
149460    iWrite = iVal - *piPrev;
149461  }else{
149462    iWrite = *piPrev - iVal;
149463  }
149464  assert( *pbFirst || *piPrev==0 );
149465  assert( *pbFirst==0 || iWrite>0 );
149466  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
149467  *piPrev = iVal;
149468  *pbFirst = 1;
149469}
149470
149471
149472/*
149473** This macro is used by various functions that merge doclists. The two
149474** arguments are 64-bit docid values. If the value of the stack variable
149475** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
149476** Otherwise, (i2-i1).
149477**
149478** Using this makes it easier to write code that can merge doclists that are
149479** sorted in either ascending or descending order.
149480*/
149481#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
149482
149483/*
149484** This function does an "OR" merge of two doclists (output contains all
149485** positions contained in either argument doclist). If the docids in the
149486** input doclists are sorted in ascending order, parameter bDescDoclist
149487** should be false. If they are sorted in ascending order, it should be
149488** passed a non-zero value.
149489**
149490** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
149491** containing the output doclist and SQLITE_OK is returned. In this case
149492** *pnOut is set to the number of bytes in the output doclist.
149493**
149494** If an error occurs, an SQLite error code is returned. The output values
149495** are undefined in this case.
149496*/
149497static int fts3DoclistOrMerge(
149498  int bDescDoclist,               /* True if arguments are desc */
149499  char *a1, int n1,               /* First doclist */
149500  char *a2, int n2,               /* Second doclist */
149501  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
149502){
149503  sqlite3_int64 i1 = 0;
149504  sqlite3_int64 i2 = 0;
149505  sqlite3_int64 iPrev = 0;
149506  char *pEnd1 = &a1[n1];
149507  char *pEnd2 = &a2[n2];
149508  char *p1 = a1;
149509  char *p2 = a2;
149510  char *p;
149511  char *aOut;
149512  int bFirstOut = 0;
149513
149514  *paOut = 0;
149515  *pnOut = 0;
149516
149517  /* Allocate space for the output. Both the input and output doclists
149518  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
149519  ** then the first docid in each list is simply encoded as a varint. For
149520  ** each subsequent docid, the varint stored is the difference between the
149521  ** current and previous docid (a positive number - since the list is in
149522  ** ascending order).
149523  **
149524  ** The first docid written to the output is therefore encoded using the
149525  ** same number of bytes as it is in whichever of the input lists it is
149526  ** read from. And each subsequent docid read from the same input list
149527  ** consumes either the same or less bytes as it did in the input (since
149528  ** the difference between it and the previous value in the output must
149529  ** be a positive value less than or equal to the delta value read from
149530  ** the input list). The same argument applies to all but the first docid
149531  ** read from the 'other' list. And to the contents of all position lists
149532  ** that will be copied and merged from the input to the output.
149533  **
149534  ** However, if the first docid copied to the output is a negative number,
149535  ** then the encoding of the first docid from the 'other' input list may
149536  ** be larger in the output than it was in the input (since the delta value
149537  ** may be a larger positive integer than the actual docid).
149538  **
149539  ** The space required to store the output is therefore the sum of the
149540  ** sizes of the two inputs, plus enough space for exactly one of the input
149541  ** docids to grow.
149542  **
149543  ** A symetric argument may be made if the doclists are in descending
149544  ** order.
149545  */
149546  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
149547  if( !aOut ) return SQLITE_NOMEM;
149548
149549  p = aOut;
149550  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
149551  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
149552  while( p1 || p2 ){
149553    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
149554
149555    if( p2 && p1 && iDiff==0 ){
149556      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
149557      fts3PoslistMerge(&p, &p1, &p2);
149558      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
149559      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
149560    }else if( !p2 || (p1 && iDiff<0) ){
149561      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
149562      fts3PoslistCopy(&p, &p1);
149563      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
149564    }else{
149565      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
149566      fts3PoslistCopy(&p, &p2);
149567      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
149568    }
149569  }
149570
149571  *paOut = aOut;
149572  *pnOut = (int)(p-aOut);
149573  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
149574  return SQLITE_OK;
149575}
149576
149577/*
149578** This function does a "phrase" merge of two doclists. In a phrase merge,
149579** the output contains a copy of each position from the right-hand input
149580** doclist for which there is a position in the left-hand input doclist
149581** exactly nDist tokens before it.
149582**
149583** If the docids in the input doclists are sorted in ascending order,
149584** parameter bDescDoclist should be false. If they are sorted in ascending
149585** order, it should be passed a non-zero value.
149586**
149587** The right-hand input doclist is overwritten by this function.
149588*/
149589static int fts3DoclistPhraseMerge(
149590  int bDescDoclist,               /* True if arguments are desc */
149591  int nDist,                      /* Distance from left to right (1=adjacent) */
149592  char *aLeft, int nLeft,         /* Left doclist */
149593  char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
149594){
149595  sqlite3_int64 i1 = 0;
149596  sqlite3_int64 i2 = 0;
149597  sqlite3_int64 iPrev = 0;
149598  char *aRight = *paRight;
149599  char *pEnd1 = &aLeft[nLeft];
149600  char *pEnd2 = &aRight[*pnRight];
149601  char *p1 = aLeft;
149602  char *p2 = aRight;
149603  char *p;
149604  int bFirstOut = 0;
149605  char *aOut;
149606
149607  assert( nDist>0 );
149608  if( bDescDoclist ){
149609    aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
149610    if( aOut==0 ) return SQLITE_NOMEM;
149611  }else{
149612    aOut = aRight;
149613  }
149614  p = aOut;
149615
149616  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
149617  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
149618
149619  while( p1 && p2 ){
149620    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
149621    if( iDiff==0 ){
149622      char *pSave = p;
149623      sqlite3_int64 iPrevSave = iPrev;
149624      int bFirstOutSave = bFirstOut;
149625
149626      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
149627      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
149628        p = pSave;
149629        iPrev = iPrevSave;
149630        bFirstOut = bFirstOutSave;
149631      }
149632      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
149633      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
149634    }else if( iDiff<0 ){
149635      fts3PoslistCopy(0, &p1);
149636      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
149637    }else{
149638      fts3PoslistCopy(0, &p2);
149639      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
149640    }
149641  }
149642
149643  *pnRight = (int)(p - aOut);
149644  if( bDescDoclist ){
149645    sqlite3_free(aRight);
149646    *paRight = aOut;
149647  }
149648
149649  return SQLITE_OK;
149650}
149651
149652/*
149653** Argument pList points to a position list nList bytes in size. This
149654** function checks to see if the position list contains any entries for
149655** a token in position 0 (of any column). If so, it writes argument iDelta
149656** to the output buffer pOut, followed by a position list consisting only
149657** of the entries from pList at position 0, and terminated by an 0x00 byte.
149658** The value returned is the number of bytes written to pOut (if any).
149659*/
149660SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
149661  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
149662  char *pList,                    /* Position list (no 0x00 term) */
149663  int nList,                      /* Size of pList in bytes */
149664  char *pOut                      /* Write output here */
149665){
149666  int nOut = 0;
149667  int bWritten = 0;               /* True once iDelta has been written */
149668  char *p = pList;
149669  char *pEnd = &pList[nList];
149670
149671  if( *p!=0x01 ){
149672    if( *p==0x02 ){
149673      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
149674      pOut[nOut++] = 0x02;
149675      bWritten = 1;
149676    }
149677    fts3ColumnlistCopy(0, &p);
149678  }
149679
149680  while( p<pEnd ){
149681    sqlite3_int64 iCol;
149682    p++;
149683    p += sqlite3Fts3GetVarint(p, &iCol);
149684    if( *p==0x02 ){
149685      if( bWritten==0 ){
149686        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
149687        bWritten = 1;
149688      }
149689      pOut[nOut++] = 0x01;
149690      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
149691      pOut[nOut++] = 0x02;
149692    }
149693    fts3ColumnlistCopy(0, &p);
149694  }
149695  if( bWritten ){
149696    pOut[nOut++] = 0x00;
149697  }
149698
149699  return nOut;
149700}
149701
149702
149703/*
149704** Merge all doclists in the TermSelect.aaOutput[] array into a single
149705** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
149706** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
149707**
149708** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
149709** the responsibility of the caller to free any doclists left in the
149710** TermSelect.aaOutput[] array.
149711*/
149712static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
149713  char *aOut = 0;
149714  int nOut = 0;
149715  int i;
149716
149717  /* Loop through the doclists in the aaOutput[] array. Merge them all
149718  ** into a single doclist.
149719  */
149720  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
149721    if( pTS->aaOutput[i] ){
149722      if( !aOut ){
149723        aOut = pTS->aaOutput[i];
149724        nOut = pTS->anOutput[i];
149725        pTS->aaOutput[i] = 0;
149726      }else{
149727        int nNew;
149728        char *aNew;
149729
149730        int rc = fts3DoclistOrMerge(p->bDescIdx,
149731            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
149732        );
149733        if( rc!=SQLITE_OK ){
149734          sqlite3_free(aOut);
149735          return rc;
149736        }
149737
149738        sqlite3_free(pTS->aaOutput[i]);
149739        sqlite3_free(aOut);
149740        pTS->aaOutput[i] = 0;
149741        aOut = aNew;
149742        nOut = nNew;
149743      }
149744    }
149745  }
149746
149747  pTS->aaOutput[0] = aOut;
149748  pTS->anOutput[0] = nOut;
149749  return SQLITE_OK;
149750}
149751
149752/*
149753** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
149754** as the first argument. The merge is an "OR" merge (see function
149755** fts3DoclistOrMerge() for details).
149756**
149757** This function is called with the doclist for each term that matches
149758** a queried prefix. It merges all these doclists into one, the doclist
149759** for the specified prefix. Since there can be a very large number of
149760** doclists to merge, the merging is done pair-wise using the TermSelect
149761** object.
149762**
149763** This function returns SQLITE_OK if the merge is successful, or an
149764** SQLite error code (SQLITE_NOMEM) if an error occurs.
149765*/
149766static int fts3TermSelectMerge(
149767  Fts3Table *p,                   /* FTS table handle */
149768  TermSelect *pTS,                /* TermSelect object to merge into */
149769  char *aDoclist,                 /* Pointer to doclist */
149770  int nDoclist                    /* Size of aDoclist in bytes */
149771){
149772  if( pTS->aaOutput[0]==0 ){
149773    /* If this is the first term selected, copy the doclist to the output
149774    ** buffer using memcpy().
149775    **
149776    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
149777    ** allocation. This is so as to ensure that the buffer is big enough
149778    ** to hold the current doclist AND'd with any other doclist. If the
149779    ** doclists are stored in order=ASC order, this padding would not be
149780    ** required (since the size of [doclistA AND doclistB] is always less
149781    ** than or equal to the size of [doclistA] in that case). But this is
149782    ** not true for order=DESC. For example, a doclist containing (1, -1)
149783    ** may be smaller than (-1), as in the first example the -1 may be stored
149784    ** as a single-byte delta, whereas in the second it must be stored as a
149785    ** FTS3_VARINT_MAX byte varint.
149786    **
149787    ** Similar padding is added in the fts3DoclistOrMerge() function.
149788    */
149789    pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
149790    pTS->anOutput[0] = nDoclist;
149791    if( pTS->aaOutput[0] ){
149792      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
149793    }else{
149794      return SQLITE_NOMEM;
149795    }
149796  }else{
149797    char *aMerge = aDoclist;
149798    int nMerge = nDoclist;
149799    int iOut;
149800
149801    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
149802      if( pTS->aaOutput[iOut]==0 ){
149803        assert( iOut>0 );
149804        pTS->aaOutput[iOut] = aMerge;
149805        pTS->anOutput[iOut] = nMerge;
149806        break;
149807      }else{
149808        char *aNew;
149809        int nNew;
149810
149811        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
149812            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
149813        );
149814        if( rc!=SQLITE_OK ){
149815          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
149816          return rc;
149817        }
149818
149819        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
149820        sqlite3_free(pTS->aaOutput[iOut]);
149821        pTS->aaOutput[iOut] = 0;
149822
149823        aMerge = aNew;
149824        nMerge = nNew;
149825        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
149826          pTS->aaOutput[iOut] = aMerge;
149827          pTS->anOutput[iOut] = nMerge;
149828        }
149829      }
149830    }
149831  }
149832  return SQLITE_OK;
149833}
149834
149835/*
149836** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
149837*/
149838static int fts3SegReaderCursorAppend(
149839  Fts3MultiSegReader *pCsr,
149840  Fts3SegReader *pNew
149841){
149842  if( (pCsr->nSegment%16)==0 ){
149843    Fts3SegReader **apNew;
149844    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
149845    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
149846    if( !apNew ){
149847      sqlite3Fts3SegReaderFree(pNew);
149848      return SQLITE_NOMEM;
149849    }
149850    pCsr->apSegment = apNew;
149851  }
149852  pCsr->apSegment[pCsr->nSegment++] = pNew;
149853  return SQLITE_OK;
149854}
149855
149856/*
149857** Add seg-reader objects to the Fts3MultiSegReader object passed as the
149858** 8th argument.
149859**
149860** This function returns SQLITE_OK if successful, or an SQLite error code
149861** otherwise.
149862*/
149863static int fts3SegReaderCursor(
149864  Fts3Table *p,                   /* FTS3 table handle */
149865  int iLangid,                    /* Language id */
149866  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
149867  int iLevel,                     /* Level of segments to scan */
149868  const char *zTerm,              /* Term to query for */
149869  int nTerm,                      /* Size of zTerm in bytes */
149870  int isPrefix,                   /* True for a prefix search */
149871  int isScan,                     /* True to scan from zTerm to EOF */
149872  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
149873){
149874  int rc = SQLITE_OK;             /* Error code */
149875  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
149876  int rc2;                        /* Result of sqlite3_reset() */
149877
149878  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
149879  ** for the pending-terms. If this is a scan, then this call must be being
149880  ** made by an fts4aux module, not an FTS table. In this case calling
149881  ** Fts3SegReaderPending might segfault, as the data structures used by
149882  ** fts4aux are not completely populated. So it's easiest to filter these
149883  ** calls out here.  */
149884  if( iLevel<0 && p->aIndex ){
149885    Fts3SegReader *pSeg = 0;
149886    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
149887    if( rc==SQLITE_OK && pSeg ){
149888      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
149889    }
149890  }
149891
149892  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
149893    if( rc==SQLITE_OK ){
149894      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
149895    }
149896
149897    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
149898      Fts3SegReader *pSeg = 0;
149899
149900      /* Read the values returned by the SELECT into local variables. */
149901      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
149902      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
149903      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
149904      int nRoot = sqlite3_column_bytes(pStmt, 4);
149905      char const *zRoot = sqlite3_column_blob(pStmt, 4);
149906
149907      /* If zTerm is not NULL, and this segment is not stored entirely on its
149908      ** root node, the range of leaves scanned can be reduced. Do this. */
149909      if( iStartBlock && zTerm ){
149910        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
149911        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
149912        if( rc!=SQLITE_OK ) goto finished;
149913        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
149914      }
149915
149916      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
149917          (isPrefix==0 && isScan==0),
149918          iStartBlock, iLeavesEndBlock,
149919          iEndBlock, zRoot, nRoot, &pSeg
149920      );
149921      if( rc!=SQLITE_OK ) goto finished;
149922      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
149923    }
149924  }
149925
149926 finished:
149927  rc2 = sqlite3_reset(pStmt);
149928  if( rc==SQLITE_DONE ) rc = rc2;
149929
149930  return rc;
149931}
149932
149933/*
149934** Set up a cursor object for iterating through a full-text index or a
149935** single level therein.
149936*/
149937SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
149938  Fts3Table *p,                   /* FTS3 table handle */
149939  int iLangid,                    /* Language-id to search */
149940  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
149941  int iLevel,                     /* Level of segments to scan */
149942  const char *zTerm,              /* Term to query for */
149943  int nTerm,                      /* Size of zTerm in bytes */
149944  int isPrefix,                   /* True for a prefix search */
149945  int isScan,                     /* True to scan from zTerm to EOF */
149946  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
149947){
149948  assert( iIndex>=0 && iIndex<p->nIndex );
149949  assert( iLevel==FTS3_SEGCURSOR_ALL
149950      ||  iLevel==FTS3_SEGCURSOR_PENDING
149951      ||  iLevel>=0
149952  );
149953  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
149954  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
149955  assert( isPrefix==0 || isScan==0 );
149956
149957  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
149958  return fts3SegReaderCursor(
149959      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
149960  );
149961}
149962
149963/*
149964** In addition to its current configuration, have the Fts3MultiSegReader
149965** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
149966**
149967** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
149968*/
149969static int fts3SegReaderCursorAddZero(
149970  Fts3Table *p,                   /* FTS virtual table handle */
149971  int iLangid,
149972  const char *zTerm,              /* Term to scan doclist of */
149973  int nTerm,                      /* Number of bytes in zTerm */
149974  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
149975){
149976  return fts3SegReaderCursor(p,
149977      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
149978  );
149979}
149980
149981/*
149982** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
149983** if isPrefix is true, to scan the doclist for all terms for which
149984** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
149985** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
149986** an SQLite error code.
149987**
149988** It is the responsibility of the caller to free this object by eventually
149989** passing it to fts3SegReaderCursorFree()
149990**
149991** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
149992** Output parameter *ppSegcsr is set to 0 if an error occurs.
149993*/
149994static int fts3TermSegReaderCursor(
149995  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
149996  const char *zTerm,              /* Term to query for */
149997  int nTerm,                      /* Size of zTerm in bytes */
149998  int isPrefix,                   /* True for a prefix search */
149999  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
150000){
150001  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
150002  int rc = SQLITE_NOMEM;          /* Return code */
150003
150004  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
150005  if( pSegcsr ){
150006    int i;
150007    int bFound = 0;               /* True once an index has been found */
150008    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
150009
150010    if( isPrefix ){
150011      for(i=1; bFound==0 && i<p->nIndex; i++){
150012        if( p->aIndex[i].nPrefix==nTerm ){
150013          bFound = 1;
150014          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
150015              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
150016          );
150017          pSegcsr->bLookup = 1;
150018        }
150019      }
150020
150021      for(i=1; bFound==0 && i<p->nIndex; i++){
150022        if( p->aIndex[i].nPrefix==nTerm+1 ){
150023          bFound = 1;
150024          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
150025              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
150026          );
150027          if( rc==SQLITE_OK ){
150028            rc = fts3SegReaderCursorAddZero(
150029                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
150030            );
150031          }
150032        }
150033      }
150034    }
150035
150036    if( bFound==0 ){
150037      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
150038          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
150039      );
150040      pSegcsr->bLookup = !isPrefix;
150041    }
150042  }
150043
150044  *ppSegcsr = pSegcsr;
150045  return rc;
150046}
150047
150048/*
150049** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
150050*/
150051static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
150052  sqlite3Fts3SegReaderFinish(pSegcsr);
150053  sqlite3_free(pSegcsr);
150054}
150055
150056/*
150057** This function retrieves the doclist for the specified term (or term
150058** prefix) from the database.
150059*/
150060static int fts3TermSelect(
150061  Fts3Table *p,                   /* Virtual table handle */
150062  Fts3PhraseToken *pTok,          /* Token to query for */
150063  int iColumn,                    /* Column to query (or -ve for all columns) */
150064  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
150065  char **ppOut                    /* OUT: Malloced result buffer */
150066){
150067  int rc;                         /* Return code */
150068  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
150069  TermSelect tsc;                 /* Object for pair-wise doclist merging */
150070  Fts3SegFilter filter;           /* Segment term filter configuration */
150071
150072  pSegcsr = pTok->pSegcsr;
150073  memset(&tsc, 0, sizeof(TermSelect));
150074
150075  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
150076        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
150077        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
150078        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
150079  filter.iCol = iColumn;
150080  filter.zTerm = pTok->z;
150081  filter.nTerm = pTok->n;
150082
150083  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
150084  while( SQLITE_OK==rc
150085      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
150086  ){
150087    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
150088  }
150089
150090  if( rc==SQLITE_OK ){
150091    rc = fts3TermSelectFinishMerge(p, &tsc);
150092  }
150093  if( rc==SQLITE_OK ){
150094    *ppOut = tsc.aaOutput[0];
150095    *pnOut = tsc.anOutput[0];
150096  }else{
150097    int i;
150098    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
150099      sqlite3_free(tsc.aaOutput[i]);
150100    }
150101  }
150102
150103  fts3SegReaderCursorFree(pSegcsr);
150104  pTok->pSegcsr = 0;
150105  return rc;
150106}
150107
150108/*
150109** This function counts the total number of docids in the doclist stored
150110** in buffer aList[], size nList bytes.
150111**
150112** If the isPoslist argument is true, then it is assumed that the doclist
150113** contains a position-list following each docid. Otherwise, it is assumed
150114** that the doclist is simply a list of docids stored as delta encoded
150115** varints.
150116*/
150117static int fts3DoclistCountDocids(char *aList, int nList){
150118  int nDoc = 0;                   /* Return value */
150119  if( aList ){
150120    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
150121    char *p = aList;              /* Cursor */
150122    while( p<aEnd ){
150123      nDoc++;
150124      while( (*p++)&0x80 );     /* Skip docid varint */
150125      fts3PoslistCopy(0, &p);   /* Skip over position list */
150126    }
150127  }
150128
150129  return nDoc;
150130}
150131
150132/*
150133** Advance the cursor to the next row in the %_content table that
150134** matches the search criteria.  For a MATCH search, this will be
150135** the next row that matches. For a full-table scan, this will be
150136** simply the next row in the %_content table.  For a docid lookup,
150137** this routine simply sets the EOF flag.
150138**
150139** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
150140** even if we reach end-of-file.  The fts3EofMethod() will be called
150141** subsequently to determine whether or not an EOF was hit.
150142*/
150143static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
150144  int rc;
150145  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
150146  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
150147    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
150148      pCsr->isEof = 1;
150149      rc = sqlite3_reset(pCsr->pStmt);
150150    }else{
150151      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
150152      rc = SQLITE_OK;
150153    }
150154  }else{
150155    rc = fts3EvalNext((Fts3Cursor *)pCursor);
150156  }
150157  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
150158  return rc;
150159}
150160
150161/*
150162** The following are copied from sqliteInt.h.
150163**
150164** Constants for the largest and smallest possible 64-bit signed integers.
150165** These macros are designed to work correctly on both 32-bit and 64-bit
150166** compilers.
150167*/
150168#ifndef SQLITE_AMALGAMATION
150169# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
150170# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
150171#endif
150172
150173/*
150174** If the numeric type of argument pVal is "integer", then return it
150175** converted to a 64-bit signed integer. Otherwise, return a copy of
150176** the second parameter, iDefault.
150177*/
150178static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
150179  if( pVal ){
150180    int eType = sqlite3_value_numeric_type(pVal);
150181    if( eType==SQLITE_INTEGER ){
150182      return sqlite3_value_int64(pVal);
150183    }
150184  }
150185  return iDefault;
150186}
150187
150188/*
150189** This is the xFilter interface for the virtual table.  See
150190** the virtual table xFilter method documentation for additional
150191** information.
150192**
150193** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
150194** the %_content table.
150195**
150196** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
150197** in the %_content table.
150198**
150199** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
150200** column on the left-hand side of the MATCH operator is column
150201** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
150202** side of the MATCH operator.
150203*/
150204static int fts3FilterMethod(
150205  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
150206  int idxNum,                     /* Strategy index */
150207  const char *idxStr,             /* Unused */
150208  int nVal,                       /* Number of elements in apVal */
150209  sqlite3_value **apVal           /* Arguments for the indexing scheme */
150210){
150211  int rc = SQLITE_OK;
150212  char *zSql;                     /* SQL statement used to access %_content */
150213  int eSearch;
150214  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
150215  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
150216
150217  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
150218  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
150219  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
150220  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
150221  int iIdx;
150222
150223  UNUSED_PARAMETER(idxStr);
150224  UNUSED_PARAMETER(nVal);
150225
150226  eSearch = (idxNum & 0x0000FFFF);
150227  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
150228  assert( p->pSegments==0 );
150229
150230  /* Collect arguments into local variables */
150231  iIdx = 0;
150232  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
150233  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
150234  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
150235  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
150236  assert( iIdx==nVal );
150237
150238  /* In case the cursor has been used before, clear it now. */
150239  fts3ClearCursor(pCsr);
150240
150241  /* Set the lower and upper bounds on docids to return */
150242  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
150243  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
150244
150245  if( idxStr ){
150246    pCsr->bDesc = (idxStr[0]=='D');
150247  }else{
150248    pCsr->bDesc = p->bDescIdx;
150249  }
150250  pCsr->eSearch = (i16)eSearch;
150251
150252  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
150253    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
150254    const char *zQuery = (const char *)sqlite3_value_text(pCons);
150255
150256    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
150257      return SQLITE_NOMEM;
150258    }
150259
150260    pCsr->iLangid = 0;
150261    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
150262
150263    assert( p->base.zErrMsg==0 );
150264    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
150265        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
150266        &p->base.zErrMsg
150267    );
150268    if( rc!=SQLITE_OK ){
150269      return rc;
150270    }
150271
150272    rc = fts3EvalStart(pCsr);
150273    sqlite3Fts3SegmentsClose(p);
150274    if( rc!=SQLITE_OK ) return rc;
150275    pCsr->pNextId = pCsr->aDoclist;
150276    pCsr->iPrevId = 0;
150277  }
150278
150279  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
150280  ** statement loops through all rows of the %_content table. For a
150281  ** full-text query or docid lookup, the statement retrieves a single
150282  ** row by docid.
150283  */
150284  if( eSearch==FTS3_FULLSCAN_SEARCH ){
150285    if( pDocidGe || pDocidLe ){
150286      zSql = sqlite3_mprintf(
150287          "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
150288          p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
150289          (pCsr->bDesc ? "DESC" : "ASC")
150290      );
150291    }else{
150292      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
150293          p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
150294      );
150295    }
150296    if( zSql ){
150297      rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
150298      sqlite3_free(zSql);
150299    }else{
150300      rc = SQLITE_NOMEM;
150301    }
150302  }else if( eSearch==FTS3_DOCID_SEARCH ){
150303    rc = fts3CursorSeekStmt(pCsr);
150304    if( rc==SQLITE_OK ){
150305      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
150306    }
150307  }
150308  if( rc!=SQLITE_OK ) return rc;
150309
150310  return fts3NextMethod(pCursor);
150311}
150312
150313/*
150314** This is the xEof method of the virtual table. SQLite calls this
150315** routine to find out if it has reached the end of a result set.
150316*/
150317static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
150318  Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
150319  if( pCsr->isEof ){
150320    fts3ClearCursor(pCsr);
150321    pCsr->isEof = 1;
150322  }
150323  return pCsr->isEof;
150324}
150325
150326/*
150327** This is the xRowid method. The SQLite core calls this routine to
150328** retrieve the rowid for the current row of the result set. fts3
150329** exposes %_content.docid as the rowid for the virtual table. The
150330** rowid should be written to *pRowid.
150331*/
150332static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
150333  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
150334  *pRowid = pCsr->iPrevId;
150335  return SQLITE_OK;
150336}
150337
150338/*
150339** This is the xColumn method, called by SQLite to request a value from
150340** the row that the supplied cursor currently points to.
150341**
150342** If:
150343**
150344**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
150345**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
150346**   (iCol == p->nColumn+1) -> Docid column
150347**   (iCol == p->nColumn+2) -> Langid column
150348*/
150349static int fts3ColumnMethod(
150350  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
150351  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
150352  int iCol                        /* Index of column to read value from */
150353){
150354  int rc = SQLITE_OK;             /* Return Code */
150355  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
150356  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
150357
150358  /* The column value supplied by SQLite must be in range. */
150359  assert( iCol>=0 && iCol<=p->nColumn+2 );
150360
150361  switch( iCol-p->nColumn ){
150362    case 0:
150363      /* The special 'table-name' column */
150364      sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
150365      break;
150366
150367    case 1:
150368      /* The docid column */
150369      sqlite3_result_int64(pCtx, pCsr->iPrevId);
150370      break;
150371
150372    case 2:
150373      if( pCsr->pExpr ){
150374        sqlite3_result_int64(pCtx, pCsr->iLangid);
150375        break;
150376      }else if( p->zLanguageid==0 ){
150377        sqlite3_result_int(pCtx, 0);
150378        break;
150379      }else{
150380        iCol = p->nColumn;
150381        /* fall-through */
150382      }
150383
150384    default:
150385      /* A user column. Or, if this is a full-table scan, possibly the
150386      ** language-id column. Seek the cursor. */
150387      rc = fts3CursorSeek(0, pCsr);
150388      if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
150389        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
150390      }
150391      break;
150392  }
150393
150394  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
150395  return rc;
150396}
150397
150398/*
150399** This function is the implementation of the xUpdate callback used by
150400** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
150401** inserted, updated or deleted.
150402*/
150403static int fts3UpdateMethod(
150404  sqlite3_vtab *pVtab,            /* Virtual table handle */
150405  int nArg,                       /* Size of argument array */
150406  sqlite3_value **apVal,          /* Array of arguments */
150407  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
150408){
150409  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
150410}
150411
150412/*
150413** Implementation of xSync() method. Flush the contents of the pending-terms
150414** hash-table to the database.
150415*/
150416static int fts3SyncMethod(sqlite3_vtab *pVtab){
150417
150418  /* Following an incremental-merge operation, assuming that the input
150419  ** segments are not completely consumed (the usual case), they are updated
150420  ** in place to remove the entries that have already been merged. This
150421  ** involves updating the leaf block that contains the smallest unmerged
150422  ** entry and each block (if any) between the leaf and the root node. So
150423  ** if the height of the input segment b-trees is N, and input segments
150424  ** are merged eight at a time, updating the input segments at the end
150425  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
150426  ** small - often between 0 and 2. So the overhead of the incremental
150427  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
150428  ** dwarfing the actual productive work accomplished, the incremental merge
150429  ** is only attempted if it will write at least 64 leaf blocks. Hence
150430  ** nMinMerge.
150431  **
150432  ** Of course, updating the input segments also involves deleting a bunch
150433  ** of blocks from the segments table. But this is not considered overhead
150434  ** as it would also be required by a crisis-merge that used the same input
150435  ** segments.
150436  */
150437  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
150438
150439  Fts3Table *p = (Fts3Table*)pVtab;
150440  int rc;
150441  i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
150442
150443  rc = sqlite3Fts3PendingTermsFlush(p);
150444  if( rc==SQLITE_OK
150445   && p->nLeafAdd>(nMinMerge/16)
150446   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
150447  ){
150448    int mxLevel = 0;              /* Maximum relative level value in db */
150449    int A;                        /* Incr-merge parameter A */
150450
150451    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
150452    assert( rc==SQLITE_OK || mxLevel==0 );
150453    A = p->nLeafAdd * mxLevel;
150454    A += (A/2);
150455    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
150456  }
150457  sqlite3Fts3SegmentsClose(p);
150458  sqlite3_set_last_insert_rowid(p->db, iLastRowid);
150459  return rc;
150460}
150461
150462/*
150463** If it is currently unknown whether or not the FTS table has an %_stat
150464** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
150465** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
150466** if an error occurs.
150467*/
150468static int fts3SetHasStat(Fts3Table *p){
150469  int rc = SQLITE_OK;
150470  if( p->bHasStat==2 ){
150471    char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
150472    if( zTbl ){
150473      int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
150474      sqlite3_free(zTbl);
150475      p->bHasStat = (res==SQLITE_OK);
150476    }else{
150477      rc = SQLITE_NOMEM;
150478    }
150479  }
150480  return rc;
150481}
150482
150483/*
150484** Implementation of xBegin() method.
150485*/
150486static int fts3BeginMethod(sqlite3_vtab *pVtab){
150487  Fts3Table *p = (Fts3Table*)pVtab;
150488  UNUSED_PARAMETER(pVtab);
150489  assert( p->pSegments==0 );
150490  assert( p->nPendingData==0 );
150491  assert( p->inTransaction!=1 );
150492  TESTONLY( p->inTransaction = 1 );
150493  TESTONLY( p->mxSavepoint = -1; );
150494  p->nLeafAdd = 0;
150495  return fts3SetHasStat(p);
150496}
150497
150498/*
150499** Implementation of xCommit() method. This is a no-op. The contents of
150500** the pending-terms hash-table have already been flushed into the database
150501** by fts3SyncMethod().
150502*/
150503static int fts3CommitMethod(sqlite3_vtab *pVtab){
150504  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
150505  UNUSED_PARAMETER(pVtab);
150506  assert( p->nPendingData==0 );
150507  assert( p->inTransaction!=0 );
150508  assert( p->pSegments==0 );
150509  TESTONLY( p->inTransaction = 0 );
150510  TESTONLY( p->mxSavepoint = -1; );
150511  return SQLITE_OK;
150512}
150513
150514/*
150515** Implementation of xRollback(). Discard the contents of the pending-terms
150516** hash-table. Any changes made to the database are reverted by SQLite.
150517*/
150518static int fts3RollbackMethod(sqlite3_vtab *pVtab){
150519  Fts3Table *p = (Fts3Table*)pVtab;
150520  sqlite3Fts3PendingTermsClear(p);
150521  assert( p->inTransaction!=0 );
150522  TESTONLY( p->inTransaction = 0 );
150523  TESTONLY( p->mxSavepoint = -1; );
150524  return SQLITE_OK;
150525}
150526
150527/*
150528** When called, *ppPoslist must point to the byte immediately following the
150529** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
150530** moves *ppPoslist so that it instead points to the first byte of the
150531** same position list.
150532*/
150533static void fts3ReversePoslist(char *pStart, char **ppPoslist){
150534  char *p = &(*ppPoslist)[-2];
150535  char c = 0;
150536
150537  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
150538  while( p>pStart && (c=*p--)==0 );
150539
150540  /* Search backwards for a varint with value zero (the end of the previous
150541  ** poslist). This is an 0x00 byte preceded by some byte that does not
150542  ** have the 0x80 bit set.  */
150543  while( p>pStart && (*p & 0x80) | c ){
150544    c = *p--;
150545  }
150546  assert( p==pStart || c==0 );
150547
150548  /* At this point p points to that preceding byte without the 0x80 bit
150549  ** set. So to find the start of the poslist, skip forward 2 bytes then
150550  ** over a varint.
150551  **
150552  ** Normally. The other case is that p==pStart and the poslist to return
150553  ** is the first in the doclist. In this case do not skip forward 2 bytes.
150554  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
150555  ** is required for cases where the first byte of a doclist and the
150556  ** doclist is empty. For example, if the first docid is 10, a doclist
150557  ** that begins with:
150558  **
150559  **   0x0A 0x00 <next docid delta varint>
150560  */
150561  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
150562  while( *p++&0x80 );
150563  *ppPoslist = p;
150564}
150565
150566/*
150567** Helper function used by the implementation of the overloaded snippet(),
150568** offsets() and optimize() SQL functions.
150569**
150570** If the value passed as the third argument is a blob of size
150571** sizeof(Fts3Cursor*), then the blob contents are copied to the
150572** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
150573** message is written to context pContext and SQLITE_ERROR returned. The
150574** string passed via zFunc is used as part of the error message.
150575*/
150576static int fts3FunctionArg(
150577  sqlite3_context *pContext,      /* SQL function call context */
150578  const char *zFunc,              /* Function name */
150579  sqlite3_value *pVal,            /* argv[0] passed to function */
150580  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
150581){
150582  int rc;
150583  *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
150584  if( (*ppCsr)!=0 ){
150585    rc = SQLITE_OK;
150586  }else{
150587    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
150588    sqlite3_result_error(pContext, zErr, -1);
150589    sqlite3_free(zErr);
150590    rc = SQLITE_ERROR;
150591  }
150592  return rc;
150593}
150594
150595/*
150596** Implementation of the snippet() function for FTS3
150597*/
150598static void fts3SnippetFunc(
150599  sqlite3_context *pContext,      /* SQLite function call context */
150600  int nVal,                       /* Size of apVal[] array */
150601  sqlite3_value **apVal           /* Array of arguments */
150602){
150603  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
150604  const char *zStart = "<b>";
150605  const char *zEnd = "</b>";
150606  const char *zEllipsis = "<b>...</b>";
150607  int iCol = -1;
150608  int nToken = 15;                /* Default number of tokens in snippet */
150609
150610  /* There must be at least one argument passed to this function (otherwise
150611  ** the non-overloaded version would have been called instead of this one).
150612  */
150613  assert( nVal>=1 );
150614
150615  if( nVal>6 ){
150616    sqlite3_result_error(pContext,
150617        "wrong number of arguments to function snippet()", -1);
150618    return;
150619  }
150620  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
150621
150622  switch( nVal ){
150623    case 6: nToken = sqlite3_value_int(apVal[5]);
150624    case 5: iCol = sqlite3_value_int(apVal[4]);
150625    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
150626    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
150627    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
150628  }
150629  if( !zEllipsis || !zEnd || !zStart ){
150630    sqlite3_result_error_nomem(pContext);
150631  }else if( nToken==0 ){
150632    sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
150633  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
150634    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
150635  }
150636}
150637
150638/*
150639** Implementation of the offsets() function for FTS3
150640*/
150641static void fts3OffsetsFunc(
150642  sqlite3_context *pContext,      /* SQLite function call context */
150643  int nVal,                       /* Size of argument array */
150644  sqlite3_value **apVal           /* Array of arguments */
150645){
150646  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
150647
150648  UNUSED_PARAMETER(nVal);
150649
150650  assert( nVal==1 );
150651  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
150652  assert( pCsr );
150653  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
150654    sqlite3Fts3Offsets(pContext, pCsr);
150655  }
150656}
150657
150658/*
150659** Implementation of the special optimize() function for FTS3. This
150660** function merges all segments in the database to a single segment.
150661** Example usage is:
150662**
150663**   SELECT optimize(t) FROM t LIMIT 1;
150664**
150665** where 't' is the name of an FTS3 table.
150666*/
150667static void fts3OptimizeFunc(
150668  sqlite3_context *pContext,      /* SQLite function call context */
150669  int nVal,                       /* Size of argument array */
150670  sqlite3_value **apVal           /* Array of arguments */
150671){
150672  int rc;                         /* Return code */
150673  Fts3Table *p;                   /* Virtual table handle */
150674  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
150675
150676  UNUSED_PARAMETER(nVal);
150677
150678  assert( nVal==1 );
150679  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
150680  p = (Fts3Table *)pCursor->base.pVtab;
150681  assert( p );
150682
150683  rc = sqlite3Fts3Optimize(p);
150684
150685  switch( rc ){
150686    case SQLITE_OK:
150687      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
150688      break;
150689    case SQLITE_DONE:
150690      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
150691      break;
150692    default:
150693      sqlite3_result_error_code(pContext, rc);
150694      break;
150695  }
150696}
150697
150698/*
150699** Implementation of the matchinfo() function for FTS3
150700*/
150701static void fts3MatchinfoFunc(
150702  sqlite3_context *pContext,      /* SQLite function call context */
150703  int nVal,                       /* Size of argument array */
150704  sqlite3_value **apVal           /* Array of arguments */
150705){
150706  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
150707  assert( nVal==1 || nVal==2 );
150708  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
150709    const char *zArg = 0;
150710    if( nVal>1 ){
150711      zArg = (const char *)sqlite3_value_text(apVal[1]);
150712    }
150713    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
150714  }
150715}
150716
150717/*
150718** This routine implements the xFindFunction method for the FTS3
150719** virtual table.
150720*/
150721static int fts3FindFunctionMethod(
150722  sqlite3_vtab *pVtab,            /* Virtual table handle */
150723  int nArg,                       /* Number of SQL function arguments */
150724  const char *zName,              /* Name of SQL function */
150725  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
150726  void **ppArg                    /* Unused */
150727){
150728  struct Overloaded {
150729    const char *zName;
150730    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
150731  } aOverload[] = {
150732    { "snippet", fts3SnippetFunc },
150733    { "offsets", fts3OffsetsFunc },
150734    { "optimize", fts3OptimizeFunc },
150735    { "matchinfo", fts3MatchinfoFunc },
150736  };
150737  int i;                          /* Iterator variable */
150738
150739  UNUSED_PARAMETER(pVtab);
150740  UNUSED_PARAMETER(nArg);
150741  UNUSED_PARAMETER(ppArg);
150742
150743  for(i=0; i<SizeofArray(aOverload); i++){
150744    if( strcmp(zName, aOverload[i].zName)==0 ){
150745      *pxFunc = aOverload[i].xFunc;
150746      return 1;
150747    }
150748  }
150749
150750  /* No function of the specified name was found. Return 0. */
150751  return 0;
150752}
150753
150754/*
150755** Implementation of FTS3 xRename method. Rename an fts3 table.
150756*/
150757static int fts3RenameMethod(
150758  sqlite3_vtab *pVtab,            /* Virtual table handle */
150759  const char *zName               /* New name of table */
150760){
150761  Fts3Table *p = (Fts3Table *)pVtab;
150762  sqlite3 *db = p->db;            /* Database connection */
150763  int rc;                         /* Return Code */
150764
150765  /* At this point it must be known if the %_stat table exists or not.
150766  ** So bHasStat may not be 2.  */
150767  rc = fts3SetHasStat(p);
150768
150769  /* As it happens, the pending terms table is always empty here. This is
150770  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
150771  ** always opens a savepoint transaction. And the xSavepoint() method
150772  ** flushes the pending terms table. But leave the (no-op) call to
150773  ** PendingTermsFlush() in in case that changes.
150774  */
150775  assert( p->nPendingData==0 );
150776  if( rc==SQLITE_OK ){
150777    rc = sqlite3Fts3PendingTermsFlush(p);
150778  }
150779
150780  if( p->zContentTbl==0 ){
150781    fts3DbExec(&rc, db,
150782      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
150783      p->zDb, p->zName, zName
150784    );
150785  }
150786
150787  if( p->bHasDocsize ){
150788    fts3DbExec(&rc, db,
150789      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
150790      p->zDb, p->zName, zName
150791    );
150792  }
150793  if( p->bHasStat ){
150794    fts3DbExec(&rc, db,
150795      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
150796      p->zDb, p->zName, zName
150797    );
150798  }
150799  fts3DbExec(&rc, db,
150800    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
150801    p->zDb, p->zName, zName
150802  );
150803  fts3DbExec(&rc, db,
150804    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
150805    p->zDb, p->zName, zName
150806  );
150807  return rc;
150808}
150809
150810/*
150811** The xSavepoint() method.
150812**
150813** Flush the contents of the pending-terms table to disk.
150814*/
150815static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
150816  int rc = SQLITE_OK;
150817  UNUSED_PARAMETER(iSavepoint);
150818  assert( ((Fts3Table *)pVtab)->inTransaction );
150819  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
150820  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
150821  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
150822    rc = fts3SyncMethod(pVtab);
150823  }
150824  return rc;
150825}
150826
150827/*
150828** The xRelease() method.
150829**
150830** This is a no-op.
150831*/
150832static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
150833  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
150834  UNUSED_PARAMETER(iSavepoint);
150835  UNUSED_PARAMETER(pVtab);
150836  assert( p->inTransaction );
150837  assert( p->mxSavepoint >= iSavepoint );
150838  TESTONLY( p->mxSavepoint = iSavepoint-1 );
150839  return SQLITE_OK;
150840}
150841
150842/*
150843** The xRollbackTo() method.
150844**
150845** Discard the contents of the pending terms table.
150846*/
150847static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
150848  Fts3Table *p = (Fts3Table*)pVtab;
150849  UNUSED_PARAMETER(iSavepoint);
150850  assert( p->inTransaction );
150851  assert( p->mxSavepoint >= iSavepoint );
150852  TESTONLY( p->mxSavepoint = iSavepoint );
150853  sqlite3Fts3PendingTermsClear(p);
150854  return SQLITE_OK;
150855}
150856
150857static const sqlite3_module fts3Module = {
150858  /* iVersion      */ 2,
150859  /* xCreate       */ fts3CreateMethod,
150860  /* xConnect      */ fts3ConnectMethod,
150861  /* xBestIndex    */ fts3BestIndexMethod,
150862  /* xDisconnect   */ fts3DisconnectMethod,
150863  /* xDestroy      */ fts3DestroyMethod,
150864  /* xOpen         */ fts3OpenMethod,
150865  /* xClose        */ fts3CloseMethod,
150866  /* xFilter       */ fts3FilterMethod,
150867  /* xNext         */ fts3NextMethod,
150868  /* xEof          */ fts3EofMethod,
150869  /* xColumn       */ fts3ColumnMethod,
150870  /* xRowid        */ fts3RowidMethod,
150871  /* xUpdate       */ fts3UpdateMethod,
150872  /* xBegin        */ fts3BeginMethod,
150873  /* xSync         */ fts3SyncMethod,
150874  /* xCommit       */ fts3CommitMethod,
150875  /* xRollback     */ fts3RollbackMethod,
150876  /* xFindFunction */ fts3FindFunctionMethod,
150877  /* xRename */       fts3RenameMethod,
150878  /* xSavepoint    */ fts3SavepointMethod,
150879  /* xRelease      */ fts3ReleaseMethod,
150880  /* xRollbackTo   */ fts3RollbackToMethod,
150881};
150882
150883/*
150884** This function is registered as the module destructor (called when an
150885** FTS3 enabled database connection is closed). It frees the memory
150886** allocated for the tokenizer hash table.
150887*/
150888static void hashDestroy(void *p){
150889  Fts3Hash *pHash = (Fts3Hash *)p;
150890  sqlite3Fts3HashClear(pHash);
150891  sqlite3_free(pHash);
150892}
150893
150894/*
150895** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
150896** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
150897** respectively. The following three forward declarations are for functions
150898** declared in these files used to retrieve the respective implementations.
150899**
150900** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
150901** to by the argument to point to the "simple" tokenizer implementation.
150902** And so on.
150903*/
150904SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
150905SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
150906#ifndef SQLITE_DISABLE_FTS3_UNICODE
150907SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
150908#endif
150909#ifdef SQLITE_ENABLE_ICU
150910SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
150911#endif
150912
150913/*
150914** Initialize the fts3 extension. If this extension is built as part
150915** of the sqlite library, then this function is called directly by
150916** SQLite. If fts3 is built as a dynamically loadable extension, this
150917** function is called by the sqlite3_extension_init() entry point.
150918*/
150919SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
150920  int rc = SQLITE_OK;
150921  Fts3Hash *pHash = 0;
150922  const sqlite3_tokenizer_module *pSimple = 0;
150923  const sqlite3_tokenizer_module *pPorter = 0;
150924#ifndef SQLITE_DISABLE_FTS3_UNICODE
150925  const sqlite3_tokenizer_module *pUnicode = 0;
150926#endif
150927
150928#ifdef SQLITE_ENABLE_ICU
150929  const sqlite3_tokenizer_module *pIcu = 0;
150930  sqlite3Fts3IcuTokenizerModule(&pIcu);
150931#endif
150932
150933#ifndef SQLITE_DISABLE_FTS3_UNICODE
150934  sqlite3Fts3UnicodeTokenizer(&pUnicode);
150935#endif
150936
150937#ifdef SQLITE_TEST
150938  rc = sqlite3Fts3InitTerm(db);
150939  if( rc!=SQLITE_OK ) return rc;
150940#endif
150941
150942  rc = sqlite3Fts3InitAux(db);
150943  if( rc!=SQLITE_OK ) return rc;
150944
150945  sqlite3Fts3SimpleTokenizerModule(&pSimple);
150946  sqlite3Fts3PorterTokenizerModule(&pPorter);
150947
150948  /* Allocate and initialize the hash-table used to store tokenizers. */
150949  pHash = sqlite3_malloc(sizeof(Fts3Hash));
150950  if( !pHash ){
150951    rc = SQLITE_NOMEM;
150952  }else{
150953    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
150954  }
150955
150956  /* Load the built-in tokenizers into the hash table */
150957  if( rc==SQLITE_OK ){
150958    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
150959     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
150960
150961#ifndef SQLITE_DISABLE_FTS3_UNICODE
150962     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
150963#endif
150964#ifdef SQLITE_ENABLE_ICU
150965     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
150966#endif
150967    ){
150968      rc = SQLITE_NOMEM;
150969    }
150970  }
150971
150972#ifdef SQLITE_TEST
150973  if( rc==SQLITE_OK ){
150974    rc = sqlite3Fts3ExprInitTestInterface(db);
150975  }
150976#endif
150977
150978  /* Create the virtual table wrapper around the hash-table and overload
150979  ** the four scalar functions. If this is successful, register the
150980  ** module with sqlite.
150981  */
150982  if( SQLITE_OK==rc
150983   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
150984   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
150985   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
150986   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
150987   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
150988   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
150989  ){
150990    rc = sqlite3_create_module_v2(
150991        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
150992    );
150993    if( rc==SQLITE_OK ){
150994      rc = sqlite3_create_module_v2(
150995          db, "fts4", &fts3Module, (void *)pHash, 0
150996      );
150997    }
150998    if( rc==SQLITE_OK ){
150999      rc = sqlite3Fts3InitTok(db, (void *)pHash);
151000    }
151001    return rc;
151002  }
151003
151004
151005  /* An error has occurred. Delete the hash table and return the error code. */
151006  assert( rc!=SQLITE_OK );
151007  if( pHash ){
151008    sqlite3Fts3HashClear(pHash);
151009    sqlite3_free(pHash);
151010  }
151011  return rc;
151012}
151013
151014/*
151015** Allocate an Fts3MultiSegReader for each token in the expression headed
151016** by pExpr.
151017**
151018** An Fts3SegReader object is a cursor that can seek or scan a range of
151019** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
151020** Fts3SegReader objects internally to provide an interface to seek or scan
151021** within the union of all segments of a b-tree. Hence the name.
151022**
151023** If the allocated Fts3MultiSegReader just seeks to a single entry in a
151024** segment b-tree (if the term is not a prefix or it is a prefix for which
151025** there exists prefix b-tree of the right length) then it may be traversed
151026** and merged incrementally. Otherwise, it has to be merged into an in-memory
151027** doclist and then traversed.
151028*/
151029static void fts3EvalAllocateReaders(
151030  Fts3Cursor *pCsr,               /* FTS cursor handle */
151031  Fts3Expr *pExpr,                /* Allocate readers for this expression */
151032  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
151033  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
151034  int *pRc                        /* IN/OUT: Error code */
151035){
151036  if( pExpr && SQLITE_OK==*pRc ){
151037    if( pExpr->eType==FTSQUERY_PHRASE ){
151038      int i;
151039      int nToken = pExpr->pPhrase->nToken;
151040      *pnToken += nToken;
151041      for(i=0; i<nToken; i++){
151042        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
151043        int rc = fts3TermSegReaderCursor(pCsr,
151044            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
151045        );
151046        if( rc!=SQLITE_OK ){
151047          *pRc = rc;
151048          return;
151049        }
151050      }
151051      assert( pExpr->pPhrase->iDoclistToken==0 );
151052      pExpr->pPhrase->iDoclistToken = -1;
151053    }else{
151054      *pnOr += (pExpr->eType==FTSQUERY_OR);
151055      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
151056      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
151057    }
151058  }
151059}
151060
151061/*
151062** Arguments pList/nList contain the doclist for token iToken of phrase p.
151063** It is merged into the main doclist stored in p->doclist.aAll/nAll.
151064**
151065** This function assumes that pList points to a buffer allocated using
151066** sqlite3_malloc(). This function takes responsibility for eventually
151067** freeing the buffer.
151068**
151069** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
151070*/
151071static int fts3EvalPhraseMergeToken(
151072  Fts3Table *pTab,                /* FTS Table pointer */
151073  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
151074  int iToken,                     /* Token pList/nList corresponds to */
151075  char *pList,                    /* Pointer to doclist */
151076  int nList                       /* Number of bytes in pList */
151077){
151078  int rc = SQLITE_OK;
151079  assert( iToken!=p->iDoclistToken );
151080
151081  if( pList==0 ){
151082    sqlite3_free(p->doclist.aAll);
151083    p->doclist.aAll = 0;
151084    p->doclist.nAll = 0;
151085  }
151086
151087  else if( p->iDoclistToken<0 ){
151088    p->doclist.aAll = pList;
151089    p->doclist.nAll = nList;
151090  }
151091
151092  else if( p->doclist.aAll==0 ){
151093    sqlite3_free(pList);
151094  }
151095
151096  else {
151097    char *pLeft;
151098    char *pRight;
151099    int nLeft;
151100    int nRight;
151101    int nDiff;
151102
151103    if( p->iDoclistToken<iToken ){
151104      pLeft = p->doclist.aAll;
151105      nLeft = p->doclist.nAll;
151106      pRight = pList;
151107      nRight = nList;
151108      nDiff = iToken - p->iDoclistToken;
151109    }else{
151110      pRight = p->doclist.aAll;
151111      nRight = p->doclist.nAll;
151112      pLeft = pList;
151113      nLeft = nList;
151114      nDiff = p->iDoclistToken - iToken;
151115    }
151116
151117    rc = fts3DoclistPhraseMerge(
151118        pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
151119    );
151120    sqlite3_free(pLeft);
151121    p->doclist.aAll = pRight;
151122    p->doclist.nAll = nRight;
151123  }
151124
151125  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
151126  return rc;
151127}
151128
151129/*
151130** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
151131** does not take deferred tokens into account.
151132**
151133** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151134*/
151135static int fts3EvalPhraseLoad(
151136  Fts3Cursor *pCsr,               /* FTS Cursor handle */
151137  Fts3Phrase *p                   /* Phrase object */
151138){
151139  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151140  int iToken;
151141  int rc = SQLITE_OK;
151142
151143  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
151144    Fts3PhraseToken *pToken = &p->aToken[iToken];
151145    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
151146
151147    if( pToken->pSegcsr ){
151148      int nThis = 0;
151149      char *pThis = 0;
151150      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
151151      if( rc==SQLITE_OK ){
151152        rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
151153      }
151154    }
151155    assert( pToken->pSegcsr==0 );
151156  }
151157
151158  return rc;
151159}
151160
151161/*
151162** This function is called on each phrase after the position lists for
151163** any deferred tokens have been loaded into memory. It updates the phrases
151164** current position list to include only those positions that are really
151165** instances of the phrase (after considering deferred tokens). If this
151166** means that the phrase does not appear in the current row, doclist.pList
151167** and doclist.nList are both zeroed.
151168**
151169** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151170*/
151171static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
151172  int iToken;                     /* Used to iterate through phrase tokens */
151173  char *aPoslist = 0;             /* Position list for deferred tokens */
151174  int nPoslist = 0;               /* Number of bytes in aPoslist */
151175  int iPrev = -1;                 /* Token number of previous deferred token */
151176
151177  assert( pPhrase->doclist.bFreeList==0 );
151178
151179  for(iToken=0; iToken<pPhrase->nToken; iToken++){
151180    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
151181    Fts3DeferredToken *pDeferred = pToken->pDeferred;
151182
151183    if( pDeferred ){
151184      char *pList;
151185      int nList;
151186      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
151187      if( rc!=SQLITE_OK ) return rc;
151188
151189      if( pList==0 ){
151190        sqlite3_free(aPoslist);
151191        pPhrase->doclist.pList = 0;
151192        pPhrase->doclist.nList = 0;
151193        return SQLITE_OK;
151194
151195      }else if( aPoslist==0 ){
151196        aPoslist = pList;
151197        nPoslist = nList;
151198
151199      }else{
151200        char *aOut = pList;
151201        char *p1 = aPoslist;
151202        char *p2 = aOut;
151203
151204        assert( iPrev>=0 );
151205        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
151206        sqlite3_free(aPoslist);
151207        aPoslist = pList;
151208        nPoslist = (int)(aOut - aPoslist);
151209        if( nPoslist==0 ){
151210          sqlite3_free(aPoslist);
151211          pPhrase->doclist.pList = 0;
151212          pPhrase->doclist.nList = 0;
151213          return SQLITE_OK;
151214        }
151215      }
151216      iPrev = iToken;
151217    }
151218  }
151219
151220  if( iPrev>=0 ){
151221    int nMaxUndeferred = pPhrase->iDoclistToken;
151222    if( nMaxUndeferred<0 ){
151223      pPhrase->doclist.pList = aPoslist;
151224      pPhrase->doclist.nList = nPoslist;
151225      pPhrase->doclist.iDocid = pCsr->iPrevId;
151226      pPhrase->doclist.bFreeList = 1;
151227    }else{
151228      int nDistance;
151229      char *p1;
151230      char *p2;
151231      char *aOut;
151232
151233      if( nMaxUndeferred>iPrev ){
151234        p1 = aPoslist;
151235        p2 = pPhrase->doclist.pList;
151236        nDistance = nMaxUndeferred - iPrev;
151237      }else{
151238        p1 = pPhrase->doclist.pList;
151239        p2 = aPoslist;
151240        nDistance = iPrev - nMaxUndeferred;
151241      }
151242
151243      aOut = (char *)sqlite3_malloc(nPoslist+8);
151244      if( !aOut ){
151245        sqlite3_free(aPoslist);
151246        return SQLITE_NOMEM;
151247      }
151248
151249      pPhrase->doclist.pList = aOut;
151250      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
151251        pPhrase->doclist.bFreeList = 1;
151252        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
151253      }else{
151254        sqlite3_free(aOut);
151255        pPhrase->doclist.pList = 0;
151256        pPhrase->doclist.nList = 0;
151257      }
151258      sqlite3_free(aPoslist);
151259    }
151260  }
151261
151262  return SQLITE_OK;
151263}
151264
151265/*
151266** Maximum number of tokens a phrase may have to be considered for the
151267** incremental doclists strategy.
151268*/
151269#define MAX_INCR_PHRASE_TOKENS 4
151270
151271/*
151272** This function is called for each Fts3Phrase in a full-text query
151273** expression to initialize the mechanism for returning rows. Once this
151274** function has been called successfully on an Fts3Phrase, it may be
151275** used with fts3EvalPhraseNext() to iterate through the matching docids.
151276**
151277** If parameter bOptOk is true, then the phrase may (or may not) use the
151278** incremental loading strategy. Otherwise, the entire doclist is loaded into
151279** memory within this call.
151280**
151281** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
151282*/
151283static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
151284  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151285  int rc = SQLITE_OK;             /* Error code */
151286  int i;
151287
151288  /* Determine if doclists may be loaded from disk incrementally. This is
151289  ** possible if the bOptOk argument is true, the FTS doclists will be
151290  ** scanned in forward order, and the phrase consists of
151291  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
151292  ** tokens or prefix tokens that cannot use a prefix-index.  */
151293  int bHaveIncr = 0;
151294  int bIncrOk = (bOptOk
151295   && pCsr->bDesc==pTab->bDescIdx
151296   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
151297#ifdef SQLITE_TEST
151298   && pTab->bNoIncrDoclist==0
151299#endif
151300  );
151301  for(i=0; bIncrOk==1 && i<p->nToken; i++){
151302    Fts3PhraseToken *pToken = &p->aToken[i];
151303    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
151304      bIncrOk = 0;
151305    }
151306    if( pToken->pSegcsr ) bHaveIncr = 1;
151307  }
151308
151309  if( bIncrOk && bHaveIncr ){
151310    /* Use the incremental approach. */
151311    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
151312    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
151313      Fts3PhraseToken *pToken = &p->aToken[i];
151314      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
151315      if( pSegcsr ){
151316        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
151317      }
151318    }
151319    p->bIncr = 1;
151320  }else{
151321    /* Load the full doclist for the phrase into memory. */
151322    rc = fts3EvalPhraseLoad(pCsr, p);
151323    p->bIncr = 0;
151324  }
151325
151326  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
151327  return rc;
151328}
151329
151330/*
151331** This function is used to iterate backwards (from the end to start)
151332** through doclists. It is used by this module to iterate through phrase
151333** doclists in reverse and by the fts3_write.c module to iterate through
151334** pending-terms lists when writing to databases with "order=desc".
151335**
151336** The doclist may be sorted in ascending (parameter bDescIdx==0) or
151337** descending (parameter bDescIdx==1) order of docid. Regardless, this
151338** function iterates from the end of the doclist to the beginning.
151339*/
151340SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
151341  int bDescIdx,                   /* True if the doclist is desc */
151342  char *aDoclist,                 /* Pointer to entire doclist */
151343  int nDoclist,                   /* Length of aDoclist in bytes */
151344  char **ppIter,                  /* IN/OUT: Iterator pointer */
151345  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
151346  int *pnList,                    /* OUT: List length pointer */
151347  u8 *pbEof                       /* OUT: End-of-file flag */
151348){
151349  char *p = *ppIter;
151350
151351  assert( nDoclist>0 );
151352  assert( *pbEof==0 );
151353  assert( p || *piDocid==0 );
151354  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
151355
151356  if( p==0 ){
151357    sqlite3_int64 iDocid = 0;
151358    char *pNext = 0;
151359    char *pDocid = aDoclist;
151360    char *pEnd = &aDoclist[nDoclist];
151361    int iMul = 1;
151362
151363    while( pDocid<pEnd ){
151364      sqlite3_int64 iDelta;
151365      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
151366      iDocid += (iMul * iDelta);
151367      pNext = pDocid;
151368      fts3PoslistCopy(0, &pDocid);
151369      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
151370      iMul = (bDescIdx ? -1 : 1);
151371    }
151372
151373    *pnList = (int)(pEnd - pNext);
151374    *ppIter = pNext;
151375    *piDocid = iDocid;
151376  }else{
151377    int iMul = (bDescIdx ? -1 : 1);
151378    sqlite3_int64 iDelta;
151379    fts3GetReverseVarint(&p, aDoclist, &iDelta);
151380    *piDocid -= (iMul * iDelta);
151381
151382    if( p==aDoclist ){
151383      *pbEof = 1;
151384    }else{
151385      char *pSave = p;
151386      fts3ReversePoslist(aDoclist, &p);
151387      *pnList = (int)(pSave - p);
151388    }
151389    *ppIter = p;
151390  }
151391}
151392
151393/*
151394** Iterate forwards through a doclist.
151395*/
151396SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
151397  int bDescIdx,                   /* True if the doclist is desc */
151398  char *aDoclist,                 /* Pointer to entire doclist */
151399  int nDoclist,                   /* Length of aDoclist in bytes */
151400  char **ppIter,                  /* IN/OUT: Iterator pointer */
151401  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
151402  u8 *pbEof                       /* OUT: End-of-file flag */
151403){
151404  char *p = *ppIter;
151405
151406  assert( nDoclist>0 );
151407  assert( *pbEof==0 );
151408  assert( p || *piDocid==0 );
151409  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
151410
151411  if( p==0 ){
151412    p = aDoclist;
151413    p += sqlite3Fts3GetVarint(p, piDocid);
151414  }else{
151415    fts3PoslistCopy(0, &p);
151416    while( p<&aDoclist[nDoclist] && *p==0 ) p++;
151417    if( p>=&aDoclist[nDoclist] ){
151418      *pbEof = 1;
151419    }else{
151420      sqlite3_int64 iVar;
151421      p += sqlite3Fts3GetVarint(p, &iVar);
151422      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
151423    }
151424  }
151425
151426  *ppIter = p;
151427}
151428
151429/*
151430** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
151431** to true if EOF is reached.
151432*/
151433static void fts3EvalDlPhraseNext(
151434  Fts3Table *pTab,
151435  Fts3Doclist *pDL,
151436  u8 *pbEof
151437){
151438  char *pIter;                            /* Used to iterate through aAll */
151439  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
151440
151441  if( pDL->pNextDocid ){
151442    pIter = pDL->pNextDocid;
151443  }else{
151444    pIter = pDL->aAll;
151445  }
151446
151447  if( pIter>=pEnd ){
151448    /* We have already reached the end of this doclist. EOF. */
151449    *pbEof = 1;
151450  }else{
151451    sqlite3_int64 iDelta;
151452    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
151453    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
151454      pDL->iDocid += iDelta;
151455    }else{
151456      pDL->iDocid -= iDelta;
151457    }
151458    pDL->pList = pIter;
151459    fts3PoslistCopy(0, &pIter);
151460    pDL->nList = (int)(pIter - pDL->pList);
151461
151462    /* pIter now points just past the 0x00 that terminates the position-
151463    ** list for document pDL->iDocid. However, if this position-list was
151464    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
151465    ** point to the start of the next docid value. The following line deals
151466    ** with this case by advancing pIter past the zero-padding added by
151467    ** fts3EvalNearTrim().  */
151468    while( pIter<pEnd && *pIter==0 ) pIter++;
151469
151470    pDL->pNextDocid = pIter;
151471    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
151472    *pbEof = 0;
151473  }
151474}
151475
151476/*
151477** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
151478*/
151479typedef struct TokenDoclist TokenDoclist;
151480struct TokenDoclist {
151481  int bIgnore;
151482  sqlite3_int64 iDocid;
151483  char *pList;
151484  int nList;
151485};
151486
151487/*
151488** Token pToken is an incrementally loaded token that is part of a
151489** multi-token phrase. Advance it to the next matching document in the
151490** database and populate output variable *p with the details of the new
151491** entry. Or, if the iterator has reached EOF, set *pbEof to true.
151492**
151493** If an error occurs, return an SQLite error code. Otherwise, return
151494** SQLITE_OK.
151495*/
151496static int incrPhraseTokenNext(
151497  Fts3Table *pTab,                /* Virtual table handle */
151498  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
151499  int iToken,                     /* Specific token to advance */
151500  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
151501  u8 *pbEof                       /* OUT: True if iterator is at EOF */
151502){
151503  int rc = SQLITE_OK;
151504
151505  if( pPhrase->iDoclistToken==iToken ){
151506    assert( p->bIgnore==0 );
151507    assert( pPhrase->aToken[iToken].pSegcsr==0 );
151508    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
151509    p->pList = pPhrase->doclist.pList;
151510    p->nList = pPhrase->doclist.nList;
151511    p->iDocid = pPhrase->doclist.iDocid;
151512  }else{
151513    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
151514    assert( pToken->pDeferred==0 );
151515    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
151516    if( pToken->pSegcsr ){
151517      assert( p->bIgnore==0 );
151518      rc = sqlite3Fts3MsrIncrNext(
151519          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
151520      );
151521      if( p->pList==0 ) *pbEof = 1;
151522    }else{
151523      p->bIgnore = 1;
151524    }
151525  }
151526
151527  return rc;
151528}
151529
151530
151531/*
151532** The phrase iterator passed as the second argument:
151533**
151534**   * features at least one token that uses an incremental doclist, and
151535**
151536**   * does not contain any deferred tokens.
151537**
151538** Advance it to the next matching documnent in the database and populate
151539** the Fts3Doclist.pList and nList fields.
151540**
151541** If there is no "next" entry and no error occurs, then *pbEof is set to
151542** 1 before returning. Otherwise, if no error occurs and the iterator is
151543** successfully advanced, *pbEof is set to 0.
151544**
151545** If an error occurs, return an SQLite error code. Otherwise, return
151546** SQLITE_OK.
151547*/
151548static int fts3EvalIncrPhraseNext(
151549  Fts3Cursor *pCsr,               /* FTS Cursor handle */
151550  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
151551  u8 *pbEof                       /* OUT: Set to 1 if EOF */
151552){
151553  int rc = SQLITE_OK;
151554  Fts3Doclist *pDL = &p->doclist;
151555  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151556  u8 bEof = 0;
151557
151558  /* This is only called if it is guaranteed that the phrase has at least
151559  ** one incremental token. In which case the bIncr flag is set. */
151560  assert( p->bIncr==1 );
151561
151562  if( p->nToken==1 ){
151563    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
151564        &pDL->iDocid, &pDL->pList, &pDL->nList
151565    );
151566    if( pDL->pList==0 ) bEof = 1;
151567  }else{
151568    int bDescDoclist = pCsr->bDesc;
151569    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
151570
151571    memset(a, 0, sizeof(a));
151572    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
151573    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
151574
151575    while( bEof==0 ){
151576      int bMaxSet = 0;
151577      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
151578      int i;                      /* Used to iterate through tokens */
151579
151580      /* Advance the iterator for each token in the phrase once. */
151581      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
151582        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
151583        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
151584          iMax = a[i].iDocid;
151585          bMaxSet = 1;
151586        }
151587      }
151588      assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
151589      assert( rc!=SQLITE_OK || bMaxSet );
151590
151591      /* Keep advancing iterators until they all point to the same document */
151592      for(i=0; i<p->nToken; i++){
151593        while( rc==SQLITE_OK && bEof==0
151594            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
151595        ){
151596          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
151597          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
151598            iMax = a[i].iDocid;
151599            i = 0;
151600          }
151601        }
151602      }
151603
151604      /* Check if the current entries really are a phrase match */
151605      if( bEof==0 ){
151606        int nList = 0;
151607        int nByte = a[p->nToken-1].nList;
151608        char *aDoclist = sqlite3_malloc(nByte+1);
151609        if( !aDoclist ) return SQLITE_NOMEM;
151610        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
151611
151612        for(i=0; i<(p->nToken-1); i++){
151613          if( a[i].bIgnore==0 ){
151614            char *pL = a[i].pList;
151615            char *pR = aDoclist;
151616            char *pOut = aDoclist;
151617            int nDist = p->nToken-1-i;
151618            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
151619            if( res==0 ) break;
151620            nList = (int)(pOut - aDoclist);
151621          }
151622        }
151623        if( i==(p->nToken-1) ){
151624          pDL->iDocid = iMax;
151625          pDL->pList = aDoclist;
151626          pDL->nList = nList;
151627          pDL->bFreeList = 1;
151628          break;
151629        }
151630        sqlite3_free(aDoclist);
151631      }
151632    }
151633  }
151634
151635  *pbEof = bEof;
151636  return rc;
151637}
151638
151639/*
151640** Attempt to move the phrase iterator to point to the next matching docid.
151641** If an error occurs, return an SQLite error code. Otherwise, return
151642** SQLITE_OK.
151643**
151644** If there is no "next" entry and no error occurs, then *pbEof is set to
151645** 1 before returning. Otherwise, if no error occurs and the iterator is
151646** successfully advanced, *pbEof is set to 0.
151647*/
151648static int fts3EvalPhraseNext(
151649  Fts3Cursor *pCsr,               /* FTS Cursor handle */
151650  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
151651  u8 *pbEof                       /* OUT: Set to 1 if EOF */
151652){
151653  int rc = SQLITE_OK;
151654  Fts3Doclist *pDL = &p->doclist;
151655  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151656
151657  if( p->bIncr ){
151658    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
151659  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
151660    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
151661        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
151662    );
151663    pDL->pList = pDL->pNextDocid;
151664  }else{
151665    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
151666  }
151667
151668  return rc;
151669}
151670
151671/*
151672**
151673** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
151674** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
151675** expression. Also the Fts3Expr.bDeferred variable is set to true for any
151676** expressions for which all descendent tokens are deferred.
151677**
151678** If parameter bOptOk is zero, then it is guaranteed that the
151679** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
151680** each phrase in the expression (subject to deferred token processing).
151681** Or, if bOptOk is non-zero, then one or more tokens within the expression
151682** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
151683**
151684** If an error occurs within this function, *pRc is set to an SQLite error
151685** code before returning.
151686*/
151687static void fts3EvalStartReaders(
151688  Fts3Cursor *pCsr,               /* FTS Cursor handle */
151689  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
151690  int *pRc                        /* IN/OUT: Error code */
151691){
151692  if( pExpr && SQLITE_OK==*pRc ){
151693    if( pExpr->eType==FTSQUERY_PHRASE ){
151694      int nToken = pExpr->pPhrase->nToken;
151695      if( nToken ){
151696        int i;
151697        for(i=0; i<nToken; i++){
151698          if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
151699        }
151700        pExpr->bDeferred = (i==nToken);
151701      }
151702      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
151703    }else{
151704      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
151705      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
151706      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
151707    }
151708  }
151709}
151710
151711/*
151712** An array of the following structures is assembled as part of the process
151713** of selecting tokens to defer before the query starts executing (as part
151714** of the xFilter() method). There is one element in the array for each
151715** token in the FTS expression.
151716**
151717** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
151718** to phrases that are connected only by AND and NEAR operators (not OR or
151719** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
151720** separately. The root of a tokens AND/NEAR cluster is stored in
151721** Fts3TokenAndCost.pRoot.
151722*/
151723typedef struct Fts3TokenAndCost Fts3TokenAndCost;
151724struct Fts3TokenAndCost {
151725  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
151726  int iToken;                     /* Position of token in phrase */
151727  Fts3PhraseToken *pToken;        /* The token itself */
151728  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
151729  int nOvfl;                      /* Number of overflow pages to load doclist */
151730  int iCol;                       /* The column the token must match */
151731};
151732
151733/*
151734** This function is used to populate an allocated Fts3TokenAndCost array.
151735**
151736** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
151737** Otherwise, if an error occurs during execution, *pRc is set to an
151738** SQLite error code.
151739*/
151740static void fts3EvalTokenCosts(
151741  Fts3Cursor *pCsr,               /* FTS Cursor handle */
151742  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
151743  Fts3Expr *pExpr,                /* Expression to consider */
151744  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
151745  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
151746  int *pRc                        /* IN/OUT: Error code */
151747){
151748  if( *pRc==SQLITE_OK ){
151749    if( pExpr->eType==FTSQUERY_PHRASE ){
151750      Fts3Phrase *pPhrase = pExpr->pPhrase;
151751      int i;
151752      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
151753        Fts3TokenAndCost *pTC = (*ppTC)++;
151754        pTC->pPhrase = pPhrase;
151755        pTC->iToken = i;
151756        pTC->pRoot = pRoot;
151757        pTC->pToken = &pPhrase->aToken[i];
151758        pTC->iCol = pPhrase->iColumn;
151759        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
151760      }
151761    }else if( pExpr->eType!=FTSQUERY_NOT ){
151762      assert( pExpr->eType==FTSQUERY_OR
151763           || pExpr->eType==FTSQUERY_AND
151764           || pExpr->eType==FTSQUERY_NEAR
151765      );
151766      assert( pExpr->pLeft && pExpr->pRight );
151767      if( pExpr->eType==FTSQUERY_OR ){
151768        pRoot = pExpr->pLeft;
151769        **ppOr = pRoot;
151770        (*ppOr)++;
151771      }
151772      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
151773      if( pExpr->eType==FTSQUERY_OR ){
151774        pRoot = pExpr->pRight;
151775        **ppOr = pRoot;
151776        (*ppOr)++;
151777      }
151778      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
151779    }
151780  }
151781}
151782
151783/*
151784** Determine the average document (row) size in pages. If successful,
151785** write this value to *pnPage and return SQLITE_OK. Otherwise, return
151786** an SQLite error code.
151787**
151788** The average document size in pages is calculated by first calculating
151789** determining the average size in bytes, B. If B is less than the amount
151790** of data that will fit on a single leaf page of an intkey table in
151791** this database, then the average docsize is 1. Otherwise, it is 1 plus
151792** the number of overflow pages consumed by a record B bytes in size.
151793*/
151794static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
151795  int rc = SQLITE_OK;
151796  if( pCsr->nRowAvg==0 ){
151797    /* The average document size, which is required to calculate the cost
151798    ** of each doclist, has not yet been determined. Read the required
151799    ** data from the %_stat table to calculate it.
151800    **
151801    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
151802    ** varints, where nCol is the number of columns in the FTS3 table.
151803    ** The first varint is the number of documents currently stored in
151804    ** the table. The following nCol varints contain the total amount of
151805    ** data stored in all rows of each column of the table, from left
151806    ** to right.
151807    */
151808    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
151809    sqlite3_stmt *pStmt;
151810    sqlite3_int64 nDoc = 0;
151811    sqlite3_int64 nByte = 0;
151812    const char *pEnd;
151813    const char *a;
151814
151815    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
151816    if( rc!=SQLITE_OK ) return rc;
151817    a = sqlite3_column_blob(pStmt, 0);
151818    assert( a );
151819
151820    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
151821    a += sqlite3Fts3GetVarint(a, &nDoc);
151822    while( a<pEnd ){
151823      a += sqlite3Fts3GetVarint(a, &nByte);
151824    }
151825    if( nDoc==0 || nByte==0 ){
151826      sqlite3_reset(pStmt);
151827      return FTS_CORRUPT_VTAB;
151828    }
151829
151830    pCsr->nDoc = nDoc;
151831    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
151832    assert( pCsr->nRowAvg>0 );
151833    rc = sqlite3_reset(pStmt);
151834  }
151835
151836  *pnPage = pCsr->nRowAvg;
151837  return rc;
151838}
151839
151840/*
151841** This function is called to select the tokens (if any) that will be
151842** deferred. The array aTC[] has already been populated when this is
151843** called.
151844**
151845** This function is called once for each AND/NEAR cluster in the
151846** expression. Each invocation determines which tokens to defer within
151847** the cluster with root node pRoot. See comments above the definition
151848** of struct Fts3TokenAndCost for more details.
151849**
151850** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
151851** called on each token to defer. Otherwise, an SQLite error code is
151852** returned.
151853*/
151854static int fts3EvalSelectDeferred(
151855  Fts3Cursor *pCsr,               /* FTS Cursor handle */
151856  Fts3Expr *pRoot,                /* Consider tokens with this root node */
151857  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
151858  int nTC                         /* Number of entries in aTC[] */
151859){
151860  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151861  int nDocSize = 0;               /* Number of pages per doc loaded */
151862  int rc = SQLITE_OK;             /* Return code */
151863  int ii;                         /* Iterator variable for various purposes */
151864  int nOvfl = 0;                  /* Total overflow pages used by doclists */
151865  int nToken = 0;                 /* Total number of tokens in cluster */
151866
151867  int nMinEst = 0;                /* The minimum count for any phrase so far. */
151868  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
151869
151870  /* Tokens are never deferred for FTS tables created using the content=xxx
151871  ** option. The reason being that it is not guaranteed that the content
151872  ** table actually contains the same data as the index. To prevent this from
151873  ** causing any problems, the deferred token optimization is completely
151874  ** disabled for content=xxx tables. */
151875  if( pTab->zContentTbl ){
151876    return SQLITE_OK;
151877  }
151878
151879  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
151880  ** associated with the tokens spill onto overflow pages, or if there is
151881  ** only 1 token, exit early. No tokens to defer in this case. */
151882  for(ii=0; ii<nTC; ii++){
151883    if( aTC[ii].pRoot==pRoot ){
151884      nOvfl += aTC[ii].nOvfl;
151885      nToken++;
151886    }
151887  }
151888  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
151889
151890  /* Obtain the average docsize (in pages). */
151891  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
151892  assert( rc!=SQLITE_OK || nDocSize>0 );
151893
151894
151895  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
151896  ** of the number of overflow pages that will be loaded by the pager layer
151897  ** to retrieve the entire doclist for the token from the full-text index.
151898  ** Load the doclists for tokens that are either:
151899  **
151900  **   a. The cheapest token in the entire query (i.e. the one visited by the
151901  **      first iteration of this loop), or
151902  **
151903  **   b. Part of a multi-token phrase.
151904  **
151905  ** After each token doclist is loaded, merge it with the others from the
151906  ** same phrase and count the number of documents that the merged doclist
151907  ** contains. Set variable "nMinEst" to the smallest number of documents in
151908  ** any phrase doclist for which 1 or more token doclists have been loaded.
151909  ** Let nOther be the number of other phrases for which it is certain that
151910  ** one or more tokens will not be deferred.
151911  **
151912  ** Then, for each token, defer it if loading the doclist would result in
151913  ** loading N or more overflow pages into memory, where N is computed as:
151914  **
151915  **    (nMinEst + 4^nOther - 1) / (4^nOther)
151916  */
151917  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
151918    int iTC;                      /* Used to iterate through aTC[] array. */
151919    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
151920
151921    /* Set pTC to point to the cheapest remaining token. */
151922    for(iTC=0; iTC<nTC; iTC++){
151923      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
151924       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
151925      ){
151926        pTC = &aTC[iTC];
151927      }
151928    }
151929    assert( pTC );
151930
151931    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
151932      /* The number of overflow pages to load for this (and therefore all
151933      ** subsequent) tokens is greater than the estimated number of pages
151934      ** that will be loaded if all subsequent tokens are deferred.
151935      */
151936      Fts3PhraseToken *pToken = pTC->pToken;
151937      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
151938      fts3SegReaderCursorFree(pToken->pSegcsr);
151939      pToken->pSegcsr = 0;
151940    }else{
151941      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
151942      ** for-loop. Except, limit the value to 2^24 to prevent it from
151943      ** overflowing the 32-bit integer it is stored in. */
151944      if( ii<12 ) nLoad4 = nLoad4*4;
151945
151946      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
151947        /* Either this is the cheapest token in the entire query, or it is
151948        ** part of a multi-token phrase. Either way, the entire doclist will
151949        ** (eventually) be loaded into memory. It may as well be now. */
151950        Fts3PhraseToken *pToken = pTC->pToken;
151951        int nList = 0;
151952        char *pList = 0;
151953        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
151954        assert( rc==SQLITE_OK || pList==0 );
151955        if( rc==SQLITE_OK ){
151956          rc = fts3EvalPhraseMergeToken(
151957              pTab, pTC->pPhrase, pTC->iToken,pList,nList
151958          );
151959        }
151960        if( rc==SQLITE_OK ){
151961          int nCount;
151962          nCount = fts3DoclistCountDocids(
151963              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
151964          );
151965          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
151966        }
151967      }
151968    }
151969    pTC->pToken = 0;
151970  }
151971
151972  return rc;
151973}
151974
151975/*
151976** This function is called from within the xFilter method. It initializes
151977** the full-text query currently stored in pCsr->pExpr. To iterate through
151978** the results of a query, the caller does:
151979**
151980**    fts3EvalStart(pCsr);
151981**    while( 1 ){
151982**      fts3EvalNext(pCsr);
151983**      if( pCsr->bEof ) break;
151984**      ... return row pCsr->iPrevId to the caller ...
151985**    }
151986*/
151987static int fts3EvalStart(Fts3Cursor *pCsr){
151988  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
151989  int rc = SQLITE_OK;
151990  int nToken = 0;
151991  int nOr = 0;
151992
151993  /* Allocate a MultiSegReader for each token in the expression. */
151994  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
151995
151996  /* Determine which, if any, tokens in the expression should be deferred. */
151997#ifndef SQLITE_DISABLE_FTS4_DEFERRED
151998  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
151999    Fts3TokenAndCost *aTC;
152000    Fts3Expr **apOr;
152001    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
152002        sizeof(Fts3TokenAndCost) * nToken
152003      + sizeof(Fts3Expr *) * nOr * 2
152004    );
152005    apOr = (Fts3Expr **)&aTC[nToken];
152006
152007    if( !aTC ){
152008      rc = SQLITE_NOMEM;
152009    }else{
152010      int ii;
152011      Fts3TokenAndCost *pTC = aTC;
152012      Fts3Expr **ppOr = apOr;
152013
152014      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
152015      nToken = (int)(pTC-aTC);
152016      nOr = (int)(ppOr-apOr);
152017
152018      if( rc==SQLITE_OK ){
152019        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
152020        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
152021          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
152022        }
152023      }
152024
152025      sqlite3_free(aTC);
152026    }
152027  }
152028#endif
152029
152030  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
152031  return rc;
152032}
152033
152034/*
152035** Invalidate the current position list for phrase pPhrase.
152036*/
152037static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
152038  if( pPhrase->doclist.bFreeList ){
152039    sqlite3_free(pPhrase->doclist.pList);
152040  }
152041  pPhrase->doclist.pList = 0;
152042  pPhrase->doclist.nList = 0;
152043  pPhrase->doclist.bFreeList = 0;
152044}
152045
152046/*
152047** This function is called to edit the position list associated with
152048** the phrase object passed as the fifth argument according to a NEAR
152049** condition. For example:
152050**
152051**     abc NEAR/5 "def ghi"
152052**
152053** Parameter nNear is passed the NEAR distance of the expression (5 in
152054** the example above). When this function is called, *paPoslist points to
152055** the position list, and *pnToken is the number of phrase tokens in, the
152056** phrase on the other side of the NEAR operator to pPhrase. For example,
152057** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
152058** the position list associated with phrase "abc".
152059**
152060** All positions in the pPhrase position list that are not sufficiently
152061** close to a position in the *paPoslist position list are removed. If this
152062** leaves 0 positions, zero is returned. Otherwise, non-zero.
152063**
152064** Before returning, *paPoslist is set to point to the position lsit
152065** associated with pPhrase. And *pnToken is set to the number of tokens in
152066** pPhrase.
152067*/
152068static int fts3EvalNearTrim(
152069  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
152070  char *aTmp,                     /* Temporary space to use */
152071  char **paPoslist,               /* IN/OUT: Position list */
152072  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
152073  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
152074){
152075  int nParam1 = nNear + pPhrase->nToken;
152076  int nParam2 = nNear + *pnToken;
152077  int nNew;
152078  char *p2;
152079  char *pOut;
152080  int res;
152081
152082  assert( pPhrase->doclist.pList );
152083
152084  p2 = pOut = pPhrase->doclist.pList;
152085  res = fts3PoslistNearMerge(
152086    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
152087  );
152088  if( res ){
152089    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
152090    assert( pPhrase->doclist.pList[nNew]=='\0' );
152091    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
152092    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
152093    pPhrase->doclist.nList = nNew;
152094    *paPoslist = pPhrase->doclist.pList;
152095    *pnToken = pPhrase->nToken;
152096  }
152097
152098  return res;
152099}
152100
152101/*
152102** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
152103** Otherwise, it advances the expression passed as the second argument to
152104** point to the next matching row in the database. Expressions iterate through
152105** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
152106** or descending if it is non-zero.
152107**
152108** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
152109** successful, the following variables in pExpr are set:
152110**
152111**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
152112**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
152113**
152114** If the expression is of type FTSQUERY_PHRASE, and the expression is not
152115** at EOF, then the following variables are populated with the position list
152116** for the phrase for the visited row:
152117**
152118**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
152119**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
152120**
152121** It says above that this function advances the expression to the next
152122** matching row. This is usually true, but there are the following exceptions:
152123**
152124**   1. Deferred tokens are not taken into account. If a phrase consists
152125**      entirely of deferred tokens, it is assumed to match every row in
152126**      the db. In this case the position-list is not populated at all.
152127**
152128**      Or, if a phrase contains one or more deferred tokens and one or
152129**      more non-deferred tokens, then the expression is advanced to the
152130**      next possible match, considering only non-deferred tokens. In other
152131**      words, if the phrase is "A B C", and "B" is deferred, the expression
152132**      is advanced to the next row that contains an instance of "A * C",
152133**      where "*" may match any single token. The position list in this case
152134**      is populated as for "A * C" before returning.
152135**
152136**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
152137**      advanced to point to the next row that matches "x AND y".
152138**
152139** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
152140** really a match, taking into account deferred tokens and NEAR operators.
152141*/
152142static void fts3EvalNextRow(
152143  Fts3Cursor *pCsr,               /* FTS Cursor handle */
152144  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
152145  int *pRc                        /* IN/OUT: Error code */
152146){
152147  if( *pRc==SQLITE_OK ){
152148    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
152149    assert( pExpr->bEof==0 );
152150    pExpr->bStart = 1;
152151
152152    switch( pExpr->eType ){
152153      case FTSQUERY_NEAR:
152154      case FTSQUERY_AND: {
152155        Fts3Expr *pLeft = pExpr->pLeft;
152156        Fts3Expr *pRight = pExpr->pRight;
152157        assert( !pLeft->bDeferred || !pRight->bDeferred );
152158
152159        if( pLeft->bDeferred ){
152160          /* LHS is entirely deferred. So we assume it matches every row.
152161          ** Advance the RHS iterator to find the next row visited. */
152162          fts3EvalNextRow(pCsr, pRight, pRc);
152163          pExpr->iDocid = pRight->iDocid;
152164          pExpr->bEof = pRight->bEof;
152165        }else if( pRight->bDeferred ){
152166          /* RHS is entirely deferred. So we assume it matches every row.
152167          ** Advance the LHS iterator to find the next row visited. */
152168          fts3EvalNextRow(pCsr, pLeft, pRc);
152169          pExpr->iDocid = pLeft->iDocid;
152170          pExpr->bEof = pLeft->bEof;
152171        }else{
152172          /* Neither the RHS or LHS are deferred. */
152173          fts3EvalNextRow(pCsr, pLeft, pRc);
152174          fts3EvalNextRow(pCsr, pRight, pRc);
152175          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
152176            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152177            if( iDiff==0 ) break;
152178            if( iDiff<0 ){
152179              fts3EvalNextRow(pCsr, pLeft, pRc);
152180            }else{
152181              fts3EvalNextRow(pCsr, pRight, pRc);
152182            }
152183          }
152184          pExpr->iDocid = pLeft->iDocid;
152185          pExpr->bEof = (pLeft->bEof || pRight->bEof);
152186          if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
152187            assert( pRight->eType==FTSQUERY_PHRASE );
152188            if( pRight->pPhrase->doclist.aAll ){
152189              Fts3Doclist *pDl = &pRight->pPhrase->doclist;
152190              while( *pRc==SQLITE_OK && pRight->bEof==0 ){
152191                memset(pDl->pList, 0, pDl->nList);
152192                fts3EvalNextRow(pCsr, pRight, pRc);
152193              }
152194            }
152195            if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
152196              Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
152197              while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
152198                memset(pDl->pList, 0, pDl->nList);
152199                fts3EvalNextRow(pCsr, pLeft, pRc);
152200              }
152201            }
152202          }
152203        }
152204        break;
152205      }
152206
152207      case FTSQUERY_OR: {
152208        Fts3Expr *pLeft = pExpr->pLeft;
152209        Fts3Expr *pRight = pExpr->pRight;
152210        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152211
152212        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
152213        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
152214
152215        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
152216          fts3EvalNextRow(pCsr, pLeft, pRc);
152217        }else if( pLeft->bEof || iCmp>0 ){
152218          fts3EvalNextRow(pCsr, pRight, pRc);
152219        }else{
152220          fts3EvalNextRow(pCsr, pLeft, pRc);
152221          fts3EvalNextRow(pCsr, pRight, pRc);
152222        }
152223
152224        pExpr->bEof = (pLeft->bEof && pRight->bEof);
152225        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
152226        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
152227          pExpr->iDocid = pLeft->iDocid;
152228        }else{
152229          pExpr->iDocid = pRight->iDocid;
152230        }
152231
152232        break;
152233      }
152234
152235      case FTSQUERY_NOT: {
152236        Fts3Expr *pLeft = pExpr->pLeft;
152237        Fts3Expr *pRight = pExpr->pRight;
152238
152239        if( pRight->bStart==0 ){
152240          fts3EvalNextRow(pCsr, pRight, pRc);
152241          assert( *pRc!=SQLITE_OK || pRight->bStart );
152242        }
152243
152244        fts3EvalNextRow(pCsr, pLeft, pRc);
152245        if( pLeft->bEof==0 ){
152246          while( !*pRc
152247              && !pRight->bEof
152248              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
152249          ){
152250            fts3EvalNextRow(pCsr, pRight, pRc);
152251          }
152252        }
152253        pExpr->iDocid = pLeft->iDocid;
152254        pExpr->bEof = pLeft->bEof;
152255        break;
152256      }
152257
152258      default: {
152259        Fts3Phrase *pPhrase = pExpr->pPhrase;
152260        fts3EvalInvalidatePoslist(pPhrase);
152261        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
152262        pExpr->iDocid = pPhrase->doclist.iDocid;
152263        break;
152264      }
152265    }
152266  }
152267}
152268
152269/*
152270** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
152271** cluster, then this function returns 1 immediately.
152272**
152273** Otherwise, it checks if the current row really does match the NEAR
152274** expression, using the data currently stored in the position lists
152275** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
152276**
152277** If the current row is a match, the position list associated with each
152278** phrase in the NEAR expression is edited in place to contain only those
152279** phrase instances sufficiently close to their peers to satisfy all NEAR
152280** constraints. In this case it returns 1. If the NEAR expression does not
152281** match the current row, 0 is returned. The position lists may or may not
152282** be edited if 0 is returned.
152283*/
152284static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
152285  int res = 1;
152286
152287  /* The following block runs if pExpr is the root of a NEAR query.
152288  ** For example, the query:
152289  **
152290  **         "w" NEAR "x" NEAR "y" NEAR "z"
152291  **
152292  ** which is represented in tree form as:
152293  **
152294  **                               |
152295  **                          +--NEAR--+      <-- root of NEAR query
152296  **                          |        |
152297  **                     +--NEAR--+   "z"
152298  **                     |        |
152299  **                +--NEAR--+   "y"
152300  **                |        |
152301  **               "w"      "x"
152302  **
152303  ** The right-hand child of a NEAR node is always a phrase. The
152304  ** left-hand child may be either a phrase or a NEAR node. There are
152305  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
152306  */
152307  if( *pRc==SQLITE_OK
152308   && pExpr->eType==FTSQUERY_NEAR
152309   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
152310  ){
152311    Fts3Expr *p;
152312    int nTmp = 0;                 /* Bytes of temp space */
152313    char *aTmp;                   /* Temp space for PoslistNearMerge() */
152314
152315    /* Allocate temporary working space. */
152316    for(p=pExpr; p->pLeft; p=p->pLeft){
152317      assert( p->pRight->pPhrase->doclist.nList>0 );
152318      nTmp += p->pRight->pPhrase->doclist.nList;
152319    }
152320    nTmp += p->pPhrase->doclist.nList;
152321    aTmp = sqlite3_malloc(nTmp*2);
152322    if( !aTmp ){
152323      *pRc = SQLITE_NOMEM;
152324      res = 0;
152325    }else{
152326      char *aPoslist = p->pPhrase->doclist.pList;
152327      int nToken = p->pPhrase->nToken;
152328
152329      for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
152330        Fts3Phrase *pPhrase = p->pRight->pPhrase;
152331        int nNear = p->nNear;
152332        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
152333      }
152334
152335      aPoslist = pExpr->pRight->pPhrase->doclist.pList;
152336      nToken = pExpr->pRight->pPhrase->nToken;
152337      for(p=pExpr->pLeft; p && res; p=p->pLeft){
152338        int nNear;
152339        Fts3Phrase *pPhrase;
152340        assert( p->pParent && p->pParent->pLeft==p );
152341        nNear = p->pParent->nNear;
152342        pPhrase = (
152343            p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
152344        );
152345        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
152346      }
152347    }
152348
152349    sqlite3_free(aTmp);
152350  }
152351
152352  return res;
152353}
152354
152355/*
152356** This function is a helper function for sqlite3Fts3EvalTestDeferred().
152357** Assuming no error occurs or has occurred, It returns non-zero if the
152358** expression passed as the second argument matches the row that pCsr
152359** currently points to, or zero if it does not.
152360**
152361** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
152362** If an error occurs during execution of this function, *pRc is set to
152363** the appropriate SQLite error code. In this case the returned value is
152364** undefined.
152365*/
152366static int fts3EvalTestExpr(
152367  Fts3Cursor *pCsr,               /* FTS cursor handle */
152368  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
152369  int *pRc                        /* IN/OUT: Error code */
152370){
152371  int bHit = 1;                   /* Return value */
152372  if( *pRc==SQLITE_OK ){
152373    switch( pExpr->eType ){
152374      case FTSQUERY_NEAR:
152375      case FTSQUERY_AND:
152376        bHit = (
152377            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
152378         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
152379         && fts3EvalNearTest(pExpr, pRc)
152380        );
152381
152382        /* If the NEAR expression does not match any rows, zero the doclist for
152383        ** all phrases involved in the NEAR. This is because the snippet(),
152384        ** offsets() and matchinfo() functions are not supposed to recognize
152385        ** any instances of phrases that are part of unmatched NEAR queries.
152386        ** For example if this expression:
152387        **
152388        **    ... MATCH 'a OR (b NEAR c)'
152389        **
152390        ** is matched against a row containing:
152391        **
152392        **        'a b d e'
152393        **
152394        ** then any snippet() should ony highlight the "a" term, not the "b"
152395        ** (as "b" is part of a non-matching NEAR clause).
152396        */
152397        if( bHit==0
152398         && pExpr->eType==FTSQUERY_NEAR
152399         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
152400        ){
152401          Fts3Expr *p;
152402          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
152403            if( p->pRight->iDocid==pCsr->iPrevId ){
152404              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
152405            }
152406          }
152407          if( p->iDocid==pCsr->iPrevId ){
152408            fts3EvalInvalidatePoslist(p->pPhrase);
152409          }
152410        }
152411
152412        break;
152413
152414      case FTSQUERY_OR: {
152415        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
152416        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
152417        bHit = bHit1 || bHit2;
152418        break;
152419      }
152420
152421      case FTSQUERY_NOT:
152422        bHit = (
152423            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
152424         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
152425        );
152426        break;
152427
152428      default: {
152429#ifndef SQLITE_DISABLE_FTS4_DEFERRED
152430        if( pCsr->pDeferred
152431         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
152432        ){
152433          Fts3Phrase *pPhrase = pExpr->pPhrase;
152434          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
152435          if( pExpr->bDeferred ){
152436            fts3EvalInvalidatePoslist(pPhrase);
152437          }
152438          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
152439          bHit = (pPhrase->doclist.pList!=0);
152440          pExpr->iDocid = pCsr->iPrevId;
152441        }else
152442#endif
152443        {
152444          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
152445        }
152446        break;
152447      }
152448    }
152449  }
152450  return bHit;
152451}
152452
152453/*
152454** This function is called as the second part of each xNext operation when
152455** iterating through the results of a full-text query. At this point the
152456** cursor points to a row that matches the query expression, with the
152457** following caveats:
152458**
152459**   * Up until this point, "NEAR" operators in the expression have been
152460**     treated as "AND".
152461**
152462**   * Deferred tokens have not yet been considered.
152463**
152464** If *pRc is not SQLITE_OK when this function is called, it immediately
152465** returns 0. Otherwise, it tests whether or not after considering NEAR
152466** operators and deferred tokens the current row is still a match for the
152467** expression. It returns 1 if both of the following are true:
152468**
152469**   1. *pRc is SQLITE_OK when this function returns, and
152470**
152471**   2. After scanning the current FTS table row for the deferred tokens,
152472**      it is determined that the row does *not* match the query.
152473**
152474** Or, if no error occurs and it seems the current row does match the FTS
152475** query, return 0.
152476*/
152477SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
152478  int rc = *pRc;
152479  int bMiss = 0;
152480  if( rc==SQLITE_OK ){
152481
152482    /* If there are one or more deferred tokens, load the current row into
152483    ** memory and scan it to determine the position list for each deferred
152484    ** token. Then, see if this row is really a match, considering deferred
152485    ** tokens and NEAR operators (neither of which were taken into account
152486    ** earlier, by fts3EvalNextRow()).
152487    */
152488    if( pCsr->pDeferred ){
152489      rc = fts3CursorSeek(0, pCsr);
152490      if( rc==SQLITE_OK ){
152491        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
152492      }
152493    }
152494    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
152495
152496    /* Free the position-lists accumulated for each deferred token above. */
152497    sqlite3Fts3FreeDeferredDoclists(pCsr);
152498    *pRc = rc;
152499  }
152500  return (rc==SQLITE_OK && bMiss);
152501}
152502
152503/*
152504** Advance to the next document that matches the FTS expression in
152505** Fts3Cursor.pExpr.
152506*/
152507static int fts3EvalNext(Fts3Cursor *pCsr){
152508  int rc = SQLITE_OK;             /* Return Code */
152509  Fts3Expr *pExpr = pCsr->pExpr;
152510  assert( pCsr->isEof==0 );
152511  if( pExpr==0 ){
152512    pCsr->isEof = 1;
152513  }else{
152514    do {
152515      if( pCsr->isRequireSeek==0 ){
152516        sqlite3_reset(pCsr->pStmt);
152517      }
152518      assert( sqlite3_data_count(pCsr->pStmt)==0 );
152519      fts3EvalNextRow(pCsr, pExpr, &rc);
152520      pCsr->isEof = pExpr->bEof;
152521      pCsr->isRequireSeek = 1;
152522      pCsr->isMatchinfoNeeded = 1;
152523      pCsr->iPrevId = pExpr->iDocid;
152524    }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
152525  }
152526
152527  /* Check if the cursor is past the end of the docid range specified
152528  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
152529  if( rc==SQLITE_OK && (
152530        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
152531     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
152532  )){
152533    pCsr->isEof = 1;
152534  }
152535
152536  return rc;
152537}
152538
152539/*
152540** Restart interation for expression pExpr so that the next call to
152541** fts3EvalNext() visits the first row. Do not allow incremental
152542** loading or merging of phrase doclists for this iteration.
152543**
152544** If *pRc is other than SQLITE_OK when this function is called, it is
152545** a no-op. If an error occurs within this function, *pRc is set to an
152546** SQLite error code before returning.
152547*/
152548static void fts3EvalRestart(
152549  Fts3Cursor *pCsr,
152550  Fts3Expr *pExpr,
152551  int *pRc
152552){
152553  if( pExpr && *pRc==SQLITE_OK ){
152554    Fts3Phrase *pPhrase = pExpr->pPhrase;
152555
152556    if( pPhrase ){
152557      fts3EvalInvalidatePoslist(pPhrase);
152558      if( pPhrase->bIncr ){
152559        int i;
152560        for(i=0; i<pPhrase->nToken; i++){
152561          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
152562          assert( pToken->pDeferred==0 );
152563          if( pToken->pSegcsr ){
152564            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
152565          }
152566        }
152567        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
152568      }
152569      pPhrase->doclist.pNextDocid = 0;
152570      pPhrase->doclist.iDocid = 0;
152571      pPhrase->pOrPoslist = 0;
152572    }
152573
152574    pExpr->iDocid = 0;
152575    pExpr->bEof = 0;
152576    pExpr->bStart = 0;
152577
152578    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
152579    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
152580  }
152581}
152582
152583/*
152584** After allocating the Fts3Expr.aMI[] array for each phrase in the
152585** expression rooted at pExpr, the cursor iterates through all rows matched
152586** by pExpr, calling this function for each row. This function increments
152587** the values in Fts3Expr.aMI[] according to the position-list currently
152588** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
152589** expression nodes.
152590*/
152591static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
152592  if( pExpr ){
152593    Fts3Phrase *pPhrase = pExpr->pPhrase;
152594    if( pPhrase && pPhrase->doclist.pList ){
152595      int iCol = 0;
152596      char *p = pPhrase->doclist.pList;
152597
152598      assert( *p );
152599      while( 1 ){
152600        u8 c = 0;
152601        int iCnt = 0;
152602        while( 0xFE & (*p | c) ){
152603          if( (c&0x80)==0 ) iCnt++;
152604          c = *p++ & 0x80;
152605        }
152606
152607        /* aMI[iCol*3 + 1] = Number of occurrences
152608        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
152609        */
152610        pExpr->aMI[iCol*3 + 1] += iCnt;
152611        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
152612        if( *p==0x00 ) break;
152613        p++;
152614        p += fts3GetVarint32(p, &iCol);
152615      }
152616    }
152617
152618    fts3EvalUpdateCounts(pExpr->pLeft);
152619    fts3EvalUpdateCounts(pExpr->pRight);
152620  }
152621}
152622
152623/*
152624** Expression pExpr must be of type FTSQUERY_PHRASE.
152625**
152626** If it is not already allocated and populated, this function allocates and
152627** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
152628** of a NEAR expression, then it also allocates and populates the same array
152629** for all other phrases that are part of the NEAR expression.
152630**
152631** SQLITE_OK is returned if the aMI[] array is successfully allocated and
152632** populated. Otherwise, if an error occurs, an SQLite error code is returned.
152633*/
152634static int fts3EvalGatherStats(
152635  Fts3Cursor *pCsr,               /* Cursor object */
152636  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
152637){
152638  int rc = SQLITE_OK;             /* Return code */
152639
152640  assert( pExpr->eType==FTSQUERY_PHRASE );
152641  if( pExpr->aMI==0 ){
152642    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152643    Fts3Expr *pRoot;                /* Root of NEAR expression */
152644    Fts3Expr *p;                    /* Iterator used for several purposes */
152645
152646    sqlite3_int64 iPrevId = pCsr->iPrevId;
152647    sqlite3_int64 iDocid;
152648    u8 bEof;
152649
152650    /* Find the root of the NEAR expression */
152651    pRoot = pExpr;
152652    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
152653      pRoot = pRoot->pParent;
152654    }
152655    iDocid = pRoot->iDocid;
152656    bEof = pRoot->bEof;
152657    assert( pRoot->bStart );
152658
152659    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
152660    for(p=pRoot; p; p=p->pLeft){
152661      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
152662      assert( pE->aMI==0 );
152663      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
152664      if( !pE->aMI ) return SQLITE_NOMEM;
152665      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
152666    }
152667
152668    fts3EvalRestart(pCsr, pRoot, &rc);
152669
152670    while( pCsr->isEof==0 && rc==SQLITE_OK ){
152671
152672      do {
152673        /* Ensure the %_content statement is reset. */
152674        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
152675        assert( sqlite3_data_count(pCsr->pStmt)==0 );
152676
152677        /* Advance to the next document */
152678        fts3EvalNextRow(pCsr, pRoot, &rc);
152679        pCsr->isEof = pRoot->bEof;
152680        pCsr->isRequireSeek = 1;
152681        pCsr->isMatchinfoNeeded = 1;
152682        pCsr->iPrevId = pRoot->iDocid;
152683      }while( pCsr->isEof==0
152684           && pRoot->eType==FTSQUERY_NEAR
152685           && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
152686      );
152687
152688      if( rc==SQLITE_OK && pCsr->isEof==0 ){
152689        fts3EvalUpdateCounts(pRoot);
152690      }
152691    }
152692
152693    pCsr->isEof = 0;
152694    pCsr->iPrevId = iPrevId;
152695
152696    if( bEof ){
152697      pRoot->bEof = bEof;
152698    }else{
152699      /* Caution: pRoot may iterate through docids in ascending or descending
152700      ** order. For this reason, even though it seems more defensive, the
152701      ** do loop can not be written:
152702      **
152703      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
152704      */
152705      fts3EvalRestart(pCsr, pRoot, &rc);
152706      do {
152707        fts3EvalNextRow(pCsr, pRoot, &rc);
152708        assert( pRoot->bEof==0 );
152709      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
152710    }
152711  }
152712  return rc;
152713}
152714
152715/*
152716** This function is used by the matchinfo() module to query a phrase
152717** expression node for the following information:
152718**
152719**   1. The total number of occurrences of the phrase in each column of
152720**      the FTS table (considering all rows), and
152721**
152722**   2. For each column, the number of rows in the table for which the
152723**      column contains at least one instance of the phrase.
152724**
152725** If no error occurs, SQLITE_OK is returned and the values for each column
152726** written into the array aiOut as follows:
152727**
152728**   aiOut[iCol*3 + 1] = Number of occurrences
152729**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
152730**
152731** Caveats:
152732**
152733**   * If a phrase consists entirely of deferred tokens, then all output
152734**     values are set to the number of documents in the table. In other
152735**     words we assume that very common tokens occur exactly once in each
152736**     column of each row of the table.
152737**
152738**   * If a phrase contains some deferred tokens (and some non-deferred
152739**     tokens), count the potential occurrence identified by considering
152740**     the non-deferred tokens instead of actual phrase occurrences.
152741**
152742**   * If the phrase is part of a NEAR expression, then only phrase instances
152743**     that meet the NEAR constraint are included in the counts.
152744*/
152745SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
152746  Fts3Cursor *pCsr,               /* FTS cursor handle */
152747  Fts3Expr *pExpr,                /* Phrase expression */
152748  u32 *aiOut                      /* Array to write results into (see above) */
152749){
152750  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152751  int rc = SQLITE_OK;
152752  int iCol;
152753
152754  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
152755    assert( pCsr->nDoc>0 );
152756    for(iCol=0; iCol<pTab->nColumn; iCol++){
152757      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
152758      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
152759    }
152760  }else{
152761    rc = fts3EvalGatherStats(pCsr, pExpr);
152762    if( rc==SQLITE_OK ){
152763      assert( pExpr->aMI );
152764      for(iCol=0; iCol<pTab->nColumn; iCol++){
152765        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
152766        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
152767      }
152768    }
152769  }
152770
152771  return rc;
152772}
152773
152774/*
152775** The expression pExpr passed as the second argument to this function
152776** must be of type FTSQUERY_PHRASE.
152777**
152778** The returned value is either NULL or a pointer to a buffer containing
152779** a position-list indicating the occurrences of the phrase in column iCol
152780** of the current row.
152781**
152782** More specifically, the returned buffer contains 1 varint for each
152783** occurrence of the phrase in the column, stored using the normal (delta+2)
152784** compression and is terminated by either an 0x01 or 0x00 byte. For example,
152785** if the requested column contains "a b X c d X X" and the position-list
152786** for 'X' is requested, the buffer returned may contain:
152787**
152788**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
152789**
152790** This function works regardless of whether or not the phrase is deferred,
152791** incremental, or neither.
152792*/
152793SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
152794  Fts3Cursor *pCsr,               /* FTS3 cursor object */
152795  Fts3Expr *pExpr,                /* Phrase to return doclist for */
152796  int iCol,                       /* Column to return position list for */
152797  char **ppOut                    /* OUT: Pointer to position list */
152798){
152799  Fts3Phrase *pPhrase = pExpr->pPhrase;
152800  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
152801  char *pIter;
152802  int iThis;
152803  sqlite3_int64 iDocid;
152804
152805  /* If this phrase is applies specifically to some column other than
152806  ** column iCol, return a NULL pointer.  */
152807  *ppOut = 0;
152808  assert( iCol>=0 && iCol<pTab->nColumn );
152809  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
152810    return SQLITE_OK;
152811  }
152812
152813  iDocid = pExpr->iDocid;
152814  pIter = pPhrase->doclist.pList;
152815  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
152816    int rc = SQLITE_OK;
152817    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
152818    int bOr = 0;
152819    u8 bTreeEof = 0;
152820    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
152821    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
152822    int bMatch;
152823
152824    /* Check if this phrase descends from an OR expression node. If not,
152825    ** return NULL. Otherwise, the entry that corresponds to docid
152826    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
152827    ** tree that the node is part of has been marked as EOF, but the node
152828    ** itself is not EOF, then it may point to an earlier entry. */
152829    pNear = pExpr;
152830    for(p=pExpr->pParent; p; p=p->pParent){
152831      if( p->eType==FTSQUERY_OR ) bOr = 1;
152832      if( p->eType==FTSQUERY_NEAR ) pNear = p;
152833      if( p->bEof ) bTreeEof = 1;
152834    }
152835    if( bOr==0 ) return SQLITE_OK;
152836
152837    /* This is the descendent of an OR node. In this case we cannot use
152838    ** an incremental phrase. Load the entire doclist for the phrase
152839    ** into memory in this case.  */
152840    if( pPhrase->bIncr ){
152841      int bEofSave = pNear->bEof;
152842      fts3EvalRestart(pCsr, pNear, &rc);
152843      while( rc==SQLITE_OK && !pNear->bEof ){
152844        fts3EvalNextRow(pCsr, pNear, &rc);
152845        if( bEofSave==0 && pNear->iDocid==iDocid ) break;
152846      }
152847      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
152848    }
152849    if( bTreeEof ){
152850      while( rc==SQLITE_OK && !pNear->bEof ){
152851        fts3EvalNextRow(pCsr, pNear, &rc);
152852      }
152853    }
152854    if( rc!=SQLITE_OK ) return rc;
152855
152856    bMatch = 1;
152857    for(p=pNear; p; p=p->pLeft){
152858      u8 bEof = 0;
152859      Fts3Expr *pTest = p;
152860      Fts3Phrase *pPh;
152861      assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
152862      if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
152863      assert( pTest->eType==FTSQUERY_PHRASE );
152864      pPh = pTest->pPhrase;
152865
152866      pIter = pPh->pOrPoslist;
152867      iDocid = pPh->iOrDocid;
152868      if( pCsr->bDesc==bDescDoclist ){
152869        bEof = !pPh->doclist.nAll ||
152870          (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
152871        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
152872          sqlite3Fts3DoclistNext(
152873              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
152874              &pIter, &iDocid, &bEof
152875          );
152876        }
152877      }else{
152878        bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
152879        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
152880          int dummy;
152881          sqlite3Fts3DoclistPrev(
152882              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
152883              &pIter, &iDocid, &dummy, &bEof
152884              );
152885        }
152886      }
152887      pPh->pOrPoslist = pIter;
152888      pPh->iOrDocid = iDocid;
152889      if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
152890    }
152891
152892    if( bMatch ){
152893      pIter = pPhrase->pOrPoslist;
152894    }else{
152895      pIter = 0;
152896    }
152897  }
152898  if( pIter==0 ) return SQLITE_OK;
152899
152900  if( *pIter==0x01 ){
152901    pIter++;
152902    pIter += fts3GetVarint32(pIter, &iThis);
152903  }else{
152904    iThis = 0;
152905  }
152906  while( iThis<iCol ){
152907    fts3ColumnlistCopy(0, &pIter);
152908    if( *pIter==0x00 ) return SQLITE_OK;
152909    pIter++;
152910    pIter += fts3GetVarint32(pIter, &iThis);
152911  }
152912  if( *pIter==0x00 ){
152913    pIter = 0;
152914  }
152915
152916  *ppOut = ((iCol==iThis)?pIter:0);
152917  return SQLITE_OK;
152918}
152919
152920/*
152921** Free all components of the Fts3Phrase structure that were allocated by
152922** the eval module. Specifically, this means to free:
152923**
152924**   * the contents of pPhrase->doclist, and
152925**   * any Fts3MultiSegReader objects held by phrase tokens.
152926*/
152927SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
152928  if( pPhrase ){
152929    int i;
152930    sqlite3_free(pPhrase->doclist.aAll);
152931    fts3EvalInvalidatePoslist(pPhrase);
152932    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
152933    for(i=0; i<pPhrase->nToken; i++){
152934      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
152935      pPhrase->aToken[i].pSegcsr = 0;
152936    }
152937  }
152938}
152939
152940
152941/*
152942** Return SQLITE_CORRUPT_VTAB.
152943*/
152944#ifdef SQLITE_DEBUG
152945SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
152946  return SQLITE_CORRUPT_VTAB;
152947}
152948#endif
152949
152950#if !SQLITE_CORE
152951/*
152952** Initialize API pointer table, if required.
152953*/
152954#ifdef _WIN32
152955__declspec(dllexport)
152956#endif
152957SQLITE_API int sqlite3_fts3_init(
152958  sqlite3 *db,
152959  char **pzErrMsg,
152960  const sqlite3_api_routines *pApi
152961){
152962  SQLITE_EXTENSION_INIT2(pApi)
152963  return sqlite3Fts3Init(db);
152964}
152965#endif
152966
152967#endif
152968
152969/************** End of fts3.c ************************************************/
152970/************** Begin file fts3_aux.c ****************************************/
152971/*
152972** 2011 Jan 27
152973**
152974** The author disclaims copyright to this source code.  In place of
152975** a legal notice, here is a blessing:
152976**
152977**    May you do good and not evil.
152978**    May you find forgiveness for yourself and forgive others.
152979**    May you share freely, never taking more than you give.
152980**
152981******************************************************************************
152982**
152983*/
152984/* #include "fts3Int.h" */
152985#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
152986
152987/* #include <string.h> */
152988/* #include <assert.h> */
152989
152990typedef struct Fts3auxTable Fts3auxTable;
152991typedef struct Fts3auxCursor Fts3auxCursor;
152992
152993struct Fts3auxTable {
152994  sqlite3_vtab base;              /* Base class used by SQLite core */
152995  Fts3Table *pFts3Tab;
152996};
152997
152998struct Fts3auxCursor {
152999  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
153000  Fts3MultiSegReader csr;        /* Must be right after "base" */
153001  Fts3SegFilter filter;
153002  char *zStop;
153003  int nStop;                      /* Byte-length of string zStop */
153004  int iLangid;                    /* Language id to query */
153005  int isEof;                      /* True if cursor is at EOF */
153006  sqlite3_int64 iRowid;           /* Current rowid */
153007
153008  int iCol;                       /* Current value of 'col' column */
153009  int nStat;                      /* Size of aStat[] array */
153010  struct Fts3auxColstats {
153011    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
153012    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
153013  } *aStat;
153014};
153015
153016/*
153017** Schema of the terms table.
153018*/
153019#define FTS3_AUX_SCHEMA \
153020  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
153021
153022/*
153023** This function does all the work for both the xConnect and xCreate methods.
153024** These tables have no persistent representation of their own, so xConnect
153025** and xCreate are identical operations.
153026*/
153027static int fts3auxConnectMethod(
153028  sqlite3 *db,                    /* Database connection */
153029  void *pUnused,                  /* Unused */
153030  int argc,                       /* Number of elements in argv array */
153031  const char * const *argv,       /* xCreate/xConnect argument array */
153032  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
153033  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
153034){
153035  char const *zDb;                /* Name of database (e.g. "main") */
153036  char const *zFts3;              /* Name of fts3 table */
153037  int nDb;                        /* Result of strlen(zDb) */
153038  int nFts3;                      /* Result of strlen(zFts3) */
153039  int nByte;                      /* Bytes of space to allocate here */
153040  int rc;                         /* value returned by declare_vtab() */
153041  Fts3auxTable *p;                /* Virtual table object to return */
153042
153043  UNUSED_PARAMETER(pUnused);
153044
153045  /* The user should invoke this in one of two forms:
153046  **
153047  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
153048  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
153049  */
153050  if( argc!=4 && argc!=5 ) goto bad_args;
153051
153052  zDb = argv[1];
153053  nDb = (int)strlen(zDb);
153054  if( argc==5 ){
153055    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
153056      zDb = argv[3];
153057      nDb = (int)strlen(zDb);
153058      zFts3 = argv[4];
153059    }else{
153060      goto bad_args;
153061    }
153062  }else{
153063    zFts3 = argv[3];
153064  }
153065  nFts3 = (int)strlen(zFts3);
153066
153067  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
153068  if( rc!=SQLITE_OK ) return rc;
153069
153070  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
153071  p = (Fts3auxTable *)sqlite3_malloc(nByte);
153072  if( !p ) return SQLITE_NOMEM;
153073  memset(p, 0, nByte);
153074
153075  p->pFts3Tab = (Fts3Table *)&p[1];
153076  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
153077  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
153078  p->pFts3Tab->db = db;
153079  p->pFts3Tab->nIndex = 1;
153080
153081  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
153082  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
153083  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
153084
153085  *ppVtab = (sqlite3_vtab *)p;
153086  return SQLITE_OK;
153087
153088 bad_args:
153089  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
153090  return SQLITE_ERROR;
153091}
153092
153093/*
153094** This function does the work for both the xDisconnect and xDestroy methods.
153095** These tables have no persistent representation of their own, so xDisconnect
153096** and xDestroy are identical operations.
153097*/
153098static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
153099  Fts3auxTable *p = (Fts3auxTable *)pVtab;
153100  Fts3Table *pFts3 = p->pFts3Tab;
153101  int i;
153102
153103  /* Free any prepared statements held */
153104  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
153105    sqlite3_finalize(pFts3->aStmt[i]);
153106  }
153107  sqlite3_free(pFts3->zSegmentsTbl);
153108  sqlite3_free(p);
153109  return SQLITE_OK;
153110}
153111
153112#define FTS4AUX_EQ_CONSTRAINT 1
153113#define FTS4AUX_GE_CONSTRAINT 2
153114#define FTS4AUX_LE_CONSTRAINT 4
153115
153116/*
153117** xBestIndex - Analyze a WHERE and ORDER BY clause.
153118*/
153119static int fts3auxBestIndexMethod(
153120  sqlite3_vtab *pVTab,
153121  sqlite3_index_info *pInfo
153122){
153123  int i;
153124  int iEq = -1;
153125  int iGe = -1;
153126  int iLe = -1;
153127  int iLangid = -1;
153128  int iNext = 1;                  /* Next free argvIndex value */
153129
153130  UNUSED_PARAMETER(pVTab);
153131
153132  /* This vtab delivers always results in "ORDER BY term ASC" order. */
153133  if( pInfo->nOrderBy==1
153134   && pInfo->aOrderBy[0].iColumn==0
153135   && pInfo->aOrderBy[0].desc==0
153136  ){
153137    pInfo->orderByConsumed = 1;
153138  }
153139
153140  /* Search for equality and range constraints on the "term" column.
153141  ** And equality constraints on the hidden "languageid" column. */
153142  for(i=0; i<pInfo->nConstraint; i++){
153143    if( pInfo->aConstraint[i].usable ){
153144      int op = pInfo->aConstraint[i].op;
153145      int iCol = pInfo->aConstraint[i].iColumn;
153146
153147      if( iCol==0 ){
153148        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
153149        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
153150        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
153151        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
153152        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
153153      }
153154      if( iCol==4 ){
153155        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
153156      }
153157    }
153158  }
153159
153160  if( iEq>=0 ){
153161    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
153162    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
153163    pInfo->estimatedCost = 5;
153164  }else{
153165    pInfo->idxNum = 0;
153166    pInfo->estimatedCost = 20000;
153167    if( iGe>=0 ){
153168      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
153169      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
153170      pInfo->estimatedCost /= 2;
153171    }
153172    if( iLe>=0 ){
153173      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
153174      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
153175      pInfo->estimatedCost /= 2;
153176    }
153177  }
153178  if( iLangid>=0 ){
153179    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
153180    pInfo->estimatedCost--;
153181  }
153182
153183  return SQLITE_OK;
153184}
153185
153186/*
153187** xOpen - Open a cursor.
153188*/
153189static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
153190  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
153191
153192  UNUSED_PARAMETER(pVTab);
153193
153194  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
153195  if( !pCsr ) return SQLITE_NOMEM;
153196  memset(pCsr, 0, sizeof(Fts3auxCursor));
153197
153198  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
153199  return SQLITE_OK;
153200}
153201
153202/*
153203** xClose - Close a cursor.
153204*/
153205static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
153206  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153207  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153208
153209  sqlite3Fts3SegmentsClose(pFts3);
153210  sqlite3Fts3SegReaderFinish(&pCsr->csr);
153211  sqlite3_free((void *)pCsr->filter.zTerm);
153212  sqlite3_free(pCsr->zStop);
153213  sqlite3_free(pCsr->aStat);
153214  sqlite3_free(pCsr);
153215  return SQLITE_OK;
153216}
153217
153218static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
153219  if( nSize>pCsr->nStat ){
153220    struct Fts3auxColstats *aNew;
153221    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
153222        sizeof(struct Fts3auxColstats) * nSize
153223    );
153224    if( aNew==0 ) return SQLITE_NOMEM;
153225    memset(&aNew[pCsr->nStat], 0,
153226        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
153227    );
153228    pCsr->aStat = aNew;
153229    pCsr->nStat = nSize;
153230  }
153231  return SQLITE_OK;
153232}
153233
153234/*
153235** xNext - Advance the cursor to the next row, if any.
153236*/
153237static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
153238  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153239  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153240  int rc;
153241
153242  /* Increment our pretend rowid value. */
153243  pCsr->iRowid++;
153244
153245  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
153246    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
153247  }
153248
153249  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
153250  if( rc==SQLITE_ROW ){
153251    int i = 0;
153252    int nDoclist = pCsr->csr.nDoclist;
153253    char *aDoclist = pCsr->csr.aDoclist;
153254    int iCol;
153255
153256    int eState = 0;
153257
153258    if( pCsr->zStop ){
153259      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
153260      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
153261      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
153262        pCsr->isEof = 1;
153263        return SQLITE_OK;
153264      }
153265    }
153266
153267    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
153268    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
153269    iCol = 0;
153270
153271    while( i<nDoclist ){
153272      sqlite3_int64 v = 0;
153273
153274      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
153275      switch( eState ){
153276        /* State 0. In this state the integer just read was a docid. */
153277        case 0:
153278          pCsr->aStat[0].nDoc++;
153279          eState = 1;
153280          iCol = 0;
153281          break;
153282
153283        /* State 1. In this state we are expecting either a 1, indicating
153284        ** that the following integer will be a column number, or the
153285        ** start of a position list for column 0.
153286        **
153287        ** The only difference between state 1 and state 2 is that if the
153288        ** integer encountered in state 1 is not 0 or 1, then we need to
153289        ** increment the column 0 "nDoc" count for this term.
153290        */
153291        case 1:
153292          assert( iCol==0 );
153293          if( v>1 ){
153294            pCsr->aStat[1].nDoc++;
153295          }
153296          eState = 2;
153297          /* fall through */
153298
153299        case 2:
153300          if( v==0 ){       /* 0x00. Next integer will be a docid. */
153301            eState = 0;
153302          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
153303            eState = 3;
153304          }else{            /* 2 or greater. A position. */
153305            pCsr->aStat[iCol+1].nOcc++;
153306            pCsr->aStat[0].nOcc++;
153307          }
153308          break;
153309
153310        /* State 3. The integer just read is a column number. */
153311        default: assert( eState==3 );
153312          iCol = (int)v;
153313          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
153314          pCsr->aStat[iCol+1].nDoc++;
153315          eState = 2;
153316          break;
153317      }
153318    }
153319
153320    pCsr->iCol = 0;
153321    rc = SQLITE_OK;
153322  }else{
153323    pCsr->isEof = 1;
153324  }
153325  return rc;
153326}
153327
153328/*
153329** xFilter - Initialize a cursor to point at the start of its data.
153330*/
153331static int fts3auxFilterMethod(
153332  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
153333  int idxNum,                     /* Strategy index */
153334  const char *idxStr,             /* Unused */
153335  int nVal,                       /* Number of elements in apVal */
153336  sqlite3_value **apVal           /* Arguments for the indexing scheme */
153337){
153338  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153339  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
153340  int rc;
153341  int isScan = 0;
153342  int iLangVal = 0;               /* Language id to query */
153343
153344  int iEq = -1;                   /* Index of term=? value in apVal */
153345  int iGe = -1;                   /* Index of term>=? value in apVal */
153346  int iLe = -1;                   /* Index of term<=? value in apVal */
153347  int iLangid = -1;               /* Index of languageid=? value in apVal */
153348  int iNext = 0;
153349
153350  UNUSED_PARAMETER(nVal);
153351  UNUSED_PARAMETER(idxStr);
153352
153353  assert( idxStr==0 );
153354  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
153355       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
153356       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
153357  );
153358
153359  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
153360    iEq = iNext++;
153361  }else{
153362    isScan = 1;
153363    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
153364      iGe = iNext++;
153365    }
153366    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
153367      iLe = iNext++;
153368    }
153369  }
153370  if( iNext<nVal ){
153371    iLangid = iNext++;
153372  }
153373
153374  /* In case this cursor is being reused, close and zero it. */
153375  testcase(pCsr->filter.zTerm);
153376  sqlite3Fts3SegReaderFinish(&pCsr->csr);
153377  sqlite3_free((void *)pCsr->filter.zTerm);
153378  sqlite3_free(pCsr->aStat);
153379  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
153380
153381  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
153382  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
153383
153384  if( iEq>=0 || iGe>=0 ){
153385    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
153386    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
153387    if( zStr ){
153388      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
153389      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
153390      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
153391    }
153392  }
153393
153394  if( iLe>=0 ){
153395    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
153396    pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
153397    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
153398  }
153399
153400  if( iLangid>=0 ){
153401    iLangVal = sqlite3_value_int(apVal[iLangid]);
153402
153403    /* If the user specified a negative value for the languageid, use zero
153404    ** instead. This works, as the "languageid=?" constraint will also
153405    ** be tested by the VDBE layer. The test will always be false (since
153406    ** this module will not return a row with a negative languageid), and
153407    ** so the overall query will return zero rows.  */
153408    if( iLangVal<0 ) iLangVal = 0;
153409  }
153410  pCsr->iLangid = iLangVal;
153411
153412  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
153413      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
153414  );
153415  if( rc==SQLITE_OK ){
153416    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
153417  }
153418
153419  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
153420  return rc;
153421}
153422
153423/*
153424** xEof - Return true if the cursor is at EOF, or false otherwise.
153425*/
153426static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
153427  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153428  return pCsr->isEof;
153429}
153430
153431/*
153432** xColumn - Return a column value.
153433*/
153434static int fts3auxColumnMethod(
153435  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
153436  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
153437  int iCol                        /* Index of column to read value from */
153438){
153439  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
153440
153441  assert( p->isEof==0 );
153442  switch( iCol ){
153443    case 0: /* term */
153444      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
153445      break;
153446
153447    case 1: /* col */
153448      if( p->iCol ){
153449        sqlite3_result_int(pCtx, p->iCol-1);
153450      }else{
153451        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
153452      }
153453      break;
153454
153455    case 2: /* documents */
153456      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
153457      break;
153458
153459    case 3: /* occurrences */
153460      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
153461      break;
153462
153463    default: /* languageid */
153464      assert( iCol==4 );
153465      sqlite3_result_int(pCtx, p->iLangid);
153466      break;
153467  }
153468
153469  return SQLITE_OK;
153470}
153471
153472/*
153473** xRowid - Return the current rowid for the cursor.
153474*/
153475static int fts3auxRowidMethod(
153476  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
153477  sqlite_int64 *pRowid            /* OUT: Rowid value */
153478){
153479  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
153480  *pRowid = pCsr->iRowid;
153481  return SQLITE_OK;
153482}
153483
153484/*
153485** Register the fts3aux module with database connection db. Return SQLITE_OK
153486** if successful or an error code if sqlite3_create_module() fails.
153487*/
153488SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
153489  static const sqlite3_module fts3aux_module = {
153490     0,                           /* iVersion      */
153491     fts3auxConnectMethod,        /* xCreate       */
153492     fts3auxConnectMethod,        /* xConnect      */
153493     fts3auxBestIndexMethod,      /* xBestIndex    */
153494     fts3auxDisconnectMethod,     /* xDisconnect   */
153495     fts3auxDisconnectMethod,     /* xDestroy      */
153496     fts3auxOpenMethod,           /* xOpen         */
153497     fts3auxCloseMethod,          /* xClose        */
153498     fts3auxFilterMethod,         /* xFilter       */
153499     fts3auxNextMethod,           /* xNext         */
153500     fts3auxEofMethod,            /* xEof          */
153501     fts3auxColumnMethod,         /* xColumn       */
153502     fts3auxRowidMethod,          /* xRowid        */
153503     0,                           /* xUpdate       */
153504     0,                           /* xBegin        */
153505     0,                           /* xSync         */
153506     0,                           /* xCommit       */
153507     0,                           /* xRollback     */
153508     0,                           /* xFindFunction */
153509     0,                           /* xRename       */
153510     0,                           /* xSavepoint    */
153511     0,                           /* xRelease      */
153512     0                            /* xRollbackTo   */
153513  };
153514  int rc;                         /* Return code */
153515
153516  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
153517  return rc;
153518}
153519
153520#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153521
153522/************** End of fts3_aux.c ********************************************/
153523/************** Begin file fts3_expr.c ***************************************/
153524/*
153525** 2008 Nov 28
153526**
153527** The author disclaims copyright to this source code.  In place of
153528** a legal notice, here is a blessing:
153529**
153530**    May you do good and not evil.
153531**    May you find forgiveness for yourself and forgive others.
153532**    May you share freely, never taking more than you give.
153533**
153534******************************************************************************
153535**
153536** This module contains code that implements a parser for fts3 query strings
153537** (the right-hand argument to the MATCH operator). Because the supported
153538** syntax is relatively simple, the whole tokenizer/parser system is
153539** hand-coded.
153540*/
153541/* #include "fts3Int.h" */
153542#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153543
153544/*
153545** By default, this module parses the legacy syntax that has been
153546** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
153547** is defined, then it uses the new syntax. The differences between
153548** the new and the old syntaxes are:
153549**
153550**  a) The new syntax supports parenthesis. The old does not.
153551**
153552**  b) The new syntax supports the AND and NOT operators. The old does not.
153553**
153554**  c) The old syntax supports the "-" token qualifier. This is not
153555**     supported by the new syntax (it is replaced by the NOT operator).
153556**
153557**  d) When using the old syntax, the OR operator has a greater precedence
153558**     than an implicit AND. When using the new, both implicity and explicit
153559**     AND operators have a higher precedence than OR.
153560**
153561** If compiled with SQLITE_TEST defined, then this module exports the
153562** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
153563** to zero causes the module to use the old syntax. If it is set to
153564** non-zero the new syntax is activated. This is so both syntaxes can
153565** be tested using a single build of testfixture.
153566**
153567** The following describes the syntax supported by the fts3 MATCH
153568** operator in a similar format to that used by the lemon parser
153569** generator. This module does not use actually lemon, it uses a
153570** custom parser.
153571**
153572**   query ::= andexpr (OR andexpr)*.
153573**
153574**   andexpr ::= notexpr (AND? notexpr)*.
153575**
153576**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
153577**   notexpr ::= LP query RP.
153578**
153579**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
153580**
153581**   distance_opt ::= .
153582**   distance_opt ::= / INTEGER.
153583**
153584**   phrase ::= TOKEN.
153585**   phrase ::= COLUMN:TOKEN.
153586**   phrase ::= "TOKEN TOKEN TOKEN...".
153587*/
153588
153589#ifdef SQLITE_TEST
153590SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
153591#else
153592# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
153593#  define sqlite3_fts3_enable_parentheses 1
153594# else
153595#  define sqlite3_fts3_enable_parentheses 0
153596# endif
153597#endif
153598
153599/*
153600** Default span for NEAR operators.
153601*/
153602#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
153603
153604/* #include <string.h> */
153605/* #include <assert.h> */
153606
153607/*
153608** isNot:
153609**   This variable is used by function getNextNode(). When getNextNode() is
153610**   called, it sets ParseContext.isNot to true if the 'next node' is a
153611**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
153612**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
153613**   zero.
153614*/
153615typedef struct ParseContext ParseContext;
153616struct ParseContext {
153617  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
153618  int iLangid;                        /* Language id used with tokenizer */
153619  const char **azCol;                 /* Array of column names for fts3 table */
153620  int bFts4;                          /* True to allow FTS4-only syntax */
153621  int nCol;                           /* Number of entries in azCol[] */
153622  int iDefaultCol;                    /* Default column to query */
153623  int isNot;                          /* True if getNextNode() sees a unary - */
153624  sqlite3_context *pCtx;              /* Write error message here */
153625  int nNest;                          /* Number of nested brackets */
153626};
153627
153628/*
153629** This function is equivalent to the standard isspace() function.
153630**
153631** The standard isspace() can be awkward to use safely, because although it
153632** is defined to accept an argument of type int, its behavior when passed
153633** an integer that falls outside of the range of the unsigned char type
153634** is undefined (and sometimes, "undefined" means segfault). This wrapper
153635** is defined to accept an argument of type char, and always returns 0 for
153636** any values that fall outside of the range of the unsigned char type (i.e.
153637** negative values).
153638*/
153639static int fts3isspace(char c){
153640  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
153641}
153642
153643/*
153644** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
153645** zero the memory before returning a pointer to it. If unsuccessful,
153646** return NULL.
153647*/
153648static void *fts3MallocZero(int nByte){
153649  void *pRet = sqlite3_malloc(nByte);
153650  if( pRet ) memset(pRet, 0, nByte);
153651  return pRet;
153652}
153653
153654SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
153655  sqlite3_tokenizer *pTokenizer,
153656  int iLangid,
153657  const char *z,
153658  int n,
153659  sqlite3_tokenizer_cursor **ppCsr
153660){
153661  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
153662  sqlite3_tokenizer_cursor *pCsr = 0;
153663  int rc;
153664
153665  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
153666  assert( rc==SQLITE_OK || pCsr==0 );
153667  if( rc==SQLITE_OK ){
153668    pCsr->pTokenizer = pTokenizer;
153669    if( pModule->iVersion>=1 ){
153670      rc = pModule->xLanguageid(pCsr, iLangid);
153671      if( rc!=SQLITE_OK ){
153672        pModule->xClose(pCsr);
153673        pCsr = 0;
153674      }
153675    }
153676  }
153677  *ppCsr = pCsr;
153678  return rc;
153679}
153680
153681/*
153682** Function getNextNode(), which is called by fts3ExprParse(), may itself
153683** call fts3ExprParse(). So this forward declaration is required.
153684*/
153685static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
153686
153687/*
153688** Extract the next token from buffer z (length n) using the tokenizer
153689** and other information (column names etc.) in pParse. Create an Fts3Expr
153690** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
153691** single token and set *ppExpr to point to it. If the end of the buffer is
153692** reached before a token is found, set *ppExpr to zero. It is the
153693** responsibility of the caller to eventually deallocate the allocated
153694** Fts3Expr structure (if any) by passing it to sqlite3_free().
153695**
153696** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
153697** fails.
153698*/
153699static int getNextToken(
153700  ParseContext *pParse,                   /* fts3 query parse context */
153701  int iCol,                               /* Value for Fts3Phrase.iColumn */
153702  const char *z, int n,                   /* Input string */
153703  Fts3Expr **ppExpr,                      /* OUT: expression */
153704  int *pnConsumed                         /* OUT: Number of bytes consumed */
153705){
153706  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
153707  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
153708  int rc;
153709  sqlite3_tokenizer_cursor *pCursor;
153710  Fts3Expr *pRet = 0;
153711  int i = 0;
153712
153713  /* Set variable i to the maximum number of bytes of input to tokenize. */
153714  for(i=0; i<n; i++){
153715    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
153716    if( z[i]=='"' ) break;
153717  }
153718
153719  *pnConsumed = i;
153720  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
153721  if( rc==SQLITE_OK ){
153722    const char *zToken;
153723    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
153724    int nByte;                               /* total space to allocate */
153725
153726    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
153727    if( rc==SQLITE_OK ){
153728      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
153729      pRet = (Fts3Expr *)fts3MallocZero(nByte);
153730      if( !pRet ){
153731        rc = SQLITE_NOMEM;
153732      }else{
153733        pRet->eType = FTSQUERY_PHRASE;
153734        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
153735        pRet->pPhrase->nToken = 1;
153736        pRet->pPhrase->iColumn = iCol;
153737        pRet->pPhrase->aToken[0].n = nToken;
153738        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
153739        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
153740
153741        if( iEnd<n && z[iEnd]=='*' ){
153742          pRet->pPhrase->aToken[0].isPrefix = 1;
153743          iEnd++;
153744        }
153745
153746        while( 1 ){
153747          if( !sqlite3_fts3_enable_parentheses
153748           && iStart>0 && z[iStart-1]=='-'
153749          ){
153750            pParse->isNot = 1;
153751            iStart--;
153752          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
153753            pRet->pPhrase->aToken[0].bFirst = 1;
153754            iStart--;
153755          }else{
153756            break;
153757          }
153758        }
153759
153760      }
153761      *pnConsumed = iEnd;
153762    }else if( i && rc==SQLITE_DONE ){
153763      rc = SQLITE_OK;
153764    }
153765
153766    pModule->xClose(pCursor);
153767  }
153768
153769  *ppExpr = pRet;
153770  return rc;
153771}
153772
153773
153774/*
153775** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
153776** then free the old allocation.
153777*/
153778static void *fts3ReallocOrFree(void *pOrig, int nNew){
153779  void *pRet = sqlite3_realloc(pOrig, nNew);
153780  if( !pRet ){
153781    sqlite3_free(pOrig);
153782  }
153783  return pRet;
153784}
153785
153786/*
153787** Buffer zInput, length nInput, contains the contents of a quoted string
153788** that appeared as part of an fts3 query expression. Neither quote character
153789** is included in the buffer. This function attempts to tokenize the entire
153790** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
153791** containing the results.
153792**
153793** If successful, SQLITE_OK is returned and *ppExpr set to point at the
153794** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
153795** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
153796** to 0.
153797*/
153798static int getNextString(
153799  ParseContext *pParse,                   /* fts3 query parse context */
153800  const char *zInput, int nInput,         /* Input string */
153801  Fts3Expr **ppExpr                       /* OUT: expression */
153802){
153803  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
153804  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
153805  int rc;
153806  Fts3Expr *p = 0;
153807  sqlite3_tokenizer_cursor *pCursor = 0;
153808  char *zTemp = 0;
153809  int nTemp = 0;
153810
153811  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
153812  int nToken = 0;
153813
153814  /* The final Fts3Expr data structure, including the Fts3Phrase,
153815  ** Fts3PhraseToken structures token buffers are all stored as a single
153816  ** allocation so that the expression can be freed with a single call to
153817  ** sqlite3_free(). Setting this up requires a two pass approach.
153818  **
153819  ** The first pass, in the block below, uses a tokenizer cursor to iterate
153820  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
153821  ** to assemble data in two dynamic buffers:
153822  **
153823  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
153824  **             structure, followed by the array of Fts3PhraseToken
153825  **             structures. This pass only populates the Fts3PhraseToken array.
153826  **
153827  **   Buffer zTemp: Contains copies of all tokens.
153828  **
153829  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
153830  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
153831  ** structures.
153832  */
153833  rc = sqlite3Fts3OpenTokenizer(
153834      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
153835  if( rc==SQLITE_OK ){
153836    int ii;
153837    for(ii=0; rc==SQLITE_OK; ii++){
153838      const char *zByte;
153839      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
153840      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
153841      if( rc==SQLITE_OK ){
153842        Fts3PhraseToken *pToken;
153843
153844        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
153845        if( !p ) goto no_mem;
153846
153847        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
153848        if( !zTemp ) goto no_mem;
153849
153850        assert( nToken==ii );
153851        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
153852        memset(pToken, 0, sizeof(Fts3PhraseToken));
153853
153854        memcpy(&zTemp[nTemp], zByte, nByte);
153855        nTemp += nByte;
153856
153857        pToken->n = nByte;
153858        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
153859        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
153860        nToken = ii+1;
153861      }
153862    }
153863
153864    pModule->xClose(pCursor);
153865    pCursor = 0;
153866  }
153867
153868  if( rc==SQLITE_DONE ){
153869    int jj;
153870    char *zBuf = 0;
153871
153872    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
153873    if( !p ) goto no_mem;
153874    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
153875    p->eType = FTSQUERY_PHRASE;
153876    p->pPhrase = (Fts3Phrase *)&p[1];
153877    p->pPhrase->iColumn = pParse->iDefaultCol;
153878    p->pPhrase->nToken = nToken;
153879
153880    zBuf = (char *)&p->pPhrase->aToken[nToken];
153881    if( zTemp ){
153882      memcpy(zBuf, zTemp, nTemp);
153883      sqlite3_free(zTemp);
153884    }else{
153885      assert( nTemp==0 );
153886    }
153887
153888    for(jj=0; jj<p->pPhrase->nToken; jj++){
153889      p->pPhrase->aToken[jj].z = zBuf;
153890      zBuf += p->pPhrase->aToken[jj].n;
153891    }
153892    rc = SQLITE_OK;
153893  }
153894
153895  *ppExpr = p;
153896  return rc;
153897no_mem:
153898
153899  if( pCursor ){
153900    pModule->xClose(pCursor);
153901  }
153902  sqlite3_free(zTemp);
153903  sqlite3_free(p);
153904  *ppExpr = 0;
153905  return SQLITE_NOMEM;
153906}
153907
153908/*
153909** The output variable *ppExpr is populated with an allocated Fts3Expr
153910** structure, or set to 0 if the end of the input buffer is reached.
153911**
153912** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
153913** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
153914** If SQLITE_ERROR is returned, pContext is populated with an error message.
153915*/
153916static int getNextNode(
153917  ParseContext *pParse,                   /* fts3 query parse context */
153918  const char *z, int n,                   /* Input string */
153919  Fts3Expr **ppExpr,                      /* OUT: expression */
153920  int *pnConsumed                         /* OUT: Number of bytes consumed */
153921){
153922  static const struct Fts3Keyword {
153923    char *z;                              /* Keyword text */
153924    unsigned char n;                      /* Length of the keyword */
153925    unsigned char parenOnly;              /* Only valid in paren mode */
153926    unsigned char eType;                  /* Keyword code */
153927  } aKeyword[] = {
153928    { "OR" ,  2, 0, FTSQUERY_OR   },
153929    { "AND",  3, 1, FTSQUERY_AND  },
153930    { "NOT",  3, 1, FTSQUERY_NOT  },
153931    { "NEAR", 4, 0, FTSQUERY_NEAR }
153932  };
153933  int ii;
153934  int iCol;
153935  int iColLen;
153936  int rc;
153937  Fts3Expr *pRet = 0;
153938
153939  const char *zInput = z;
153940  int nInput = n;
153941
153942  pParse->isNot = 0;
153943
153944  /* Skip over any whitespace before checking for a keyword, an open or
153945  ** close bracket, or a quoted string.
153946  */
153947  while( nInput>0 && fts3isspace(*zInput) ){
153948    nInput--;
153949    zInput++;
153950  }
153951  if( nInput==0 ){
153952    return SQLITE_DONE;
153953  }
153954
153955  /* See if we are dealing with a keyword. */
153956  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
153957    const struct Fts3Keyword *pKey = &aKeyword[ii];
153958
153959    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
153960      continue;
153961    }
153962
153963    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
153964      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
153965      int nKey = pKey->n;
153966      char cNext;
153967
153968      /* If this is a "NEAR" keyword, check for an explicit nearness. */
153969      if( pKey->eType==FTSQUERY_NEAR ){
153970        assert( nKey==4 );
153971        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
153972          nNear = 0;
153973          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
153974            nNear = nNear * 10 + (zInput[nKey] - '0');
153975          }
153976        }
153977      }
153978
153979      /* At this point this is probably a keyword. But for that to be true,
153980      ** the next byte must contain either whitespace, an open or close
153981      ** parenthesis, a quote character, or EOF.
153982      */
153983      cNext = zInput[nKey];
153984      if( fts3isspace(cNext)
153985       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
153986      ){
153987        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
153988        if( !pRet ){
153989          return SQLITE_NOMEM;
153990        }
153991        pRet->eType = pKey->eType;
153992        pRet->nNear = nNear;
153993        *ppExpr = pRet;
153994        *pnConsumed = (int)((zInput - z) + nKey);
153995        return SQLITE_OK;
153996      }
153997
153998      /* Turns out that wasn't a keyword after all. This happens if the
153999      ** user has supplied a token such as "ORacle". Continue.
154000      */
154001    }
154002  }
154003
154004  /* See if we are dealing with a quoted phrase. If this is the case, then
154005  ** search for the closing quote and pass the whole string to getNextString()
154006  ** for processing. This is easy to do, as fts3 has no syntax for escaping
154007  ** a quote character embedded in a string.
154008  */
154009  if( *zInput=='"' ){
154010    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
154011    *pnConsumed = (int)((zInput - z) + ii + 1);
154012    if( ii==nInput ){
154013      return SQLITE_ERROR;
154014    }
154015    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
154016  }
154017
154018  if( sqlite3_fts3_enable_parentheses ){
154019    if( *zInput=='(' ){
154020      int nConsumed = 0;
154021      pParse->nNest++;
154022      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
154023      if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
154024      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
154025      return rc;
154026    }else if( *zInput==')' ){
154027      pParse->nNest--;
154028      *pnConsumed = (int)((zInput - z) + 1);
154029      *ppExpr = 0;
154030      return SQLITE_DONE;
154031    }
154032  }
154033
154034  /* If control flows to this point, this must be a regular token, or
154035  ** the end of the input. Read a regular token using the sqlite3_tokenizer
154036  ** interface. Before doing so, figure out if there is an explicit
154037  ** column specifier for the token.
154038  **
154039  ** TODO: Strangely, it is not possible to associate a column specifier
154040  ** with a quoted phrase, only with a single token. Not sure if this was
154041  ** an implementation artifact or an intentional decision when fts3 was
154042  ** first implemented. Whichever it was, this module duplicates the
154043  ** limitation.
154044  */
154045  iCol = pParse->iDefaultCol;
154046  iColLen = 0;
154047  for(ii=0; ii<pParse->nCol; ii++){
154048    const char *zStr = pParse->azCol[ii];
154049    int nStr = (int)strlen(zStr);
154050    if( nInput>nStr && zInput[nStr]==':'
154051     && sqlite3_strnicmp(zStr, zInput, nStr)==0
154052    ){
154053      iCol = ii;
154054      iColLen = (int)((zInput - z) + nStr + 1);
154055      break;
154056    }
154057  }
154058  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
154059  *pnConsumed += iColLen;
154060  return rc;
154061}
154062
154063/*
154064** The argument is an Fts3Expr structure for a binary operator (any type
154065** except an FTSQUERY_PHRASE). Return an integer value representing the
154066** precedence of the operator. Lower values have a higher precedence (i.e.
154067** group more tightly). For example, in the C language, the == operator
154068** groups more tightly than ||, and would therefore have a higher precedence.
154069**
154070** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
154071** is defined), the order of the operators in precedence from highest to
154072** lowest is:
154073**
154074**   NEAR
154075**   NOT
154076**   AND (including implicit ANDs)
154077**   OR
154078**
154079** Note that when using the old query syntax, the OR operator has a higher
154080** precedence than the AND operator.
154081*/
154082static int opPrecedence(Fts3Expr *p){
154083  assert( p->eType!=FTSQUERY_PHRASE );
154084  if( sqlite3_fts3_enable_parentheses ){
154085    return p->eType;
154086  }else if( p->eType==FTSQUERY_NEAR ){
154087    return 1;
154088  }else if( p->eType==FTSQUERY_OR ){
154089    return 2;
154090  }
154091  assert( p->eType==FTSQUERY_AND );
154092  return 3;
154093}
154094
154095/*
154096** Argument ppHead contains a pointer to the current head of a query
154097** expression tree being parsed. pPrev is the expression node most recently
154098** inserted into the tree. This function adds pNew, which is always a binary
154099** operator node, into the expression tree based on the relative precedence
154100** of pNew and the existing nodes of the tree. This may result in the head
154101** of the tree changing, in which case *ppHead is set to the new root node.
154102*/
154103static void insertBinaryOperator(
154104  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
154105  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
154106  Fts3Expr *pNew           /* New binary node to insert into expression tree */
154107){
154108  Fts3Expr *pSplit = pPrev;
154109  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
154110    pSplit = pSplit->pParent;
154111  }
154112
154113  if( pSplit->pParent ){
154114    assert( pSplit->pParent->pRight==pSplit );
154115    pSplit->pParent->pRight = pNew;
154116    pNew->pParent = pSplit->pParent;
154117  }else{
154118    *ppHead = pNew;
154119  }
154120  pNew->pLeft = pSplit;
154121  pSplit->pParent = pNew;
154122}
154123
154124/*
154125** Parse the fts3 query expression found in buffer z, length n. This function
154126** returns either when the end of the buffer is reached or an unmatched
154127** closing bracket - ')' - is encountered.
154128**
154129** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
154130** parsed form of the expression and *pnConsumed is set to the number of
154131** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
154132** (out of memory error) or SQLITE_ERROR (parse error) is returned.
154133*/
154134static int fts3ExprParse(
154135  ParseContext *pParse,                   /* fts3 query parse context */
154136  const char *z, int n,                   /* Text of MATCH query */
154137  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
154138  int *pnConsumed                         /* OUT: Number of bytes consumed */
154139){
154140  Fts3Expr *pRet = 0;
154141  Fts3Expr *pPrev = 0;
154142  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
154143  int nIn = n;
154144  const char *zIn = z;
154145  int rc = SQLITE_OK;
154146  int isRequirePhrase = 1;
154147
154148  while( rc==SQLITE_OK ){
154149    Fts3Expr *p = 0;
154150    int nByte = 0;
154151
154152    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
154153    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
154154    if( rc==SQLITE_OK ){
154155      if( p ){
154156        int isPhrase;
154157
154158        if( !sqlite3_fts3_enable_parentheses
154159            && p->eType==FTSQUERY_PHRASE && pParse->isNot
154160        ){
154161          /* Create an implicit NOT operator. */
154162          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
154163          if( !pNot ){
154164            sqlite3Fts3ExprFree(p);
154165            rc = SQLITE_NOMEM;
154166            goto exprparse_out;
154167          }
154168          pNot->eType = FTSQUERY_NOT;
154169          pNot->pRight = p;
154170          p->pParent = pNot;
154171          if( pNotBranch ){
154172            pNot->pLeft = pNotBranch;
154173            pNotBranch->pParent = pNot;
154174          }
154175          pNotBranch = pNot;
154176          p = pPrev;
154177        }else{
154178          int eType = p->eType;
154179          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
154180
154181          /* The isRequirePhrase variable is set to true if a phrase or
154182          ** an expression contained in parenthesis is required. If a
154183          ** binary operator (AND, OR, NOT or NEAR) is encounted when
154184          ** isRequirePhrase is set, this is a syntax error.
154185          */
154186          if( !isPhrase && isRequirePhrase ){
154187            sqlite3Fts3ExprFree(p);
154188            rc = SQLITE_ERROR;
154189            goto exprparse_out;
154190          }
154191
154192          if( isPhrase && !isRequirePhrase ){
154193            /* Insert an implicit AND operator. */
154194            Fts3Expr *pAnd;
154195            assert( pRet && pPrev );
154196            pAnd = fts3MallocZero(sizeof(Fts3Expr));
154197            if( !pAnd ){
154198              sqlite3Fts3ExprFree(p);
154199              rc = SQLITE_NOMEM;
154200              goto exprparse_out;
154201            }
154202            pAnd->eType = FTSQUERY_AND;
154203            insertBinaryOperator(&pRet, pPrev, pAnd);
154204            pPrev = pAnd;
154205          }
154206
154207          /* This test catches attempts to make either operand of a NEAR
154208           ** operator something other than a phrase. For example, either of
154209           ** the following:
154210           **
154211           **    (bracketed expression) NEAR phrase
154212           **    phrase NEAR (bracketed expression)
154213           **
154214           ** Return an error in either case.
154215           */
154216          if( pPrev && (
154217            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
154218         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
154219          )){
154220            sqlite3Fts3ExprFree(p);
154221            rc = SQLITE_ERROR;
154222            goto exprparse_out;
154223          }
154224
154225          if( isPhrase ){
154226            if( pRet ){
154227              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
154228              pPrev->pRight = p;
154229              p->pParent = pPrev;
154230            }else{
154231              pRet = p;
154232            }
154233          }else{
154234            insertBinaryOperator(&pRet, pPrev, p);
154235          }
154236          isRequirePhrase = !isPhrase;
154237        }
154238        pPrev = p;
154239      }
154240      assert( nByte>0 );
154241    }
154242    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
154243    nIn -= nByte;
154244    zIn += nByte;
154245  }
154246
154247  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
154248    rc = SQLITE_ERROR;
154249  }
154250
154251  if( rc==SQLITE_DONE ){
154252    rc = SQLITE_OK;
154253    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
154254      if( !pRet ){
154255        rc = SQLITE_ERROR;
154256      }else{
154257        Fts3Expr *pIter = pNotBranch;
154258        while( pIter->pLeft ){
154259          pIter = pIter->pLeft;
154260        }
154261        pIter->pLeft = pRet;
154262        pRet->pParent = pIter;
154263        pRet = pNotBranch;
154264      }
154265    }
154266  }
154267  *pnConsumed = n - nIn;
154268
154269exprparse_out:
154270  if( rc!=SQLITE_OK ){
154271    sqlite3Fts3ExprFree(pRet);
154272    sqlite3Fts3ExprFree(pNotBranch);
154273    pRet = 0;
154274  }
154275  *ppExpr = pRet;
154276  return rc;
154277}
154278
154279/*
154280** Return SQLITE_ERROR if the maximum depth of the expression tree passed
154281** as the only argument is more than nMaxDepth.
154282*/
154283static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
154284  int rc = SQLITE_OK;
154285  if( p ){
154286    if( nMaxDepth<0 ){
154287      rc = SQLITE_TOOBIG;
154288    }else{
154289      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
154290      if( rc==SQLITE_OK ){
154291        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
154292      }
154293    }
154294  }
154295  return rc;
154296}
154297
154298/*
154299** This function attempts to transform the expression tree at (*pp) to
154300** an equivalent but more balanced form. The tree is modified in place.
154301** If successful, SQLITE_OK is returned and (*pp) set to point to the
154302** new root expression node.
154303**
154304** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
154305**
154306** Otherwise, if an error occurs, an SQLite error code is returned and
154307** expression (*pp) freed.
154308*/
154309static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
154310  int rc = SQLITE_OK;             /* Return code */
154311  Fts3Expr *pRoot = *pp;          /* Initial root node */
154312  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
154313  int eType = pRoot->eType;       /* Type of node in this tree */
154314
154315  if( nMaxDepth==0 ){
154316    rc = SQLITE_ERROR;
154317  }
154318
154319  if( rc==SQLITE_OK ){
154320    if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
154321      Fts3Expr **apLeaf;
154322      apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
154323      if( 0==apLeaf ){
154324        rc = SQLITE_NOMEM;
154325      }else{
154326        memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
154327      }
154328
154329      if( rc==SQLITE_OK ){
154330        int i;
154331        Fts3Expr *p;
154332
154333        /* Set $p to point to the left-most leaf in the tree of eType nodes. */
154334        for(p=pRoot; p->eType==eType; p=p->pLeft){
154335          assert( p->pParent==0 || p->pParent->pLeft==p );
154336          assert( p->pLeft && p->pRight );
154337        }
154338
154339        /* This loop runs once for each leaf in the tree of eType nodes. */
154340        while( 1 ){
154341          int iLvl;
154342          Fts3Expr *pParent = p->pParent;     /* Current parent of p */
154343
154344          assert( pParent==0 || pParent->pLeft==p );
154345          p->pParent = 0;
154346          if( pParent ){
154347            pParent->pLeft = 0;
154348          }else{
154349            pRoot = 0;
154350          }
154351          rc = fts3ExprBalance(&p, nMaxDepth-1);
154352          if( rc!=SQLITE_OK ) break;
154353
154354          for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
154355            if( apLeaf[iLvl]==0 ){
154356              apLeaf[iLvl] = p;
154357              p = 0;
154358            }else{
154359              assert( pFree );
154360              pFree->pLeft = apLeaf[iLvl];
154361              pFree->pRight = p;
154362              pFree->pLeft->pParent = pFree;
154363              pFree->pRight->pParent = pFree;
154364
154365              p = pFree;
154366              pFree = pFree->pParent;
154367              p->pParent = 0;
154368              apLeaf[iLvl] = 0;
154369            }
154370          }
154371          if( p ){
154372            sqlite3Fts3ExprFree(p);
154373            rc = SQLITE_TOOBIG;
154374            break;
154375          }
154376
154377          /* If that was the last leaf node, break out of the loop */
154378          if( pParent==0 ) break;
154379
154380          /* Set $p to point to the next leaf in the tree of eType nodes */
154381          for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
154382
154383          /* Remove pParent from the original tree. */
154384          assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
154385          pParent->pRight->pParent = pParent->pParent;
154386          if( pParent->pParent ){
154387            pParent->pParent->pLeft = pParent->pRight;
154388          }else{
154389            assert( pParent==pRoot );
154390            pRoot = pParent->pRight;
154391          }
154392
154393          /* Link pParent into the free node list. It will be used as an
154394          ** internal node of the new tree.  */
154395          pParent->pParent = pFree;
154396          pFree = pParent;
154397        }
154398
154399        if( rc==SQLITE_OK ){
154400          p = 0;
154401          for(i=0; i<nMaxDepth; i++){
154402            if( apLeaf[i] ){
154403              if( p==0 ){
154404                p = apLeaf[i];
154405                p->pParent = 0;
154406              }else{
154407                assert( pFree!=0 );
154408                pFree->pRight = p;
154409                pFree->pLeft = apLeaf[i];
154410                pFree->pLeft->pParent = pFree;
154411                pFree->pRight->pParent = pFree;
154412
154413                p = pFree;
154414                pFree = pFree->pParent;
154415                p->pParent = 0;
154416              }
154417            }
154418          }
154419          pRoot = p;
154420        }else{
154421          /* An error occurred. Delete the contents of the apLeaf[] array
154422          ** and pFree list. Everything else is cleaned up by the call to
154423          ** sqlite3Fts3ExprFree(pRoot) below.  */
154424          Fts3Expr *pDel;
154425          for(i=0; i<nMaxDepth; i++){
154426            sqlite3Fts3ExprFree(apLeaf[i]);
154427          }
154428          while( (pDel=pFree)!=0 ){
154429            pFree = pDel->pParent;
154430            sqlite3_free(pDel);
154431          }
154432        }
154433
154434        assert( pFree==0 );
154435        sqlite3_free( apLeaf );
154436      }
154437    }else if( eType==FTSQUERY_NOT ){
154438      Fts3Expr *pLeft = pRoot->pLeft;
154439      Fts3Expr *pRight = pRoot->pRight;
154440
154441      pRoot->pLeft = 0;
154442      pRoot->pRight = 0;
154443      pLeft->pParent = 0;
154444      pRight->pParent = 0;
154445
154446      rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
154447      if( rc==SQLITE_OK ){
154448        rc = fts3ExprBalance(&pRight, nMaxDepth-1);
154449      }
154450
154451      if( rc!=SQLITE_OK ){
154452        sqlite3Fts3ExprFree(pRight);
154453        sqlite3Fts3ExprFree(pLeft);
154454      }else{
154455        assert( pLeft && pRight );
154456        pRoot->pLeft = pLeft;
154457        pLeft->pParent = pRoot;
154458        pRoot->pRight = pRight;
154459        pRight->pParent = pRoot;
154460      }
154461    }
154462  }
154463
154464  if( rc!=SQLITE_OK ){
154465    sqlite3Fts3ExprFree(pRoot);
154466    pRoot = 0;
154467  }
154468  *pp = pRoot;
154469  return rc;
154470}
154471
154472/*
154473** This function is similar to sqlite3Fts3ExprParse(), with the following
154474** differences:
154475**
154476**   1. It does not do expression rebalancing.
154477**   2. It does not check that the expression does not exceed the
154478**      maximum allowable depth.
154479**   3. Even if it fails, *ppExpr may still be set to point to an
154480**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
154481**      in this case.
154482*/
154483static int fts3ExprParseUnbalanced(
154484  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
154485  int iLangid,                        /* Language id for tokenizer */
154486  char **azCol,                       /* Array of column names for fts3 table */
154487  int bFts4,                          /* True to allow FTS4-only syntax */
154488  int nCol,                           /* Number of entries in azCol[] */
154489  int iDefaultCol,                    /* Default column to query */
154490  const char *z, int n,               /* Text of MATCH query */
154491  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
154492){
154493  int nParsed;
154494  int rc;
154495  ParseContext sParse;
154496
154497  memset(&sParse, 0, sizeof(ParseContext));
154498  sParse.pTokenizer = pTokenizer;
154499  sParse.iLangid = iLangid;
154500  sParse.azCol = (const char **)azCol;
154501  sParse.nCol = nCol;
154502  sParse.iDefaultCol = iDefaultCol;
154503  sParse.bFts4 = bFts4;
154504  if( z==0 ){
154505    *ppExpr = 0;
154506    return SQLITE_OK;
154507  }
154508  if( n<0 ){
154509    n = (int)strlen(z);
154510  }
154511  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
154512  assert( rc==SQLITE_OK || *ppExpr==0 );
154513
154514  /* Check for mismatched parenthesis */
154515  if( rc==SQLITE_OK && sParse.nNest ){
154516    rc = SQLITE_ERROR;
154517  }
154518
154519  return rc;
154520}
154521
154522/*
154523** Parameters z and n contain a pointer to and length of a buffer containing
154524** an fts3 query expression, respectively. This function attempts to parse the
154525** query expression and create a tree of Fts3Expr structures representing the
154526** parsed expression. If successful, *ppExpr is set to point to the head
154527** of the parsed expression tree and SQLITE_OK is returned. If an error
154528** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
154529** error) is returned and *ppExpr is set to 0.
154530**
154531** If parameter n is a negative number, then z is assumed to point to a
154532** nul-terminated string and the length is determined using strlen().
154533**
154534** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
154535** use to normalize query tokens while parsing the expression. The azCol[]
154536** array, which is assumed to contain nCol entries, should contain the names
154537** of each column in the target fts3 table, in order from left to right.
154538** Column names must be nul-terminated strings.
154539**
154540** The iDefaultCol parameter should be passed the index of the table column
154541** that appears on the left-hand-side of the MATCH operator (the default
154542** column to match against for tokens for which a column name is not explicitly
154543** specified as part of the query string), or -1 if tokens may by default
154544** match any table column.
154545*/
154546SQLITE_PRIVATE int sqlite3Fts3ExprParse(
154547  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
154548  int iLangid,                        /* Language id for tokenizer */
154549  char **azCol,                       /* Array of column names for fts3 table */
154550  int bFts4,                          /* True to allow FTS4-only syntax */
154551  int nCol,                           /* Number of entries in azCol[] */
154552  int iDefaultCol,                    /* Default column to query */
154553  const char *z, int n,               /* Text of MATCH query */
154554  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
154555  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
154556){
154557  int rc = fts3ExprParseUnbalanced(
154558      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
154559  );
154560
154561  /* Rebalance the expression. And check that its depth does not exceed
154562  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
154563  if( rc==SQLITE_OK && *ppExpr ){
154564    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
154565    if( rc==SQLITE_OK ){
154566      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
154567    }
154568  }
154569
154570  if( rc!=SQLITE_OK ){
154571    sqlite3Fts3ExprFree(*ppExpr);
154572    *ppExpr = 0;
154573    if( rc==SQLITE_TOOBIG ){
154574      sqlite3Fts3ErrMsg(pzErr,
154575          "FTS expression tree is too large (maximum depth %d)",
154576          SQLITE_FTS3_MAX_EXPR_DEPTH
154577      );
154578      rc = SQLITE_ERROR;
154579    }else if( rc==SQLITE_ERROR ){
154580      sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
154581    }
154582  }
154583
154584  return rc;
154585}
154586
154587/*
154588** Free a single node of an expression tree.
154589*/
154590static void fts3FreeExprNode(Fts3Expr *p){
154591  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
154592  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
154593  sqlite3_free(p->aMI);
154594  sqlite3_free(p);
154595}
154596
154597/*
154598** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
154599**
154600** This function would be simpler if it recursively called itself. But
154601** that would mean passing a sufficiently large expression to ExprParse()
154602** could cause a stack overflow.
154603*/
154604SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
154605  Fts3Expr *p;
154606  assert( pDel==0 || pDel->pParent==0 );
154607  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
154608    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
154609  }
154610  while( p ){
154611    Fts3Expr *pParent = p->pParent;
154612    fts3FreeExprNode(p);
154613    if( pParent && p==pParent->pLeft && pParent->pRight ){
154614      p = pParent->pRight;
154615      while( p && (p->pLeft || p->pRight) ){
154616        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
154617        p = (p->pLeft ? p->pLeft : p->pRight);
154618      }
154619    }else{
154620      p = pParent;
154621    }
154622  }
154623}
154624
154625/****************************************************************************
154626*****************************************************************************
154627** Everything after this point is just test code.
154628*/
154629
154630#ifdef SQLITE_TEST
154631
154632/* #include <stdio.h> */
154633
154634/*
154635** Function to query the hash-table of tokenizers (see README.tokenizers).
154636*/
154637static int queryTestTokenizer(
154638  sqlite3 *db,
154639  const char *zName,
154640  const sqlite3_tokenizer_module **pp
154641){
154642  int rc;
154643  sqlite3_stmt *pStmt;
154644  const char zSql[] = "SELECT fts3_tokenizer(?)";
154645
154646  *pp = 0;
154647  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
154648  if( rc!=SQLITE_OK ){
154649    return rc;
154650  }
154651
154652  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
154653  if( SQLITE_ROW==sqlite3_step(pStmt) ){
154654    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
154655      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
154656    }
154657  }
154658
154659  return sqlite3_finalize(pStmt);
154660}
154661
154662/*
154663** Return a pointer to a buffer containing a text representation of the
154664** expression passed as the first argument. The buffer is obtained from
154665** sqlite3_malloc(). It is the responsibility of the caller to use
154666** sqlite3_free() to release the memory. If an OOM condition is encountered,
154667** NULL is returned.
154668**
154669** If the second argument is not NULL, then its contents are prepended to
154670** the returned expression text and then freed using sqlite3_free().
154671*/
154672static char *exprToString(Fts3Expr *pExpr, char *zBuf){
154673  if( pExpr==0 ){
154674    return sqlite3_mprintf("");
154675  }
154676  switch( pExpr->eType ){
154677    case FTSQUERY_PHRASE: {
154678      Fts3Phrase *pPhrase = pExpr->pPhrase;
154679      int i;
154680      zBuf = sqlite3_mprintf(
154681          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
154682      for(i=0; zBuf && i<pPhrase->nToken; i++){
154683        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
154684            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
154685            (pPhrase->aToken[i].isPrefix?"+":"")
154686        );
154687      }
154688      return zBuf;
154689    }
154690
154691    case FTSQUERY_NEAR:
154692      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
154693      break;
154694    case FTSQUERY_NOT:
154695      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
154696      break;
154697    case FTSQUERY_AND:
154698      zBuf = sqlite3_mprintf("%zAND ", zBuf);
154699      break;
154700    case FTSQUERY_OR:
154701      zBuf = sqlite3_mprintf("%zOR ", zBuf);
154702      break;
154703  }
154704
154705  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
154706  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
154707  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
154708
154709  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
154710  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
154711
154712  return zBuf;
154713}
154714
154715/*
154716** This is the implementation of a scalar SQL function used to test the
154717** expression parser. It should be called as follows:
154718**
154719**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
154720**
154721** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
154722** to parse the query expression (see README.tokenizers). The second argument
154723** is the query expression to parse. Each subsequent argument is the name
154724** of a column of the fts3 table that the query expression may refer to.
154725** For example:
154726**
154727**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
154728*/
154729static void fts3ExprTest(
154730  sqlite3_context *context,
154731  int argc,
154732  sqlite3_value **argv
154733){
154734  sqlite3_tokenizer_module const *pModule = 0;
154735  sqlite3_tokenizer *pTokenizer = 0;
154736  int rc;
154737  char **azCol = 0;
154738  const char *zExpr;
154739  int nExpr;
154740  int nCol;
154741  int ii;
154742  Fts3Expr *pExpr;
154743  char *zBuf = 0;
154744  sqlite3 *db = sqlite3_context_db_handle(context);
154745
154746  if( argc<3 ){
154747    sqlite3_result_error(context,
154748        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
154749    );
154750    return;
154751  }
154752
154753  rc = queryTestTokenizer(db,
154754                          (const char *)sqlite3_value_text(argv[0]), &pModule);
154755  if( rc==SQLITE_NOMEM ){
154756    sqlite3_result_error_nomem(context);
154757    goto exprtest_out;
154758  }else if( !pModule ){
154759    sqlite3_result_error(context, "No such tokenizer module", -1);
154760    goto exprtest_out;
154761  }
154762
154763  rc = pModule->xCreate(0, 0, &pTokenizer);
154764  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
154765  if( rc==SQLITE_NOMEM ){
154766    sqlite3_result_error_nomem(context);
154767    goto exprtest_out;
154768  }
154769  pTokenizer->pModule = pModule;
154770
154771  zExpr = (const char *)sqlite3_value_text(argv[1]);
154772  nExpr = sqlite3_value_bytes(argv[1]);
154773  nCol = argc-2;
154774  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
154775  if( !azCol ){
154776    sqlite3_result_error_nomem(context);
154777    goto exprtest_out;
154778  }
154779  for(ii=0; ii<nCol; ii++){
154780    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
154781  }
154782
154783  if( sqlite3_user_data(context) ){
154784    char *zDummy = 0;
154785    rc = sqlite3Fts3ExprParse(
154786        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
154787    );
154788    assert( rc==SQLITE_OK || pExpr==0 );
154789    sqlite3_free(zDummy);
154790  }else{
154791    rc = fts3ExprParseUnbalanced(
154792        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
154793    );
154794  }
154795
154796  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
154797    sqlite3Fts3ExprFree(pExpr);
154798    sqlite3_result_error(context, "Error parsing expression", -1);
154799  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
154800    sqlite3_result_error_nomem(context);
154801  }else{
154802    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
154803    sqlite3_free(zBuf);
154804  }
154805
154806  sqlite3Fts3ExprFree(pExpr);
154807
154808exprtest_out:
154809  if( pModule && pTokenizer ){
154810    rc = pModule->xDestroy(pTokenizer);
154811  }
154812  sqlite3_free(azCol);
154813}
154814
154815/*
154816** Register the query expression parser test function fts3_exprtest()
154817** with database connection db.
154818*/
154819SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
154820  int rc = sqlite3_create_function(
154821      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
154822  );
154823  if( rc==SQLITE_OK ){
154824    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
154825        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
154826    );
154827  }
154828  return rc;
154829}
154830
154831#endif
154832#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
154833
154834/************** End of fts3_expr.c *******************************************/
154835/************** Begin file fts3_hash.c ***************************************/
154836/*
154837** 2001 September 22
154838**
154839** The author disclaims copyright to this source code.  In place of
154840** a legal notice, here is a blessing:
154841**
154842**    May you do good and not evil.
154843**    May you find forgiveness for yourself and forgive others.
154844**    May you share freely, never taking more than you give.
154845**
154846*************************************************************************
154847** This is the implementation of generic hash-tables used in SQLite.
154848** We've modified it slightly to serve as a standalone hash table
154849** implementation for the full-text indexing module.
154850*/
154851
154852/*
154853** The code in this file is only compiled if:
154854**
154855**     * The FTS3 module is being built as an extension
154856**       (in which case SQLITE_CORE is not defined), or
154857**
154858**     * The FTS3 module is being built into the core of
154859**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
154860*/
154861/* #include "fts3Int.h" */
154862#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
154863
154864/* #include <assert.h> */
154865/* #include <stdlib.h> */
154866/* #include <string.h> */
154867
154868/* #include "fts3_hash.h" */
154869
154870/*
154871** Malloc and Free functions
154872*/
154873static void *fts3HashMalloc(int n){
154874  void *p = sqlite3_malloc(n);
154875  if( p ){
154876    memset(p, 0, n);
154877  }
154878  return p;
154879}
154880static void fts3HashFree(void *p){
154881  sqlite3_free(p);
154882}
154883
154884/* Turn bulk memory into a hash table object by initializing the
154885** fields of the Hash structure.
154886**
154887** "pNew" is a pointer to the hash table that is to be initialized.
154888** keyClass is one of the constants
154889** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
154890** determines what kind of key the hash table will use.  "copyKey" is
154891** true if the hash table should make its own private copy of keys and
154892** false if it should just use the supplied pointer.
154893*/
154894SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
154895  assert( pNew!=0 );
154896  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
154897  pNew->keyClass = keyClass;
154898  pNew->copyKey = copyKey;
154899  pNew->first = 0;
154900  pNew->count = 0;
154901  pNew->htsize = 0;
154902  pNew->ht = 0;
154903}
154904
154905/* Remove all entries from a hash table.  Reclaim all memory.
154906** Call this routine to delete a hash table or to reset a hash table
154907** to the empty state.
154908*/
154909SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
154910  Fts3HashElem *elem;         /* For looping over all elements of the table */
154911
154912  assert( pH!=0 );
154913  elem = pH->first;
154914  pH->first = 0;
154915  fts3HashFree(pH->ht);
154916  pH->ht = 0;
154917  pH->htsize = 0;
154918  while( elem ){
154919    Fts3HashElem *next_elem = elem->next;
154920    if( pH->copyKey && elem->pKey ){
154921      fts3HashFree(elem->pKey);
154922    }
154923    fts3HashFree(elem);
154924    elem = next_elem;
154925  }
154926  pH->count = 0;
154927}
154928
154929/*
154930** Hash and comparison functions when the mode is FTS3_HASH_STRING
154931*/
154932static int fts3StrHash(const void *pKey, int nKey){
154933  const char *z = (const char *)pKey;
154934  unsigned h = 0;
154935  if( nKey<=0 ) nKey = (int) strlen(z);
154936  while( nKey > 0  ){
154937    h = (h<<3) ^ h ^ *z++;
154938    nKey--;
154939  }
154940  return (int)(h & 0x7fffffff);
154941}
154942static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
154943  if( n1!=n2 ) return 1;
154944  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
154945}
154946
154947/*
154948** Hash and comparison functions when the mode is FTS3_HASH_BINARY
154949*/
154950static int fts3BinHash(const void *pKey, int nKey){
154951  int h = 0;
154952  const char *z = (const char *)pKey;
154953  while( nKey-- > 0 ){
154954    h = (h<<3) ^ h ^ *(z++);
154955  }
154956  return h & 0x7fffffff;
154957}
154958static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
154959  if( n1!=n2 ) return 1;
154960  return memcmp(pKey1,pKey2,n1);
154961}
154962
154963/*
154964** Return a pointer to the appropriate hash function given the key class.
154965**
154966** The C syntax in this function definition may be unfamilar to some
154967** programmers, so we provide the following additional explanation:
154968**
154969** The name of the function is "ftsHashFunction".  The function takes a
154970** single parameter "keyClass".  The return value of ftsHashFunction()
154971** is a pointer to another function.  Specifically, the return value
154972** of ftsHashFunction() is a pointer to a function that takes two parameters
154973** with types "const void*" and "int" and returns an "int".
154974*/
154975static int (*ftsHashFunction(int keyClass))(const void*,int){
154976  if( keyClass==FTS3_HASH_STRING ){
154977    return &fts3StrHash;
154978  }else{
154979    assert( keyClass==FTS3_HASH_BINARY );
154980    return &fts3BinHash;
154981  }
154982}
154983
154984/*
154985** Return a pointer to the appropriate hash function given the key class.
154986**
154987** For help in interpreted the obscure C code in the function definition,
154988** see the header comment on the previous function.
154989*/
154990static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
154991  if( keyClass==FTS3_HASH_STRING ){
154992    return &fts3StrCompare;
154993  }else{
154994    assert( keyClass==FTS3_HASH_BINARY );
154995    return &fts3BinCompare;
154996  }
154997}
154998
154999/* Link an element into the hash table
155000*/
155001static void fts3HashInsertElement(
155002  Fts3Hash *pH,            /* The complete hash table */
155003  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
155004  Fts3HashElem *pNew       /* The element to be inserted */
155005){
155006  Fts3HashElem *pHead;     /* First element already in pEntry */
155007  pHead = pEntry->chain;
155008  if( pHead ){
155009    pNew->next = pHead;
155010    pNew->prev = pHead->prev;
155011    if( pHead->prev ){ pHead->prev->next = pNew; }
155012    else             { pH->first = pNew; }
155013    pHead->prev = pNew;
155014  }else{
155015    pNew->next = pH->first;
155016    if( pH->first ){ pH->first->prev = pNew; }
155017    pNew->prev = 0;
155018    pH->first = pNew;
155019  }
155020  pEntry->count++;
155021  pEntry->chain = pNew;
155022}
155023
155024
155025/* Resize the hash table so that it cantains "new_size" buckets.
155026** "new_size" must be a power of 2.  The hash table might fail
155027** to resize if sqliteMalloc() fails.
155028**
155029** Return non-zero if a memory allocation error occurs.
155030*/
155031static int fts3Rehash(Fts3Hash *pH, int new_size){
155032  struct _fts3ht *new_ht;          /* The new hash table */
155033  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
155034  int (*xHash)(const void*,int);   /* The hash function */
155035
155036  assert( (new_size & (new_size-1))==0 );
155037  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
155038  if( new_ht==0 ) return 1;
155039  fts3HashFree(pH->ht);
155040  pH->ht = new_ht;
155041  pH->htsize = new_size;
155042  xHash = ftsHashFunction(pH->keyClass);
155043  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
155044    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
155045    next_elem = elem->next;
155046    fts3HashInsertElement(pH, &new_ht[h], elem);
155047  }
155048  return 0;
155049}
155050
155051/* This function (for internal use only) locates an element in an
155052** hash table that matches the given key.  The hash for this key has
155053** already been computed and is passed as the 4th parameter.
155054*/
155055static Fts3HashElem *fts3FindElementByHash(
155056  const Fts3Hash *pH, /* The pH to be searched */
155057  const void *pKey,   /* The key we are searching for */
155058  int nKey,
155059  int h               /* The hash for this key. */
155060){
155061  Fts3HashElem *elem;            /* Used to loop thru the element list */
155062  int count;                     /* Number of elements left to test */
155063  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
155064
155065  if( pH->ht ){
155066    struct _fts3ht *pEntry = &pH->ht[h];
155067    elem = pEntry->chain;
155068    count = pEntry->count;
155069    xCompare = ftsCompareFunction(pH->keyClass);
155070    while( count-- && elem ){
155071      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
155072        return elem;
155073      }
155074      elem = elem->next;
155075    }
155076  }
155077  return 0;
155078}
155079
155080/* Remove a single entry from the hash table given a pointer to that
155081** element and a hash on the element's key.
155082*/
155083static void fts3RemoveElementByHash(
155084  Fts3Hash *pH,         /* The pH containing "elem" */
155085  Fts3HashElem* elem,   /* The element to be removed from the pH */
155086  int h                 /* Hash value for the element */
155087){
155088  struct _fts3ht *pEntry;
155089  if( elem->prev ){
155090    elem->prev->next = elem->next;
155091  }else{
155092    pH->first = elem->next;
155093  }
155094  if( elem->next ){
155095    elem->next->prev = elem->prev;
155096  }
155097  pEntry = &pH->ht[h];
155098  if( pEntry->chain==elem ){
155099    pEntry->chain = elem->next;
155100  }
155101  pEntry->count--;
155102  if( pEntry->count<=0 ){
155103    pEntry->chain = 0;
155104  }
155105  if( pH->copyKey && elem->pKey ){
155106    fts3HashFree(elem->pKey);
155107  }
155108  fts3HashFree( elem );
155109  pH->count--;
155110  if( pH->count<=0 ){
155111    assert( pH->first==0 );
155112    assert( pH->count==0 );
155113    fts3HashClear(pH);
155114  }
155115}
155116
155117SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
155118  const Fts3Hash *pH,
155119  const void *pKey,
155120  int nKey
155121){
155122  int h;                          /* A hash on key */
155123  int (*xHash)(const void*,int);  /* The hash function */
155124
155125  if( pH==0 || pH->ht==0 ) return 0;
155126  xHash = ftsHashFunction(pH->keyClass);
155127  assert( xHash!=0 );
155128  h = (*xHash)(pKey,nKey);
155129  assert( (pH->htsize & (pH->htsize-1))==0 );
155130  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
155131}
155132
155133/*
155134** Attempt to locate an element of the hash table pH with a key
155135** that matches pKey,nKey.  Return the data for this element if it is
155136** found, or NULL if there is no match.
155137*/
155138SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
155139  Fts3HashElem *pElem;            /* The element that matches key (if any) */
155140
155141  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
155142  return pElem ? pElem->data : 0;
155143}
155144
155145/* Insert an element into the hash table pH.  The key is pKey,nKey
155146** and the data is "data".
155147**
155148** If no element exists with a matching key, then a new
155149** element is created.  A copy of the key is made if the copyKey
155150** flag is set.  NULL is returned.
155151**
155152** If another element already exists with the same key, then the
155153** new data replaces the old data and the old data is returned.
155154** The key is not copied in this instance.  If a malloc fails, then
155155** the new data is returned and the hash table is unchanged.
155156**
155157** If the "data" parameter to this function is NULL, then the
155158** element corresponding to "key" is removed from the hash table.
155159*/
155160SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
155161  Fts3Hash *pH,        /* The hash table to insert into */
155162  const void *pKey,    /* The key */
155163  int nKey,            /* Number of bytes in the key */
155164  void *data           /* The data */
155165){
155166  int hraw;                 /* Raw hash value of the key */
155167  int h;                    /* the hash of the key modulo hash table size */
155168  Fts3HashElem *elem;       /* Used to loop thru the element list */
155169  Fts3HashElem *new_elem;   /* New element added to the pH */
155170  int (*xHash)(const void*,int);  /* The hash function */
155171
155172  assert( pH!=0 );
155173  xHash = ftsHashFunction(pH->keyClass);
155174  assert( xHash!=0 );
155175  hraw = (*xHash)(pKey, nKey);
155176  assert( (pH->htsize & (pH->htsize-1))==0 );
155177  h = hraw & (pH->htsize-1);
155178  elem = fts3FindElementByHash(pH,pKey,nKey,h);
155179  if( elem ){
155180    void *old_data = elem->data;
155181    if( data==0 ){
155182      fts3RemoveElementByHash(pH,elem,h);
155183    }else{
155184      elem->data = data;
155185    }
155186    return old_data;
155187  }
155188  if( data==0 ) return 0;
155189  if( (pH->htsize==0 && fts3Rehash(pH,8))
155190   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
155191  ){
155192    pH->count = 0;
155193    return data;
155194  }
155195  assert( pH->htsize>0 );
155196  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
155197  if( new_elem==0 ) return data;
155198  if( pH->copyKey && pKey!=0 ){
155199    new_elem->pKey = fts3HashMalloc( nKey );
155200    if( new_elem->pKey==0 ){
155201      fts3HashFree(new_elem);
155202      return data;
155203    }
155204    memcpy((void*)new_elem->pKey, pKey, nKey);
155205  }else{
155206    new_elem->pKey = (void*)pKey;
155207  }
155208  new_elem->nKey = nKey;
155209  pH->count++;
155210  assert( pH->htsize>0 );
155211  assert( (pH->htsize & (pH->htsize-1))==0 );
155212  h = hraw & (pH->htsize-1);
155213  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
155214  new_elem->data = data;
155215  return 0;
155216}
155217
155218#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
155219
155220/************** End of fts3_hash.c *******************************************/
155221/************** Begin file fts3_porter.c *************************************/
155222/*
155223** 2006 September 30
155224**
155225** The author disclaims copyright to this source code.  In place of
155226** a legal notice, here is a blessing:
155227**
155228**    May you do good and not evil.
155229**    May you find forgiveness for yourself and forgive others.
155230**    May you share freely, never taking more than you give.
155231**
155232*************************************************************************
155233** Implementation of the full-text-search tokenizer that implements
155234** a Porter stemmer.
155235*/
155236
155237/*
155238** The code in this file is only compiled if:
155239**
155240**     * The FTS3 module is being built as an extension
155241**       (in which case SQLITE_CORE is not defined), or
155242**
155243**     * The FTS3 module is being built into the core of
155244**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
155245*/
155246/* #include "fts3Int.h" */
155247#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
155248
155249/* #include <assert.h> */
155250/* #include <stdlib.h> */
155251/* #include <stdio.h> */
155252/* #include <string.h> */
155253
155254/* #include "fts3_tokenizer.h" */
155255
155256/*
155257** Class derived from sqlite3_tokenizer
155258*/
155259typedef struct porter_tokenizer {
155260  sqlite3_tokenizer base;      /* Base class */
155261} porter_tokenizer;
155262
155263/*
155264** Class derived from sqlite3_tokenizer_cursor
155265*/
155266typedef struct porter_tokenizer_cursor {
155267  sqlite3_tokenizer_cursor base;
155268  const char *zInput;          /* input we are tokenizing */
155269  int nInput;                  /* size of the input */
155270  int iOffset;                 /* current position in zInput */
155271  int iToken;                  /* index of next token to be returned */
155272  char *zToken;                /* storage for current token */
155273  int nAllocated;              /* space allocated to zToken buffer */
155274} porter_tokenizer_cursor;
155275
155276
155277/*
155278** Create a new tokenizer instance.
155279*/
155280static int porterCreate(
155281  int argc, const char * const *argv,
155282  sqlite3_tokenizer **ppTokenizer
155283){
155284  porter_tokenizer *t;
155285
155286  UNUSED_PARAMETER(argc);
155287  UNUSED_PARAMETER(argv);
155288
155289  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
155290  if( t==NULL ) return SQLITE_NOMEM;
155291  memset(t, 0, sizeof(*t));
155292  *ppTokenizer = &t->base;
155293  return SQLITE_OK;
155294}
155295
155296/*
155297** Destroy a tokenizer
155298*/
155299static int porterDestroy(sqlite3_tokenizer *pTokenizer){
155300  sqlite3_free(pTokenizer);
155301  return SQLITE_OK;
155302}
155303
155304/*
155305** Prepare to begin tokenizing a particular string.  The input
155306** string to be tokenized is zInput[0..nInput-1].  A cursor
155307** used to incrementally tokenize this string is returned in
155308** *ppCursor.
155309*/
155310static int porterOpen(
155311  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
155312  const char *zInput, int nInput,        /* String to be tokenized */
155313  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
155314){
155315  porter_tokenizer_cursor *c;
155316
155317  UNUSED_PARAMETER(pTokenizer);
155318
155319  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
155320  if( c==NULL ) return SQLITE_NOMEM;
155321
155322  c->zInput = zInput;
155323  if( zInput==0 ){
155324    c->nInput = 0;
155325  }else if( nInput<0 ){
155326    c->nInput = (int)strlen(zInput);
155327  }else{
155328    c->nInput = nInput;
155329  }
155330  c->iOffset = 0;                 /* start tokenizing at the beginning */
155331  c->iToken = 0;
155332  c->zToken = NULL;               /* no space allocated, yet. */
155333  c->nAllocated = 0;
155334
155335  *ppCursor = &c->base;
155336  return SQLITE_OK;
155337}
155338
155339/*
155340** Close a tokenization cursor previously opened by a call to
155341** porterOpen() above.
155342*/
155343static int porterClose(sqlite3_tokenizer_cursor *pCursor){
155344  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
155345  sqlite3_free(c->zToken);
155346  sqlite3_free(c);
155347  return SQLITE_OK;
155348}
155349/*
155350** Vowel or consonant
155351*/
155352static const char cType[] = {
155353   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
155354   1, 1, 1, 2, 1
155355};
155356
155357/*
155358** isConsonant() and isVowel() determine if their first character in
155359** the string they point to is a consonant or a vowel, according
155360** to Porter ruls.
155361**
155362** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
155363** 'Y' is a consonant unless it follows another consonant,
155364** in which case it is a vowel.
155365**
155366** In these routine, the letters are in reverse order.  So the 'y' rule
155367** is that 'y' is a consonant unless it is followed by another
155368** consonent.
155369*/
155370static int isVowel(const char*);
155371static int isConsonant(const char *z){
155372  int j;
155373  char x = *z;
155374  if( x==0 ) return 0;
155375  assert( x>='a' && x<='z' );
155376  j = cType[x-'a'];
155377  if( j<2 ) return j;
155378  return z[1]==0 || isVowel(z + 1);
155379}
155380static int isVowel(const char *z){
155381  int j;
155382  char x = *z;
155383  if( x==0 ) return 0;
155384  assert( x>='a' && x<='z' );
155385  j = cType[x-'a'];
155386  if( j<2 ) return 1-j;
155387  return isConsonant(z + 1);
155388}
155389
155390/*
155391** Let any sequence of one or more vowels be represented by V and let
155392** C be sequence of one or more consonants.  Then every word can be
155393** represented as:
155394**
155395**           [C] (VC){m} [V]
155396**
155397** In prose:  A word is an optional consonant followed by zero or
155398** vowel-consonant pairs followed by an optional vowel.  "m" is the
155399** number of vowel consonant pairs.  This routine computes the value
155400** of m for the first i bytes of a word.
155401**
155402** Return true if the m-value for z is 1 or more.  In other words,
155403** return true if z contains at least one vowel that is followed
155404** by a consonant.
155405**
155406** In this routine z[] is in reverse order.  So we are really looking
155407** for an instance of a consonant followed by a vowel.
155408*/
155409static int m_gt_0(const char *z){
155410  while( isVowel(z) ){ z++; }
155411  if( *z==0 ) return 0;
155412  while( isConsonant(z) ){ z++; }
155413  return *z!=0;
155414}
155415
155416/* Like mgt0 above except we are looking for a value of m which is
155417** exactly 1
155418*/
155419static int m_eq_1(const char *z){
155420  while( isVowel(z) ){ z++; }
155421  if( *z==0 ) return 0;
155422  while( isConsonant(z) ){ z++; }
155423  if( *z==0 ) return 0;
155424  while( isVowel(z) ){ z++; }
155425  if( *z==0 ) return 1;
155426  while( isConsonant(z) ){ z++; }
155427  return *z==0;
155428}
155429
155430/* Like mgt0 above except we are looking for a value of m>1 instead
155431** or m>0
155432*/
155433static int m_gt_1(const char *z){
155434  while( isVowel(z) ){ z++; }
155435  if( *z==0 ) return 0;
155436  while( isConsonant(z) ){ z++; }
155437  if( *z==0 ) return 0;
155438  while( isVowel(z) ){ z++; }
155439  if( *z==0 ) return 0;
155440  while( isConsonant(z) ){ z++; }
155441  return *z!=0;
155442}
155443
155444/*
155445** Return TRUE if there is a vowel anywhere within z[0..n-1]
155446*/
155447static int hasVowel(const char *z){
155448  while( isConsonant(z) ){ z++; }
155449  return *z!=0;
155450}
155451
155452/*
155453** Return TRUE if the word ends in a double consonant.
155454**
155455** The text is reversed here. So we are really looking at
155456** the first two characters of z[].
155457*/
155458static int doubleConsonant(const char *z){
155459  return isConsonant(z) && z[0]==z[1];
155460}
155461
155462/*
155463** Return TRUE if the word ends with three letters which
155464** are consonant-vowel-consonent and where the final consonant
155465** is not 'w', 'x', or 'y'.
155466**
155467** The word is reversed here.  So we are really checking the
155468** first three letters and the first one cannot be in [wxy].
155469*/
155470static int star_oh(const char *z){
155471  return
155472    isConsonant(z) &&
155473    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
155474    isVowel(z+1) &&
155475    isConsonant(z+2);
155476}
155477
155478/*
155479** If the word ends with zFrom and xCond() is true for the stem
155480** of the word that preceeds the zFrom ending, then change the
155481** ending to zTo.
155482**
155483** The input word *pz and zFrom are both in reverse order.  zTo
155484** is in normal order.
155485**
155486** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
155487** match.  Not that TRUE is returned even if xCond() fails and
155488** no substitution occurs.
155489*/
155490static int stem(
155491  char **pz,             /* The word being stemmed (Reversed) */
155492  const char *zFrom,     /* If the ending matches this... (Reversed) */
155493  const char *zTo,       /* ... change the ending to this (not reversed) */
155494  int (*xCond)(const char*)   /* Condition that must be true */
155495){
155496  char *z = *pz;
155497  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
155498  if( *zFrom!=0 ) return 0;
155499  if( xCond && !xCond(z) ) return 1;
155500  while( *zTo ){
155501    *(--z) = *(zTo++);
155502  }
155503  *pz = z;
155504  return 1;
155505}
155506
155507/*
155508** This is the fallback stemmer used when the porter stemmer is
155509** inappropriate.  The input word is copied into the output with
155510** US-ASCII case folding.  If the input word is too long (more
155511** than 20 bytes if it contains no digits or more than 6 bytes if
155512** it contains digits) then word is truncated to 20 or 6 bytes
155513** by taking 10 or 3 bytes from the beginning and end.
155514*/
155515static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
155516  int i, mx, j;
155517  int hasDigit = 0;
155518  for(i=0; i<nIn; i++){
155519    char c = zIn[i];
155520    if( c>='A' && c<='Z' ){
155521      zOut[i] = c - 'A' + 'a';
155522    }else{
155523      if( c>='0' && c<='9' ) hasDigit = 1;
155524      zOut[i] = c;
155525    }
155526  }
155527  mx = hasDigit ? 3 : 10;
155528  if( nIn>mx*2 ){
155529    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
155530      zOut[j] = zOut[i];
155531    }
155532    i = j;
155533  }
155534  zOut[i] = 0;
155535  *pnOut = i;
155536}
155537
155538
155539/*
155540** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
155541** zOut is at least big enough to hold nIn bytes.  Write the actual
155542** size of the output word (exclusive of the '\0' terminator) into *pnOut.
155543**
155544** Any upper-case characters in the US-ASCII character set ([A-Z])
155545** are converted to lower case.  Upper-case UTF characters are
155546** unchanged.
155547**
155548** Words that are longer than about 20 bytes are stemmed by retaining
155549** a few bytes from the beginning and the end of the word.  If the
155550** word contains digits, 3 bytes are taken from the beginning and
155551** 3 bytes from the end.  For long words without digits, 10 bytes
155552** are taken from each end.  US-ASCII case folding still applies.
155553**
155554** If the input word contains not digits but does characters not
155555** in [a-zA-Z] then no stemming is attempted and this routine just
155556** copies the input into the input into the output with US-ASCII
155557** case folding.
155558**
155559** Stemming never increases the length of the word.  So there is
155560** no chance of overflowing the zOut buffer.
155561*/
155562static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
155563  int i, j;
155564  char zReverse[28];
155565  char *z, *z2;
155566  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
155567    /* The word is too big or too small for the porter stemmer.
155568    ** Fallback to the copy stemmer */
155569    copy_stemmer(zIn, nIn, zOut, pnOut);
155570    return;
155571  }
155572  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
155573    char c = zIn[i];
155574    if( c>='A' && c<='Z' ){
155575      zReverse[j] = c + 'a' - 'A';
155576    }else if( c>='a' && c<='z' ){
155577      zReverse[j] = c;
155578    }else{
155579      /* The use of a character not in [a-zA-Z] means that we fallback
155580      ** to the copy stemmer */
155581      copy_stemmer(zIn, nIn, zOut, pnOut);
155582      return;
155583    }
155584  }
155585  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
155586  z = &zReverse[j+1];
155587
155588
155589  /* Step 1a */
155590  if( z[0]=='s' ){
155591    if(
155592     !stem(&z, "sess", "ss", 0) &&
155593     !stem(&z, "sei", "i", 0)  &&
155594     !stem(&z, "ss", "ss", 0)
155595    ){
155596      z++;
155597    }
155598  }
155599
155600  /* Step 1b */
155601  z2 = z;
155602  if( stem(&z, "dee", "ee", m_gt_0) ){
155603    /* Do nothing.  The work was all in the test */
155604  }else if(
155605     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
155606      && z!=z2
155607  ){
155608     if( stem(&z, "ta", "ate", 0) ||
155609         stem(&z, "lb", "ble", 0) ||
155610         stem(&z, "zi", "ize", 0) ){
155611       /* Do nothing.  The work was all in the test */
155612     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
155613       z++;
155614     }else if( m_eq_1(z) && star_oh(z) ){
155615       *(--z) = 'e';
155616     }
155617  }
155618
155619  /* Step 1c */
155620  if( z[0]=='y' && hasVowel(z+1) ){
155621    z[0] = 'i';
155622  }
155623
155624  /* Step 2 */
155625  switch( z[1] ){
155626   case 'a':
155627     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
155628       stem(&z, "lanoit", "tion", m_gt_0);
155629     }
155630     break;
155631   case 'c':
155632     if( !stem(&z, "icne", "ence", m_gt_0) ){
155633       stem(&z, "icna", "ance", m_gt_0);
155634     }
155635     break;
155636   case 'e':
155637     stem(&z, "rezi", "ize", m_gt_0);
155638     break;
155639   case 'g':
155640     stem(&z, "igol", "log", m_gt_0);
155641     break;
155642   case 'l':
155643     if( !stem(&z, "ilb", "ble", m_gt_0)
155644      && !stem(&z, "illa", "al", m_gt_0)
155645      && !stem(&z, "iltne", "ent", m_gt_0)
155646      && !stem(&z, "ile", "e", m_gt_0)
155647     ){
155648       stem(&z, "ilsuo", "ous", m_gt_0);
155649     }
155650     break;
155651   case 'o':
155652     if( !stem(&z, "noitazi", "ize", m_gt_0)
155653      && !stem(&z, "noita", "ate", m_gt_0)
155654     ){
155655       stem(&z, "rota", "ate", m_gt_0);
155656     }
155657     break;
155658   case 's':
155659     if( !stem(&z, "msila", "al", m_gt_0)
155660      && !stem(&z, "ssenevi", "ive", m_gt_0)
155661      && !stem(&z, "ssenluf", "ful", m_gt_0)
155662     ){
155663       stem(&z, "ssensuo", "ous", m_gt_0);
155664     }
155665     break;
155666   case 't':
155667     if( !stem(&z, "itila", "al", m_gt_0)
155668      && !stem(&z, "itivi", "ive", m_gt_0)
155669     ){
155670       stem(&z, "itilib", "ble", m_gt_0);
155671     }
155672     break;
155673  }
155674
155675  /* Step 3 */
155676  switch( z[0] ){
155677   case 'e':
155678     if( !stem(&z, "etaci", "ic", m_gt_0)
155679      && !stem(&z, "evita", "", m_gt_0)
155680     ){
155681       stem(&z, "ezila", "al", m_gt_0);
155682     }
155683     break;
155684   case 'i':
155685     stem(&z, "itici", "ic", m_gt_0);
155686     break;
155687   case 'l':
155688     if( !stem(&z, "laci", "ic", m_gt_0) ){
155689       stem(&z, "luf", "", m_gt_0);
155690     }
155691     break;
155692   case 's':
155693     stem(&z, "ssen", "", m_gt_0);
155694     break;
155695  }
155696
155697  /* Step 4 */
155698  switch( z[1] ){
155699   case 'a':
155700     if( z[0]=='l' && m_gt_1(z+2) ){
155701       z += 2;
155702     }
155703     break;
155704   case 'c':
155705     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
155706       z += 4;
155707     }
155708     break;
155709   case 'e':
155710     if( z[0]=='r' && m_gt_1(z+2) ){
155711       z += 2;
155712     }
155713     break;
155714   case 'i':
155715     if( z[0]=='c' && m_gt_1(z+2) ){
155716       z += 2;
155717     }
155718     break;
155719   case 'l':
155720     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
155721       z += 4;
155722     }
155723     break;
155724   case 'n':
155725     if( z[0]=='t' ){
155726       if( z[2]=='a' ){
155727         if( m_gt_1(z+3) ){
155728           z += 3;
155729         }
155730       }else if( z[2]=='e' ){
155731         if( !stem(&z, "tneme", "", m_gt_1)
155732          && !stem(&z, "tnem", "", m_gt_1)
155733         ){
155734           stem(&z, "tne", "", m_gt_1);
155735         }
155736       }
155737     }
155738     break;
155739   case 'o':
155740     if( z[0]=='u' ){
155741       if( m_gt_1(z+2) ){
155742         z += 2;
155743       }
155744     }else if( z[3]=='s' || z[3]=='t' ){
155745       stem(&z, "noi", "", m_gt_1);
155746     }
155747     break;
155748   case 's':
155749     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
155750       z += 3;
155751     }
155752     break;
155753   case 't':
155754     if( !stem(&z, "eta", "", m_gt_1) ){
155755       stem(&z, "iti", "", m_gt_1);
155756     }
155757     break;
155758   case 'u':
155759     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
155760       z += 3;
155761     }
155762     break;
155763   case 'v':
155764   case 'z':
155765     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
155766       z += 3;
155767     }
155768     break;
155769  }
155770
155771  /* Step 5a */
155772  if( z[0]=='e' ){
155773    if( m_gt_1(z+1) ){
155774      z++;
155775    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
155776      z++;
155777    }
155778  }
155779
155780  /* Step 5b */
155781  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
155782    z++;
155783  }
155784
155785  /* z[] is now the stemmed word in reverse order.  Flip it back
155786  ** around into forward order and return.
155787  */
155788  *pnOut = i = (int)strlen(z);
155789  zOut[i] = 0;
155790  while( *z ){
155791    zOut[--i] = *(z++);
155792  }
155793}
155794
155795/*
155796** Characters that can be part of a token.  We assume any character
155797** whose value is greater than 0x80 (any UTF character) can be
155798** part of a token.  In other words, delimiters all must have
155799** values of 0x7f or lower.
155800*/
155801static const char porterIdChar[] = {
155802/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
155803    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
155804    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
155805    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
155806    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
155807    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
155808};
155809#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
155810
155811/*
155812** Extract the next token from a tokenization cursor.  The cursor must
155813** have been opened by a prior call to porterOpen().
155814*/
155815static int porterNext(
155816  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
155817  const char **pzToken,               /* OUT: *pzToken is the token text */
155818  int *pnBytes,                       /* OUT: Number of bytes in token */
155819  int *piStartOffset,                 /* OUT: Starting offset of token */
155820  int *piEndOffset,                   /* OUT: Ending offset of token */
155821  int *piPosition                     /* OUT: Position integer of token */
155822){
155823  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
155824  const char *z = c->zInput;
155825
155826  while( c->iOffset<c->nInput ){
155827    int iStartOffset, ch;
155828
155829    /* Scan past delimiter characters */
155830    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
155831      c->iOffset++;
155832    }
155833
155834    /* Count non-delimiter characters. */
155835    iStartOffset = c->iOffset;
155836    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
155837      c->iOffset++;
155838    }
155839
155840    if( c->iOffset>iStartOffset ){
155841      int n = c->iOffset-iStartOffset;
155842      if( n>c->nAllocated ){
155843        char *pNew;
155844        c->nAllocated = n+20;
155845        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
155846        if( !pNew ) return SQLITE_NOMEM;
155847        c->zToken = pNew;
155848      }
155849      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
155850      *pzToken = c->zToken;
155851      *piStartOffset = iStartOffset;
155852      *piEndOffset = c->iOffset;
155853      *piPosition = c->iToken++;
155854      return SQLITE_OK;
155855    }
155856  }
155857  return SQLITE_DONE;
155858}
155859
155860/*
155861** The set of routines that implement the porter-stemmer tokenizer
155862*/
155863static const sqlite3_tokenizer_module porterTokenizerModule = {
155864  0,
155865  porterCreate,
155866  porterDestroy,
155867  porterOpen,
155868  porterClose,
155869  porterNext,
155870  0
155871};
155872
155873/*
155874** Allocate a new porter tokenizer.  Return a pointer to the new
155875** tokenizer in *ppModule
155876*/
155877SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
155878  sqlite3_tokenizer_module const**ppModule
155879){
155880  *ppModule = &porterTokenizerModule;
155881}
155882
155883#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
155884
155885/************** End of fts3_porter.c *****************************************/
155886/************** Begin file fts3_tokenizer.c **********************************/
155887/*
155888** 2007 June 22
155889**
155890** The author disclaims copyright to this source code.  In place of
155891** a legal notice, here is a blessing:
155892**
155893**    May you do good and not evil.
155894**    May you find forgiveness for yourself and forgive others.
155895**    May you share freely, never taking more than you give.
155896**
155897******************************************************************************
155898**
155899** This is part of an SQLite module implementing full-text search.
155900** This particular file implements the generic tokenizer interface.
155901*/
155902
155903/*
155904** The code in this file is only compiled if:
155905**
155906**     * The FTS3 module is being built as an extension
155907**       (in which case SQLITE_CORE is not defined), or
155908**
155909**     * The FTS3 module is being built into the core of
155910**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
155911*/
155912/* #include "fts3Int.h" */
155913#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
155914
155915/* #include <assert.h> */
155916/* #include <string.h> */
155917
155918/*
155919** Return true if the two-argument version of fts3_tokenizer()
155920** has been activated via a prior call to sqlite3_db_config(db,
155921** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
155922*/
155923static int fts3TokenizerEnabled(sqlite3_context *context){
155924  sqlite3 *db = sqlite3_context_db_handle(context);
155925  int isEnabled = 0;
155926  sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
155927  return isEnabled;
155928}
155929
155930/*
155931** Implementation of the SQL scalar function for accessing the underlying
155932** hash table. This function may be called as follows:
155933**
155934**   SELECT <function-name>(<key-name>);
155935**   SELECT <function-name>(<key-name>, <pointer>);
155936**
155937** where <function-name> is the name passed as the second argument
155938** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
155939**
155940** If the <pointer> argument is specified, it must be a blob value
155941** containing a pointer to be stored as the hash data corresponding
155942** to the string <key-name>. If <pointer> is not specified, then
155943** the string <key-name> must already exist in the has table. Otherwise,
155944** an error is returned.
155945**
155946** Whether or not the <pointer> argument is specified, the value returned
155947** is a blob containing the pointer stored as the hash data corresponding
155948** to string <key-name> (after the hash-table is updated, if applicable).
155949*/
155950static void fts3TokenizerFunc(
155951  sqlite3_context *context,
155952  int argc,
155953  sqlite3_value **argv
155954){
155955  Fts3Hash *pHash;
155956  void *pPtr = 0;
155957  const unsigned char *zName;
155958  int nName;
155959
155960  assert( argc==1 || argc==2 );
155961
155962  pHash = (Fts3Hash *)sqlite3_user_data(context);
155963
155964  zName = sqlite3_value_text(argv[0]);
155965  nName = sqlite3_value_bytes(argv[0])+1;
155966
155967  if( argc==2 ){
155968    if( fts3TokenizerEnabled(context) ){
155969      void *pOld;
155970      int n = sqlite3_value_bytes(argv[1]);
155971      if( zName==0 || n!=sizeof(pPtr) ){
155972        sqlite3_result_error(context, "argument type mismatch", -1);
155973        return;
155974      }
155975      pPtr = *(void **)sqlite3_value_blob(argv[1]);
155976      pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
155977      if( pOld==pPtr ){
155978        sqlite3_result_error(context, "out of memory", -1);
155979      }
155980    }else{
155981      sqlite3_result_error(context, "fts3tokenize disabled", -1);
155982      return;
155983    }
155984  }else{
155985    if( zName ){
155986      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
155987    }
155988    if( !pPtr ){
155989      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
155990      sqlite3_result_error(context, zErr, -1);
155991      sqlite3_free(zErr);
155992      return;
155993    }
155994  }
155995  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
155996}
155997
155998SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
155999  static const char isFtsIdChar[] = {
156000      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
156001      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
156002      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
156003      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
156004      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
156005      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
156006      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
156007      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
156008  };
156009  return (c&0x80 || isFtsIdChar[(int)(c)]);
156010}
156011
156012SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
156013  const char *z1;
156014  const char *z2 = 0;
156015
156016  /* Find the start of the next token. */
156017  z1 = zStr;
156018  while( z2==0 ){
156019    char c = *z1;
156020    switch( c ){
156021      case '\0': return 0;        /* No more tokens here */
156022      case '\'':
156023      case '"':
156024      case '`': {
156025        z2 = z1;
156026        while( *++z2 && (*z2!=c || *++z2==c) );
156027        break;
156028      }
156029      case '[':
156030        z2 = &z1[1];
156031        while( *z2 && z2[0]!=']' ) z2++;
156032        if( *z2 ) z2++;
156033        break;
156034
156035      default:
156036        if( sqlite3Fts3IsIdChar(*z1) ){
156037          z2 = &z1[1];
156038          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
156039        }else{
156040          z1++;
156041        }
156042    }
156043  }
156044
156045  *pn = (int)(z2-z1);
156046  return z1;
156047}
156048
156049SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
156050  Fts3Hash *pHash,                /* Tokenizer hash table */
156051  const char *zArg,               /* Tokenizer name */
156052  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
156053  char **pzErr                    /* OUT: Set to malloced error message */
156054){
156055  int rc;
156056  char *z = (char *)zArg;
156057  int n = 0;
156058  char *zCopy;
156059  char *zEnd;                     /* Pointer to nul-term of zCopy */
156060  sqlite3_tokenizer_module *m;
156061
156062  zCopy = sqlite3_mprintf("%s", zArg);
156063  if( !zCopy ) return SQLITE_NOMEM;
156064  zEnd = &zCopy[strlen(zCopy)];
156065
156066  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
156067  if( z==0 ){
156068    assert( n==0 );
156069    z = zCopy;
156070  }
156071  z[n] = '\0';
156072  sqlite3Fts3Dequote(z);
156073
156074  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
156075  if( !m ){
156076    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
156077    rc = SQLITE_ERROR;
156078  }else{
156079    char const **aArg = 0;
156080    int iArg = 0;
156081    z = &z[n+1];
156082    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
156083      int nNew = sizeof(char *)*(iArg+1);
156084      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
156085      if( !aNew ){
156086        sqlite3_free(zCopy);
156087        sqlite3_free((void *)aArg);
156088        return SQLITE_NOMEM;
156089      }
156090      aArg = aNew;
156091      aArg[iArg++] = z;
156092      z[n] = '\0';
156093      sqlite3Fts3Dequote(z);
156094      z = &z[n+1];
156095    }
156096    rc = m->xCreate(iArg, aArg, ppTok);
156097    assert( rc!=SQLITE_OK || *ppTok );
156098    if( rc!=SQLITE_OK ){
156099      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
156100    }else{
156101      (*ppTok)->pModule = m;
156102    }
156103    sqlite3_free((void *)aArg);
156104  }
156105
156106  sqlite3_free(zCopy);
156107  return rc;
156108}
156109
156110
156111#ifdef SQLITE_TEST
156112
156113#if defined(INCLUDE_SQLITE_TCL_H)
156114#  include "sqlite_tcl.h"
156115#else
156116#  include "tcl.h"
156117#endif
156118/* #include <string.h> */
156119
156120/*
156121** Implementation of a special SQL scalar function for testing tokenizers
156122** designed to be used in concert with the Tcl testing framework. This
156123** function must be called with two or more arguments:
156124**
156125**   SELECT <function-name>(<key-name>, ..., <input-string>);
156126**
156127** where <function-name> is the name passed as the second argument
156128** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
156129** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
156130**
156131** The return value is a string that may be interpreted as a Tcl
156132** list. For each token in the <input-string>, three elements are
156133** added to the returned list. The first is the token position, the
156134** second is the token text (folded, stemmed, etc.) and the third is the
156135** substring of <input-string> associated with the token. For example,
156136** using the built-in "simple" tokenizer:
156137**
156138**   SELECT fts_tokenizer_test('simple', 'I don't see how');
156139**
156140** will return the string:
156141**
156142**   "{0 i I 1 dont don't 2 see see 3 how how}"
156143**
156144*/
156145static void testFunc(
156146  sqlite3_context *context,
156147  int argc,
156148  sqlite3_value **argv
156149){
156150  Fts3Hash *pHash;
156151  sqlite3_tokenizer_module *p;
156152  sqlite3_tokenizer *pTokenizer = 0;
156153  sqlite3_tokenizer_cursor *pCsr = 0;
156154
156155  const char *zErr = 0;
156156
156157  const char *zName;
156158  int nName;
156159  const char *zInput;
156160  int nInput;
156161
156162  const char *azArg[64];
156163
156164  const char *zToken;
156165  int nToken = 0;
156166  int iStart = 0;
156167  int iEnd = 0;
156168  int iPos = 0;
156169  int i;
156170
156171  Tcl_Obj *pRet;
156172
156173  if( argc<2 ){
156174    sqlite3_result_error(context, "insufficient arguments", -1);
156175    return;
156176  }
156177
156178  nName = sqlite3_value_bytes(argv[0]);
156179  zName = (const char *)sqlite3_value_text(argv[0]);
156180  nInput = sqlite3_value_bytes(argv[argc-1]);
156181  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
156182
156183  pHash = (Fts3Hash *)sqlite3_user_data(context);
156184  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
156185
156186  if( !p ){
156187    char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
156188    sqlite3_result_error(context, zErr2, -1);
156189    sqlite3_free(zErr2);
156190    return;
156191  }
156192
156193  pRet = Tcl_NewObj();
156194  Tcl_IncrRefCount(pRet);
156195
156196  for(i=1; i<argc-1; i++){
156197    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
156198  }
156199
156200  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
156201    zErr = "error in xCreate()";
156202    goto finish;
156203  }
156204  pTokenizer->pModule = p;
156205  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
156206    zErr = "error in xOpen()";
156207    goto finish;
156208  }
156209
156210  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
156211    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
156212    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
156213    zToken = &zInput[iStart];
156214    nToken = iEnd-iStart;
156215    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
156216  }
156217
156218  if( SQLITE_OK!=p->xClose(pCsr) ){
156219    zErr = "error in xClose()";
156220    goto finish;
156221  }
156222  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
156223    zErr = "error in xDestroy()";
156224    goto finish;
156225  }
156226
156227finish:
156228  if( zErr ){
156229    sqlite3_result_error(context, zErr, -1);
156230  }else{
156231    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
156232  }
156233  Tcl_DecrRefCount(pRet);
156234}
156235
156236static
156237int registerTokenizer(
156238  sqlite3 *db,
156239  char *zName,
156240  const sqlite3_tokenizer_module *p
156241){
156242  int rc;
156243  sqlite3_stmt *pStmt;
156244  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
156245
156246  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
156247  if( rc!=SQLITE_OK ){
156248    return rc;
156249  }
156250
156251  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
156252  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
156253  sqlite3_step(pStmt);
156254
156255  return sqlite3_finalize(pStmt);
156256}
156257
156258
156259static
156260int queryTokenizer(
156261  sqlite3 *db,
156262  char *zName,
156263  const sqlite3_tokenizer_module **pp
156264){
156265  int rc;
156266  sqlite3_stmt *pStmt;
156267  const char zSql[] = "SELECT fts3_tokenizer(?)";
156268
156269  *pp = 0;
156270  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
156271  if( rc!=SQLITE_OK ){
156272    return rc;
156273  }
156274
156275  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
156276  if( SQLITE_ROW==sqlite3_step(pStmt) ){
156277    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
156278      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
156279    }
156280  }
156281
156282  return sqlite3_finalize(pStmt);
156283}
156284
156285SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
156286
156287/*
156288** Implementation of the scalar function fts3_tokenizer_internal_test().
156289** This function is used for testing only, it is not included in the
156290** build unless SQLITE_TEST is defined.
156291**
156292** The purpose of this is to test that the fts3_tokenizer() function
156293** can be used as designed by the C-code in the queryTokenizer and
156294** registerTokenizer() functions above. These two functions are repeated
156295** in the README.tokenizer file as an example, so it is important to
156296** test them.
156297**
156298** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
156299** function with no arguments. An assert() will fail if a problem is
156300** detected. i.e.:
156301**
156302**     SELECT fts3_tokenizer_internal_test();
156303**
156304*/
156305static void intTestFunc(
156306  sqlite3_context *context,
156307  int argc,
156308  sqlite3_value **argv
156309){
156310  int rc;
156311  const sqlite3_tokenizer_module *p1;
156312  const sqlite3_tokenizer_module *p2;
156313  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
156314
156315  UNUSED_PARAMETER(argc);
156316  UNUSED_PARAMETER(argv);
156317
156318  /* Test the query function */
156319  sqlite3Fts3SimpleTokenizerModule(&p1);
156320  rc = queryTokenizer(db, "simple", &p2);
156321  assert( rc==SQLITE_OK );
156322  assert( p1==p2 );
156323  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
156324  assert( rc==SQLITE_ERROR );
156325  assert( p2==0 );
156326  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
156327
156328  /* Test the storage function */
156329  if( fts3TokenizerEnabled(context) ){
156330    rc = registerTokenizer(db, "nosuchtokenizer", p1);
156331    assert( rc==SQLITE_OK );
156332    rc = queryTokenizer(db, "nosuchtokenizer", &p2);
156333    assert( rc==SQLITE_OK );
156334    assert( p2==p1 );
156335  }
156336
156337  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
156338}
156339
156340#endif
156341
156342/*
156343** Set up SQL objects in database db used to access the contents of
156344** the hash table pointed to by argument pHash. The hash table must
156345** been initialized to use string keys, and to take a private copy
156346** of the key when a value is inserted. i.e. by a call similar to:
156347**
156348**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
156349**
156350** This function adds a scalar function (see header comment above
156351** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
156352** defined at compilation time, a temporary virtual table (see header
156353** comment above struct HashTableVtab) to the database schema. Both
156354** provide read/write access to the contents of *pHash.
156355**
156356** The third argument to this function, zName, is used as the name
156357** of both the scalar and, if created, the virtual table.
156358*/
156359SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
156360  sqlite3 *db,
156361  Fts3Hash *pHash,
156362  const char *zName
156363){
156364  int rc = SQLITE_OK;
156365  void *p = (void *)pHash;
156366  const int any = SQLITE_ANY;
156367
156368#ifdef SQLITE_TEST
156369  char *zTest = 0;
156370  char *zTest2 = 0;
156371  void *pdb = (void *)db;
156372  zTest = sqlite3_mprintf("%s_test", zName);
156373  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
156374  if( !zTest || !zTest2 ){
156375    rc = SQLITE_NOMEM;
156376  }
156377#endif
156378
156379  if( SQLITE_OK==rc ){
156380    rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
156381  }
156382  if( SQLITE_OK==rc ){
156383    rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
156384  }
156385#ifdef SQLITE_TEST
156386  if( SQLITE_OK==rc ){
156387    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
156388  }
156389  if( SQLITE_OK==rc ){
156390    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
156391  }
156392#endif
156393
156394#ifdef SQLITE_TEST
156395  sqlite3_free(zTest);
156396  sqlite3_free(zTest2);
156397#endif
156398
156399  return rc;
156400}
156401
156402#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
156403
156404/************** End of fts3_tokenizer.c **************************************/
156405/************** Begin file fts3_tokenizer1.c *********************************/
156406/*
156407** 2006 Oct 10
156408**
156409** The author disclaims copyright to this source code.  In place of
156410** a legal notice, here is a blessing:
156411**
156412**    May you do good and not evil.
156413**    May you find forgiveness for yourself and forgive others.
156414**    May you share freely, never taking more than you give.
156415**
156416******************************************************************************
156417**
156418** Implementation of the "simple" full-text-search tokenizer.
156419*/
156420
156421/*
156422** The code in this file is only compiled if:
156423**
156424**     * The FTS3 module is being built as an extension
156425**       (in which case SQLITE_CORE is not defined), or
156426**
156427**     * The FTS3 module is being built into the core of
156428**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
156429*/
156430/* #include "fts3Int.h" */
156431#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
156432
156433/* #include <assert.h> */
156434/* #include <stdlib.h> */
156435/* #include <stdio.h> */
156436/* #include <string.h> */
156437
156438/* #include "fts3_tokenizer.h" */
156439
156440typedef struct simple_tokenizer {
156441  sqlite3_tokenizer base;
156442  char delim[128];             /* flag ASCII delimiters */
156443} simple_tokenizer;
156444
156445typedef struct simple_tokenizer_cursor {
156446  sqlite3_tokenizer_cursor base;
156447  const char *pInput;          /* input we are tokenizing */
156448  int nBytes;                  /* size of the input */
156449  int iOffset;                 /* current position in pInput */
156450  int iToken;                  /* index of next token to be returned */
156451  char *pToken;                /* storage for current token */
156452  int nTokenAllocated;         /* space allocated to zToken buffer */
156453} simple_tokenizer_cursor;
156454
156455
156456static int simpleDelim(simple_tokenizer *t, unsigned char c){
156457  return c<0x80 && t->delim[c];
156458}
156459static int fts3_isalnum(int x){
156460  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
156461}
156462
156463/*
156464** Create a new tokenizer instance.
156465*/
156466static int simpleCreate(
156467  int argc, const char * const *argv,
156468  sqlite3_tokenizer **ppTokenizer
156469){
156470  simple_tokenizer *t;
156471
156472  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
156473  if( t==NULL ) return SQLITE_NOMEM;
156474  memset(t, 0, sizeof(*t));
156475
156476  /* TODO(shess) Delimiters need to remain the same from run to run,
156477  ** else we need to reindex.  One solution would be a meta-table to
156478  ** track such information in the database, then we'd only want this
156479  ** information on the initial create.
156480  */
156481  if( argc>1 ){
156482    int i, n = (int)strlen(argv[1]);
156483    for(i=0; i<n; i++){
156484      unsigned char ch = argv[1][i];
156485      /* We explicitly don't support UTF-8 delimiters for now. */
156486      if( ch>=0x80 ){
156487        sqlite3_free(t);
156488        return SQLITE_ERROR;
156489      }
156490      t->delim[ch] = 1;
156491    }
156492  } else {
156493    /* Mark non-alphanumeric ASCII characters as delimiters */
156494    int i;
156495    for(i=1; i<0x80; i++){
156496      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
156497    }
156498  }
156499
156500  *ppTokenizer = &t->base;
156501  return SQLITE_OK;
156502}
156503
156504/*
156505** Destroy a tokenizer
156506*/
156507static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
156508  sqlite3_free(pTokenizer);
156509  return SQLITE_OK;
156510}
156511
156512/*
156513** Prepare to begin tokenizing a particular string.  The input
156514** string to be tokenized is pInput[0..nBytes-1].  A cursor
156515** used to incrementally tokenize this string is returned in
156516** *ppCursor.
156517*/
156518static int simpleOpen(
156519  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
156520  const char *pInput, int nBytes,        /* String to be tokenized */
156521  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
156522){
156523  simple_tokenizer_cursor *c;
156524
156525  UNUSED_PARAMETER(pTokenizer);
156526
156527  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
156528  if( c==NULL ) return SQLITE_NOMEM;
156529
156530  c->pInput = pInput;
156531  if( pInput==0 ){
156532    c->nBytes = 0;
156533  }else if( nBytes<0 ){
156534    c->nBytes = (int)strlen(pInput);
156535  }else{
156536    c->nBytes = nBytes;
156537  }
156538  c->iOffset = 0;                 /* start tokenizing at the beginning */
156539  c->iToken = 0;
156540  c->pToken = NULL;               /* no space allocated, yet. */
156541  c->nTokenAllocated = 0;
156542
156543  *ppCursor = &c->base;
156544  return SQLITE_OK;
156545}
156546
156547/*
156548** Close a tokenization cursor previously opened by a call to
156549** simpleOpen() above.
156550*/
156551static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
156552  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
156553  sqlite3_free(c->pToken);
156554  sqlite3_free(c);
156555  return SQLITE_OK;
156556}
156557
156558/*
156559** Extract the next token from a tokenization cursor.  The cursor must
156560** have been opened by a prior call to simpleOpen().
156561*/
156562static int simpleNext(
156563  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
156564  const char **ppToken,               /* OUT: *ppToken is the token text */
156565  int *pnBytes,                       /* OUT: Number of bytes in token */
156566  int *piStartOffset,                 /* OUT: Starting offset of token */
156567  int *piEndOffset,                   /* OUT: Ending offset of token */
156568  int *piPosition                     /* OUT: Position integer of token */
156569){
156570  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
156571  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
156572  unsigned char *p = (unsigned char *)c->pInput;
156573
156574  while( c->iOffset<c->nBytes ){
156575    int iStartOffset;
156576
156577    /* Scan past delimiter characters */
156578    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
156579      c->iOffset++;
156580    }
156581
156582    /* Count non-delimiter characters. */
156583    iStartOffset = c->iOffset;
156584    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
156585      c->iOffset++;
156586    }
156587
156588    if( c->iOffset>iStartOffset ){
156589      int i, n = c->iOffset-iStartOffset;
156590      if( n>c->nTokenAllocated ){
156591        char *pNew;
156592        c->nTokenAllocated = n+20;
156593        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
156594        if( !pNew ) return SQLITE_NOMEM;
156595        c->pToken = pNew;
156596      }
156597      for(i=0; i<n; i++){
156598        /* TODO(shess) This needs expansion to handle UTF-8
156599        ** case-insensitivity.
156600        */
156601        unsigned char ch = p[iStartOffset+i];
156602        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
156603      }
156604      *ppToken = c->pToken;
156605      *pnBytes = n;
156606      *piStartOffset = iStartOffset;
156607      *piEndOffset = c->iOffset;
156608      *piPosition = c->iToken++;
156609
156610      return SQLITE_OK;
156611    }
156612  }
156613  return SQLITE_DONE;
156614}
156615
156616/*
156617** The set of routines that implement the simple tokenizer
156618*/
156619static const sqlite3_tokenizer_module simpleTokenizerModule = {
156620  0,
156621  simpleCreate,
156622  simpleDestroy,
156623  simpleOpen,
156624  simpleClose,
156625  simpleNext,
156626  0,
156627};
156628
156629/*
156630** Allocate a new simple tokenizer.  Return a pointer to the new
156631** tokenizer in *ppModule
156632*/
156633SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
156634  sqlite3_tokenizer_module const**ppModule
156635){
156636  *ppModule = &simpleTokenizerModule;
156637}
156638
156639#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
156640
156641/************** End of fts3_tokenizer1.c *************************************/
156642/************** Begin file fts3_tokenize_vtab.c ******************************/
156643/*
156644** 2013 Apr 22
156645**
156646** The author disclaims copyright to this source code.  In place of
156647** a legal notice, here is a blessing:
156648**
156649**    May you do good and not evil.
156650**    May you find forgiveness for yourself and forgive others.
156651**    May you share freely, never taking more than you give.
156652**
156653******************************************************************************
156654**
156655** This file contains code for the "fts3tokenize" virtual table module.
156656** An fts3tokenize virtual table is created as follows:
156657**
156658**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
156659**       <tokenizer-name>, <arg-1>, ...
156660**   );
156661**
156662** The table created has the following schema:
156663**
156664**   CREATE TABLE <tbl>(input, token, start, end, position)
156665**
156666** When queried, the query must include a WHERE clause of type:
156667**
156668**   input = <string>
156669**
156670** The virtual table module tokenizes this <string>, using the FTS3
156671** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
156672** statement and returns one row for each token in the result. With
156673** fields set as follows:
156674**
156675**   input:   Always set to a copy of <string>
156676**   token:   A token from the input.
156677**   start:   Byte offset of the token within the input <string>.
156678**   end:     Byte offset of the byte immediately following the end of the
156679**            token within the input string.
156680**   pos:     Token offset of token within input.
156681**
156682*/
156683/* #include "fts3Int.h" */
156684#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
156685
156686/* #include <string.h> */
156687/* #include <assert.h> */
156688
156689typedef struct Fts3tokTable Fts3tokTable;
156690typedef struct Fts3tokCursor Fts3tokCursor;
156691
156692/*
156693** Virtual table structure.
156694*/
156695struct Fts3tokTable {
156696  sqlite3_vtab base;              /* Base class used by SQLite core */
156697  const sqlite3_tokenizer_module *pMod;
156698  sqlite3_tokenizer *pTok;
156699};
156700
156701/*
156702** Virtual table cursor structure.
156703*/
156704struct Fts3tokCursor {
156705  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
156706  char *zInput;                   /* Input string */
156707  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
156708  int iRowid;                     /* Current 'rowid' value */
156709  const char *zToken;             /* Current 'token' value */
156710  int nToken;                     /* Size of zToken in bytes */
156711  int iStart;                     /* Current 'start' value */
156712  int iEnd;                       /* Current 'end' value */
156713  int iPos;                       /* Current 'pos' value */
156714};
156715
156716/*
156717** Query FTS for the tokenizer implementation named zName.
156718*/
156719static int fts3tokQueryTokenizer(
156720  Fts3Hash *pHash,
156721  const char *zName,
156722  const sqlite3_tokenizer_module **pp,
156723  char **pzErr
156724){
156725  sqlite3_tokenizer_module *p;
156726  int nName = (int)strlen(zName);
156727
156728  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
156729  if( !p ){
156730    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
156731    return SQLITE_ERROR;
156732  }
156733
156734  *pp = p;
156735  return SQLITE_OK;
156736}
156737
156738/*
156739** The second argument, argv[], is an array of pointers to nul-terminated
156740** strings. This function makes a copy of the array and strings into a
156741** single block of memory. It then dequotes any of the strings that appear
156742** to be quoted.
156743**
156744** If successful, output parameter *pazDequote is set to point at the
156745** array of dequoted strings and SQLITE_OK is returned. The caller is
156746** responsible for eventually calling sqlite3_free() to free the array
156747** in this case. Or, if an error occurs, an SQLite error code is returned.
156748** The final value of *pazDequote is undefined in this case.
156749*/
156750static int fts3tokDequoteArray(
156751  int argc,                       /* Number of elements in argv[] */
156752  const char * const *argv,       /* Input array */
156753  char ***pazDequote              /* Output array */
156754){
156755  int rc = SQLITE_OK;             /* Return code */
156756  if( argc==0 ){
156757    *pazDequote = 0;
156758  }else{
156759    int i;
156760    int nByte = 0;
156761    char **azDequote;
156762
156763    for(i=0; i<argc; i++){
156764      nByte += (int)(strlen(argv[i]) + 1);
156765    }
156766
156767    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
156768    if( azDequote==0 ){
156769      rc = SQLITE_NOMEM;
156770    }else{
156771      char *pSpace = (char *)&azDequote[argc];
156772      for(i=0; i<argc; i++){
156773        int n = (int)strlen(argv[i]);
156774        azDequote[i] = pSpace;
156775        memcpy(pSpace, argv[i], n+1);
156776        sqlite3Fts3Dequote(pSpace);
156777        pSpace += (n+1);
156778      }
156779    }
156780  }
156781
156782  return rc;
156783}
156784
156785/*
156786** Schema of the tokenizer table.
156787*/
156788#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
156789
156790/*
156791** This function does all the work for both the xConnect and xCreate methods.
156792** These tables have no persistent representation of their own, so xConnect
156793** and xCreate are identical operations.
156794**
156795**   argv[0]: module name
156796**   argv[1]: database name
156797**   argv[2]: table name
156798**   argv[3]: first argument (tokenizer name)
156799*/
156800static int fts3tokConnectMethod(
156801  sqlite3 *db,                    /* Database connection */
156802  void *pHash,                    /* Hash table of tokenizers */
156803  int argc,                       /* Number of elements in argv array */
156804  const char * const *argv,       /* xCreate/xConnect argument array */
156805  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
156806  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
156807){
156808  Fts3tokTable *pTab = 0;
156809  const sqlite3_tokenizer_module *pMod = 0;
156810  sqlite3_tokenizer *pTok = 0;
156811  int rc;
156812  char **azDequote = 0;
156813  int nDequote;
156814
156815  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
156816  if( rc!=SQLITE_OK ) return rc;
156817
156818  nDequote = argc-3;
156819  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
156820
156821  if( rc==SQLITE_OK ){
156822    const char *zModule;
156823    if( nDequote<1 ){
156824      zModule = "simple";
156825    }else{
156826      zModule = azDequote[0];
156827    }
156828    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
156829  }
156830
156831  assert( (rc==SQLITE_OK)==(pMod!=0) );
156832  if( rc==SQLITE_OK ){
156833    const char * const *azArg = (const char * const *)&azDequote[1];
156834    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
156835  }
156836
156837  if( rc==SQLITE_OK ){
156838    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
156839    if( pTab==0 ){
156840      rc = SQLITE_NOMEM;
156841    }
156842  }
156843
156844  if( rc==SQLITE_OK ){
156845    memset(pTab, 0, sizeof(Fts3tokTable));
156846    pTab->pMod = pMod;
156847    pTab->pTok = pTok;
156848    *ppVtab = &pTab->base;
156849  }else{
156850    if( pTok ){
156851      pMod->xDestroy(pTok);
156852    }
156853  }
156854
156855  sqlite3_free(azDequote);
156856  return rc;
156857}
156858
156859/*
156860** This function does the work for both the xDisconnect and xDestroy methods.
156861** These tables have no persistent representation of their own, so xDisconnect
156862** and xDestroy are identical operations.
156863*/
156864static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
156865  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
156866
156867  pTab->pMod->xDestroy(pTab->pTok);
156868  sqlite3_free(pTab);
156869  return SQLITE_OK;
156870}
156871
156872/*
156873** xBestIndex - Analyze a WHERE and ORDER BY clause.
156874*/
156875static int fts3tokBestIndexMethod(
156876  sqlite3_vtab *pVTab,
156877  sqlite3_index_info *pInfo
156878){
156879  int i;
156880  UNUSED_PARAMETER(pVTab);
156881
156882  for(i=0; i<pInfo->nConstraint; i++){
156883    if( pInfo->aConstraint[i].usable
156884     && pInfo->aConstraint[i].iColumn==0
156885     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
156886    ){
156887      pInfo->idxNum = 1;
156888      pInfo->aConstraintUsage[i].argvIndex = 1;
156889      pInfo->aConstraintUsage[i].omit = 1;
156890      pInfo->estimatedCost = 1;
156891      return SQLITE_OK;
156892    }
156893  }
156894
156895  pInfo->idxNum = 0;
156896  assert( pInfo->estimatedCost>1000000.0 );
156897
156898  return SQLITE_OK;
156899}
156900
156901/*
156902** xOpen - Open a cursor.
156903*/
156904static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
156905  Fts3tokCursor *pCsr;
156906  UNUSED_PARAMETER(pVTab);
156907
156908  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
156909  if( pCsr==0 ){
156910    return SQLITE_NOMEM;
156911  }
156912  memset(pCsr, 0, sizeof(Fts3tokCursor));
156913
156914  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
156915  return SQLITE_OK;
156916}
156917
156918/*
156919** Reset the tokenizer cursor passed as the only argument. As if it had
156920** just been returned by fts3tokOpenMethod().
156921*/
156922static void fts3tokResetCursor(Fts3tokCursor *pCsr){
156923  if( pCsr->pCsr ){
156924    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
156925    pTab->pMod->xClose(pCsr->pCsr);
156926    pCsr->pCsr = 0;
156927  }
156928  sqlite3_free(pCsr->zInput);
156929  pCsr->zInput = 0;
156930  pCsr->zToken = 0;
156931  pCsr->nToken = 0;
156932  pCsr->iStart = 0;
156933  pCsr->iEnd = 0;
156934  pCsr->iPos = 0;
156935  pCsr->iRowid = 0;
156936}
156937
156938/*
156939** xClose - Close a cursor.
156940*/
156941static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
156942  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
156943
156944  fts3tokResetCursor(pCsr);
156945  sqlite3_free(pCsr);
156946  return SQLITE_OK;
156947}
156948
156949/*
156950** xNext - Advance the cursor to the next row, if any.
156951*/
156952static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
156953  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
156954  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
156955  int rc;                         /* Return code */
156956
156957  pCsr->iRowid++;
156958  rc = pTab->pMod->xNext(pCsr->pCsr,
156959      &pCsr->zToken, &pCsr->nToken,
156960      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
156961  );
156962
156963  if( rc!=SQLITE_OK ){
156964    fts3tokResetCursor(pCsr);
156965    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
156966  }
156967
156968  return rc;
156969}
156970
156971/*
156972** xFilter - Initialize a cursor to point at the start of its data.
156973*/
156974static int fts3tokFilterMethod(
156975  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
156976  int idxNum,                     /* Strategy index */
156977  const char *idxStr,             /* Unused */
156978  int nVal,                       /* Number of elements in apVal */
156979  sqlite3_value **apVal           /* Arguments for the indexing scheme */
156980){
156981  int rc = SQLITE_ERROR;
156982  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
156983  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
156984  UNUSED_PARAMETER(idxStr);
156985  UNUSED_PARAMETER(nVal);
156986
156987  fts3tokResetCursor(pCsr);
156988  if( idxNum==1 ){
156989    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
156990    int nByte = sqlite3_value_bytes(apVal[0]);
156991    pCsr->zInput = sqlite3_malloc(nByte+1);
156992    if( pCsr->zInput==0 ){
156993      rc = SQLITE_NOMEM;
156994    }else{
156995      memcpy(pCsr->zInput, zByte, nByte);
156996      pCsr->zInput[nByte] = 0;
156997      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
156998      if( rc==SQLITE_OK ){
156999        pCsr->pCsr->pTokenizer = pTab->pTok;
157000      }
157001    }
157002  }
157003
157004  if( rc!=SQLITE_OK ) return rc;
157005  return fts3tokNextMethod(pCursor);
157006}
157007
157008/*
157009** xEof - Return true if the cursor is at EOF, or false otherwise.
157010*/
157011static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
157012  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157013  return (pCsr->zToken==0);
157014}
157015
157016/*
157017** xColumn - Return a column value.
157018*/
157019static int fts3tokColumnMethod(
157020  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
157021  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
157022  int iCol                        /* Index of column to read value from */
157023){
157024  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157025
157026  /* CREATE TABLE x(input, token, start, end, position) */
157027  switch( iCol ){
157028    case 0:
157029      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
157030      break;
157031    case 1:
157032      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
157033      break;
157034    case 2:
157035      sqlite3_result_int(pCtx, pCsr->iStart);
157036      break;
157037    case 3:
157038      sqlite3_result_int(pCtx, pCsr->iEnd);
157039      break;
157040    default:
157041      assert( iCol==4 );
157042      sqlite3_result_int(pCtx, pCsr->iPos);
157043      break;
157044  }
157045  return SQLITE_OK;
157046}
157047
157048/*
157049** xRowid - Return the current rowid for the cursor.
157050*/
157051static int fts3tokRowidMethod(
157052  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
157053  sqlite_int64 *pRowid            /* OUT: Rowid value */
157054){
157055  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
157056  *pRowid = (sqlite3_int64)pCsr->iRowid;
157057  return SQLITE_OK;
157058}
157059
157060/*
157061** Register the fts3tok module with database connection db. Return SQLITE_OK
157062** if successful or an error code if sqlite3_create_module() fails.
157063*/
157064SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
157065  static const sqlite3_module fts3tok_module = {
157066     0,                           /* iVersion      */
157067     fts3tokConnectMethod,        /* xCreate       */
157068     fts3tokConnectMethod,        /* xConnect      */
157069     fts3tokBestIndexMethod,      /* xBestIndex    */
157070     fts3tokDisconnectMethod,     /* xDisconnect   */
157071     fts3tokDisconnectMethod,     /* xDestroy      */
157072     fts3tokOpenMethod,           /* xOpen         */
157073     fts3tokCloseMethod,          /* xClose        */
157074     fts3tokFilterMethod,         /* xFilter       */
157075     fts3tokNextMethod,           /* xNext         */
157076     fts3tokEofMethod,            /* xEof          */
157077     fts3tokColumnMethod,         /* xColumn       */
157078     fts3tokRowidMethod,          /* xRowid        */
157079     0,                           /* xUpdate       */
157080     0,                           /* xBegin        */
157081     0,                           /* xSync         */
157082     0,                           /* xCommit       */
157083     0,                           /* xRollback     */
157084     0,                           /* xFindFunction */
157085     0,                           /* xRename       */
157086     0,                           /* xSavepoint    */
157087     0,                           /* xRelease      */
157088     0                            /* xRollbackTo   */
157089  };
157090  int rc;                         /* Return code */
157091
157092  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
157093  return rc;
157094}
157095
157096#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
157097
157098/************** End of fts3_tokenize_vtab.c **********************************/
157099/************** Begin file fts3_write.c **************************************/
157100/*
157101** 2009 Oct 23
157102**
157103** The author disclaims copyright to this source code.  In place of
157104** a legal notice, here is a blessing:
157105**
157106**    May you do good and not evil.
157107**    May you find forgiveness for yourself and forgive others.
157108**    May you share freely, never taking more than you give.
157109**
157110******************************************************************************
157111**
157112** This file is part of the SQLite FTS3 extension module. Specifically,
157113** this file contains code to insert, update and delete rows from FTS3
157114** tables. It also contains code to merge FTS3 b-tree segments. Some
157115** of the sub-routines used to merge segments are also used by the query
157116** code in fts3.c.
157117*/
157118
157119/* #include "fts3Int.h" */
157120#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
157121
157122/* #include <string.h> */
157123/* #include <assert.h> */
157124/* #include <stdlib.h> */
157125
157126
157127#define FTS_MAX_APPENDABLE_HEIGHT 16
157128
157129/*
157130** When full-text index nodes are loaded from disk, the buffer that they
157131** are loaded into has the following number of bytes of padding at the end
157132** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
157133** of 920 bytes is allocated for it.
157134**
157135** This means that if we have a pointer into a buffer containing node data,
157136** it is always safe to read up to two varints from it without risking an
157137** overread, even if the node data is corrupted.
157138*/
157139#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
157140
157141/*
157142** Under certain circumstances, b-tree nodes (doclists) can be loaded into
157143** memory incrementally instead of all at once. This can be a big performance
157144** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
157145** method before retrieving all query results (as may happen, for example,
157146** if a query has a LIMIT clause).
157147**
157148** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
157149** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
157150** The code is written so that the hard lower-limit for each of these values
157151** is 1. Clearly such small values would be inefficient, but can be useful
157152** for testing purposes.
157153**
157154** If this module is built with SQLITE_TEST defined, these constants may
157155** be overridden at runtime for testing purposes. File fts3_test.c contains
157156** a Tcl interface to read and write the values.
157157*/
157158#ifdef SQLITE_TEST
157159int test_fts3_node_chunksize = (4*1024);
157160int test_fts3_node_chunk_threshold = (4*1024)*4;
157161# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
157162# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
157163#else
157164# define FTS3_NODE_CHUNKSIZE (4*1024)
157165# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
157166#endif
157167
157168/*
157169** The two values that may be meaningfully bound to the :1 parameter in
157170** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
157171*/
157172#define FTS_STAT_DOCTOTAL      0
157173#define FTS_STAT_INCRMERGEHINT 1
157174#define FTS_STAT_AUTOINCRMERGE 2
157175
157176/*
157177** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
157178** and incremental merge operation that takes place. This is used for
157179** debugging FTS only, it should not usually be turned on in production
157180** systems.
157181*/
157182#ifdef FTS3_LOG_MERGES
157183static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
157184  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
157185}
157186#else
157187#define fts3LogMerge(x, y)
157188#endif
157189
157190
157191typedef struct PendingList PendingList;
157192typedef struct SegmentNode SegmentNode;
157193typedef struct SegmentWriter SegmentWriter;
157194
157195/*
157196** An instance of the following data structure is used to build doclists
157197** incrementally. See function fts3PendingListAppend() for details.
157198*/
157199struct PendingList {
157200  int nData;
157201  char *aData;
157202  int nSpace;
157203  sqlite3_int64 iLastDocid;
157204  sqlite3_int64 iLastCol;
157205  sqlite3_int64 iLastPos;
157206};
157207
157208
157209/*
157210** Each cursor has a (possibly empty) linked list of the following objects.
157211*/
157212struct Fts3DeferredToken {
157213  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
157214  int iCol;                       /* Column token must occur in */
157215  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
157216  PendingList *pList;             /* Doclist is assembled here */
157217};
157218
157219/*
157220** An instance of this structure is used to iterate through the terms on
157221** a contiguous set of segment b-tree leaf nodes. Although the details of
157222** this structure are only manipulated by code in this file, opaque handles
157223** of type Fts3SegReader* are also used by code in fts3.c to iterate through
157224** terms when querying the full-text index. See functions:
157225**
157226**   sqlite3Fts3SegReaderNew()
157227**   sqlite3Fts3SegReaderFree()
157228**   sqlite3Fts3SegReaderIterate()
157229**
157230** Methods used to manipulate Fts3SegReader structures:
157231**
157232**   fts3SegReaderNext()
157233**   fts3SegReaderFirstDocid()
157234**   fts3SegReaderNextDocid()
157235*/
157236struct Fts3SegReader {
157237  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
157238  u8 bLookup;                     /* True for a lookup only */
157239  u8 rootOnly;                    /* True for a root-only reader */
157240
157241  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
157242  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
157243  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
157244  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
157245
157246  char *aNode;                    /* Pointer to node data (or NULL) */
157247  int nNode;                      /* Size of buffer at aNode (or 0) */
157248  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
157249  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
157250
157251  Fts3HashElem **ppNextElem;
157252
157253  /* Variables set by fts3SegReaderNext(). These may be read directly
157254  ** by the caller. They are valid from the time SegmentReaderNew() returns
157255  ** until SegmentReaderNext() returns something other than SQLITE_OK
157256  ** (i.e. SQLITE_DONE).
157257  */
157258  int nTerm;                      /* Number of bytes in current term */
157259  char *zTerm;                    /* Pointer to current term */
157260  int nTermAlloc;                 /* Allocated size of zTerm buffer */
157261  char *aDoclist;                 /* Pointer to doclist of current entry */
157262  int nDoclist;                   /* Size of doclist in current entry */
157263
157264  /* The following variables are used by fts3SegReaderNextDocid() to iterate
157265  ** through the current doclist (aDoclist/nDoclist).
157266  */
157267  char *pOffsetList;
157268  int nOffsetList;                /* For descending pending seg-readers only */
157269  sqlite3_int64 iDocid;
157270};
157271
157272#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
157273#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
157274
157275/*
157276** An instance of this structure is used to create a segment b-tree in the
157277** database. The internal details of this type are only accessed by the
157278** following functions:
157279**
157280**   fts3SegWriterAdd()
157281**   fts3SegWriterFlush()
157282**   fts3SegWriterFree()
157283*/
157284struct SegmentWriter {
157285  SegmentNode *pTree;             /* Pointer to interior tree structure */
157286  sqlite3_int64 iFirst;           /* First slot in %_segments written */
157287  sqlite3_int64 iFree;            /* Next free slot in %_segments */
157288  char *zTerm;                    /* Pointer to previous term buffer */
157289  int nTerm;                      /* Number of bytes in zTerm */
157290  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
157291  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
157292  int nSize;                      /* Size of allocation at aData */
157293  int nData;                      /* Bytes of data in aData */
157294  char *aData;                    /* Pointer to block from malloc() */
157295  i64 nLeafData;                  /* Number of bytes of leaf data written */
157296};
157297
157298/*
157299** Type SegmentNode is used by the following three functions to create
157300** the interior part of the segment b+-tree structures (everything except
157301** the leaf nodes). These functions and type are only ever used by code
157302** within the fts3SegWriterXXX() family of functions described above.
157303**
157304**   fts3NodeAddTerm()
157305**   fts3NodeWrite()
157306**   fts3NodeFree()
157307**
157308** When a b+tree is written to the database (either as a result of a merge
157309** or the pending-terms table being flushed), leaves are written into the
157310** database file as soon as they are completely populated. The interior of
157311** the tree is assembled in memory and written out only once all leaves have
157312** been populated and stored. This is Ok, as the b+-tree fanout is usually
157313** very large, meaning that the interior of the tree consumes relatively
157314** little memory.
157315*/
157316struct SegmentNode {
157317  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
157318  SegmentNode *pRight;            /* Pointer to right-sibling */
157319  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
157320  int nEntry;                     /* Number of terms written to node so far */
157321  char *zTerm;                    /* Pointer to previous term buffer */
157322  int nTerm;                      /* Number of bytes in zTerm */
157323  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
157324  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
157325  int nData;                      /* Bytes of valid data so far */
157326  char *aData;                    /* Node data */
157327};
157328
157329/*
157330** Valid values for the second argument to fts3SqlStmt().
157331*/
157332#define SQL_DELETE_CONTENT             0
157333#define SQL_IS_EMPTY                   1
157334#define SQL_DELETE_ALL_CONTENT         2
157335#define SQL_DELETE_ALL_SEGMENTS        3
157336#define SQL_DELETE_ALL_SEGDIR          4
157337#define SQL_DELETE_ALL_DOCSIZE         5
157338#define SQL_DELETE_ALL_STAT            6
157339#define SQL_SELECT_CONTENT_BY_ROWID    7
157340#define SQL_NEXT_SEGMENT_INDEX         8
157341#define SQL_INSERT_SEGMENTS            9
157342#define SQL_NEXT_SEGMENTS_ID          10
157343#define SQL_INSERT_SEGDIR             11
157344#define SQL_SELECT_LEVEL              12
157345#define SQL_SELECT_LEVEL_RANGE        13
157346#define SQL_SELECT_LEVEL_COUNT        14
157347#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
157348#define SQL_DELETE_SEGDIR_LEVEL       16
157349#define SQL_DELETE_SEGMENTS_RANGE     17
157350#define SQL_CONTENT_INSERT            18
157351#define SQL_DELETE_DOCSIZE            19
157352#define SQL_REPLACE_DOCSIZE           20
157353#define SQL_SELECT_DOCSIZE            21
157354#define SQL_SELECT_STAT               22
157355#define SQL_REPLACE_STAT              23
157356
157357#define SQL_SELECT_ALL_PREFIX_LEVEL   24
157358#define SQL_DELETE_ALL_TERMS_SEGDIR   25
157359#define SQL_DELETE_SEGDIR_RANGE       26
157360#define SQL_SELECT_ALL_LANGID         27
157361#define SQL_FIND_MERGE_LEVEL          28
157362#define SQL_MAX_LEAF_NODE_ESTIMATE    29
157363#define SQL_DELETE_SEGDIR_ENTRY       30
157364#define SQL_SHIFT_SEGDIR_ENTRY        31
157365#define SQL_SELECT_SEGDIR             32
157366#define SQL_CHOMP_SEGDIR              33
157367#define SQL_SEGMENT_IS_APPENDABLE     34
157368#define SQL_SELECT_INDEXES            35
157369#define SQL_SELECT_MXLEVEL            36
157370
157371#define SQL_SELECT_LEVEL_RANGE2       37
157372#define SQL_UPDATE_LEVEL_IDX          38
157373#define SQL_UPDATE_LEVEL              39
157374
157375/*
157376** This function is used to obtain an SQLite prepared statement handle
157377** for the statement identified by the second argument. If successful,
157378** *pp is set to the requested statement handle and SQLITE_OK returned.
157379** Otherwise, an SQLite error code is returned and *pp is set to 0.
157380**
157381** If argument apVal is not NULL, then it must point to an array with
157382** at least as many entries as the requested statement has bound
157383** parameters. The values are bound to the statements parameters before
157384** returning.
157385*/
157386static int fts3SqlStmt(
157387  Fts3Table *p,                   /* Virtual table handle */
157388  int eStmt,                      /* One of the SQL_XXX constants above */
157389  sqlite3_stmt **pp,              /* OUT: Statement handle */
157390  sqlite3_value **apVal           /* Values to bind to statement */
157391){
157392  const char *azSql[] = {
157393/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
157394/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
157395/* 2  */  "DELETE FROM %Q.'%q_content'",
157396/* 3  */  "DELETE FROM %Q.'%q_segments'",
157397/* 4  */  "DELETE FROM %Q.'%q_segdir'",
157398/* 5  */  "DELETE FROM %Q.'%q_docsize'",
157399/* 6  */  "DELETE FROM %Q.'%q_stat'",
157400/* 7  */  "SELECT %s WHERE rowid=?",
157401/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
157402/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
157403/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
157404/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
157405
157406          /* Return segments in order from oldest to newest.*/
157407/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
157408            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
157409/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
157410            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
157411            "ORDER BY level DESC, idx ASC",
157412
157413/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
157414/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
157415
157416/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
157417/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
157418/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
157419/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
157420/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
157421/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
157422/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
157423/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
157424/* 24 */  "",
157425/* 25 */  "",
157426
157427/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
157428/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
157429
157430/* This statement is used to determine which level to read the input from
157431** when performing an incremental merge. It returns the absolute level number
157432** of the oldest level in the db that contains at least ? segments. Or,
157433** if no level in the FTS index contains more than ? segments, the statement
157434** returns zero rows.  */
157435/* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
157436         "  GROUP BY level HAVING cnt>=?"
157437         "  ORDER BY (level %% 1024) ASC LIMIT 1",
157438
157439/* Estimate the upper limit on the number of leaf nodes in a new segment
157440** created by merging the oldest :2 segments from absolute level :1. See
157441** function sqlite3Fts3Incrmerge() for details.  */
157442/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
157443         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
157444
157445/* SQL_DELETE_SEGDIR_ENTRY
157446**   Delete the %_segdir entry on absolute level :1 with index :2.  */
157447/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
157448
157449/* SQL_SHIFT_SEGDIR_ENTRY
157450**   Modify the idx value for the segment with idx=:3 on absolute level :2
157451**   to :1.  */
157452/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
157453
157454/* SQL_SELECT_SEGDIR
157455**   Read a single entry from the %_segdir table. The entry from absolute
157456**   level :1 with index value :2.  */
157457/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
157458            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
157459
157460/* SQL_CHOMP_SEGDIR
157461**   Update the start_block (:1) and root (:2) fields of the %_segdir
157462**   entry located on absolute level :3 with index :4.  */
157463/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
157464            "WHERE level = ? AND idx = ?",
157465
157466/* SQL_SEGMENT_IS_APPENDABLE
157467**   Return a single row if the segment with end_block=? is appendable. Or
157468**   no rows otherwise.  */
157469/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
157470
157471/* SQL_SELECT_INDEXES
157472**   Return the list of valid segment indexes for absolute level ?  */
157473/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
157474
157475/* SQL_SELECT_MXLEVEL
157476**   Return the largest relative level in the FTS index or indexes.  */
157477/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
157478
157479          /* Return segments in order from oldest to newest.*/
157480/* 37 */  "SELECT level, idx, end_block "
157481            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
157482            "ORDER BY level DESC, idx ASC",
157483
157484          /* Update statements used while promoting segments */
157485/* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
157486            "WHERE level=? AND idx=?",
157487/* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
157488
157489  };
157490  int rc = SQLITE_OK;
157491  sqlite3_stmt *pStmt;
157492
157493  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
157494  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
157495
157496  pStmt = p->aStmt[eStmt];
157497  if( !pStmt ){
157498    char *zSql;
157499    if( eStmt==SQL_CONTENT_INSERT ){
157500      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
157501    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
157502      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
157503    }else{
157504      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
157505    }
157506    if( !zSql ){
157507      rc = SQLITE_NOMEM;
157508    }else{
157509      rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
157510                              &pStmt, NULL);
157511      sqlite3_free(zSql);
157512      assert( rc==SQLITE_OK || pStmt==0 );
157513      p->aStmt[eStmt] = pStmt;
157514    }
157515  }
157516  if( apVal ){
157517    int i;
157518    int nParam = sqlite3_bind_parameter_count(pStmt);
157519    for(i=0; rc==SQLITE_OK && i<nParam; i++){
157520      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
157521    }
157522  }
157523  *pp = pStmt;
157524  return rc;
157525}
157526
157527
157528static int fts3SelectDocsize(
157529  Fts3Table *pTab,                /* FTS3 table handle */
157530  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
157531  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
157532){
157533  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
157534  int rc;                         /* Return code */
157535
157536  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
157537  if( rc==SQLITE_OK ){
157538    sqlite3_bind_int64(pStmt, 1, iDocid);
157539    rc = sqlite3_step(pStmt);
157540    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
157541      rc = sqlite3_reset(pStmt);
157542      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
157543      pStmt = 0;
157544    }else{
157545      rc = SQLITE_OK;
157546    }
157547  }
157548
157549  *ppStmt = pStmt;
157550  return rc;
157551}
157552
157553SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
157554  Fts3Table *pTab,                /* Fts3 table handle */
157555  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
157556){
157557  sqlite3_stmt *pStmt = 0;
157558  int rc;
157559  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
157560  if( rc==SQLITE_OK ){
157561    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
157562    if( sqlite3_step(pStmt)!=SQLITE_ROW
157563     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
157564    ){
157565      rc = sqlite3_reset(pStmt);
157566      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
157567      pStmt = 0;
157568    }
157569  }
157570  *ppStmt = pStmt;
157571  return rc;
157572}
157573
157574SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
157575  Fts3Table *pTab,                /* Fts3 table handle */
157576  sqlite3_int64 iDocid,           /* Docid to read size data for */
157577  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
157578){
157579  return fts3SelectDocsize(pTab, iDocid, ppStmt);
157580}
157581
157582/*
157583** Similar to fts3SqlStmt(). Except, after binding the parameters in
157584** array apVal[] to the SQL statement identified by eStmt, the statement
157585** is executed.
157586**
157587** Returns SQLITE_OK if the statement is successfully executed, or an
157588** SQLite error code otherwise.
157589*/
157590static void fts3SqlExec(
157591  int *pRC,                /* Result code */
157592  Fts3Table *p,            /* The FTS3 table */
157593  int eStmt,               /* Index of statement to evaluate */
157594  sqlite3_value **apVal    /* Parameters to bind */
157595){
157596  sqlite3_stmt *pStmt;
157597  int rc;
157598  if( *pRC ) return;
157599  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
157600  if( rc==SQLITE_OK ){
157601    sqlite3_step(pStmt);
157602    rc = sqlite3_reset(pStmt);
157603  }
157604  *pRC = rc;
157605}
157606
157607
157608/*
157609** This function ensures that the caller has obtained an exclusive
157610** shared-cache table-lock on the %_segdir table. This is required before
157611** writing data to the fts3 table. If this lock is not acquired first, then
157612** the caller may end up attempting to take this lock as part of committing
157613** a transaction, causing SQLite to return SQLITE_LOCKED or
157614** LOCKED_SHAREDCACHEto a COMMIT command.
157615**
157616** It is best to avoid this because if FTS3 returns any error when
157617** committing a transaction, the whole transaction will be rolled back.
157618** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
157619** It can still happen if the user locks the underlying tables directly
157620** instead of accessing them via FTS.
157621*/
157622static int fts3Writelock(Fts3Table *p){
157623  int rc = SQLITE_OK;
157624
157625  if( p->nPendingData==0 ){
157626    sqlite3_stmt *pStmt;
157627    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
157628    if( rc==SQLITE_OK ){
157629      sqlite3_bind_null(pStmt, 1);
157630      sqlite3_step(pStmt);
157631      rc = sqlite3_reset(pStmt);
157632    }
157633  }
157634
157635  return rc;
157636}
157637
157638/*
157639** FTS maintains a separate indexes for each language-id (a 32-bit integer).
157640** Within each language id, a separate index is maintained to store the
157641** document terms, and each configured prefix size (configured the FTS
157642** "prefix=" option). And each index consists of multiple levels ("relative
157643** levels").
157644**
157645** All three of these values (the language id, the specific index and the
157646** level within the index) are encoded in 64-bit integer values stored
157647** in the %_segdir table on disk. This function is used to convert three
157648** separate component values into the single 64-bit integer value that
157649** can be used to query the %_segdir table.
157650**
157651** Specifically, each language-id/index combination is allocated 1024
157652** 64-bit integer level values ("absolute levels"). The main terms index
157653** for language-id 0 is allocate values 0-1023. The first prefix index
157654** (if any) for language-id 0 is allocated values 1024-2047. And so on.
157655** Language 1 indexes are allocated immediately following language 0.
157656**
157657** So, for a system with nPrefix prefix indexes configured, the block of
157658** absolute levels that corresponds to language-id iLangid and index
157659** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
157660*/
157661static sqlite3_int64 getAbsoluteLevel(
157662  Fts3Table *p,                   /* FTS3 table handle */
157663  int iLangid,                    /* Language id */
157664  int iIndex,                     /* Index in p->aIndex[] */
157665  int iLevel                      /* Level of segments */
157666){
157667  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
157668  assert( iLangid>=0 );
157669  assert( p->nIndex>0 );
157670  assert( iIndex>=0 && iIndex<p->nIndex );
157671
157672  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
157673  return iBase + iLevel;
157674}
157675
157676/*
157677** Set *ppStmt to a statement handle that may be used to iterate through
157678** all rows in the %_segdir table, from oldest to newest. If successful,
157679** return SQLITE_OK. If an error occurs while preparing the statement,
157680** return an SQLite error code.
157681**
157682** There is only ever one instance of this SQL statement compiled for
157683** each FTS3 table.
157684**
157685** The statement returns the following columns from the %_segdir table:
157686**
157687**   0: idx
157688**   1: start_block
157689**   2: leaves_end_block
157690**   3: end_block
157691**   4: root
157692*/
157693SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
157694  Fts3Table *p,                   /* FTS3 table */
157695  int iLangid,                    /* Language being queried */
157696  int iIndex,                     /* Index for p->aIndex[] */
157697  int iLevel,                     /* Level to select (relative level) */
157698  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
157699){
157700  int rc;
157701  sqlite3_stmt *pStmt = 0;
157702
157703  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
157704  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
157705  assert( iIndex>=0 && iIndex<p->nIndex );
157706
157707  if( iLevel<0 ){
157708    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
157709    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
157710    if( rc==SQLITE_OK ){
157711      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
157712      sqlite3_bind_int64(pStmt, 2,
157713          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
157714      );
157715    }
157716  }else{
157717    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
157718    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
157719    if( rc==SQLITE_OK ){
157720      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
157721    }
157722  }
157723  *ppStmt = pStmt;
157724  return rc;
157725}
157726
157727
157728/*
157729** Append a single varint to a PendingList buffer. SQLITE_OK is returned
157730** if successful, or an SQLite error code otherwise.
157731**
157732** This function also serves to allocate the PendingList structure itself.
157733** For example, to create a new PendingList structure containing two
157734** varints:
157735**
157736**   PendingList *p = 0;
157737**   fts3PendingListAppendVarint(&p, 1);
157738**   fts3PendingListAppendVarint(&p, 2);
157739*/
157740static int fts3PendingListAppendVarint(
157741  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
157742  sqlite3_int64 i                 /* Value to append to data */
157743){
157744  PendingList *p = *pp;
157745
157746  /* Allocate or grow the PendingList as required. */
157747  if( !p ){
157748    p = sqlite3_malloc(sizeof(*p) + 100);
157749    if( !p ){
157750      return SQLITE_NOMEM;
157751    }
157752    p->nSpace = 100;
157753    p->aData = (char *)&p[1];
157754    p->nData = 0;
157755  }
157756  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
157757    int nNew = p->nSpace * 2;
157758    p = sqlite3_realloc(p, sizeof(*p) + nNew);
157759    if( !p ){
157760      sqlite3_free(*pp);
157761      *pp = 0;
157762      return SQLITE_NOMEM;
157763    }
157764    p->nSpace = nNew;
157765    p->aData = (char *)&p[1];
157766  }
157767
157768  /* Append the new serialized varint to the end of the list. */
157769  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
157770  p->aData[p->nData] = '\0';
157771  *pp = p;
157772  return SQLITE_OK;
157773}
157774
157775/*
157776** Add a docid/column/position entry to a PendingList structure. Non-zero
157777** is returned if the structure is sqlite3_realloced as part of adding
157778** the entry. Otherwise, zero.
157779**
157780** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
157781** Zero is always returned in this case. Otherwise, if no OOM error occurs,
157782** it is set to SQLITE_OK.
157783*/
157784static int fts3PendingListAppend(
157785  PendingList **pp,               /* IN/OUT: PendingList structure */
157786  sqlite3_int64 iDocid,           /* Docid for entry to add */
157787  sqlite3_int64 iCol,             /* Column for entry to add */
157788  sqlite3_int64 iPos,             /* Position of term for entry to add */
157789  int *pRc                        /* OUT: Return code */
157790){
157791  PendingList *p = *pp;
157792  int rc = SQLITE_OK;
157793
157794  assert( !p || p->iLastDocid<=iDocid );
157795
157796  if( !p || p->iLastDocid!=iDocid ){
157797    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
157798    if( p ){
157799      assert( p->nData<p->nSpace );
157800      assert( p->aData[p->nData]==0 );
157801      p->nData++;
157802    }
157803    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
157804      goto pendinglistappend_out;
157805    }
157806    p->iLastCol = -1;
157807    p->iLastPos = 0;
157808    p->iLastDocid = iDocid;
157809  }
157810  if( iCol>0 && p->iLastCol!=iCol ){
157811    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
157812     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
157813    ){
157814      goto pendinglistappend_out;
157815    }
157816    p->iLastCol = iCol;
157817    p->iLastPos = 0;
157818  }
157819  if( iCol>=0 ){
157820    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
157821    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
157822    if( rc==SQLITE_OK ){
157823      p->iLastPos = iPos;
157824    }
157825  }
157826
157827 pendinglistappend_out:
157828  *pRc = rc;
157829  if( p!=*pp ){
157830    *pp = p;
157831    return 1;
157832  }
157833  return 0;
157834}
157835
157836/*
157837** Free a PendingList object allocated by fts3PendingListAppend().
157838*/
157839static void fts3PendingListDelete(PendingList *pList){
157840  sqlite3_free(pList);
157841}
157842
157843/*
157844** Add an entry to one of the pending-terms hash tables.
157845*/
157846static int fts3PendingTermsAddOne(
157847  Fts3Table *p,
157848  int iCol,
157849  int iPos,
157850  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
157851  const char *zToken,
157852  int nToken
157853){
157854  PendingList *pList;
157855  int rc = SQLITE_OK;
157856
157857  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
157858  if( pList ){
157859    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
157860  }
157861  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
157862    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
157863      /* Malloc failed while inserting the new entry. This can only
157864      ** happen if there was no previous entry for this token.
157865      */
157866      assert( 0==fts3HashFind(pHash, zToken, nToken) );
157867      sqlite3_free(pList);
157868      rc = SQLITE_NOMEM;
157869    }
157870  }
157871  if( rc==SQLITE_OK ){
157872    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
157873  }
157874  return rc;
157875}
157876
157877/*
157878** Tokenize the nul-terminated string zText and add all tokens to the
157879** pending-terms hash-table. The docid used is that currently stored in
157880** p->iPrevDocid, and the column is specified by argument iCol.
157881**
157882** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
157883*/
157884static int fts3PendingTermsAdd(
157885  Fts3Table *p,                   /* Table into which text will be inserted */
157886  int iLangid,                    /* Language id to use */
157887  const char *zText,              /* Text of document to be inserted */
157888  int iCol,                       /* Column into which text is being inserted */
157889  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
157890){
157891  int rc;
157892  int iStart = 0;
157893  int iEnd = 0;
157894  int iPos = 0;
157895  int nWord = 0;
157896
157897  char const *zToken;
157898  int nToken = 0;
157899
157900  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
157901  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
157902  sqlite3_tokenizer_cursor *pCsr;
157903  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
157904      const char**,int*,int*,int*,int*);
157905
157906  assert( pTokenizer && pModule );
157907
157908  /* If the user has inserted a NULL value, this function may be called with
157909  ** zText==0. In this case, add zero token entries to the hash table and
157910  ** return early. */
157911  if( zText==0 ){
157912    *pnWord = 0;
157913    return SQLITE_OK;
157914  }
157915
157916  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
157917  if( rc!=SQLITE_OK ){
157918    return rc;
157919  }
157920
157921  xNext = pModule->xNext;
157922  while( SQLITE_OK==rc
157923      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
157924  ){
157925    int i;
157926    if( iPos>=nWord ) nWord = iPos+1;
157927
157928    /* Positions cannot be negative; we use -1 as a terminator internally.
157929    ** Tokens must have a non-zero length.
157930    */
157931    if( iPos<0 || !zToken || nToken<=0 ){
157932      rc = SQLITE_ERROR;
157933      break;
157934    }
157935
157936    /* Add the term to the terms index */
157937    rc = fts3PendingTermsAddOne(
157938        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
157939    );
157940
157941    /* Add the term to each of the prefix indexes that it is not too
157942    ** short for. */
157943    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
157944      struct Fts3Index *pIndex = &p->aIndex[i];
157945      if( nToken<pIndex->nPrefix ) continue;
157946      rc = fts3PendingTermsAddOne(
157947          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
157948      );
157949    }
157950  }
157951
157952  pModule->xClose(pCsr);
157953  *pnWord += nWord;
157954  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
157955}
157956
157957/*
157958** Calling this function indicates that subsequent calls to
157959** fts3PendingTermsAdd() are to add term/position-list pairs for the
157960** contents of the document with docid iDocid.
157961*/
157962static int fts3PendingTermsDocid(
157963  Fts3Table *p,                   /* Full-text table handle */
157964  int bDelete,                    /* True if this op is a delete */
157965  int iLangid,                    /* Language id of row being written */
157966  sqlite_int64 iDocid             /* Docid of row being written */
157967){
157968  assert( iLangid>=0 );
157969  assert( bDelete==1 || bDelete==0 );
157970
157971  /* TODO(shess) Explore whether partially flushing the buffer on
157972  ** forced-flush would provide better performance.  I suspect that if
157973  ** we ordered the doclists by size and flushed the largest until the
157974  ** buffer was half empty, that would let the less frequent terms
157975  ** generate longer doclists.
157976  */
157977  if( iDocid<p->iPrevDocid
157978   || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
157979   || p->iPrevLangid!=iLangid
157980   || p->nPendingData>p->nMaxPendingData
157981  ){
157982    int rc = sqlite3Fts3PendingTermsFlush(p);
157983    if( rc!=SQLITE_OK ) return rc;
157984  }
157985  p->iPrevDocid = iDocid;
157986  p->iPrevLangid = iLangid;
157987  p->bPrevDelete = bDelete;
157988  return SQLITE_OK;
157989}
157990
157991/*
157992** Discard the contents of the pending-terms hash tables.
157993*/
157994SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
157995  int i;
157996  for(i=0; i<p->nIndex; i++){
157997    Fts3HashElem *pElem;
157998    Fts3Hash *pHash = &p->aIndex[i].hPending;
157999    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
158000      PendingList *pList = (PendingList *)fts3HashData(pElem);
158001      fts3PendingListDelete(pList);
158002    }
158003    fts3HashClear(pHash);
158004  }
158005  p->nPendingData = 0;
158006}
158007
158008/*
158009** This function is called by the xUpdate() method as part of an INSERT
158010** operation. It adds entries for each term in the new record to the
158011** pendingTerms hash table.
158012**
158013** Argument apVal is the same as the similarly named argument passed to
158014** fts3InsertData(). Parameter iDocid is the docid of the new row.
158015*/
158016static int fts3InsertTerms(
158017  Fts3Table *p,
158018  int iLangid,
158019  sqlite3_value **apVal,
158020  u32 *aSz
158021){
158022  int i;                          /* Iterator variable */
158023  for(i=2; i<p->nColumn+2; i++){
158024    int iCol = i-2;
158025    if( p->abNotindexed[iCol]==0 ){
158026      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
158027      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
158028      if( rc!=SQLITE_OK ){
158029        return rc;
158030      }
158031      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
158032    }
158033  }
158034  return SQLITE_OK;
158035}
158036
158037/*
158038** This function is called by the xUpdate() method for an INSERT operation.
158039** The apVal parameter is passed a copy of the apVal argument passed by
158040** SQLite to the xUpdate() method. i.e:
158041**
158042**   apVal[0]                Not used for INSERT.
158043**   apVal[1]                rowid
158044**   apVal[2]                Left-most user-defined column
158045**   ...
158046**   apVal[p->nColumn+1]     Right-most user-defined column
158047**   apVal[p->nColumn+2]     Hidden column with same name as table
158048**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
158049**   apVal[p->nColumn+4]     Hidden languageid column
158050*/
158051static int fts3InsertData(
158052  Fts3Table *p,                   /* Full-text table */
158053  sqlite3_value **apVal,          /* Array of values to insert */
158054  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
158055){
158056  int rc;                         /* Return code */
158057  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
158058
158059  if( p->zContentTbl ){
158060    sqlite3_value *pRowid = apVal[p->nColumn+3];
158061    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
158062      pRowid = apVal[1];
158063    }
158064    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
158065      return SQLITE_CONSTRAINT;
158066    }
158067    *piDocid = sqlite3_value_int64(pRowid);
158068    return SQLITE_OK;
158069  }
158070
158071  /* Locate the statement handle used to insert data into the %_content
158072  ** table. The SQL for this statement is:
158073  **
158074  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
158075  **
158076  ** The statement features N '?' variables, where N is the number of user
158077  ** defined columns in the FTS3 table, plus one for the docid field.
158078  */
158079  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
158080  if( rc==SQLITE_OK && p->zLanguageid ){
158081    rc = sqlite3_bind_int(
158082        pContentInsert, p->nColumn+2,
158083        sqlite3_value_int(apVal[p->nColumn+4])
158084    );
158085  }
158086  if( rc!=SQLITE_OK ) return rc;
158087
158088  /* There is a quirk here. The users INSERT statement may have specified
158089  ** a value for the "rowid" field, for the "docid" field, or for both.
158090  ** Which is a problem, since "rowid" and "docid" are aliases for the
158091  ** same value. For example:
158092  **
158093  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
158094  **
158095  ** In FTS3, this is an error. It is an error to specify non-NULL values
158096  ** for both docid and some other rowid alias.
158097  */
158098  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
158099    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
158100     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
158101    ){
158102      /* A rowid/docid conflict. */
158103      return SQLITE_ERROR;
158104    }
158105    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
158106    if( rc!=SQLITE_OK ) return rc;
158107  }
158108
158109  /* Execute the statement to insert the record. Set *piDocid to the
158110  ** new docid value.
158111  */
158112  sqlite3_step(pContentInsert);
158113  rc = sqlite3_reset(pContentInsert);
158114
158115  *piDocid = sqlite3_last_insert_rowid(p->db);
158116  return rc;
158117}
158118
158119
158120
158121/*
158122** Remove all data from the FTS3 table. Clear the hash table containing
158123** pending terms.
158124*/
158125static int fts3DeleteAll(Fts3Table *p, int bContent){
158126  int rc = SQLITE_OK;             /* Return code */
158127
158128  /* Discard the contents of the pending-terms hash table. */
158129  sqlite3Fts3PendingTermsClear(p);
158130
158131  /* Delete everything from the shadow tables. Except, leave %_content as
158132  ** is if bContent is false.  */
158133  assert( p->zContentTbl==0 || bContent==0 );
158134  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
158135  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
158136  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
158137  if( p->bHasDocsize ){
158138    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
158139  }
158140  if( p->bHasStat ){
158141    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
158142  }
158143  return rc;
158144}
158145
158146/*
158147**
158148*/
158149static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
158150  int iLangid = 0;
158151  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
158152  return iLangid;
158153}
158154
158155/*
158156** The first element in the apVal[] array is assumed to contain the docid
158157** (an integer) of a row about to be deleted. Remove all terms from the
158158** full-text index.
158159*/
158160static void fts3DeleteTerms(
158161  int *pRC,               /* Result code */
158162  Fts3Table *p,           /* The FTS table to delete from */
158163  sqlite3_value *pRowid,  /* The docid to be deleted */
158164  u32 *aSz,               /* Sizes of deleted document written here */
158165  int *pbFound            /* OUT: Set to true if row really does exist */
158166){
158167  int rc;
158168  sqlite3_stmt *pSelect;
158169
158170  assert( *pbFound==0 );
158171  if( *pRC ) return;
158172  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
158173  if( rc==SQLITE_OK ){
158174    if( SQLITE_ROW==sqlite3_step(pSelect) ){
158175      int i;
158176      int iLangid = langidFromSelect(p, pSelect);
158177      i64 iDocid = sqlite3_column_int64(pSelect, 0);
158178      rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
158179      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
158180        int iCol = i-1;
158181        if( p->abNotindexed[iCol]==0 ){
158182          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
158183          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
158184          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
158185        }
158186      }
158187      if( rc!=SQLITE_OK ){
158188        sqlite3_reset(pSelect);
158189        *pRC = rc;
158190        return;
158191      }
158192      *pbFound = 1;
158193    }
158194    rc = sqlite3_reset(pSelect);
158195  }else{
158196    sqlite3_reset(pSelect);
158197  }
158198  *pRC = rc;
158199}
158200
158201/*
158202** Forward declaration to account for the circular dependency between
158203** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
158204*/
158205static int fts3SegmentMerge(Fts3Table *, int, int, int);
158206
158207/*
158208** This function allocates a new level iLevel index in the segdir table.
158209** Usually, indexes are allocated within a level sequentially starting
158210** with 0, so the allocated index is one greater than the value returned
158211** by:
158212**
158213**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
158214**
158215** However, if there are already FTS3_MERGE_COUNT indexes at the requested
158216** level, they are merged into a single level (iLevel+1) segment and the
158217** allocated index is 0.
158218**
158219** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
158220** returned. Otherwise, an SQLite error code is returned.
158221*/
158222static int fts3AllocateSegdirIdx(
158223  Fts3Table *p,
158224  int iLangid,                    /* Language id */
158225  int iIndex,                     /* Index for p->aIndex */
158226  int iLevel,
158227  int *piIdx
158228){
158229  int rc;                         /* Return Code */
158230  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
158231  int iNext = 0;                  /* Result of query pNextIdx */
158232
158233  assert( iLangid>=0 );
158234  assert( p->nIndex>=1 );
158235
158236  /* Set variable iNext to the next available segdir index at level iLevel. */
158237  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
158238  if( rc==SQLITE_OK ){
158239    sqlite3_bind_int64(
158240        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
158241    );
158242    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
158243      iNext = sqlite3_column_int(pNextIdx, 0);
158244    }
158245    rc = sqlite3_reset(pNextIdx);
158246  }
158247
158248  if( rc==SQLITE_OK ){
158249    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
158250    ** full, merge all segments in level iLevel into a single iLevel+1
158251    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
158252    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
158253    */
158254    if( iNext>=FTS3_MERGE_COUNT ){
158255      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
158256      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
158257      *piIdx = 0;
158258    }else{
158259      *piIdx = iNext;
158260    }
158261  }
158262
158263  return rc;
158264}
158265
158266/*
158267** The %_segments table is declared as follows:
158268**
158269**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
158270**
158271** This function reads data from a single row of the %_segments table. The
158272** specific row is identified by the iBlockid parameter. If paBlob is not
158273** NULL, then a buffer is allocated using sqlite3_malloc() and populated
158274** with the contents of the blob stored in the "block" column of the
158275** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
158276** to the size of the blob in bytes before returning.
158277**
158278** If an error occurs, or the table does not contain the specified row,
158279** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
158280** paBlob is non-NULL, then it is the responsibility of the caller to
158281** eventually free the returned buffer.
158282**
158283** This function may leave an open sqlite3_blob* handle in the
158284** Fts3Table.pSegments variable. This handle is reused by subsequent calls
158285** to this function. The handle may be closed by calling the
158286** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
158287** performance improvement, but the blob handle should always be closed
158288** before control is returned to the user (to prevent a lock being held
158289** on the database file for longer than necessary). Thus, any virtual table
158290** method (xFilter etc.) that may directly or indirectly call this function
158291** must call sqlite3Fts3SegmentsClose() before returning.
158292*/
158293SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
158294  Fts3Table *p,                   /* FTS3 table handle */
158295  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
158296  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
158297  int *pnBlob,                    /* OUT: Size of blob data */
158298  int *pnLoad                     /* OUT: Bytes actually loaded */
158299){
158300  int rc;                         /* Return code */
158301
158302  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
158303  assert( pnBlob );
158304
158305  if( p->pSegments ){
158306    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
158307  }else{
158308    if( 0==p->zSegmentsTbl ){
158309      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
158310      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
158311    }
158312    rc = sqlite3_blob_open(
158313       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
158314    );
158315  }
158316
158317  if( rc==SQLITE_OK ){
158318    int nByte = sqlite3_blob_bytes(p->pSegments);
158319    *pnBlob = nByte;
158320    if( paBlob ){
158321      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
158322      if( !aByte ){
158323        rc = SQLITE_NOMEM;
158324      }else{
158325        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
158326          nByte = FTS3_NODE_CHUNKSIZE;
158327          *pnLoad = nByte;
158328        }
158329        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
158330        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
158331        if( rc!=SQLITE_OK ){
158332          sqlite3_free(aByte);
158333          aByte = 0;
158334        }
158335      }
158336      *paBlob = aByte;
158337    }
158338  }
158339
158340  return rc;
158341}
158342
158343/*
158344** Close the blob handle at p->pSegments, if it is open. See comments above
158345** the sqlite3Fts3ReadBlock() function for details.
158346*/
158347SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
158348  sqlite3_blob_close(p->pSegments);
158349  p->pSegments = 0;
158350}
158351
158352static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
158353  int nRead;                      /* Number of bytes to read */
158354  int rc;                         /* Return code */
158355
158356  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
158357  rc = sqlite3_blob_read(
158358      pReader->pBlob,
158359      &pReader->aNode[pReader->nPopulate],
158360      nRead,
158361      pReader->nPopulate
158362  );
158363
158364  if( rc==SQLITE_OK ){
158365    pReader->nPopulate += nRead;
158366    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
158367    if( pReader->nPopulate==pReader->nNode ){
158368      sqlite3_blob_close(pReader->pBlob);
158369      pReader->pBlob = 0;
158370      pReader->nPopulate = 0;
158371    }
158372  }
158373  return rc;
158374}
158375
158376static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
158377  int rc = SQLITE_OK;
158378  assert( !pReader->pBlob
158379       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
158380  );
158381  while( pReader->pBlob && rc==SQLITE_OK
158382     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
158383  ){
158384    rc = fts3SegReaderIncrRead(pReader);
158385  }
158386  return rc;
158387}
158388
158389/*
158390** Set an Fts3SegReader cursor to point at EOF.
158391*/
158392static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
158393  if( !fts3SegReaderIsRootOnly(pSeg) ){
158394    sqlite3_free(pSeg->aNode);
158395    sqlite3_blob_close(pSeg->pBlob);
158396    pSeg->pBlob = 0;
158397  }
158398  pSeg->aNode = 0;
158399}
158400
158401/*
158402** Move the iterator passed as the first argument to the next term in the
158403** segment. If successful, SQLITE_OK is returned. If there is no next term,
158404** SQLITE_DONE. Otherwise, an SQLite error code.
158405*/
158406static int fts3SegReaderNext(
158407  Fts3Table *p,
158408  Fts3SegReader *pReader,
158409  int bIncr
158410){
158411  int rc;                         /* Return code of various sub-routines */
158412  char *pNext;                    /* Cursor variable */
158413  int nPrefix;                    /* Number of bytes in term prefix */
158414  int nSuffix;                    /* Number of bytes in term suffix */
158415
158416  if( !pReader->aDoclist ){
158417    pNext = pReader->aNode;
158418  }else{
158419    pNext = &pReader->aDoclist[pReader->nDoclist];
158420  }
158421
158422  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
158423
158424    if( fts3SegReaderIsPending(pReader) ){
158425      Fts3HashElem *pElem = *(pReader->ppNextElem);
158426      sqlite3_free(pReader->aNode);
158427      pReader->aNode = 0;
158428      if( pElem ){
158429        char *aCopy;
158430        PendingList *pList = (PendingList *)fts3HashData(pElem);
158431        int nCopy = pList->nData+1;
158432        pReader->zTerm = (char *)fts3HashKey(pElem);
158433        pReader->nTerm = fts3HashKeysize(pElem);
158434        aCopy = (char*)sqlite3_malloc(nCopy);
158435        if( !aCopy ) return SQLITE_NOMEM;
158436        memcpy(aCopy, pList->aData, nCopy);
158437        pReader->nNode = pReader->nDoclist = nCopy;
158438        pReader->aNode = pReader->aDoclist = aCopy;
158439        pReader->ppNextElem++;
158440        assert( pReader->aNode );
158441      }
158442      return SQLITE_OK;
158443    }
158444
158445    fts3SegReaderSetEof(pReader);
158446
158447    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
158448    ** blocks have already been traversed.  */
158449    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
158450    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
158451      return SQLITE_OK;
158452    }
158453
158454    rc = sqlite3Fts3ReadBlock(
158455        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
158456        (bIncr ? &pReader->nPopulate : 0)
158457    );
158458    if( rc!=SQLITE_OK ) return rc;
158459    assert( pReader->pBlob==0 );
158460    if( bIncr && pReader->nPopulate<pReader->nNode ){
158461      pReader->pBlob = p->pSegments;
158462      p->pSegments = 0;
158463    }
158464    pNext = pReader->aNode;
158465  }
158466
158467  assert( !fts3SegReaderIsPending(pReader) );
158468
158469  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
158470  if( rc!=SQLITE_OK ) return rc;
158471
158472  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
158473  ** safe (no risk of overread) even if the node data is corrupted. */
158474  pNext += fts3GetVarint32(pNext, &nPrefix);
158475  pNext += fts3GetVarint32(pNext, &nSuffix);
158476  if( nPrefix<0 || nSuffix<=0
158477   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
158478  ){
158479    return FTS_CORRUPT_VTAB;
158480  }
158481
158482  if( nPrefix+nSuffix>pReader->nTermAlloc ){
158483    int nNew = (nPrefix+nSuffix)*2;
158484    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
158485    if( !zNew ){
158486      return SQLITE_NOMEM;
158487    }
158488    pReader->zTerm = zNew;
158489    pReader->nTermAlloc = nNew;
158490  }
158491
158492  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
158493  if( rc!=SQLITE_OK ) return rc;
158494
158495  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
158496  pReader->nTerm = nPrefix+nSuffix;
158497  pNext += nSuffix;
158498  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
158499  pReader->aDoclist = pNext;
158500  pReader->pOffsetList = 0;
158501
158502  /* Check that the doclist does not appear to extend past the end of the
158503  ** b-tree node. And that the final byte of the doclist is 0x00. If either
158504  ** of these statements is untrue, then the data structure is corrupt.
158505  */
158506  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
158507   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
158508  ){
158509    return FTS_CORRUPT_VTAB;
158510  }
158511  return SQLITE_OK;
158512}
158513
158514/*
158515** Set the SegReader to point to the first docid in the doclist associated
158516** with the current term.
158517*/
158518static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
158519  int rc = SQLITE_OK;
158520  assert( pReader->aDoclist );
158521  assert( !pReader->pOffsetList );
158522  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
158523    u8 bEof = 0;
158524    pReader->iDocid = 0;
158525    pReader->nOffsetList = 0;
158526    sqlite3Fts3DoclistPrev(0,
158527        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
158528        &pReader->iDocid, &pReader->nOffsetList, &bEof
158529    );
158530  }else{
158531    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
158532    if( rc==SQLITE_OK ){
158533      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
158534      pReader->pOffsetList = &pReader->aDoclist[n];
158535    }
158536  }
158537  return rc;
158538}
158539
158540/*
158541** Advance the SegReader to point to the next docid in the doclist
158542** associated with the current term.
158543**
158544** If arguments ppOffsetList and pnOffsetList are not NULL, then
158545** *ppOffsetList is set to point to the first column-offset list
158546** in the doclist entry (i.e. immediately past the docid varint).
158547** *pnOffsetList is set to the length of the set of column-offset
158548** lists, not including the nul-terminator byte. For example:
158549*/
158550static int fts3SegReaderNextDocid(
158551  Fts3Table *pTab,
158552  Fts3SegReader *pReader,         /* Reader to advance to next docid */
158553  char **ppOffsetList,            /* OUT: Pointer to current position-list */
158554  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
158555){
158556  int rc = SQLITE_OK;
158557  char *p = pReader->pOffsetList;
158558  char c = 0;
158559
158560  assert( p );
158561
158562  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
158563    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
158564    ** Pending-terms doclists are always built up in ascending order, so
158565    ** we have to iterate through them backwards here. */
158566    u8 bEof = 0;
158567    if( ppOffsetList ){
158568      *ppOffsetList = pReader->pOffsetList;
158569      *pnOffsetList = pReader->nOffsetList - 1;
158570    }
158571    sqlite3Fts3DoclistPrev(0,
158572        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
158573        &pReader->nOffsetList, &bEof
158574    );
158575    if( bEof ){
158576      pReader->pOffsetList = 0;
158577    }else{
158578      pReader->pOffsetList = p;
158579    }
158580  }else{
158581    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
158582
158583    /* Pointer p currently points at the first byte of an offset list. The
158584    ** following block advances it to point one byte past the end of
158585    ** the same offset list. */
158586    while( 1 ){
158587
158588      /* The following line of code (and the "p++" below the while() loop) is
158589      ** normally all that is required to move pointer p to the desired
158590      ** position. The exception is if this node is being loaded from disk
158591      ** incrementally and pointer "p" now points to the first byte past
158592      ** the populated part of pReader->aNode[].
158593      */
158594      while( *p | c ) c = *p++ & 0x80;
158595      assert( *p==0 );
158596
158597      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
158598      rc = fts3SegReaderIncrRead(pReader);
158599      if( rc!=SQLITE_OK ) return rc;
158600    }
158601    p++;
158602
158603    /* If required, populate the output variables with a pointer to and the
158604    ** size of the previous offset-list.
158605    */
158606    if( ppOffsetList ){
158607      *ppOffsetList = pReader->pOffsetList;
158608      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
158609    }
158610
158611    /* List may have been edited in place by fts3EvalNearTrim() */
158612    while( p<pEnd && *p==0 ) p++;
158613
158614    /* If there are no more entries in the doclist, set pOffsetList to
158615    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
158616    ** Fts3SegReader.pOffsetList to point to the next offset list before
158617    ** returning.
158618    */
158619    if( p>=pEnd ){
158620      pReader->pOffsetList = 0;
158621    }else{
158622      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
158623      if( rc==SQLITE_OK ){
158624        sqlite3_int64 iDelta;
158625        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
158626        if( pTab->bDescIdx ){
158627          pReader->iDocid -= iDelta;
158628        }else{
158629          pReader->iDocid += iDelta;
158630        }
158631      }
158632    }
158633  }
158634
158635  return SQLITE_OK;
158636}
158637
158638
158639SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
158640  Fts3Cursor *pCsr,
158641  Fts3MultiSegReader *pMsr,
158642  int *pnOvfl
158643){
158644  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
158645  int nOvfl = 0;
158646  int ii;
158647  int rc = SQLITE_OK;
158648  int pgsz = p->nPgsz;
158649
158650  assert( p->bFts4 );
158651  assert( pgsz>0 );
158652
158653  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
158654    Fts3SegReader *pReader = pMsr->apSegment[ii];
158655    if( !fts3SegReaderIsPending(pReader)
158656     && !fts3SegReaderIsRootOnly(pReader)
158657    ){
158658      sqlite3_int64 jj;
158659      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
158660        int nBlob;
158661        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
158662        if( rc!=SQLITE_OK ) break;
158663        if( (nBlob+35)>pgsz ){
158664          nOvfl += (nBlob + 34)/pgsz;
158665        }
158666      }
158667    }
158668  }
158669  *pnOvfl = nOvfl;
158670  return rc;
158671}
158672
158673/*
158674** Free all allocations associated with the iterator passed as the
158675** second argument.
158676*/
158677SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
158678  if( pReader ){
158679    if( !fts3SegReaderIsPending(pReader) ){
158680      sqlite3_free(pReader->zTerm);
158681    }
158682    if( !fts3SegReaderIsRootOnly(pReader) ){
158683      sqlite3_free(pReader->aNode);
158684    }
158685    sqlite3_blob_close(pReader->pBlob);
158686  }
158687  sqlite3_free(pReader);
158688}
158689
158690/*
158691** Allocate a new SegReader object.
158692*/
158693SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
158694  int iAge,                       /* Segment "age". */
158695  int bLookup,                    /* True for a lookup only */
158696  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
158697  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
158698  sqlite3_int64 iEndBlock,        /* Final block of segment */
158699  const char *zRoot,              /* Buffer containing root node */
158700  int nRoot,                      /* Size of buffer containing root node */
158701  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
158702){
158703  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
158704  int nExtra = 0;                 /* Bytes to allocate segment root node */
158705
158706  assert( iStartLeaf<=iEndLeaf );
158707  if( iStartLeaf==0 ){
158708    nExtra = nRoot + FTS3_NODE_PADDING;
158709  }
158710
158711  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
158712  if( !pReader ){
158713    return SQLITE_NOMEM;
158714  }
158715  memset(pReader, 0, sizeof(Fts3SegReader));
158716  pReader->iIdx = iAge;
158717  pReader->bLookup = bLookup!=0;
158718  pReader->iStartBlock = iStartLeaf;
158719  pReader->iLeafEndBlock = iEndLeaf;
158720  pReader->iEndBlock = iEndBlock;
158721
158722  if( nExtra ){
158723    /* The entire segment is stored in the root node. */
158724    pReader->aNode = (char *)&pReader[1];
158725    pReader->rootOnly = 1;
158726    pReader->nNode = nRoot;
158727    memcpy(pReader->aNode, zRoot, nRoot);
158728    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
158729  }else{
158730    pReader->iCurrentBlock = iStartLeaf-1;
158731  }
158732  *ppReader = pReader;
158733  return SQLITE_OK;
158734}
158735
158736/*
158737** This is a comparison function used as a qsort() callback when sorting
158738** an array of pending terms by term. This occurs as part of flushing
158739** the contents of the pending-terms hash table to the database.
158740*/
158741static int SQLITE_CDECL fts3CompareElemByTerm(
158742  const void *lhs,
158743  const void *rhs
158744){
158745  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
158746  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
158747  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
158748  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
158749
158750  int n = (n1<n2 ? n1 : n2);
158751  int c = memcmp(z1, z2, n);
158752  if( c==0 ){
158753    c = n1 - n2;
158754  }
158755  return c;
158756}
158757
158758/*
158759** This function is used to allocate an Fts3SegReader that iterates through
158760** a subset of the terms stored in the Fts3Table.pendingTerms array.
158761**
158762** If the isPrefixIter parameter is zero, then the returned SegReader iterates
158763** through each term in the pending-terms table. Or, if isPrefixIter is
158764** non-zero, it iterates through each term and its prefixes. For example, if
158765** the pending terms hash table contains the terms "sqlite", "mysql" and
158766** "firebird", then the iterator visits the following 'terms' (in the order
158767** shown):
158768**
158769**   f fi fir fire fireb firebi firebir firebird
158770**   m my mys mysq mysql
158771**   s sq sql sqli sqlit sqlite
158772**
158773** Whereas if isPrefixIter is zero, the terms visited are:
158774**
158775**   firebird mysql sqlite
158776*/
158777SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
158778  Fts3Table *p,                   /* Virtual table handle */
158779  int iIndex,                     /* Index for p->aIndex */
158780  const char *zTerm,              /* Term to search for */
158781  int nTerm,                      /* Size of buffer zTerm */
158782  int bPrefix,                    /* True for a prefix iterator */
158783  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
158784){
158785  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
158786  Fts3HashElem *pE;               /* Iterator variable */
158787  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
158788  int nElem = 0;                  /* Size of array at aElem */
158789  int rc = SQLITE_OK;             /* Return Code */
158790  Fts3Hash *pHash;
158791
158792  pHash = &p->aIndex[iIndex].hPending;
158793  if( bPrefix ){
158794    int nAlloc = 0;               /* Size of allocated array at aElem */
158795
158796    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
158797      char *zKey = (char *)fts3HashKey(pE);
158798      int nKey = fts3HashKeysize(pE);
158799      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
158800        if( nElem==nAlloc ){
158801          Fts3HashElem **aElem2;
158802          nAlloc += 16;
158803          aElem2 = (Fts3HashElem **)sqlite3_realloc(
158804              aElem, nAlloc*sizeof(Fts3HashElem *)
158805          );
158806          if( !aElem2 ){
158807            rc = SQLITE_NOMEM;
158808            nElem = 0;
158809            break;
158810          }
158811          aElem = aElem2;
158812        }
158813
158814        aElem[nElem++] = pE;
158815      }
158816    }
158817
158818    /* If more than one term matches the prefix, sort the Fts3HashElem
158819    ** objects in term order using qsort(). This uses the same comparison
158820    ** callback as is used when flushing terms to disk.
158821    */
158822    if( nElem>1 ){
158823      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
158824    }
158825
158826  }else{
158827    /* The query is a simple term lookup that matches at most one term in
158828    ** the index. All that is required is a straight hash-lookup.
158829    **
158830    ** Because the stack address of pE may be accessed via the aElem pointer
158831    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
158832    ** within this entire function, not just this "else{...}" block.
158833    */
158834    pE = fts3HashFindElem(pHash, zTerm, nTerm);
158835    if( pE ){
158836      aElem = &pE;
158837      nElem = 1;
158838    }
158839  }
158840
158841  if( nElem>0 ){
158842    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
158843    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
158844    if( !pReader ){
158845      rc = SQLITE_NOMEM;
158846    }else{
158847      memset(pReader, 0, nByte);
158848      pReader->iIdx = 0x7FFFFFFF;
158849      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
158850      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
158851    }
158852  }
158853
158854  if( bPrefix ){
158855    sqlite3_free(aElem);
158856  }
158857  *ppReader = pReader;
158858  return rc;
158859}
158860
158861/*
158862** Compare the entries pointed to by two Fts3SegReader structures.
158863** Comparison is as follows:
158864**
158865**   1) EOF is greater than not EOF.
158866**
158867**   2) The current terms (if any) are compared using memcmp(). If one
158868**      term is a prefix of another, the longer term is considered the
158869**      larger.
158870**
158871**   3) By segment age. An older segment is considered larger.
158872*/
158873static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
158874  int rc;
158875  if( pLhs->aNode && pRhs->aNode ){
158876    int rc2 = pLhs->nTerm - pRhs->nTerm;
158877    if( rc2<0 ){
158878      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
158879    }else{
158880      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
158881    }
158882    if( rc==0 ){
158883      rc = rc2;
158884    }
158885  }else{
158886    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
158887  }
158888  if( rc==0 ){
158889    rc = pRhs->iIdx - pLhs->iIdx;
158890  }
158891  assert( rc!=0 );
158892  return rc;
158893}
158894
158895/*
158896** A different comparison function for SegReader structures. In this
158897** version, it is assumed that each SegReader points to an entry in
158898** a doclist for identical terms. Comparison is made as follows:
158899**
158900**   1) EOF (end of doclist in this case) is greater than not EOF.
158901**
158902**   2) By current docid.
158903**
158904**   3) By segment age. An older segment is considered larger.
158905*/
158906static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
158907  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
158908  if( rc==0 ){
158909    if( pLhs->iDocid==pRhs->iDocid ){
158910      rc = pRhs->iIdx - pLhs->iIdx;
158911    }else{
158912      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
158913    }
158914  }
158915  assert( pLhs->aNode && pRhs->aNode );
158916  return rc;
158917}
158918static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
158919  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
158920  if( rc==0 ){
158921    if( pLhs->iDocid==pRhs->iDocid ){
158922      rc = pRhs->iIdx - pLhs->iIdx;
158923    }else{
158924      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
158925    }
158926  }
158927  assert( pLhs->aNode && pRhs->aNode );
158928  return rc;
158929}
158930
158931/*
158932** Compare the term that the Fts3SegReader object passed as the first argument
158933** points to with the term specified by arguments zTerm and nTerm.
158934**
158935** If the pSeg iterator is already at EOF, return 0. Otherwise, return
158936** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
158937** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
158938*/
158939static int fts3SegReaderTermCmp(
158940  Fts3SegReader *pSeg,            /* Segment reader object */
158941  const char *zTerm,              /* Term to compare to */
158942  int nTerm                       /* Size of term zTerm in bytes */
158943){
158944  int res = 0;
158945  if( pSeg->aNode ){
158946    if( pSeg->nTerm>nTerm ){
158947      res = memcmp(pSeg->zTerm, zTerm, nTerm);
158948    }else{
158949      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
158950    }
158951    if( res==0 ){
158952      res = pSeg->nTerm-nTerm;
158953    }
158954  }
158955  return res;
158956}
158957
158958/*
158959** Argument apSegment is an array of nSegment elements. It is known that
158960** the final (nSegment-nSuspect) members are already in sorted order
158961** (according to the comparison function provided). This function shuffles
158962** the array around until all entries are in sorted order.
158963*/
158964static void fts3SegReaderSort(
158965  Fts3SegReader **apSegment,                     /* Array to sort entries of */
158966  int nSegment,                                  /* Size of apSegment array */
158967  int nSuspect,                                  /* Unsorted entry count */
158968  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
158969){
158970  int i;                          /* Iterator variable */
158971
158972  assert( nSuspect<=nSegment );
158973
158974  if( nSuspect==nSegment ) nSuspect--;
158975  for(i=nSuspect-1; i>=0; i--){
158976    int j;
158977    for(j=i; j<(nSegment-1); j++){
158978      Fts3SegReader *pTmp;
158979      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
158980      pTmp = apSegment[j+1];
158981      apSegment[j+1] = apSegment[j];
158982      apSegment[j] = pTmp;
158983    }
158984  }
158985
158986#ifndef NDEBUG
158987  /* Check that the list really is sorted now. */
158988  for(i=0; i<(nSuspect-1); i++){
158989    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
158990  }
158991#endif
158992}
158993
158994/*
158995** Insert a record into the %_segments table.
158996*/
158997static int fts3WriteSegment(
158998  Fts3Table *p,                   /* Virtual table handle */
158999  sqlite3_int64 iBlock,           /* Block id for new block */
159000  char *z,                        /* Pointer to buffer containing block data */
159001  int n                           /* Size of buffer z in bytes */
159002){
159003  sqlite3_stmt *pStmt;
159004  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
159005  if( rc==SQLITE_OK ){
159006    sqlite3_bind_int64(pStmt, 1, iBlock);
159007    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
159008    sqlite3_step(pStmt);
159009    rc = sqlite3_reset(pStmt);
159010  }
159011  return rc;
159012}
159013
159014/*
159015** Find the largest relative level number in the table. If successful, set
159016** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
159017** set *pnMax to zero and return an SQLite error code.
159018*/
159019SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
159020  int rc;
159021  int mxLevel = 0;
159022  sqlite3_stmt *pStmt = 0;
159023
159024  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
159025  if( rc==SQLITE_OK ){
159026    if( SQLITE_ROW==sqlite3_step(pStmt) ){
159027      mxLevel = sqlite3_column_int(pStmt, 0);
159028    }
159029    rc = sqlite3_reset(pStmt);
159030  }
159031  *pnMax = mxLevel;
159032  return rc;
159033}
159034
159035/*
159036** Insert a record into the %_segdir table.
159037*/
159038static int fts3WriteSegdir(
159039  Fts3Table *p,                   /* Virtual table handle */
159040  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
159041  int iIdx,                       /* Value for "idx" field */
159042  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
159043  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
159044  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
159045  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
159046  char *zRoot,                    /* Blob value for "root" field */
159047  int nRoot                       /* Number of bytes in buffer zRoot */
159048){
159049  sqlite3_stmt *pStmt;
159050  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
159051  if( rc==SQLITE_OK ){
159052    sqlite3_bind_int64(pStmt, 1, iLevel);
159053    sqlite3_bind_int(pStmt, 2, iIdx);
159054    sqlite3_bind_int64(pStmt, 3, iStartBlock);
159055    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
159056    if( nLeafData==0 ){
159057      sqlite3_bind_int64(pStmt, 5, iEndBlock);
159058    }else{
159059      char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
159060      if( !zEnd ) return SQLITE_NOMEM;
159061      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
159062    }
159063    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
159064    sqlite3_step(pStmt);
159065    rc = sqlite3_reset(pStmt);
159066  }
159067  return rc;
159068}
159069
159070/*
159071** Return the size of the common prefix (if any) shared by zPrev and
159072** zNext, in bytes. For example,
159073**
159074**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
159075**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
159076**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
159077*/
159078static int fts3PrefixCompress(
159079  const char *zPrev,              /* Buffer containing previous term */
159080  int nPrev,                      /* Size of buffer zPrev in bytes */
159081  const char *zNext,              /* Buffer containing next term */
159082  int nNext                       /* Size of buffer zNext in bytes */
159083){
159084  int n;
159085  UNUSED_PARAMETER(nNext);
159086  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
159087  return n;
159088}
159089
159090/*
159091** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
159092** (according to memcmp) than the previous term.
159093*/
159094static int fts3NodeAddTerm(
159095  Fts3Table *p,                   /* Virtual table handle */
159096  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
159097  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
159098  const char *zTerm,              /* Pointer to buffer containing term */
159099  int nTerm                       /* Size of term in bytes */
159100){
159101  SegmentNode *pTree = *ppTree;
159102  int rc;
159103  SegmentNode *pNew;
159104
159105  /* First try to append the term to the current node. Return early if
159106  ** this is possible.
159107  */
159108  if( pTree ){
159109    int nData = pTree->nData;     /* Current size of node in bytes */
159110    int nReq = nData;             /* Required space after adding zTerm */
159111    int nPrefix;                  /* Number of bytes of prefix compression */
159112    int nSuffix;                  /* Suffix length */
159113
159114    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
159115    nSuffix = nTerm-nPrefix;
159116
159117    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
159118    if( nReq<=p->nNodeSize || !pTree->zTerm ){
159119
159120      if( nReq>p->nNodeSize ){
159121        /* An unusual case: this is the first term to be added to the node
159122        ** and the static node buffer (p->nNodeSize bytes) is not large
159123        ** enough. Use a separately malloced buffer instead This wastes
159124        ** p->nNodeSize bytes, but since this scenario only comes about when
159125        ** the database contain two terms that share a prefix of almost 2KB,
159126        ** this is not expected to be a serious problem.
159127        */
159128        assert( pTree->aData==(char *)&pTree[1] );
159129        pTree->aData = (char *)sqlite3_malloc(nReq);
159130        if( !pTree->aData ){
159131          return SQLITE_NOMEM;
159132        }
159133      }
159134
159135      if( pTree->zTerm ){
159136        /* There is no prefix-length field for first term in a node */
159137        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
159138      }
159139
159140      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
159141      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
159142      pTree->nData = nData + nSuffix;
159143      pTree->nEntry++;
159144
159145      if( isCopyTerm ){
159146        if( pTree->nMalloc<nTerm ){
159147          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
159148          if( !zNew ){
159149            return SQLITE_NOMEM;
159150          }
159151          pTree->nMalloc = nTerm*2;
159152          pTree->zMalloc = zNew;
159153        }
159154        pTree->zTerm = pTree->zMalloc;
159155        memcpy(pTree->zTerm, zTerm, nTerm);
159156        pTree->nTerm = nTerm;
159157      }else{
159158        pTree->zTerm = (char *)zTerm;
159159        pTree->nTerm = nTerm;
159160      }
159161      return SQLITE_OK;
159162    }
159163  }
159164
159165  /* If control flows to here, it was not possible to append zTerm to the
159166  ** current node. Create a new node (a right-sibling of the current node).
159167  ** If this is the first node in the tree, the term is added to it.
159168  **
159169  ** Otherwise, the term is not added to the new node, it is left empty for
159170  ** now. Instead, the term is inserted into the parent of pTree. If pTree
159171  ** has no parent, one is created here.
159172  */
159173  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
159174  if( !pNew ){
159175    return SQLITE_NOMEM;
159176  }
159177  memset(pNew, 0, sizeof(SegmentNode));
159178  pNew->nData = 1 + FTS3_VARINT_MAX;
159179  pNew->aData = (char *)&pNew[1];
159180
159181  if( pTree ){
159182    SegmentNode *pParent = pTree->pParent;
159183    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
159184    if( pTree->pParent==0 ){
159185      pTree->pParent = pParent;
159186    }
159187    pTree->pRight = pNew;
159188    pNew->pLeftmost = pTree->pLeftmost;
159189    pNew->pParent = pParent;
159190    pNew->zMalloc = pTree->zMalloc;
159191    pNew->nMalloc = pTree->nMalloc;
159192    pTree->zMalloc = 0;
159193  }else{
159194    pNew->pLeftmost = pNew;
159195    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
159196  }
159197
159198  *ppTree = pNew;
159199  return rc;
159200}
159201
159202/*
159203** Helper function for fts3NodeWrite().
159204*/
159205static int fts3TreeFinishNode(
159206  SegmentNode *pTree,
159207  int iHeight,
159208  sqlite3_int64 iLeftChild
159209){
159210  int nStart;
159211  assert( iHeight>=1 && iHeight<128 );
159212  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
159213  pTree->aData[nStart] = (char)iHeight;
159214  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
159215  return nStart;
159216}
159217
159218/*
159219** Write the buffer for the segment node pTree and all of its peers to the
159220** database. Then call this function recursively to write the parent of
159221** pTree and its peers to the database.
159222**
159223** Except, if pTree is a root node, do not write it to the database. Instead,
159224** set output variables *paRoot and *pnRoot to contain the root node.
159225**
159226** If successful, SQLITE_OK is returned and output variable *piLast is
159227** set to the largest blockid written to the database (or zero if no
159228** blocks were written to the db). Otherwise, an SQLite error code is
159229** returned.
159230*/
159231static int fts3NodeWrite(
159232  Fts3Table *p,                   /* Virtual table handle */
159233  SegmentNode *pTree,             /* SegmentNode handle */
159234  int iHeight,                    /* Height of this node in tree */
159235  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
159236  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
159237  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
159238  char **paRoot,                  /* OUT: Data for root node */
159239  int *pnRoot                     /* OUT: Size of root node in bytes */
159240){
159241  int rc = SQLITE_OK;
159242
159243  if( !pTree->pParent ){
159244    /* Root node of the tree. */
159245    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
159246    *piLast = iFree-1;
159247    *pnRoot = pTree->nData - nStart;
159248    *paRoot = &pTree->aData[nStart];
159249  }else{
159250    SegmentNode *pIter;
159251    sqlite3_int64 iNextFree = iFree;
159252    sqlite3_int64 iNextLeaf = iLeaf;
159253    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
159254      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
159255      int nWrite = pIter->nData - nStart;
159256
159257      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
159258      iNextFree++;
159259      iNextLeaf += (pIter->nEntry+1);
159260    }
159261    if( rc==SQLITE_OK ){
159262      assert( iNextLeaf==iFree );
159263      rc = fts3NodeWrite(
159264          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
159265      );
159266    }
159267  }
159268
159269  return rc;
159270}
159271
159272/*
159273** Free all memory allocations associated with the tree pTree.
159274*/
159275static void fts3NodeFree(SegmentNode *pTree){
159276  if( pTree ){
159277    SegmentNode *p = pTree->pLeftmost;
159278    fts3NodeFree(p->pParent);
159279    while( p ){
159280      SegmentNode *pRight = p->pRight;
159281      if( p->aData!=(char *)&p[1] ){
159282        sqlite3_free(p->aData);
159283      }
159284      assert( pRight==0 || p->zMalloc==0 );
159285      sqlite3_free(p->zMalloc);
159286      sqlite3_free(p);
159287      p = pRight;
159288    }
159289  }
159290}
159291
159292/*
159293** Add a term to the segment being constructed by the SegmentWriter object
159294** *ppWriter. When adding the first term to a segment, *ppWriter should
159295** be passed NULL. This function will allocate a new SegmentWriter object
159296** and return it via the input/output variable *ppWriter in this case.
159297**
159298** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
159299*/
159300static int fts3SegWriterAdd(
159301  Fts3Table *p,                   /* Virtual table handle */
159302  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
159303  int isCopyTerm,                 /* True if buffer zTerm must be copied */
159304  const char *zTerm,              /* Pointer to buffer containing term */
159305  int nTerm,                      /* Size of term in bytes */
159306  const char *aDoclist,           /* Pointer to buffer containing doclist */
159307  int nDoclist                    /* Size of doclist in bytes */
159308){
159309  int nPrefix;                    /* Size of term prefix in bytes */
159310  int nSuffix;                    /* Size of term suffix in bytes */
159311  int nReq;                       /* Number of bytes required on leaf page */
159312  int nData;
159313  SegmentWriter *pWriter = *ppWriter;
159314
159315  if( !pWriter ){
159316    int rc;
159317    sqlite3_stmt *pStmt;
159318
159319    /* Allocate the SegmentWriter structure */
159320    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
159321    if( !pWriter ) return SQLITE_NOMEM;
159322    memset(pWriter, 0, sizeof(SegmentWriter));
159323    *ppWriter = pWriter;
159324
159325    /* Allocate a buffer in which to accumulate data */
159326    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
159327    if( !pWriter->aData ) return SQLITE_NOMEM;
159328    pWriter->nSize = p->nNodeSize;
159329
159330    /* Find the next free blockid in the %_segments table */
159331    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
159332    if( rc!=SQLITE_OK ) return rc;
159333    if( SQLITE_ROW==sqlite3_step(pStmt) ){
159334      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
159335      pWriter->iFirst = pWriter->iFree;
159336    }
159337    rc = sqlite3_reset(pStmt);
159338    if( rc!=SQLITE_OK ) return rc;
159339  }
159340  nData = pWriter->nData;
159341
159342  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
159343  nSuffix = nTerm-nPrefix;
159344
159345  /* Figure out how many bytes are required by this new entry */
159346  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
159347    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
159348    nSuffix +                               /* Term suffix */
159349    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
159350    nDoclist;                               /* Doclist data */
159351
159352  if( nData>0 && nData+nReq>p->nNodeSize ){
159353    int rc;
159354
159355    /* The current leaf node is full. Write it out to the database. */
159356    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
159357    if( rc!=SQLITE_OK ) return rc;
159358    p->nLeafAdd++;
159359
159360    /* Add the current term to the interior node tree. The term added to
159361    ** the interior tree must:
159362    **
159363    **   a) be greater than the largest term on the leaf node just written
159364    **      to the database (still available in pWriter->zTerm), and
159365    **
159366    **   b) be less than or equal to the term about to be added to the new
159367    **      leaf node (zTerm/nTerm).
159368    **
159369    ** In other words, it must be the prefix of zTerm 1 byte longer than
159370    ** the common prefix (if any) of zTerm and pWriter->zTerm.
159371    */
159372    assert( nPrefix<nTerm );
159373    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
159374    if( rc!=SQLITE_OK ) return rc;
159375
159376    nData = 0;
159377    pWriter->nTerm = 0;
159378
159379    nPrefix = 0;
159380    nSuffix = nTerm;
159381    nReq = 1 +                              /* varint containing prefix size */
159382      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
159383      nTerm +                               /* Term suffix */
159384      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
159385      nDoclist;                             /* Doclist data */
159386  }
159387
159388  /* Increase the total number of bytes written to account for the new entry. */
159389  pWriter->nLeafData += nReq;
159390
159391  /* If the buffer currently allocated is too small for this entry, realloc
159392  ** the buffer to make it large enough.
159393  */
159394  if( nReq>pWriter->nSize ){
159395    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
159396    if( !aNew ) return SQLITE_NOMEM;
159397    pWriter->aData = aNew;
159398    pWriter->nSize = nReq;
159399  }
159400  assert( nData+nReq<=pWriter->nSize );
159401
159402  /* Append the prefix-compressed term and doclist to the buffer. */
159403  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
159404  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
159405  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
159406  nData += nSuffix;
159407  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
159408  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
159409  pWriter->nData = nData + nDoclist;
159410
159411  /* Save the current term so that it can be used to prefix-compress the next.
159412  ** If the isCopyTerm parameter is true, then the buffer pointed to by
159413  ** zTerm is transient, so take a copy of the term data. Otherwise, just
159414  ** store a copy of the pointer.
159415  */
159416  if( isCopyTerm ){
159417    if( nTerm>pWriter->nMalloc ){
159418      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
159419      if( !zNew ){
159420        return SQLITE_NOMEM;
159421      }
159422      pWriter->nMalloc = nTerm*2;
159423      pWriter->zMalloc = zNew;
159424      pWriter->zTerm = zNew;
159425    }
159426    assert( pWriter->zTerm==pWriter->zMalloc );
159427    memcpy(pWriter->zTerm, zTerm, nTerm);
159428  }else{
159429    pWriter->zTerm = (char *)zTerm;
159430  }
159431  pWriter->nTerm = nTerm;
159432
159433  return SQLITE_OK;
159434}
159435
159436/*
159437** Flush all data associated with the SegmentWriter object pWriter to the
159438** database. This function must be called after all terms have been added
159439** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
159440** returned. Otherwise, an SQLite error code.
159441*/
159442static int fts3SegWriterFlush(
159443  Fts3Table *p,                   /* Virtual table handle */
159444  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
159445  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
159446  int iIdx                        /* Value for 'idx' column of %_segdir */
159447){
159448  int rc;                         /* Return code */
159449  if( pWriter->pTree ){
159450    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
159451    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
159452    char *zRoot = NULL;           /* Pointer to buffer containing root node */
159453    int nRoot = 0;                /* Size of buffer zRoot */
159454
159455    iLastLeaf = pWriter->iFree;
159456    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
159457    if( rc==SQLITE_OK ){
159458      rc = fts3NodeWrite(p, pWriter->pTree, 1,
159459          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
159460    }
159461    if( rc==SQLITE_OK ){
159462      rc = fts3WriteSegdir(p, iLevel, iIdx,
159463          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
159464    }
159465  }else{
159466    /* The entire tree fits on the root node. Write it to the segdir table. */
159467    rc = fts3WriteSegdir(p, iLevel, iIdx,
159468        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
159469  }
159470  p->nLeafAdd++;
159471  return rc;
159472}
159473
159474/*
159475** Release all memory held by the SegmentWriter object passed as the
159476** first argument.
159477*/
159478static void fts3SegWriterFree(SegmentWriter *pWriter){
159479  if( pWriter ){
159480    sqlite3_free(pWriter->aData);
159481    sqlite3_free(pWriter->zMalloc);
159482    fts3NodeFree(pWriter->pTree);
159483    sqlite3_free(pWriter);
159484  }
159485}
159486
159487/*
159488** The first value in the apVal[] array is assumed to contain an integer.
159489** This function tests if there exist any documents with docid values that
159490** are different from that integer. i.e. if deleting the document with docid
159491** pRowid would mean the FTS3 table were empty.
159492**
159493** If successful, *pisEmpty is set to true if the table is empty except for
159494** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
159495** error occurs, an SQLite error code is returned.
159496*/
159497static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
159498  sqlite3_stmt *pStmt;
159499  int rc;
159500  if( p->zContentTbl ){
159501    /* If using the content=xxx option, assume the table is never empty */
159502    *pisEmpty = 0;
159503    rc = SQLITE_OK;
159504  }else{
159505    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
159506    if( rc==SQLITE_OK ){
159507      if( SQLITE_ROW==sqlite3_step(pStmt) ){
159508        *pisEmpty = sqlite3_column_int(pStmt, 0);
159509      }
159510      rc = sqlite3_reset(pStmt);
159511    }
159512  }
159513  return rc;
159514}
159515
159516/*
159517** Set *pnMax to the largest segment level in the database for the index
159518** iIndex.
159519**
159520** Segment levels are stored in the 'level' column of the %_segdir table.
159521**
159522** Return SQLITE_OK if successful, or an SQLite error code if not.
159523*/
159524static int fts3SegmentMaxLevel(
159525  Fts3Table *p,
159526  int iLangid,
159527  int iIndex,
159528  sqlite3_int64 *pnMax
159529){
159530  sqlite3_stmt *pStmt;
159531  int rc;
159532  assert( iIndex>=0 && iIndex<p->nIndex );
159533
159534  /* Set pStmt to the compiled version of:
159535  **
159536  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
159537  **
159538  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
159539  */
159540  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
159541  if( rc!=SQLITE_OK ) return rc;
159542  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
159543  sqlite3_bind_int64(pStmt, 2,
159544      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
159545  );
159546  if( SQLITE_ROW==sqlite3_step(pStmt) ){
159547    *pnMax = sqlite3_column_int64(pStmt, 0);
159548  }
159549  return sqlite3_reset(pStmt);
159550}
159551
159552/*
159553** iAbsLevel is an absolute level that may be assumed to exist within
159554** the database. This function checks if it is the largest level number
159555** within its index. Assuming no error occurs, *pbMax is set to 1 if
159556** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
159557** is returned. If an error occurs, an error code is returned and the
159558** final value of *pbMax is undefined.
159559*/
159560static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
159561
159562  /* Set pStmt to the compiled version of:
159563  **
159564  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
159565  **
159566  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
159567  */
159568  sqlite3_stmt *pStmt;
159569  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
159570  if( rc!=SQLITE_OK ) return rc;
159571  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
159572  sqlite3_bind_int64(pStmt, 2,
159573      ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
159574  );
159575
159576  *pbMax = 0;
159577  if( SQLITE_ROW==sqlite3_step(pStmt) ){
159578    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
159579  }
159580  return sqlite3_reset(pStmt);
159581}
159582
159583/*
159584** Delete all entries in the %_segments table associated with the segment
159585** opened with seg-reader pSeg. This function does not affect the contents
159586** of the %_segdir table.
159587*/
159588static int fts3DeleteSegment(
159589  Fts3Table *p,                   /* FTS table handle */
159590  Fts3SegReader *pSeg             /* Segment to delete */
159591){
159592  int rc = SQLITE_OK;             /* Return code */
159593  if( pSeg->iStartBlock ){
159594    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
159595    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
159596    if( rc==SQLITE_OK ){
159597      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
159598      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
159599      sqlite3_step(pDelete);
159600      rc = sqlite3_reset(pDelete);
159601    }
159602  }
159603  return rc;
159604}
159605
159606/*
159607** This function is used after merging multiple segments into a single large
159608** segment to delete the old, now redundant, segment b-trees. Specifically,
159609** it:
159610**
159611**   1) Deletes all %_segments entries for the segments associated with
159612**      each of the SegReader objects in the array passed as the third
159613**      argument, and
159614**
159615**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
159616**      entries regardless of level if (iLevel<0).
159617**
159618** SQLITE_OK is returned if successful, otherwise an SQLite error code.
159619*/
159620static int fts3DeleteSegdir(
159621  Fts3Table *p,                   /* Virtual table handle */
159622  int iLangid,                    /* Language id */
159623  int iIndex,                     /* Index for p->aIndex */
159624  int iLevel,                     /* Level of %_segdir entries to delete */
159625  Fts3SegReader **apSegment,      /* Array of SegReader objects */
159626  int nReader                     /* Size of array apSegment */
159627){
159628  int rc = SQLITE_OK;             /* Return Code */
159629  int i;                          /* Iterator variable */
159630  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
159631
159632  for(i=0; rc==SQLITE_OK && i<nReader; i++){
159633    rc = fts3DeleteSegment(p, apSegment[i]);
159634  }
159635  if( rc!=SQLITE_OK ){
159636    return rc;
159637  }
159638
159639  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
159640  if( iLevel==FTS3_SEGCURSOR_ALL ){
159641    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
159642    if( rc==SQLITE_OK ){
159643      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
159644      sqlite3_bind_int64(pDelete, 2,
159645          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
159646      );
159647    }
159648  }else{
159649    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
159650    if( rc==SQLITE_OK ){
159651      sqlite3_bind_int64(
159652          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
159653      );
159654    }
159655  }
159656
159657  if( rc==SQLITE_OK ){
159658    sqlite3_step(pDelete);
159659    rc = sqlite3_reset(pDelete);
159660  }
159661
159662  return rc;
159663}
159664
159665/*
159666** When this function is called, buffer *ppList (size *pnList bytes) contains
159667** a position list that may (or may not) feature multiple columns. This
159668** function adjusts the pointer *ppList and the length *pnList so that they
159669** identify the subset of the position list that corresponds to column iCol.
159670**
159671** If there are no entries in the input position list for column iCol, then
159672** *pnList is set to zero before returning.
159673**
159674** If parameter bZero is non-zero, then any part of the input list following
159675** the end of the output list is zeroed before returning.
159676*/
159677static void fts3ColumnFilter(
159678  int iCol,                       /* Column to filter on */
159679  int bZero,                      /* Zero out anything following *ppList */
159680  char **ppList,                  /* IN/OUT: Pointer to position list */
159681  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
159682){
159683  char *pList = *ppList;
159684  int nList = *pnList;
159685  char *pEnd = &pList[nList];
159686  int iCurrent = 0;
159687  char *p = pList;
159688
159689  assert( iCol>=0 );
159690  while( 1 ){
159691    char c = 0;
159692    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
159693
159694    if( iCol==iCurrent ){
159695      nList = (int)(p - pList);
159696      break;
159697    }
159698
159699    nList -= (int)(p - pList);
159700    pList = p;
159701    if( nList==0 ){
159702      break;
159703    }
159704    p = &pList[1];
159705    p += fts3GetVarint32(p, &iCurrent);
159706  }
159707
159708  if( bZero && &pList[nList]!=pEnd ){
159709    memset(&pList[nList], 0, pEnd - &pList[nList]);
159710  }
159711  *ppList = pList;
159712  *pnList = nList;
159713}
159714
159715/*
159716** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
159717** existing data). Grow the buffer if required.
159718**
159719** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
159720** trying to resize the buffer, return SQLITE_NOMEM.
159721*/
159722static int fts3MsrBufferData(
159723  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
159724  char *pList,
159725  int nList
159726){
159727  if( nList>pMsr->nBuffer ){
159728    char *pNew;
159729    pMsr->nBuffer = nList*2;
159730    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
159731    if( !pNew ) return SQLITE_NOMEM;
159732    pMsr->aBuffer = pNew;
159733  }
159734
159735  memcpy(pMsr->aBuffer, pList, nList);
159736  return SQLITE_OK;
159737}
159738
159739SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
159740  Fts3Table *p,                   /* Virtual table handle */
159741  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
159742  sqlite3_int64 *piDocid,         /* OUT: Docid value */
159743  char **paPoslist,               /* OUT: Pointer to position list */
159744  int *pnPoslist                  /* OUT: Size of position list in bytes */
159745){
159746  int nMerge = pMsr->nAdvance;
159747  Fts3SegReader **apSegment = pMsr->apSegment;
159748  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
159749    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
159750  );
159751
159752  if( nMerge==0 ){
159753    *paPoslist = 0;
159754    return SQLITE_OK;
159755  }
159756
159757  while( 1 ){
159758    Fts3SegReader *pSeg;
159759    pSeg = pMsr->apSegment[0];
159760
159761    if( pSeg->pOffsetList==0 ){
159762      *paPoslist = 0;
159763      break;
159764    }else{
159765      int rc;
159766      char *pList;
159767      int nList;
159768      int j;
159769      sqlite3_int64 iDocid = apSegment[0]->iDocid;
159770
159771      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
159772      j = 1;
159773      while( rc==SQLITE_OK
159774        && j<nMerge
159775        && apSegment[j]->pOffsetList
159776        && apSegment[j]->iDocid==iDocid
159777      ){
159778        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
159779        j++;
159780      }
159781      if( rc!=SQLITE_OK ) return rc;
159782      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
159783
159784      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
159785        rc = fts3MsrBufferData(pMsr, pList, nList+1);
159786        if( rc!=SQLITE_OK ) return rc;
159787        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
159788        pList = pMsr->aBuffer;
159789      }
159790
159791      if( pMsr->iColFilter>=0 ){
159792        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
159793      }
159794
159795      if( nList>0 ){
159796        *paPoslist = pList;
159797        *piDocid = iDocid;
159798        *pnPoslist = nList;
159799        break;
159800      }
159801    }
159802  }
159803
159804  return SQLITE_OK;
159805}
159806
159807static int fts3SegReaderStart(
159808  Fts3Table *p,                   /* Virtual table handle */
159809  Fts3MultiSegReader *pCsr,       /* Cursor object */
159810  const char *zTerm,              /* Term searched for (or NULL) */
159811  int nTerm                       /* Length of zTerm in bytes */
159812){
159813  int i;
159814  int nSeg = pCsr->nSegment;
159815
159816  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
159817  ** for, then advance each segment iterator until it points to a term of
159818  ** equal or greater value than the specified term. This prevents many
159819  ** unnecessary merge/sort operations for the case where single segment
159820  ** b-tree leaf nodes contain more than one term.
159821  */
159822  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
159823    int res = 0;
159824    Fts3SegReader *pSeg = pCsr->apSegment[i];
159825    do {
159826      int rc = fts3SegReaderNext(p, pSeg, 0);
159827      if( rc!=SQLITE_OK ) return rc;
159828    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
159829
159830    if( pSeg->bLookup && res!=0 ){
159831      fts3SegReaderSetEof(pSeg);
159832    }
159833  }
159834  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
159835
159836  return SQLITE_OK;
159837}
159838
159839SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
159840  Fts3Table *p,                   /* Virtual table handle */
159841  Fts3MultiSegReader *pCsr,       /* Cursor object */
159842  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
159843){
159844  pCsr->pFilter = pFilter;
159845  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
159846}
159847
159848SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
159849  Fts3Table *p,                   /* Virtual table handle */
159850  Fts3MultiSegReader *pCsr,       /* Cursor object */
159851  int iCol,                       /* Column to match on. */
159852  const char *zTerm,              /* Term to iterate through a doclist for */
159853  int nTerm                       /* Number of bytes in zTerm */
159854){
159855  int i;
159856  int rc;
159857  int nSegment = pCsr->nSegment;
159858  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
159859    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
159860  );
159861
159862  assert( pCsr->pFilter==0 );
159863  assert( zTerm && nTerm>0 );
159864
159865  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
159866  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
159867  if( rc!=SQLITE_OK ) return rc;
159868
159869  /* Determine how many of the segments actually point to zTerm/nTerm. */
159870  for(i=0; i<nSegment; i++){
159871    Fts3SegReader *pSeg = pCsr->apSegment[i];
159872    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
159873      break;
159874    }
159875  }
159876  pCsr->nAdvance = i;
159877
159878  /* Advance each of the segments to point to the first docid. */
159879  for(i=0; i<pCsr->nAdvance; i++){
159880    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
159881    if( rc!=SQLITE_OK ) return rc;
159882  }
159883  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
159884
159885  assert( iCol<0 || iCol<p->nColumn );
159886  pCsr->iColFilter = iCol;
159887
159888  return SQLITE_OK;
159889}
159890
159891/*
159892** This function is called on a MultiSegReader that has been started using
159893** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
159894** have been made. Calling this function puts the MultiSegReader in such
159895** a state that if the next two calls are:
159896**
159897**   sqlite3Fts3SegReaderStart()
159898**   sqlite3Fts3SegReaderStep()
159899**
159900** then the entire doclist for the term is available in
159901** MultiSegReader.aDoclist/nDoclist.
159902*/
159903SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
159904  int i;                          /* Used to iterate through segment-readers */
159905
159906  assert( pCsr->zTerm==0 );
159907  assert( pCsr->nTerm==0 );
159908  assert( pCsr->aDoclist==0 );
159909  assert( pCsr->nDoclist==0 );
159910
159911  pCsr->nAdvance = 0;
159912  pCsr->bRestart = 1;
159913  for(i=0; i<pCsr->nSegment; i++){
159914    pCsr->apSegment[i]->pOffsetList = 0;
159915    pCsr->apSegment[i]->nOffsetList = 0;
159916    pCsr->apSegment[i]->iDocid = 0;
159917  }
159918
159919  return SQLITE_OK;
159920}
159921
159922
159923SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
159924  Fts3Table *p,                   /* Virtual table handle */
159925  Fts3MultiSegReader *pCsr        /* Cursor object */
159926){
159927  int rc = SQLITE_OK;
159928
159929  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
159930  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
159931  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
159932  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
159933  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
159934  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
159935
159936  Fts3SegReader **apSegment = pCsr->apSegment;
159937  int nSegment = pCsr->nSegment;
159938  Fts3SegFilter *pFilter = pCsr->pFilter;
159939  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
159940    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
159941  );
159942
159943  if( pCsr->nSegment==0 ) return SQLITE_OK;
159944
159945  do {
159946    int nMerge;
159947    int i;
159948
159949    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
159950    ** forward. Then sort the list in order of current term again.
159951    */
159952    for(i=0; i<pCsr->nAdvance; i++){
159953      Fts3SegReader *pSeg = apSegment[i];
159954      if( pSeg->bLookup ){
159955        fts3SegReaderSetEof(pSeg);
159956      }else{
159957        rc = fts3SegReaderNext(p, pSeg, 0);
159958      }
159959      if( rc!=SQLITE_OK ) return rc;
159960    }
159961    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
159962    pCsr->nAdvance = 0;
159963
159964    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
159965    assert( rc==SQLITE_OK );
159966    if( apSegment[0]->aNode==0 ) break;
159967
159968    pCsr->nTerm = apSegment[0]->nTerm;
159969    pCsr->zTerm = apSegment[0]->zTerm;
159970
159971    /* If this is a prefix-search, and if the term that apSegment[0] points
159972    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
159973    ** required callbacks have been made. In this case exit early.
159974    **
159975    ** Similarly, if this is a search for an exact match, and the first term
159976    ** of segment apSegment[0] is not a match, exit early.
159977    */
159978    if( pFilter->zTerm && !isScan ){
159979      if( pCsr->nTerm<pFilter->nTerm
159980       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
159981       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
159982      ){
159983        break;
159984      }
159985    }
159986
159987    nMerge = 1;
159988    while( nMerge<nSegment
159989        && apSegment[nMerge]->aNode
159990        && apSegment[nMerge]->nTerm==pCsr->nTerm
159991        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
159992    ){
159993      nMerge++;
159994    }
159995
159996    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
159997    if( nMerge==1
159998     && !isIgnoreEmpty
159999     && !isFirst
160000     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
160001    ){
160002      pCsr->nDoclist = apSegment[0]->nDoclist;
160003      if( fts3SegReaderIsPending(apSegment[0]) ){
160004        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
160005        pCsr->aDoclist = pCsr->aBuffer;
160006      }else{
160007        pCsr->aDoclist = apSegment[0]->aDoclist;
160008      }
160009      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
160010    }else{
160011      int nDoclist = 0;           /* Size of doclist */
160012      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
160013
160014      /* The current term of the first nMerge entries in the array
160015      ** of Fts3SegReader objects is the same. The doclists must be merged
160016      ** and a single term returned with the merged doclist.
160017      */
160018      for(i=0; i<nMerge; i++){
160019        fts3SegReaderFirstDocid(p, apSegment[i]);
160020      }
160021      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
160022      while( apSegment[0]->pOffsetList ){
160023        int j;                    /* Number of segments that share a docid */
160024        char *pList = 0;
160025        int nList = 0;
160026        int nByte;
160027        sqlite3_int64 iDocid = apSegment[0]->iDocid;
160028        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
160029        j = 1;
160030        while( j<nMerge
160031            && apSegment[j]->pOffsetList
160032            && apSegment[j]->iDocid==iDocid
160033        ){
160034          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
160035          j++;
160036        }
160037
160038        if( isColFilter ){
160039          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
160040        }
160041
160042        if( !isIgnoreEmpty || nList>0 ){
160043
160044          /* Calculate the 'docid' delta value to write into the merged
160045          ** doclist. */
160046          sqlite3_int64 iDelta;
160047          if( p->bDescIdx && nDoclist>0 ){
160048            iDelta = iPrev - iDocid;
160049          }else{
160050            iDelta = iDocid - iPrev;
160051          }
160052          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
160053          assert( nDoclist>0 || iDelta==iDocid );
160054
160055          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
160056          if( nDoclist+nByte>pCsr->nBuffer ){
160057            char *aNew;
160058            pCsr->nBuffer = (nDoclist+nByte)*2;
160059            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
160060            if( !aNew ){
160061              return SQLITE_NOMEM;
160062            }
160063            pCsr->aBuffer = aNew;
160064          }
160065
160066          if( isFirst ){
160067            char *a = &pCsr->aBuffer[nDoclist];
160068            int nWrite;
160069
160070            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
160071            if( nWrite ){
160072              iPrev = iDocid;
160073              nDoclist += nWrite;
160074            }
160075          }else{
160076            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
160077            iPrev = iDocid;
160078            if( isRequirePos ){
160079              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
160080              nDoclist += nList;
160081              pCsr->aBuffer[nDoclist++] = '\0';
160082            }
160083          }
160084        }
160085
160086        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
160087      }
160088      if( nDoclist>0 ){
160089        pCsr->aDoclist = pCsr->aBuffer;
160090        pCsr->nDoclist = nDoclist;
160091        rc = SQLITE_ROW;
160092      }
160093    }
160094    pCsr->nAdvance = nMerge;
160095  }while( rc==SQLITE_OK );
160096
160097  return rc;
160098}
160099
160100
160101SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
160102  Fts3MultiSegReader *pCsr       /* Cursor object */
160103){
160104  if( pCsr ){
160105    int i;
160106    for(i=0; i<pCsr->nSegment; i++){
160107      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
160108    }
160109    sqlite3_free(pCsr->apSegment);
160110    sqlite3_free(pCsr->aBuffer);
160111
160112    pCsr->nSegment = 0;
160113    pCsr->apSegment = 0;
160114    pCsr->aBuffer = 0;
160115  }
160116}
160117
160118/*
160119** Decode the "end_block" field, selected by column iCol of the SELECT
160120** statement passed as the first argument.
160121**
160122** The "end_block" field may contain either an integer, or a text field
160123** containing the text representation of two non-negative integers separated
160124** by one or more space (0x20) characters. In the first case, set *piEndBlock
160125** to the integer value and *pnByte to zero before returning. In the second,
160126** set *piEndBlock to the first value and *pnByte to the second.
160127*/
160128static void fts3ReadEndBlockField(
160129  sqlite3_stmt *pStmt,
160130  int iCol,
160131  i64 *piEndBlock,
160132  i64 *pnByte
160133){
160134  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
160135  if( zText ){
160136    int i;
160137    int iMul = 1;
160138    i64 iVal = 0;
160139    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
160140      iVal = iVal*10 + (zText[i] - '0');
160141    }
160142    *piEndBlock = iVal;
160143    while( zText[i]==' ' ) i++;
160144    iVal = 0;
160145    if( zText[i]=='-' ){
160146      i++;
160147      iMul = -1;
160148    }
160149    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
160150      iVal = iVal*10 + (zText[i] - '0');
160151    }
160152    *pnByte = (iVal * (i64)iMul);
160153  }
160154}
160155
160156
160157/*
160158** A segment of size nByte bytes has just been written to absolute level
160159** iAbsLevel. Promote any segments that should be promoted as a result.
160160*/
160161static int fts3PromoteSegments(
160162  Fts3Table *p,                   /* FTS table handle */
160163  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
160164  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
160165){
160166  int rc = SQLITE_OK;
160167  sqlite3_stmt *pRange;
160168
160169  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
160170
160171  if( rc==SQLITE_OK ){
160172    int bOk = 0;
160173    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
160174    i64 nLimit = (nByte*3)/2;
160175
160176    /* Loop through all entries in the %_segdir table corresponding to
160177    ** segments in this index on levels greater than iAbsLevel. If there is
160178    ** at least one such segment, and it is possible to determine that all
160179    ** such segments are smaller than nLimit bytes in size, they will be
160180    ** promoted to level iAbsLevel.  */
160181    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
160182    sqlite3_bind_int64(pRange, 2, iLast);
160183    while( SQLITE_ROW==sqlite3_step(pRange) ){
160184      i64 nSize = 0, dummy;
160185      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
160186      if( nSize<=0 || nSize>nLimit ){
160187        /* If nSize==0, then the %_segdir.end_block field does not not
160188        ** contain a size value. This happens if it was written by an
160189        ** old version of FTS. In this case it is not possible to determine
160190        ** the size of the segment, and so segment promotion does not
160191        ** take place.  */
160192        bOk = 0;
160193        break;
160194      }
160195      bOk = 1;
160196    }
160197    rc = sqlite3_reset(pRange);
160198
160199    if( bOk ){
160200      int iIdx = 0;
160201      sqlite3_stmt *pUpdate1 = 0;
160202      sqlite3_stmt *pUpdate2 = 0;
160203
160204      if( rc==SQLITE_OK ){
160205        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
160206      }
160207      if( rc==SQLITE_OK ){
160208        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
160209      }
160210
160211      if( rc==SQLITE_OK ){
160212
160213        /* Loop through all %_segdir entries for segments in this index with
160214        ** levels equal to or greater than iAbsLevel. As each entry is visited,
160215        ** updated it to set (level = -1) and (idx = N), where N is 0 for the
160216        ** oldest segment in the range, 1 for the next oldest, and so on.
160217        **
160218        ** In other words, move all segments being promoted to level -1,
160219        ** setting the "idx" fields as appropriate to keep them in the same
160220        ** order. The contents of level -1 (which is never used, except
160221        ** transiently here), will be moved back to level iAbsLevel below.  */
160222        sqlite3_bind_int64(pRange, 1, iAbsLevel);
160223        while( SQLITE_ROW==sqlite3_step(pRange) ){
160224          sqlite3_bind_int(pUpdate1, 1, iIdx++);
160225          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
160226          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
160227          sqlite3_step(pUpdate1);
160228          rc = sqlite3_reset(pUpdate1);
160229          if( rc!=SQLITE_OK ){
160230            sqlite3_reset(pRange);
160231            break;
160232          }
160233        }
160234      }
160235      if( rc==SQLITE_OK ){
160236        rc = sqlite3_reset(pRange);
160237      }
160238
160239      /* Move level -1 to level iAbsLevel */
160240      if( rc==SQLITE_OK ){
160241        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
160242        sqlite3_step(pUpdate2);
160243        rc = sqlite3_reset(pUpdate2);
160244      }
160245    }
160246  }
160247
160248
160249  return rc;
160250}
160251
160252/*
160253** Merge all level iLevel segments in the database into a single
160254** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
160255** single segment with a level equal to the numerically largest level
160256** currently present in the database.
160257**
160258** If this function is called with iLevel<0, but there is only one
160259** segment in the database, SQLITE_DONE is returned immediately.
160260** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
160261** an SQLite error code is returned.
160262*/
160263static int fts3SegmentMerge(
160264  Fts3Table *p,
160265  int iLangid,                    /* Language id to merge */
160266  int iIndex,                     /* Index in p->aIndex[] to merge */
160267  int iLevel                      /* Level to merge */
160268){
160269  int rc;                         /* Return code */
160270  int iIdx = 0;                   /* Index of new segment */
160271  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
160272  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
160273  Fts3SegFilter filter;           /* Segment term filter condition */
160274  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
160275  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
160276  i64 iMaxLevel = 0;              /* Max level number for this index/langid */
160277
160278  assert( iLevel==FTS3_SEGCURSOR_ALL
160279       || iLevel==FTS3_SEGCURSOR_PENDING
160280       || iLevel>=0
160281  );
160282  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
160283  assert( iIndex>=0 && iIndex<p->nIndex );
160284
160285  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
160286  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
160287
160288  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
160289    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
160290    if( rc!=SQLITE_OK ) goto finished;
160291  }
160292
160293  if( iLevel==FTS3_SEGCURSOR_ALL ){
160294    /* This call is to merge all segments in the database to a single
160295    ** segment. The level of the new segment is equal to the numerically
160296    ** greatest segment level currently present in the database for this
160297    ** index. The idx of the new segment is always 0.  */
160298    if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
160299      rc = SQLITE_DONE;
160300      goto finished;
160301    }
160302    iNewLevel = iMaxLevel;
160303    bIgnoreEmpty = 1;
160304
160305  }else{
160306    /* This call is to merge all segments at level iLevel. find the next
160307    ** available segment index at level iLevel+1. The call to
160308    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
160309    ** a single iLevel+2 segment if necessary.  */
160310    assert( FTS3_SEGCURSOR_PENDING==-1 );
160311    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
160312    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
160313    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
160314  }
160315  if( rc!=SQLITE_OK ) goto finished;
160316
160317  assert( csr.nSegment>0 );
160318  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
160319  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
160320
160321  memset(&filter, 0, sizeof(Fts3SegFilter));
160322  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
160323  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
160324
160325  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
160326  while( SQLITE_OK==rc ){
160327    rc = sqlite3Fts3SegReaderStep(p, &csr);
160328    if( rc!=SQLITE_ROW ) break;
160329    rc = fts3SegWriterAdd(p, &pWriter, 1,
160330        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
160331  }
160332  if( rc!=SQLITE_OK ) goto finished;
160333  assert( pWriter || bIgnoreEmpty );
160334
160335  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
160336    rc = fts3DeleteSegdir(
160337        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
160338    );
160339    if( rc!=SQLITE_OK ) goto finished;
160340  }
160341  if( pWriter ){
160342    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
160343    if( rc==SQLITE_OK ){
160344      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
160345        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
160346      }
160347    }
160348  }
160349
160350 finished:
160351  fts3SegWriterFree(pWriter);
160352  sqlite3Fts3SegReaderFinish(&csr);
160353  return rc;
160354}
160355
160356
160357/*
160358** Flush the contents of pendingTerms to level 0 segments.
160359*/
160360SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
160361  int rc = SQLITE_OK;
160362  int i;
160363
160364  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
160365    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
160366    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
160367  }
160368  sqlite3Fts3PendingTermsClear(p);
160369
160370  /* Determine the auto-incr-merge setting if unknown.  If enabled,
160371  ** estimate the number of leaf blocks of content to be written
160372  */
160373  if( rc==SQLITE_OK && p->bHasStat
160374   && p->nAutoincrmerge==0xff && p->nLeafAdd>0
160375  ){
160376    sqlite3_stmt *pStmt = 0;
160377    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
160378    if( rc==SQLITE_OK ){
160379      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
160380      rc = sqlite3_step(pStmt);
160381      if( rc==SQLITE_ROW ){
160382        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
160383        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
160384      }else if( rc==SQLITE_DONE ){
160385        p->nAutoincrmerge = 0;
160386      }
160387      rc = sqlite3_reset(pStmt);
160388    }
160389  }
160390  return rc;
160391}
160392
160393/*
160394** Encode N integers as varints into a blob.
160395*/
160396static void fts3EncodeIntArray(
160397  int N,             /* The number of integers to encode */
160398  u32 *a,            /* The integer values */
160399  char *zBuf,        /* Write the BLOB here */
160400  int *pNBuf         /* Write number of bytes if zBuf[] used here */
160401){
160402  int i, j;
160403  for(i=j=0; i<N; i++){
160404    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
160405  }
160406  *pNBuf = j;
160407}
160408
160409/*
160410** Decode a blob of varints into N integers
160411*/
160412static void fts3DecodeIntArray(
160413  int N,             /* The number of integers to decode */
160414  u32 *a,            /* Write the integer values */
160415  const char *zBuf,  /* The BLOB containing the varints */
160416  int nBuf           /* size of the BLOB */
160417){
160418  int i, j;
160419  UNUSED_PARAMETER(nBuf);
160420  for(i=j=0; i<N; i++){
160421    sqlite3_int64 x;
160422    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
160423    assert(j<=nBuf);
160424    a[i] = (u32)(x & 0xffffffff);
160425  }
160426}
160427
160428/*
160429** Insert the sizes (in tokens) for each column of the document
160430** with docid equal to p->iPrevDocid.  The sizes are encoded as
160431** a blob of varints.
160432*/
160433static void fts3InsertDocsize(
160434  int *pRC,                       /* Result code */
160435  Fts3Table *p,                   /* Table into which to insert */
160436  u32 *aSz                        /* Sizes of each column, in tokens */
160437){
160438  char *pBlob;             /* The BLOB encoding of the document size */
160439  int nBlob;               /* Number of bytes in the BLOB */
160440  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
160441  int rc;                  /* Result code from subfunctions */
160442
160443  if( *pRC ) return;
160444  pBlob = sqlite3_malloc( 10*p->nColumn );
160445  if( pBlob==0 ){
160446    *pRC = SQLITE_NOMEM;
160447    return;
160448  }
160449  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
160450  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
160451  if( rc ){
160452    sqlite3_free(pBlob);
160453    *pRC = rc;
160454    return;
160455  }
160456  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
160457  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
160458  sqlite3_step(pStmt);
160459  *pRC = sqlite3_reset(pStmt);
160460}
160461
160462/*
160463** Record 0 of the %_stat table contains a blob consisting of N varints,
160464** where N is the number of user defined columns in the fts3 table plus
160465** two. If nCol is the number of user defined columns, then values of the
160466** varints are set as follows:
160467**
160468**   Varint 0:       Total number of rows in the table.
160469**
160470**   Varint 1..nCol: For each column, the total number of tokens stored in
160471**                   the column for all rows of the table.
160472**
160473**   Varint 1+nCol:  The total size, in bytes, of all text values in all
160474**                   columns of all rows of the table.
160475**
160476*/
160477static void fts3UpdateDocTotals(
160478  int *pRC,                       /* The result code */
160479  Fts3Table *p,                   /* Table being updated */
160480  u32 *aSzIns,                    /* Size increases */
160481  u32 *aSzDel,                    /* Size decreases */
160482  int nChng                       /* Change in the number of documents */
160483){
160484  char *pBlob;             /* Storage for BLOB written into %_stat */
160485  int nBlob;               /* Size of BLOB written into %_stat */
160486  u32 *a;                  /* Array of integers that becomes the BLOB */
160487  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
160488  int i;                   /* Loop counter */
160489  int rc;                  /* Result code from subfunctions */
160490
160491  const int nStat = p->nColumn+2;
160492
160493  if( *pRC ) return;
160494  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
160495  if( a==0 ){
160496    *pRC = SQLITE_NOMEM;
160497    return;
160498  }
160499  pBlob = (char*)&a[nStat];
160500  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
160501  if( rc ){
160502    sqlite3_free(a);
160503    *pRC = rc;
160504    return;
160505  }
160506  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
160507  if( sqlite3_step(pStmt)==SQLITE_ROW ){
160508    fts3DecodeIntArray(nStat, a,
160509         sqlite3_column_blob(pStmt, 0),
160510         sqlite3_column_bytes(pStmt, 0));
160511  }else{
160512    memset(a, 0, sizeof(u32)*(nStat) );
160513  }
160514  rc = sqlite3_reset(pStmt);
160515  if( rc!=SQLITE_OK ){
160516    sqlite3_free(a);
160517    *pRC = rc;
160518    return;
160519  }
160520  if( nChng<0 && a[0]<(u32)(-nChng) ){
160521    a[0] = 0;
160522  }else{
160523    a[0] += nChng;
160524  }
160525  for(i=0; i<p->nColumn+1; i++){
160526    u32 x = a[i+1];
160527    if( x+aSzIns[i] < aSzDel[i] ){
160528      x = 0;
160529    }else{
160530      x = x + aSzIns[i] - aSzDel[i];
160531    }
160532    a[i+1] = x;
160533  }
160534  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
160535  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
160536  if( rc ){
160537    sqlite3_free(a);
160538    *pRC = rc;
160539    return;
160540  }
160541  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
160542  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
160543  sqlite3_step(pStmt);
160544  *pRC = sqlite3_reset(pStmt);
160545  sqlite3_free(a);
160546}
160547
160548/*
160549** Merge the entire database so that there is one segment for each
160550** iIndex/iLangid combination.
160551*/
160552static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
160553  int bSeenDone = 0;
160554  int rc;
160555  sqlite3_stmt *pAllLangid = 0;
160556
160557  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
160558  if( rc==SQLITE_OK ){
160559    int rc2;
160560    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
160561    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
160562    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
160563      int i;
160564      int iLangid = sqlite3_column_int(pAllLangid, 0);
160565      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
160566        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
160567        if( rc==SQLITE_DONE ){
160568          bSeenDone = 1;
160569          rc = SQLITE_OK;
160570        }
160571      }
160572    }
160573    rc2 = sqlite3_reset(pAllLangid);
160574    if( rc==SQLITE_OK ) rc = rc2;
160575  }
160576
160577  sqlite3Fts3SegmentsClose(p);
160578  sqlite3Fts3PendingTermsClear(p);
160579
160580  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
160581}
160582
160583/*
160584** This function is called when the user executes the following statement:
160585**
160586**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
160587**
160588** The entire FTS index is discarded and rebuilt. If the table is one
160589** created using the content=xxx option, then the new index is based on
160590** the current contents of the xxx table. Otherwise, it is rebuilt based
160591** on the contents of the %_content table.
160592*/
160593static int fts3DoRebuild(Fts3Table *p){
160594  int rc;                         /* Return Code */
160595
160596  rc = fts3DeleteAll(p, 0);
160597  if( rc==SQLITE_OK ){
160598    u32 *aSz = 0;
160599    u32 *aSzIns = 0;
160600    u32 *aSzDel = 0;
160601    sqlite3_stmt *pStmt = 0;
160602    int nEntry = 0;
160603
160604    /* Compose and prepare an SQL statement to loop through the content table */
160605    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
160606    if( !zSql ){
160607      rc = SQLITE_NOMEM;
160608    }else{
160609      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
160610      sqlite3_free(zSql);
160611    }
160612
160613    if( rc==SQLITE_OK ){
160614      int nByte = sizeof(u32) * (p->nColumn+1)*3;
160615      aSz = (u32 *)sqlite3_malloc(nByte);
160616      if( aSz==0 ){
160617        rc = SQLITE_NOMEM;
160618      }else{
160619        memset(aSz, 0, nByte);
160620        aSzIns = &aSz[p->nColumn+1];
160621        aSzDel = &aSzIns[p->nColumn+1];
160622      }
160623    }
160624
160625    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
160626      int iCol;
160627      int iLangid = langidFromSelect(p, pStmt);
160628      rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
160629      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
160630      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
160631        if( p->abNotindexed[iCol]==0 ){
160632          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
160633          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
160634          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
160635        }
160636      }
160637      if( p->bHasDocsize ){
160638        fts3InsertDocsize(&rc, p, aSz);
160639      }
160640      if( rc!=SQLITE_OK ){
160641        sqlite3_finalize(pStmt);
160642        pStmt = 0;
160643      }else{
160644        nEntry++;
160645        for(iCol=0; iCol<=p->nColumn; iCol++){
160646          aSzIns[iCol] += aSz[iCol];
160647        }
160648      }
160649    }
160650    if( p->bFts4 ){
160651      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
160652    }
160653    sqlite3_free(aSz);
160654
160655    if( pStmt ){
160656      int rc2 = sqlite3_finalize(pStmt);
160657      if( rc==SQLITE_OK ){
160658        rc = rc2;
160659      }
160660    }
160661  }
160662
160663  return rc;
160664}
160665
160666
160667/*
160668** This function opens a cursor used to read the input data for an
160669** incremental merge operation. Specifically, it opens a cursor to scan
160670** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
160671** level iAbsLevel.
160672*/
160673static int fts3IncrmergeCsr(
160674  Fts3Table *p,                   /* FTS3 table handle */
160675  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
160676  int nSeg,                       /* Number of segments to merge */
160677  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
160678){
160679  int rc;                         /* Return Code */
160680  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
160681  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
160682
160683  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
160684  memset(pCsr, 0, sizeof(*pCsr));
160685  nByte = sizeof(Fts3SegReader *) * nSeg;
160686  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
160687
160688  if( pCsr->apSegment==0 ){
160689    rc = SQLITE_NOMEM;
160690  }else{
160691    memset(pCsr->apSegment, 0, nByte);
160692    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
160693  }
160694  if( rc==SQLITE_OK ){
160695    int i;
160696    int rc2;
160697    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
160698    assert( pCsr->nSegment==0 );
160699    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
160700      rc = sqlite3Fts3SegReaderNew(i, 0,
160701          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
160702          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
160703          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
160704          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
160705          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
160706          &pCsr->apSegment[i]
160707      );
160708      pCsr->nSegment++;
160709    }
160710    rc2 = sqlite3_reset(pStmt);
160711    if( rc==SQLITE_OK ) rc = rc2;
160712  }
160713
160714  return rc;
160715}
160716
160717typedef struct IncrmergeWriter IncrmergeWriter;
160718typedef struct NodeWriter NodeWriter;
160719typedef struct Blob Blob;
160720typedef struct NodeReader NodeReader;
160721
160722/*
160723** An instance of the following structure is used as a dynamic buffer
160724** to build up nodes or other blobs of data in.
160725**
160726** The function blobGrowBuffer() is used to extend the allocation.
160727*/
160728struct Blob {
160729  char *a;                        /* Pointer to allocation */
160730  int n;                          /* Number of valid bytes of data in a[] */
160731  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
160732};
160733
160734/*
160735** This structure is used to build up buffers containing segment b-tree
160736** nodes (blocks).
160737*/
160738struct NodeWriter {
160739  sqlite3_int64 iBlock;           /* Current block id */
160740  Blob key;                       /* Last key written to the current block */
160741  Blob block;                     /* Current block image */
160742};
160743
160744/*
160745** An object of this type contains the state required to create or append
160746** to an appendable b-tree segment.
160747*/
160748struct IncrmergeWriter {
160749  int nLeafEst;                   /* Space allocated for leaf blocks */
160750  int nWork;                      /* Number of leaf pages flushed */
160751  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
160752  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
160753  sqlite3_int64 iStart;           /* Block number of first allocated block */
160754  sqlite3_int64 iEnd;             /* Block number of last allocated block */
160755  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
160756  u8 bNoLeafData;                 /* If true, store 0 for segment size */
160757  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
160758};
160759
160760/*
160761** An object of the following type is used to read data from a single
160762** FTS segment node. See the following functions:
160763**
160764**     nodeReaderInit()
160765**     nodeReaderNext()
160766**     nodeReaderRelease()
160767*/
160768struct NodeReader {
160769  const char *aNode;
160770  int nNode;
160771  int iOff;                       /* Current offset within aNode[] */
160772
160773  /* Output variables. Containing the current node entry. */
160774  sqlite3_int64 iChild;           /* Pointer to child node */
160775  Blob term;                      /* Current term */
160776  const char *aDoclist;           /* Pointer to doclist */
160777  int nDoclist;                   /* Size of doclist in bytes */
160778};
160779
160780/*
160781** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
160782** Otherwise, if the allocation at pBlob->a is not already at least nMin
160783** bytes in size, extend (realloc) it to be so.
160784**
160785** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
160786** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
160787** to reflect the new size of the pBlob->a[] buffer.
160788*/
160789static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
160790  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
160791    int nAlloc = nMin;
160792    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
160793    if( a ){
160794      pBlob->nAlloc = nAlloc;
160795      pBlob->a = a;
160796    }else{
160797      *pRc = SQLITE_NOMEM;
160798    }
160799  }
160800}
160801
160802/*
160803** Attempt to advance the node-reader object passed as the first argument to
160804** the next entry on the node.
160805**
160806** Return an error code if an error occurs (SQLITE_NOMEM is possible).
160807** Otherwise return SQLITE_OK. If there is no next entry on the node
160808** (e.g. because the current entry is the last) set NodeReader->aNode to
160809** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
160810** variables for the new entry.
160811*/
160812static int nodeReaderNext(NodeReader *p){
160813  int bFirst = (p->term.n==0);    /* True for first term on the node */
160814  int nPrefix = 0;                /* Bytes to copy from previous term */
160815  int nSuffix = 0;                /* Bytes to append to the prefix */
160816  int rc = SQLITE_OK;             /* Return code */
160817
160818  assert( p->aNode );
160819  if( p->iChild && bFirst==0 ) p->iChild++;
160820  if( p->iOff>=p->nNode ){
160821    /* EOF */
160822    p->aNode = 0;
160823  }else{
160824    if( bFirst==0 ){
160825      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
160826    }
160827    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
160828
160829    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
160830    if( rc==SQLITE_OK ){
160831      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
160832      p->term.n = nPrefix+nSuffix;
160833      p->iOff += nSuffix;
160834      if( p->iChild==0 ){
160835        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
160836        p->aDoclist = &p->aNode[p->iOff];
160837        p->iOff += p->nDoclist;
160838      }
160839    }
160840  }
160841
160842  assert( p->iOff<=p->nNode );
160843
160844  return rc;
160845}
160846
160847/*
160848** Release all dynamic resources held by node-reader object *p.
160849*/
160850static void nodeReaderRelease(NodeReader *p){
160851  sqlite3_free(p->term.a);
160852}
160853
160854/*
160855** Initialize a node-reader object to read the node in buffer aNode/nNode.
160856**
160857** If successful, SQLITE_OK is returned and the NodeReader object set to
160858** point to the first entry on the node (if any). Otherwise, an SQLite
160859** error code is returned.
160860*/
160861static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
160862  memset(p, 0, sizeof(NodeReader));
160863  p->aNode = aNode;
160864  p->nNode = nNode;
160865
160866  /* Figure out if this is a leaf or an internal node. */
160867  if( p->aNode[0] ){
160868    /* An internal node. */
160869    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
160870  }else{
160871    p->iOff = 1;
160872  }
160873
160874  return nodeReaderNext(p);
160875}
160876
160877/*
160878** This function is called while writing an FTS segment each time a leaf o
160879** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
160880** to be greater than the largest key on the node just written, but smaller
160881** than or equal to the first key that will be written to the next leaf
160882** node.
160883**
160884** The block id of the leaf node just written to disk may be found in
160885** (pWriter->aNodeWriter[0].iBlock) when this function is called.
160886*/
160887static int fts3IncrmergePush(
160888  Fts3Table *p,                   /* Fts3 table handle */
160889  IncrmergeWriter *pWriter,       /* Writer object */
160890  const char *zTerm,              /* Term to write to internal node */
160891  int nTerm                       /* Bytes at zTerm */
160892){
160893  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
160894  int iLayer;
160895
160896  assert( nTerm>0 );
160897  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
160898    sqlite3_int64 iNextPtr = 0;
160899    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
160900    int rc = SQLITE_OK;
160901    int nPrefix;
160902    int nSuffix;
160903    int nSpace;
160904
160905    /* Figure out how much space the key will consume if it is written to
160906    ** the current node of layer iLayer. Due to the prefix compression,
160907    ** the space required changes depending on which node the key is to
160908    ** be added to.  */
160909    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
160910    nSuffix = nTerm - nPrefix;
160911    nSpace  = sqlite3Fts3VarintLen(nPrefix);
160912    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
160913
160914    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
160915      /* If the current node of layer iLayer contains zero keys, or if adding
160916      ** the key to it will not cause it to grow to larger than nNodeSize
160917      ** bytes in size, write the key here.  */
160918
160919      Blob *pBlk = &pNode->block;
160920      if( pBlk->n==0 ){
160921        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
160922        if( rc==SQLITE_OK ){
160923          pBlk->a[0] = (char)iLayer;
160924          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
160925        }
160926      }
160927      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
160928      blobGrowBuffer(&pNode->key, nTerm, &rc);
160929
160930      if( rc==SQLITE_OK ){
160931        if( pNode->key.n ){
160932          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
160933        }
160934        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
160935        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
160936        pBlk->n += nSuffix;
160937
160938        memcpy(pNode->key.a, zTerm, nTerm);
160939        pNode->key.n = nTerm;
160940      }
160941    }else{
160942      /* Otherwise, flush the current node of layer iLayer to disk.
160943      ** Then allocate a new, empty sibling node. The key will be written
160944      ** into the parent of this node. */
160945      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
160946
160947      assert( pNode->block.nAlloc>=p->nNodeSize );
160948      pNode->block.a[0] = (char)iLayer;
160949      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
160950
160951      iNextPtr = pNode->iBlock;
160952      pNode->iBlock++;
160953      pNode->key.n = 0;
160954    }
160955
160956    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
160957    iPtr = iNextPtr;
160958  }
160959
160960  assert( 0 );
160961  return 0;
160962}
160963
160964/*
160965** Append a term and (optionally) doclist to the FTS segment node currently
160966** stored in blob *pNode. The node need not contain any terms, but the
160967** header must be written before this function is called.
160968**
160969** A node header is a single 0x00 byte for a leaf node, or a height varint
160970** followed by the left-hand-child varint for an internal node.
160971**
160972** The term to be appended is passed via arguments zTerm/nTerm. For a
160973** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
160974** node, both aDoclist and nDoclist must be passed 0.
160975**
160976** If the size of the value in blob pPrev is zero, then this is the first
160977** term written to the node. Otherwise, pPrev contains a copy of the
160978** previous term. Before this function returns, it is updated to contain a
160979** copy of zTerm/nTerm.
160980**
160981** It is assumed that the buffer associated with pNode is already large
160982** enough to accommodate the new entry. The buffer associated with pPrev
160983** is extended by this function if requrired.
160984**
160985** If an error (i.e. OOM condition) occurs, an SQLite error code is
160986** returned. Otherwise, SQLITE_OK.
160987*/
160988static int fts3AppendToNode(
160989  Blob *pNode,                    /* Current node image to append to */
160990  Blob *pPrev,                    /* Buffer containing previous term written */
160991  const char *zTerm,              /* New term to write */
160992  int nTerm,                      /* Size of zTerm in bytes */
160993  const char *aDoclist,           /* Doclist (or NULL) to write */
160994  int nDoclist                    /* Size of aDoclist in bytes */
160995){
160996  int rc = SQLITE_OK;             /* Return code */
160997  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
160998  int nPrefix;                    /* Size of term prefix in bytes */
160999  int nSuffix;                    /* Size of term suffix in bytes */
161000
161001  /* Node must have already been started. There must be a doclist for a
161002  ** leaf node, and there must not be a doclist for an internal node.  */
161003  assert( pNode->n>0 );
161004  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
161005
161006  blobGrowBuffer(pPrev, nTerm, &rc);
161007  if( rc!=SQLITE_OK ) return rc;
161008
161009  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
161010  nSuffix = nTerm - nPrefix;
161011  memcpy(pPrev->a, zTerm, nTerm);
161012  pPrev->n = nTerm;
161013
161014  if( bFirst==0 ){
161015    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
161016  }
161017  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
161018  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
161019  pNode->n += nSuffix;
161020
161021  if( aDoclist ){
161022    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
161023    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
161024    pNode->n += nDoclist;
161025  }
161026
161027  assert( pNode->n<=pNode->nAlloc );
161028
161029  return SQLITE_OK;
161030}
161031
161032/*
161033** Append the current term and doclist pointed to by cursor pCsr to the
161034** appendable b-tree segment opened for writing by pWriter.
161035**
161036** Return SQLITE_OK if successful, or an SQLite error code otherwise.
161037*/
161038static int fts3IncrmergeAppend(
161039  Fts3Table *p,                   /* Fts3 table handle */
161040  IncrmergeWriter *pWriter,       /* Writer object */
161041  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
161042){
161043  const char *zTerm = pCsr->zTerm;
161044  int nTerm = pCsr->nTerm;
161045  const char *aDoclist = pCsr->aDoclist;
161046  int nDoclist = pCsr->nDoclist;
161047  int rc = SQLITE_OK;           /* Return code */
161048  int nSpace;                   /* Total space in bytes required on leaf */
161049  int nPrefix;                  /* Size of prefix shared with previous term */
161050  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
161051  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
161052
161053  pLeaf = &pWriter->aNodeWriter[0];
161054  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
161055  nSuffix = nTerm - nPrefix;
161056
161057  nSpace  = sqlite3Fts3VarintLen(nPrefix);
161058  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
161059  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
161060
161061  /* If the current block is not empty, and if adding this term/doclist
161062  ** to the current block would make it larger than Fts3Table.nNodeSize
161063  ** bytes, write this block out to the database. */
161064  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
161065    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
161066    pWriter->nWork++;
161067
161068    /* Add the current term to the parent node. The term added to the
161069    ** parent must:
161070    **
161071    **   a) be greater than the largest term on the leaf node just written
161072    **      to the database (still available in pLeaf->key), and
161073    **
161074    **   b) be less than or equal to the term about to be added to the new
161075    **      leaf node (zTerm/nTerm).
161076    **
161077    ** In other words, it must be the prefix of zTerm 1 byte longer than
161078    ** the common prefix (if any) of zTerm and pWriter->zTerm.
161079    */
161080    if( rc==SQLITE_OK ){
161081      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
161082    }
161083
161084    /* Advance to the next output block */
161085    pLeaf->iBlock++;
161086    pLeaf->key.n = 0;
161087    pLeaf->block.n = 0;
161088
161089    nSuffix = nTerm;
161090    nSpace  = 1;
161091    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
161092    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
161093  }
161094
161095  pWriter->nLeafData += nSpace;
161096  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
161097  if( rc==SQLITE_OK ){
161098    if( pLeaf->block.n==0 ){
161099      pLeaf->block.n = 1;
161100      pLeaf->block.a[0] = '\0';
161101    }
161102    rc = fts3AppendToNode(
161103        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
161104    );
161105  }
161106
161107  return rc;
161108}
161109
161110/*
161111** This function is called to release all dynamic resources held by the
161112** merge-writer object pWriter, and if no error has occurred, to flush
161113** all outstanding node buffers held by pWriter to disk.
161114**
161115** If *pRc is not SQLITE_OK when this function is called, then no attempt
161116** is made to write any data to disk. Instead, this function serves only
161117** to release outstanding resources.
161118**
161119** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
161120** flushing buffers to disk, *pRc is set to an SQLite error code before
161121** returning.
161122*/
161123static void fts3IncrmergeRelease(
161124  Fts3Table *p,                   /* FTS3 table handle */
161125  IncrmergeWriter *pWriter,       /* Merge-writer object */
161126  int *pRc                        /* IN/OUT: Error code */
161127){
161128  int i;                          /* Used to iterate through non-root layers */
161129  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
161130  NodeWriter *pRoot;              /* NodeWriter for root node */
161131  int rc = *pRc;                  /* Error code */
161132
161133  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
161134  ** root node. If the segment fits entirely on a single leaf node, iRoot
161135  ** will be set to 0. If the root node is the parent of the leaves, iRoot
161136  ** will be 1. And so on.  */
161137  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
161138    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
161139    if( pNode->block.n>0 ) break;
161140    assert( *pRc || pNode->block.nAlloc==0 );
161141    assert( *pRc || pNode->key.nAlloc==0 );
161142    sqlite3_free(pNode->block.a);
161143    sqlite3_free(pNode->key.a);
161144  }
161145
161146  /* Empty output segment. This is a no-op. */
161147  if( iRoot<0 ) return;
161148
161149  /* The entire output segment fits on a single node. Normally, this means
161150  ** the node would be stored as a blob in the "root" column of the %_segdir
161151  ** table. However, this is not permitted in this case. The problem is that
161152  ** space has already been reserved in the %_segments table, and so the
161153  ** start_block and end_block fields of the %_segdir table must be populated.
161154  ** And, by design or by accident, released versions of FTS cannot handle
161155  ** segments that fit entirely on the root node with start_block!=0.
161156  **
161157  ** Instead, create a synthetic root node that contains nothing but a
161158  ** pointer to the single content node. So that the segment consists of a
161159  ** single leaf and a single interior (root) node.
161160  **
161161  ** Todo: Better might be to defer allocating space in the %_segments
161162  ** table until we are sure it is needed.
161163  */
161164  if( iRoot==0 ){
161165    Blob *pBlock = &pWriter->aNodeWriter[1].block;
161166    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
161167    if( rc==SQLITE_OK ){
161168      pBlock->a[0] = 0x01;
161169      pBlock->n = 1 + sqlite3Fts3PutVarint(
161170          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
161171      );
161172    }
161173    iRoot = 1;
161174  }
161175  pRoot = &pWriter->aNodeWriter[iRoot];
161176
161177  /* Flush all currently outstanding nodes to disk. */
161178  for(i=0; i<iRoot; i++){
161179    NodeWriter *pNode = &pWriter->aNodeWriter[i];
161180    if( pNode->block.n>0 && rc==SQLITE_OK ){
161181      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
161182    }
161183    sqlite3_free(pNode->block.a);
161184    sqlite3_free(pNode->key.a);
161185  }
161186
161187  /* Write the %_segdir record. */
161188  if( rc==SQLITE_OK ){
161189    rc = fts3WriteSegdir(p,
161190        pWriter->iAbsLevel+1,               /* level */
161191        pWriter->iIdx,                      /* idx */
161192        pWriter->iStart,                    /* start_block */
161193        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
161194        pWriter->iEnd,                      /* end_block */
161195        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
161196        pRoot->block.a, pRoot->block.n      /* root */
161197    );
161198  }
161199  sqlite3_free(pRoot->block.a);
161200  sqlite3_free(pRoot->key.a);
161201
161202  *pRc = rc;
161203}
161204
161205/*
161206** Compare the term in buffer zLhs (size in bytes nLhs) with that in
161207** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
161208** the other, it is considered to be smaller than the other.
161209**
161210** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
161211** if it is greater.
161212*/
161213static int fts3TermCmp(
161214  const char *zLhs, int nLhs,     /* LHS of comparison */
161215  const char *zRhs, int nRhs      /* RHS of comparison */
161216){
161217  int nCmp = MIN(nLhs, nRhs);
161218  int res;
161219
161220  res = memcmp(zLhs, zRhs, nCmp);
161221  if( res==0 ) res = nLhs - nRhs;
161222
161223  return res;
161224}
161225
161226
161227/*
161228** Query to see if the entry in the %_segments table with blockid iEnd is
161229** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
161230** returning. Otherwise, set *pbRes to 0.
161231**
161232** Or, if an error occurs while querying the database, return an SQLite
161233** error code. The final value of *pbRes is undefined in this case.
161234**
161235** This is used to test if a segment is an "appendable" segment. If it
161236** is, then a NULL entry has been inserted into the %_segments table
161237** with blockid %_segdir.end_block.
161238*/
161239static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
161240  int bRes = 0;                   /* Result to set *pbRes to */
161241  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
161242  int rc;                         /* Return code */
161243
161244  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
161245  if( rc==SQLITE_OK ){
161246    sqlite3_bind_int64(pCheck, 1, iEnd);
161247    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
161248    rc = sqlite3_reset(pCheck);
161249  }
161250
161251  *pbRes = bRes;
161252  return rc;
161253}
161254
161255/*
161256** This function is called when initializing an incremental-merge operation.
161257** It checks if the existing segment with index value iIdx at absolute level
161258** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
161259** merge-writer object *pWriter is initialized to write to it.
161260**
161261** An existing segment can be appended to by an incremental merge if:
161262**
161263**   * It was initially created as an appendable segment (with all required
161264**     space pre-allocated), and
161265**
161266**   * The first key read from the input (arguments zKey and nKey) is
161267**     greater than the largest key currently stored in the potential
161268**     output segment.
161269*/
161270static int fts3IncrmergeLoad(
161271  Fts3Table *p,                   /* Fts3 table handle */
161272  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
161273  int iIdx,                       /* Index of candidate output segment */
161274  const char *zKey,               /* First key to write */
161275  int nKey,                       /* Number of bytes in nKey */
161276  IncrmergeWriter *pWriter        /* Populate this object */
161277){
161278  int rc;                         /* Return code */
161279  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
161280
161281  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
161282  if( rc==SQLITE_OK ){
161283    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
161284    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
161285    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
161286    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
161287    int nRoot = 0;                /* Size of aRoot[] in bytes */
161288    int rc2;                      /* Return code from sqlite3_reset() */
161289    int bAppendable = 0;          /* Set to true if segment is appendable */
161290
161291    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
161292    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
161293    sqlite3_bind_int(pSelect, 2, iIdx);
161294    if( sqlite3_step(pSelect)==SQLITE_ROW ){
161295      iStart = sqlite3_column_int64(pSelect, 1);
161296      iLeafEnd = sqlite3_column_int64(pSelect, 2);
161297      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
161298      if( pWriter->nLeafData<0 ){
161299        pWriter->nLeafData = pWriter->nLeafData * -1;
161300      }
161301      pWriter->bNoLeafData = (pWriter->nLeafData==0);
161302      nRoot = sqlite3_column_bytes(pSelect, 4);
161303      aRoot = sqlite3_column_blob(pSelect, 4);
161304    }else{
161305      return sqlite3_reset(pSelect);
161306    }
161307
161308    /* Check for the zero-length marker in the %_segments table */
161309    rc = fts3IsAppendable(p, iEnd, &bAppendable);
161310
161311    /* Check that zKey/nKey is larger than the largest key the candidate */
161312    if( rc==SQLITE_OK && bAppendable ){
161313      char *aLeaf = 0;
161314      int nLeaf = 0;
161315
161316      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
161317      if( rc==SQLITE_OK ){
161318        NodeReader reader;
161319        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
161320            rc==SQLITE_OK && reader.aNode;
161321            rc = nodeReaderNext(&reader)
161322        ){
161323          assert( reader.aNode );
161324        }
161325        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
161326          bAppendable = 0;
161327        }
161328        nodeReaderRelease(&reader);
161329      }
161330      sqlite3_free(aLeaf);
161331    }
161332
161333    if( rc==SQLITE_OK && bAppendable ){
161334      /* It is possible to append to this segment. Set up the IncrmergeWriter
161335      ** object to do so.  */
161336      int i;
161337      int nHeight = (int)aRoot[0];
161338      NodeWriter *pNode;
161339
161340      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
161341      pWriter->iStart = iStart;
161342      pWriter->iEnd = iEnd;
161343      pWriter->iAbsLevel = iAbsLevel;
161344      pWriter->iIdx = iIdx;
161345
161346      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
161347        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
161348      }
161349
161350      pNode = &pWriter->aNodeWriter[nHeight];
161351      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
161352      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
161353      if( rc==SQLITE_OK ){
161354        memcpy(pNode->block.a, aRoot, nRoot);
161355        pNode->block.n = nRoot;
161356      }
161357
161358      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
161359        NodeReader reader;
161360        pNode = &pWriter->aNodeWriter[i];
161361
161362        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
161363        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
161364        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
161365        if( rc==SQLITE_OK ){
161366          memcpy(pNode->key.a, reader.term.a, reader.term.n);
161367          pNode->key.n = reader.term.n;
161368          if( i>0 ){
161369            char *aBlock = 0;
161370            int nBlock = 0;
161371            pNode = &pWriter->aNodeWriter[i-1];
161372            pNode->iBlock = reader.iChild;
161373            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
161374            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
161375            if( rc==SQLITE_OK ){
161376              memcpy(pNode->block.a, aBlock, nBlock);
161377              pNode->block.n = nBlock;
161378            }
161379            sqlite3_free(aBlock);
161380          }
161381        }
161382        nodeReaderRelease(&reader);
161383      }
161384    }
161385
161386    rc2 = sqlite3_reset(pSelect);
161387    if( rc==SQLITE_OK ) rc = rc2;
161388  }
161389
161390  return rc;
161391}
161392
161393/*
161394** Determine the largest segment index value that exists within absolute
161395** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
161396** one before returning SQLITE_OK. Or, if there are no segments at all
161397** within level iAbsLevel, set *piIdx to zero.
161398**
161399** If an error occurs, return an SQLite error code. The final value of
161400** *piIdx is undefined in this case.
161401*/
161402static int fts3IncrmergeOutputIdx(
161403  Fts3Table *p,                   /* FTS Table handle */
161404  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
161405  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
161406){
161407  int rc;
161408  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
161409
161410  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
161411  if( rc==SQLITE_OK ){
161412    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
161413    sqlite3_step(pOutputIdx);
161414    *piIdx = sqlite3_column_int(pOutputIdx, 0);
161415    rc = sqlite3_reset(pOutputIdx);
161416  }
161417
161418  return rc;
161419}
161420
161421/*
161422** Allocate an appendable output segment on absolute level iAbsLevel+1
161423** with idx value iIdx.
161424**
161425** In the %_segdir table, a segment is defined by the values in three
161426** columns:
161427**
161428**     start_block
161429**     leaves_end_block
161430**     end_block
161431**
161432** When an appendable segment is allocated, it is estimated that the
161433** maximum number of leaf blocks that may be required is the sum of the
161434** number of leaf blocks consumed by the input segments, plus the number
161435** of input segments, multiplied by two. This value is stored in stack
161436** variable nLeafEst.
161437**
161438** A total of 16*nLeafEst blocks are allocated when an appendable segment
161439** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
161440** array of leaf nodes starts at the first block allocated. The array
161441** of interior nodes that are parents of the leaf nodes start at block
161442** (start_block + (1 + end_block - start_block) / 16). And so on.
161443**
161444** In the actual code below, the value "16" is replaced with the
161445** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
161446*/
161447static int fts3IncrmergeWriter(
161448  Fts3Table *p,                   /* Fts3 table handle */
161449  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
161450  int iIdx,                       /* Index of new output segment */
161451  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
161452  IncrmergeWriter *pWriter        /* Populate this object */
161453){
161454  int rc;                         /* Return Code */
161455  int i;                          /* Iterator variable */
161456  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
161457  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
161458  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
161459
161460  /* Calculate nLeafEst. */
161461  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
161462  if( rc==SQLITE_OK ){
161463    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
161464    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
161465    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
161466      nLeafEst = sqlite3_column_int(pLeafEst, 0);
161467    }
161468    rc = sqlite3_reset(pLeafEst);
161469  }
161470  if( rc!=SQLITE_OK ) return rc;
161471
161472  /* Calculate the first block to use in the output segment */
161473  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
161474  if( rc==SQLITE_OK ){
161475    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
161476      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
161477      pWriter->iEnd = pWriter->iStart - 1;
161478      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
161479    }
161480    rc = sqlite3_reset(pFirstBlock);
161481  }
161482  if( rc!=SQLITE_OK ) return rc;
161483
161484  /* Insert the marker in the %_segments table to make sure nobody tries
161485  ** to steal the space just allocated. This is also used to identify
161486  ** appendable segments.  */
161487  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
161488  if( rc!=SQLITE_OK ) return rc;
161489
161490  pWriter->iAbsLevel = iAbsLevel;
161491  pWriter->nLeafEst = nLeafEst;
161492  pWriter->iIdx = iIdx;
161493
161494  /* Set up the array of NodeWriter objects */
161495  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
161496    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
161497  }
161498  return SQLITE_OK;
161499}
161500
161501/*
161502** Remove an entry from the %_segdir table. This involves running the
161503** following two statements:
161504**
161505**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
161506**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
161507**
161508** The DELETE statement removes the specific %_segdir level. The UPDATE
161509** statement ensures that the remaining segments have contiguously allocated
161510** idx values.
161511*/
161512static int fts3RemoveSegdirEntry(
161513  Fts3Table *p,                   /* FTS3 table handle */
161514  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
161515  int iIdx                        /* Index of %_segdir entry to delete */
161516){
161517  int rc;                         /* Return code */
161518  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
161519
161520  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
161521  if( rc==SQLITE_OK ){
161522    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
161523    sqlite3_bind_int(pDelete, 2, iIdx);
161524    sqlite3_step(pDelete);
161525    rc = sqlite3_reset(pDelete);
161526  }
161527
161528  return rc;
161529}
161530
161531/*
161532** One or more segments have just been removed from absolute level iAbsLevel.
161533** Update the 'idx' values of the remaining segments in the level so that
161534** the idx values are a contiguous sequence starting from 0.
161535*/
161536static int fts3RepackSegdirLevel(
161537  Fts3Table *p,                   /* FTS3 table handle */
161538  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
161539){
161540  int rc;                         /* Return code */
161541  int *aIdx = 0;                  /* Array of remaining idx values */
161542  int nIdx = 0;                   /* Valid entries in aIdx[] */
161543  int nAlloc = 0;                 /* Allocated size of aIdx[] */
161544  int i;                          /* Iterator variable */
161545  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
161546  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
161547
161548  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
161549  if( rc==SQLITE_OK ){
161550    int rc2;
161551    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
161552    while( SQLITE_ROW==sqlite3_step(pSelect) ){
161553      if( nIdx>=nAlloc ){
161554        int *aNew;
161555        nAlloc += 16;
161556        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
161557        if( !aNew ){
161558          rc = SQLITE_NOMEM;
161559          break;
161560        }
161561        aIdx = aNew;
161562      }
161563      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
161564    }
161565    rc2 = sqlite3_reset(pSelect);
161566    if( rc==SQLITE_OK ) rc = rc2;
161567  }
161568
161569  if( rc==SQLITE_OK ){
161570    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
161571  }
161572  if( rc==SQLITE_OK ){
161573    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
161574  }
161575
161576  assert( p->bIgnoreSavepoint==0 );
161577  p->bIgnoreSavepoint = 1;
161578  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
161579    if( aIdx[i]!=i ){
161580      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
161581      sqlite3_bind_int(pUpdate, 1, i);
161582      sqlite3_step(pUpdate);
161583      rc = sqlite3_reset(pUpdate);
161584    }
161585  }
161586  p->bIgnoreSavepoint = 0;
161587
161588  sqlite3_free(aIdx);
161589  return rc;
161590}
161591
161592static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
161593  pNode->a[0] = (char)iHeight;
161594  if( iChild ){
161595    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
161596    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
161597  }else{
161598    assert( pNode->nAlloc>=1 );
161599    pNode->n = 1;
161600  }
161601}
161602
161603/*
161604** The first two arguments are a pointer to and the size of a segment b-tree
161605** node. The node may be a leaf or an internal node.
161606**
161607** This function creates a new node image in blob object *pNew by copying
161608** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
161609** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
161610*/
161611static int fts3TruncateNode(
161612  const char *aNode,              /* Current node image */
161613  int nNode,                      /* Size of aNode in bytes */
161614  Blob *pNew,                     /* OUT: Write new node image here */
161615  const char *zTerm,              /* Omit all terms smaller than this */
161616  int nTerm,                      /* Size of zTerm in bytes */
161617  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
161618){
161619  NodeReader reader;              /* Reader object */
161620  Blob prev = {0, 0, 0};          /* Previous term written to new node */
161621  int rc = SQLITE_OK;             /* Return code */
161622  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
161623
161624  /* Allocate required output space */
161625  blobGrowBuffer(pNew, nNode, &rc);
161626  if( rc!=SQLITE_OK ) return rc;
161627  pNew->n = 0;
161628
161629  /* Populate new node buffer */
161630  for(rc = nodeReaderInit(&reader, aNode, nNode);
161631      rc==SQLITE_OK && reader.aNode;
161632      rc = nodeReaderNext(&reader)
161633  ){
161634    if( pNew->n==0 ){
161635      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
161636      if( res<0 || (bLeaf==0 && res==0) ) continue;
161637      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
161638      *piBlock = reader.iChild;
161639    }
161640    rc = fts3AppendToNode(
161641        pNew, &prev, reader.term.a, reader.term.n,
161642        reader.aDoclist, reader.nDoclist
161643    );
161644    if( rc!=SQLITE_OK ) break;
161645  }
161646  if( pNew->n==0 ){
161647    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
161648    *piBlock = reader.iChild;
161649  }
161650  assert( pNew->n<=pNew->nAlloc );
161651
161652  nodeReaderRelease(&reader);
161653  sqlite3_free(prev.a);
161654  return rc;
161655}
161656
161657/*
161658** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
161659** level iAbsLevel. This may involve deleting entries from the %_segments
161660** table, and modifying existing entries in both the %_segments and %_segdir
161661** tables.
161662**
161663** SQLITE_OK is returned if the segment is updated successfully. Or an
161664** SQLite error code otherwise.
161665*/
161666static int fts3TruncateSegment(
161667  Fts3Table *p,                   /* FTS3 table handle */
161668  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
161669  int iIdx,                       /* Index within level of segment to modify */
161670  const char *zTerm,              /* Remove terms smaller than this */
161671  int nTerm                      /* Number of bytes in buffer zTerm */
161672){
161673  int rc = SQLITE_OK;             /* Return code */
161674  Blob root = {0,0,0};            /* New root page image */
161675  Blob block = {0,0,0};           /* Buffer used for any other block */
161676  sqlite3_int64 iBlock = 0;       /* Block id */
161677  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
161678  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
161679  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
161680
161681  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
161682  if( rc==SQLITE_OK ){
161683    int rc2;                      /* sqlite3_reset() return code */
161684    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
161685    sqlite3_bind_int(pFetch, 2, iIdx);
161686    if( SQLITE_ROW==sqlite3_step(pFetch) ){
161687      const char *aRoot = sqlite3_column_blob(pFetch, 4);
161688      int nRoot = sqlite3_column_bytes(pFetch, 4);
161689      iOldStart = sqlite3_column_int64(pFetch, 1);
161690      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
161691    }
161692    rc2 = sqlite3_reset(pFetch);
161693    if( rc==SQLITE_OK ) rc = rc2;
161694  }
161695
161696  while( rc==SQLITE_OK && iBlock ){
161697    char *aBlock = 0;
161698    int nBlock = 0;
161699    iNewStart = iBlock;
161700
161701    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
161702    if( rc==SQLITE_OK ){
161703      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
161704    }
161705    if( rc==SQLITE_OK ){
161706      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
161707    }
161708    sqlite3_free(aBlock);
161709  }
161710
161711  /* Variable iNewStart now contains the first valid leaf node. */
161712  if( rc==SQLITE_OK && iNewStart ){
161713    sqlite3_stmt *pDel = 0;
161714    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
161715    if( rc==SQLITE_OK ){
161716      sqlite3_bind_int64(pDel, 1, iOldStart);
161717      sqlite3_bind_int64(pDel, 2, iNewStart-1);
161718      sqlite3_step(pDel);
161719      rc = sqlite3_reset(pDel);
161720    }
161721  }
161722
161723  if( rc==SQLITE_OK ){
161724    sqlite3_stmt *pChomp = 0;
161725    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
161726    if( rc==SQLITE_OK ){
161727      sqlite3_bind_int64(pChomp, 1, iNewStart);
161728      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
161729      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
161730      sqlite3_bind_int(pChomp, 4, iIdx);
161731      sqlite3_step(pChomp);
161732      rc = sqlite3_reset(pChomp);
161733    }
161734  }
161735
161736  sqlite3_free(root.a);
161737  sqlite3_free(block.a);
161738  return rc;
161739}
161740
161741/*
161742** This function is called after an incrmental-merge operation has run to
161743** merge (or partially merge) two or more segments from absolute level
161744** iAbsLevel.
161745**
161746** Each input segment is either removed from the db completely (if all of
161747** its data was copied to the output segment by the incrmerge operation)
161748** or modified in place so that it no longer contains those entries that
161749** have been duplicated in the output segment.
161750*/
161751static int fts3IncrmergeChomp(
161752  Fts3Table *p,                   /* FTS table handle */
161753  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
161754  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
161755  int *pnRem                      /* Number of segments not deleted */
161756){
161757  int i;
161758  int nRem = 0;
161759  int rc = SQLITE_OK;
161760
161761  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
161762    Fts3SegReader *pSeg = 0;
161763    int j;
161764
161765    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
161766    ** somewhere in the pCsr->apSegment[] array.  */
161767    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
161768      pSeg = pCsr->apSegment[j];
161769      if( pSeg->iIdx==i ) break;
161770    }
161771    assert( j<pCsr->nSegment && pSeg->iIdx==i );
161772
161773    if( pSeg->aNode==0 ){
161774      /* Seg-reader is at EOF. Remove the entire input segment. */
161775      rc = fts3DeleteSegment(p, pSeg);
161776      if( rc==SQLITE_OK ){
161777        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
161778      }
161779      *pnRem = 0;
161780    }else{
161781      /* The incremental merge did not copy all the data from this
161782      ** segment to the upper level. The segment is modified in place
161783      ** so that it contains no keys smaller than zTerm/nTerm. */
161784      const char *zTerm = pSeg->zTerm;
161785      int nTerm = pSeg->nTerm;
161786      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
161787      nRem++;
161788    }
161789  }
161790
161791  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
161792    rc = fts3RepackSegdirLevel(p, iAbsLevel);
161793  }
161794
161795  *pnRem = nRem;
161796  return rc;
161797}
161798
161799/*
161800** Store an incr-merge hint in the database.
161801*/
161802static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
161803  sqlite3_stmt *pReplace = 0;
161804  int rc;                         /* Return code */
161805
161806  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
161807  if( rc==SQLITE_OK ){
161808    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
161809    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
161810    sqlite3_step(pReplace);
161811    rc = sqlite3_reset(pReplace);
161812  }
161813
161814  return rc;
161815}
161816
161817/*
161818** Load an incr-merge hint from the database. The incr-merge hint, if one
161819** exists, is stored in the rowid==1 row of the %_stat table.
161820**
161821** If successful, populate blob *pHint with the value read from the %_stat
161822** table and return SQLITE_OK. Otherwise, if an error occurs, return an
161823** SQLite error code.
161824*/
161825static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
161826  sqlite3_stmt *pSelect = 0;
161827  int rc;
161828
161829  pHint->n = 0;
161830  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
161831  if( rc==SQLITE_OK ){
161832    int rc2;
161833    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
161834    if( SQLITE_ROW==sqlite3_step(pSelect) ){
161835      const char *aHint = sqlite3_column_blob(pSelect, 0);
161836      int nHint = sqlite3_column_bytes(pSelect, 0);
161837      if( aHint ){
161838        blobGrowBuffer(pHint, nHint, &rc);
161839        if( rc==SQLITE_OK ){
161840          memcpy(pHint->a, aHint, nHint);
161841          pHint->n = nHint;
161842        }
161843      }
161844    }
161845    rc2 = sqlite3_reset(pSelect);
161846    if( rc==SQLITE_OK ) rc = rc2;
161847  }
161848
161849  return rc;
161850}
161851
161852/*
161853** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
161854** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
161855** consists of two varints, the absolute level number of the input segments
161856** and the number of input segments.
161857**
161858** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
161859** set *pRc to an SQLite error code before returning.
161860*/
161861static void fts3IncrmergeHintPush(
161862  Blob *pHint,                    /* Hint blob to append to */
161863  i64 iAbsLevel,                  /* First varint to store in hint */
161864  int nInput,                     /* Second varint to store in hint */
161865  int *pRc                        /* IN/OUT: Error code */
161866){
161867  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
161868  if( *pRc==SQLITE_OK ){
161869    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
161870    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
161871  }
161872}
161873
161874/*
161875** Read the last entry (most recently pushed) from the hint blob *pHint
161876** and then remove the entry. Write the two values read to *piAbsLevel and
161877** *pnInput before returning.
161878**
161879** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
161880** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
161881*/
161882static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
161883  const int nHint = pHint->n;
161884  int i;
161885
161886  i = pHint->n-2;
161887  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
161888  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
161889
161890  pHint->n = i;
161891  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
161892  i += fts3GetVarint32(&pHint->a[i], pnInput);
161893  if( i!=nHint ) return FTS_CORRUPT_VTAB;
161894
161895  return SQLITE_OK;
161896}
161897
161898
161899/*
161900** Attempt an incremental merge that writes nMerge leaf blocks.
161901**
161902** Incremental merges happen nMin segments at a time. The segments
161903** to be merged are the nMin oldest segments (the ones with the smallest
161904** values for the _segdir.idx field) in the highest level that contains
161905** at least nMin segments. Multiple merges might occur in an attempt to
161906** write the quota of nMerge leaf blocks.
161907*/
161908SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
161909  int rc;                         /* Return code */
161910  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
161911  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
161912  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
161913  IncrmergeWriter *pWriter;       /* Writer object */
161914  int nSeg = 0;                   /* Number of input segments */
161915  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
161916  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
161917  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
161918
161919  /* Allocate space for the cursor, filter and writer objects */
161920  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
161921  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
161922  if( !pWriter ) return SQLITE_NOMEM;
161923  pFilter = (Fts3SegFilter *)&pWriter[1];
161924  pCsr = (Fts3MultiSegReader *)&pFilter[1];
161925
161926  rc = fts3IncrmergeHintLoad(p, &hint);
161927  while( rc==SQLITE_OK && nRem>0 ){
161928    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
161929    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
161930    int bUseHint = 0;             /* True if attempting to append */
161931    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
161932
161933    /* Search the %_segdir table for the absolute level with the smallest
161934    ** relative level number that contains at least nMin segments, if any.
161935    ** If one is found, set iAbsLevel to the absolute level number and
161936    ** nSeg to nMin. If no level with at least nMin segments can be found,
161937    ** set nSeg to -1.
161938    */
161939    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
161940    sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
161941    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
161942      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
161943      nSeg = sqlite3_column_int(pFindLevel, 1);
161944      assert( nSeg>=2 );
161945    }else{
161946      nSeg = -1;
161947    }
161948    rc = sqlite3_reset(pFindLevel);
161949
161950    /* If the hint read from the %_stat table is not empty, check if the
161951    ** last entry in it specifies a relative level smaller than or equal
161952    ** to the level identified by the block above (if any). If so, this
161953    ** iteration of the loop will work on merging at the hinted level.
161954    */
161955    if( rc==SQLITE_OK && hint.n ){
161956      int nHint = hint.n;
161957      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
161958      int nHintSeg = 0;                     /* Hint number of segments */
161959
161960      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
161961      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
161962        iAbsLevel = iHintAbsLevel;
161963        nSeg = nHintSeg;
161964        bUseHint = 1;
161965        bDirtyHint = 1;
161966      }else{
161967        /* This undoes the effect of the HintPop() above - so that no entry
161968        ** is removed from the hint blob.  */
161969        hint.n = nHint;
161970      }
161971    }
161972
161973    /* If nSeg is less that zero, then there is no level with at least
161974    ** nMin segments and no hint in the %_stat table. No work to do.
161975    ** Exit early in this case.  */
161976    if( nSeg<0 ) break;
161977
161978    /* Open a cursor to iterate through the contents of the oldest nSeg
161979    ** indexes of absolute level iAbsLevel. If this cursor is opened using
161980    ** the 'hint' parameters, it is possible that there are less than nSeg
161981    ** segments available in level iAbsLevel. In this case, no work is
161982    ** done on iAbsLevel - fall through to the next iteration of the loop
161983    ** to start work on some other level.  */
161984    memset(pWriter, 0, nAlloc);
161985    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
161986
161987    if( rc==SQLITE_OK ){
161988      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
161989      assert( bUseHint==1 || bUseHint==0 );
161990      if( iIdx==0 || (bUseHint && iIdx==1) ){
161991        int bIgnore = 0;
161992        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
161993        if( bIgnore ){
161994          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
161995        }
161996      }
161997    }
161998
161999    if( rc==SQLITE_OK ){
162000      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
162001    }
162002    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
162003     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
162004     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
162005    ){
162006      if( bUseHint && iIdx>0 ){
162007        const char *zKey = pCsr->zTerm;
162008        int nKey = pCsr->nTerm;
162009        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
162010      }else{
162011        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
162012      }
162013
162014      if( rc==SQLITE_OK && pWriter->nLeafEst ){
162015        fts3LogMerge(nSeg, iAbsLevel);
162016        do {
162017          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
162018          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
162019          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
162020        }while( rc==SQLITE_ROW );
162021
162022        /* Update or delete the input segments */
162023        if( rc==SQLITE_OK ){
162024          nRem -= (1 + pWriter->nWork);
162025          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
162026          if( nSeg!=0 ){
162027            bDirtyHint = 1;
162028            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
162029          }
162030        }
162031      }
162032
162033      if( nSeg!=0 ){
162034        pWriter->nLeafData = pWriter->nLeafData * -1;
162035      }
162036      fts3IncrmergeRelease(p, pWriter, &rc);
162037      if( nSeg==0 && pWriter->bNoLeafData==0 ){
162038        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
162039      }
162040    }
162041
162042    sqlite3Fts3SegReaderFinish(pCsr);
162043  }
162044
162045  /* Write the hint values into the %_stat table for the next incr-merger */
162046  if( bDirtyHint && rc==SQLITE_OK ){
162047    rc = fts3IncrmergeHintStore(p, &hint);
162048  }
162049
162050  sqlite3_free(pWriter);
162051  sqlite3_free(hint.a);
162052  return rc;
162053}
162054
162055/*
162056** Convert the text beginning at *pz into an integer and return
162057** its value.  Advance *pz to point to the first character past
162058** the integer.
162059**
162060** This function used for parameters to merge= and incrmerge=
162061** commands.
162062*/
162063static int fts3Getint(const char **pz){
162064  const char *z = *pz;
162065  int i = 0;
162066  while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
162067  *pz = z;
162068  return i;
162069}
162070
162071/*
162072** Process statements of the form:
162073**
162074**    INSERT INTO table(table) VALUES('merge=A,B');
162075**
162076** A and B are integers that decode to be the number of leaf pages
162077** written for the merge, and the minimum number of segments on a level
162078** before it will be selected for a merge, respectively.
162079*/
162080static int fts3DoIncrmerge(
162081  Fts3Table *p,                   /* FTS3 table handle */
162082  const char *zParam              /* Nul-terminated string containing "A,B" */
162083){
162084  int rc;
162085  int nMin = (FTS3_MERGE_COUNT / 2);
162086  int nMerge = 0;
162087  const char *z = zParam;
162088
162089  /* Read the first integer value */
162090  nMerge = fts3Getint(&z);
162091
162092  /* If the first integer value is followed by a ',',  read the second
162093  ** integer value. */
162094  if( z[0]==',' && z[1]!='\0' ){
162095    z++;
162096    nMin = fts3Getint(&z);
162097  }
162098
162099  if( z[0]!='\0' || nMin<2 ){
162100    rc = SQLITE_ERROR;
162101  }else{
162102    rc = SQLITE_OK;
162103    if( !p->bHasStat ){
162104      assert( p->bFts4==0 );
162105      sqlite3Fts3CreateStatTable(&rc, p);
162106    }
162107    if( rc==SQLITE_OK ){
162108      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
162109    }
162110    sqlite3Fts3SegmentsClose(p);
162111  }
162112  return rc;
162113}
162114
162115/*
162116** Process statements of the form:
162117**
162118**    INSERT INTO table(table) VALUES('automerge=X');
162119**
162120** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
162121** turn it on.  The setting is persistent.
162122*/
162123static int fts3DoAutoincrmerge(
162124  Fts3Table *p,                   /* FTS3 table handle */
162125  const char *zParam              /* Nul-terminated string containing boolean */
162126){
162127  int rc = SQLITE_OK;
162128  sqlite3_stmt *pStmt = 0;
162129  p->nAutoincrmerge = fts3Getint(&zParam);
162130  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
162131    p->nAutoincrmerge = 8;
162132  }
162133  if( !p->bHasStat ){
162134    assert( p->bFts4==0 );
162135    sqlite3Fts3CreateStatTable(&rc, p);
162136    if( rc ) return rc;
162137  }
162138  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
162139  if( rc ) return rc;
162140  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
162141  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
162142  sqlite3_step(pStmt);
162143  rc = sqlite3_reset(pStmt);
162144  return rc;
162145}
162146
162147/*
162148** Return a 64-bit checksum for the FTS index entry specified by the
162149** arguments to this function.
162150*/
162151static u64 fts3ChecksumEntry(
162152  const char *zTerm,              /* Pointer to buffer containing term */
162153  int nTerm,                      /* Size of zTerm in bytes */
162154  int iLangid,                    /* Language id for current row */
162155  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
162156  i64 iDocid,                     /* Docid for current row. */
162157  int iCol,                       /* Column number */
162158  int iPos                        /* Position */
162159){
162160  int i;
162161  u64 ret = (u64)iDocid;
162162
162163  ret += (ret<<3) + iLangid;
162164  ret += (ret<<3) + iIndex;
162165  ret += (ret<<3) + iCol;
162166  ret += (ret<<3) + iPos;
162167  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
162168
162169  return ret;
162170}
162171
162172/*
162173** Return a checksum of all entries in the FTS index that correspond to
162174** language id iLangid. The checksum is calculated by XORing the checksums
162175** of each individual entry (see fts3ChecksumEntry()) together.
162176**
162177** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
162178** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
162179** return value is undefined in this case.
162180*/
162181static u64 fts3ChecksumIndex(
162182  Fts3Table *p,                   /* FTS3 table handle */
162183  int iLangid,                    /* Language id to return cksum for */
162184  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
162185  int *pRc                        /* OUT: Return code */
162186){
162187  Fts3SegFilter filter;
162188  Fts3MultiSegReader csr;
162189  int rc;
162190  u64 cksum = 0;
162191
162192  assert( *pRc==SQLITE_OK );
162193
162194  memset(&filter, 0, sizeof(filter));
162195  memset(&csr, 0, sizeof(csr));
162196  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
162197  filter.flags |= FTS3_SEGMENT_SCAN;
162198
162199  rc = sqlite3Fts3SegReaderCursor(
162200      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
162201  );
162202  if( rc==SQLITE_OK ){
162203    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
162204  }
162205
162206  if( rc==SQLITE_OK ){
162207    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
162208      char *pCsr = csr.aDoclist;
162209      char *pEnd = &pCsr[csr.nDoclist];
162210
162211      i64 iDocid = 0;
162212      i64 iCol = 0;
162213      i64 iPos = 0;
162214
162215      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
162216      while( pCsr<pEnd ){
162217        i64 iVal = 0;
162218        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
162219        if( pCsr<pEnd ){
162220          if( iVal==0 || iVal==1 ){
162221            iCol = 0;
162222            iPos = 0;
162223            if( iVal ){
162224              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
162225            }else{
162226              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
162227              iDocid += iVal;
162228            }
162229          }else{
162230            iPos += (iVal - 2);
162231            cksum = cksum ^ fts3ChecksumEntry(
162232                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
162233                (int)iCol, (int)iPos
162234            );
162235          }
162236        }
162237      }
162238    }
162239  }
162240  sqlite3Fts3SegReaderFinish(&csr);
162241
162242  *pRc = rc;
162243  return cksum;
162244}
162245
162246/*
162247** Check if the contents of the FTS index match the current contents of the
162248** content table. If no error occurs and the contents do match, set *pbOk
162249** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
162250** to false before returning.
162251**
162252** If an error occurs (e.g. an OOM or IO error), return an SQLite error
162253** code. The final value of *pbOk is undefined in this case.
162254*/
162255static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
162256  int rc = SQLITE_OK;             /* Return code */
162257  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
162258  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
162259  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
162260
162261  /* This block calculates the checksum according to the FTS index. */
162262  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
162263  if( rc==SQLITE_OK ){
162264    int rc2;
162265    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
162266    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
162267    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
162268      int iLangid = sqlite3_column_int(pAllLangid, 0);
162269      int i;
162270      for(i=0; i<p->nIndex; i++){
162271        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
162272      }
162273    }
162274    rc2 = sqlite3_reset(pAllLangid);
162275    if( rc==SQLITE_OK ) rc = rc2;
162276  }
162277
162278  /* This block calculates the checksum according to the %_content table */
162279  if( rc==SQLITE_OK ){
162280    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
162281    sqlite3_stmt *pStmt = 0;
162282    char *zSql;
162283
162284    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
162285    if( !zSql ){
162286      rc = SQLITE_NOMEM;
162287    }else{
162288      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
162289      sqlite3_free(zSql);
162290    }
162291
162292    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
162293      i64 iDocid = sqlite3_column_int64(pStmt, 0);
162294      int iLang = langidFromSelect(p, pStmt);
162295      int iCol;
162296
162297      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
162298        if( p->abNotindexed[iCol]==0 ){
162299          const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
162300          int nText = sqlite3_column_bytes(pStmt, iCol+1);
162301          sqlite3_tokenizer_cursor *pT = 0;
162302
162303          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
162304          while( rc==SQLITE_OK ){
162305            char const *zToken;       /* Buffer containing token */
162306            int nToken = 0;           /* Number of bytes in token */
162307            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
162308            int iPos = 0;             /* Position of token in zText */
162309
162310            rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
162311            if( rc==SQLITE_OK ){
162312              int i;
162313              cksum2 = cksum2 ^ fts3ChecksumEntry(
162314                  zToken, nToken, iLang, 0, iDocid, iCol, iPos
162315              );
162316              for(i=1; i<p->nIndex; i++){
162317                if( p->aIndex[i].nPrefix<=nToken ){
162318                  cksum2 = cksum2 ^ fts3ChecksumEntry(
162319                      zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
162320                  );
162321                }
162322              }
162323            }
162324          }
162325          if( pT ) pModule->xClose(pT);
162326          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
162327        }
162328      }
162329    }
162330
162331    sqlite3_finalize(pStmt);
162332  }
162333
162334  *pbOk = (cksum1==cksum2);
162335  return rc;
162336}
162337
162338/*
162339** Run the integrity-check. If no error occurs and the current contents of
162340** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
162341** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
162342**
162343** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
162344** error code.
162345**
162346** The integrity-check works as follows. For each token and indexed token
162347** prefix in the document set, a 64-bit checksum is calculated (by code
162348** in fts3ChecksumEntry()) based on the following:
162349**
162350**     + The index number (0 for the main index, 1 for the first prefix
162351**       index etc.),
162352**     + The token (or token prefix) text itself,
162353**     + The language-id of the row it appears in,
162354**     + The docid of the row it appears in,
162355**     + The column it appears in, and
162356**     + The tokens position within that column.
162357**
162358** The checksums for all entries in the index are XORed together to create
162359** a single checksum for the entire index.
162360**
162361** The integrity-check code calculates the same checksum in two ways:
162362**
162363**     1. By scanning the contents of the FTS index, and
162364**     2. By scanning and tokenizing the content table.
162365**
162366** If the two checksums are identical, the integrity-check is deemed to have
162367** passed.
162368*/
162369static int fts3DoIntegrityCheck(
162370  Fts3Table *p                    /* FTS3 table handle */
162371){
162372  int rc;
162373  int bOk = 0;
162374  rc = fts3IntegrityCheck(p, &bOk);
162375  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
162376  return rc;
162377}
162378
162379/*
162380** Handle a 'special' INSERT of the form:
162381**
162382**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
162383**
162384** Argument pVal contains the result of <expr>. Currently the only
162385** meaningful value to insert is the text 'optimize'.
162386*/
162387static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
162388  int rc;                         /* Return Code */
162389  const char *zVal = (const char *)sqlite3_value_text(pVal);
162390  int nVal = sqlite3_value_bytes(pVal);
162391
162392  if( !zVal ){
162393    return SQLITE_NOMEM;
162394  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
162395    rc = fts3DoOptimize(p, 0);
162396  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
162397    rc = fts3DoRebuild(p);
162398  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
162399    rc = fts3DoIntegrityCheck(p);
162400  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
162401    rc = fts3DoIncrmerge(p, &zVal[6]);
162402  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
162403    rc = fts3DoAutoincrmerge(p, &zVal[10]);
162404#ifdef SQLITE_TEST
162405  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
162406    p->nNodeSize = atoi(&zVal[9]);
162407    rc = SQLITE_OK;
162408  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
162409    p->nMaxPendingData = atoi(&zVal[11]);
162410    rc = SQLITE_OK;
162411  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
162412    p->bNoIncrDoclist = atoi(&zVal[21]);
162413    rc = SQLITE_OK;
162414#endif
162415  }else{
162416    rc = SQLITE_ERROR;
162417  }
162418
162419  return rc;
162420}
162421
162422#ifndef SQLITE_DISABLE_FTS4_DEFERRED
162423/*
162424** Delete all cached deferred doclists. Deferred doclists are cached
162425** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
162426*/
162427SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
162428  Fts3DeferredToken *pDef;
162429  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
162430    fts3PendingListDelete(pDef->pList);
162431    pDef->pList = 0;
162432  }
162433}
162434
162435/*
162436** Free all entries in the pCsr->pDeffered list. Entries are added to
162437** this list using sqlite3Fts3DeferToken().
162438*/
162439SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
162440  Fts3DeferredToken *pDef;
162441  Fts3DeferredToken *pNext;
162442  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
162443    pNext = pDef->pNext;
162444    fts3PendingListDelete(pDef->pList);
162445    sqlite3_free(pDef);
162446  }
162447  pCsr->pDeferred = 0;
162448}
162449
162450/*
162451** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
162452** based on the row that pCsr currently points to.
162453**
162454** A deferred-doclist is like any other doclist with position information
162455** included, except that it only contains entries for a single row of the
162456** table, not for all rows.
162457*/
162458SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
162459  int rc = SQLITE_OK;             /* Return code */
162460  if( pCsr->pDeferred ){
162461    int i;                        /* Used to iterate through table columns */
162462    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
162463    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
162464
162465    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
162466    sqlite3_tokenizer *pT = p->pTokenizer;
162467    sqlite3_tokenizer_module const *pModule = pT->pModule;
162468
162469    assert( pCsr->isRequireSeek==0 );
162470    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
162471
162472    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
162473      if( p->abNotindexed[i]==0 ){
162474        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
162475        sqlite3_tokenizer_cursor *pTC = 0;
162476
162477        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
162478        while( rc==SQLITE_OK ){
162479          char const *zToken;       /* Buffer containing token */
162480          int nToken = 0;           /* Number of bytes in token */
162481          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
162482          int iPos = 0;             /* Position of token in zText */
162483
162484          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
162485          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
162486            Fts3PhraseToken *pPT = pDef->pToken;
162487            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
162488                && (pPT->bFirst==0 || iPos==0)
162489                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
162490                && (0==memcmp(zToken, pPT->z, pPT->n))
162491              ){
162492              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
162493            }
162494          }
162495        }
162496        if( pTC ) pModule->xClose(pTC);
162497        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
162498      }
162499    }
162500
162501    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
162502      if( pDef->pList ){
162503        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
162504      }
162505    }
162506  }
162507
162508  return rc;
162509}
162510
162511SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
162512  Fts3DeferredToken *p,
162513  char **ppData,
162514  int *pnData
162515){
162516  char *pRet;
162517  int nSkip;
162518  sqlite3_int64 dummy;
162519
162520  *ppData = 0;
162521  *pnData = 0;
162522
162523  if( p->pList==0 ){
162524    return SQLITE_OK;
162525  }
162526
162527  pRet = (char *)sqlite3_malloc(p->pList->nData);
162528  if( !pRet ) return SQLITE_NOMEM;
162529
162530  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
162531  *pnData = p->pList->nData - nSkip;
162532  *ppData = pRet;
162533
162534  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
162535  return SQLITE_OK;
162536}
162537
162538/*
162539** Add an entry for token pToken to the pCsr->pDeferred list.
162540*/
162541SQLITE_PRIVATE int sqlite3Fts3DeferToken(
162542  Fts3Cursor *pCsr,               /* Fts3 table cursor */
162543  Fts3PhraseToken *pToken,        /* Token to defer */
162544  int iCol                        /* Column that token must appear in (or -1) */
162545){
162546  Fts3DeferredToken *pDeferred;
162547  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
162548  if( !pDeferred ){
162549    return SQLITE_NOMEM;
162550  }
162551  memset(pDeferred, 0, sizeof(*pDeferred));
162552  pDeferred->pToken = pToken;
162553  pDeferred->pNext = pCsr->pDeferred;
162554  pDeferred->iCol = iCol;
162555  pCsr->pDeferred = pDeferred;
162556
162557  assert( pToken->pDeferred==0 );
162558  pToken->pDeferred = pDeferred;
162559
162560  return SQLITE_OK;
162561}
162562#endif
162563
162564/*
162565** SQLite value pRowid contains the rowid of a row that may or may not be
162566** present in the FTS3 table. If it is, delete it and adjust the contents
162567** of subsiduary data structures accordingly.
162568*/
162569static int fts3DeleteByRowid(
162570  Fts3Table *p,
162571  sqlite3_value *pRowid,
162572  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
162573  u32 *aSzDel
162574){
162575  int rc = SQLITE_OK;             /* Return code */
162576  int bFound = 0;                 /* True if *pRowid really is in the table */
162577
162578  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
162579  if( bFound && rc==SQLITE_OK ){
162580    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
162581    rc = fts3IsEmpty(p, pRowid, &isEmpty);
162582    if( rc==SQLITE_OK ){
162583      if( isEmpty ){
162584        /* Deleting this row means the whole table is empty. In this case
162585        ** delete the contents of all three tables and throw away any
162586        ** data in the pendingTerms hash table.  */
162587        rc = fts3DeleteAll(p, 1);
162588        *pnChng = 0;
162589        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
162590      }else{
162591        *pnChng = *pnChng - 1;
162592        if( p->zContentTbl==0 ){
162593          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
162594        }
162595        if( p->bHasDocsize ){
162596          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
162597        }
162598      }
162599    }
162600  }
162601
162602  return rc;
162603}
162604
162605/*
162606** This function does the work for the xUpdate method of FTS3 virtual
162607** tables. The schema of the virtual table being:
162608**
162609**     CREATE TABLE <table name>(
162610**       <user columns>,
162611**       <table name> HIDDEN,
162612**       docid HIDDEN,
162613**       <langid> HIDDEN
162614**     );
162615**
162616**
162617*/
162618SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
162619  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
162620  int nArg,                       /* Size of argument array */
162621  sqlite3_value **apVal,          /* Array of arguments */
162622  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
162623){
162624  Fts3Table *p = (Fts3Table *)pVtab;
162625  int rc = SQLITE_OK;             /* Return Code */
162626  int isRemove = 0;               /* True for an UPDATE or DELETE */
162627  u32 *aSzIns = 0;                /* Sizes of inserted documents */
162628  u32 *aSzDel = 0;                /* Sizes of deleted documents */
162629  int nChng = 0;                  /* Net change in number of documents */
162630  int bInsertDone = 0;
162631
162632  /* At this point it must be known if the %_stat table exists or not.
162633  ** So bHasStat may not be 2.  */
162634  assert( p->bHasStat==0 || p->bHasStat==1 );
162635
162636  assert( p->pSegments==0 );
162637  assert(
162638      nArg==1                     /* DELETE operations */
162639   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
162640  );
162641
162642  /* Check for a "special" INSERT operation. One of the form:
162643  **
162644  **   INSERT INTO xyz(xyz) VALUES('command');
162645  */
162646  if( nArg>1
162647   && sqlite3_value_type(apVal[0])==SQLITE_NULL
162648   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
162649  ){
162650    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
162651    goto update_out;
162652  }
162653
162654  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
162655    rc = SQLITE_CONSTRAINT;
162656    goto update_out;
162657  }
162658
162659  /* Allocate space to hold the change in document sizes */
162660  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
162661  if( aSzDel==0 ){
162662    rc = SQLITE_NOMEM;
162663    goto update_out;
162664  }
162665  aSzIns = &aSzDel[p->nColumn+1];
162666  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
162667
162668  rc = fts3Writelock(p);
162669  if( rc!=SQLITE_OK ) goto update_out;
162670
162671  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
162672  ** value, then this operation requires constraint handling.
162673  **
162674  ** If the on-conflict mode is REPLACE, this means that the existing row
162675  ** should be deleted from the database before inserting the new row. Or,
162676  ** if the on-conflict mode is other than REPLACE, then this method must
162677  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
162678  ** modify the database file.
162679  */
162680  if( nArg>1 && p->zContentTbl==0 ){
162681    /* Find the value object that holds the new rowid value. */
162682    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
162683    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
162684      pNewRowid = apVal[1];
162685    }
162686
162687    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
162688        sqlite3_value_type(apVal[0])==SQLITE_NULL
162689     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
162690    )){
162691      /* The new rowid is not NULL (in this case the rowid will be
162692      ** automatically assigned and there is no chance of a conflict), and
162693      ** the statement is either an INSERT or an UPDATE that modifies the
162694      ** rowid column. So if the conflict mode is REPLACE, then delete any
162695      ** existing row with rowid=pNewRowid.
162696      **
162697      ** Or, if the conflict mode is not REPLACE, insert the new record into
162698      ** the %_content table. If we hit the duplicate rowid constraint (or any
162699      ** other error) while doing so, return immediately.
162700      **
162701      ** This branch may also run if pNewRowid contains a value that cannot
162702      ** be losslessly converted to an integer. In this case, the eventual
162703      ** call to fts3InsertData() (either just below or further on in this
162704      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
162705      ** invoked, it will delete zero rows (since no row will have
162706      ** docid=$pNewRowid if $pNewRowid is not an integer value).
162707      */
162708      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
162709        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
162710      }else{
162711        rc = fts3InsertData(p, apVal, pRowid);
162712        bInsertDone = 1;
162713      }
162714    }
162715  }
162716  if( rc!=SQLITE_OK ){
162717    goto update_out;
162718  }
162719
162720  /* If this is a DELETE or UPDATE operation, remove the old record. */
162721  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
162722    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
162723    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
162724    isRemove = 1;
162725  }
162726
162727  /* If this is an INSERT or UPDATE operation, insert the new record. */
162728  if( nArg>1 && rc==SQLITE_OK ){
162729    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
162730    if( bInsertDone==0 ){
162731      rc = fts3InsertData(p, apVal, pRowid);
162732      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
162733        rc = FTS_CORRUPT_VTAB;
162734      }
162735    }
162736    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
162737      rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
162738    }
162739    if( rc==SQLITE_OK ){
162740      assert( p->iPrevDocid==*pRowid );
162741      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
162742    }
162743    if( p->bHasDocsize ){
162744      fts3InsertDocsize(&rc, p, aSzIns);
162745    }
162746    nChng++;
162747  }
162748
162749  if( p->bFts4 ){
162750    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
162751  }
162752
162753 update_out:
162754  sqlite3_free(aSzDel);
162755  sqlite3Fts3SegmentsClose(p);
162756  return rc;
162757}
162758
162759/*
162760** Flush any data in the pending-terms hash table to disk. If successful,
162761** merge all segments in the database (including the new segment, if
162762** there was any data to flush) into a single segment.
162763*/
162764SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
162765  int rc;
162766  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
162767  if( rc==SQLITE_OK ){
162768    rc = fts3DoOptimize(p, 1);
162769    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
162770      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
162771      if( rc2!=SQLITE_OK ) rc = rc2;
162772    }else{
162773      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
162774      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
162775    }
162776  }
162777  sqlite3Fts3SegmentsClose(p);
162778  return rc;
162779}
162780
162781#endif
162782
162783/************** End of fts3_write.c ******************************************/
162784/************** Begin file fts3_snippet.c ************************************/
162785/*
162786** 2009 Oct 23
162787**
162788** The author disclaims copyright to this source code.  In place of
162789** a legal notice, here is a blessing:
162790**
162791**    May you do good and not evil.
162792**    May you find forgiveness for yourself and forgive others.
162793**    May you share freely, never taking more than you give.
162794**
162795******************************************************************************
162796*/
162797
162798/* #include "fts3Int.h" */
162799#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
162800
162801/* #include <string.h> */
162802/* #include <assert.h> */
162803
162804/*
162805** Characters that may appear in the second argument to matchinfo().
162806*/
162807#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
162808#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
162809#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
162810#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
162811#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
162812#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
162813#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
162814#define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
162815#define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
162816
162817/*
162818** The default value for the second argument to matchinfo().
162819*/
162820#define FTS3_MATCHINFO_DEFAULT   "pcx"
162821
162822
162823/*
162824** Used as an fts3ExprIterate() context when loading phrase doclists to
162825** Fts3Expr.aDoclist[]/nDoclist.
162826*/
162827typedef struct LoadDoclistCtx LoadDoclistCtx;
162828struct LoadDoclistCtx {
162829  Fts3Cursor *pCsr;               /* FTS3 Cursor */
162830  int nPhrase;                    /* Number of phrases seen so far */
162831  int nToken;                     /* Number of tokens seen so far */
162832};
162833
162834/*
162835** The following types are used as part of the implementation of the
162836** fts3BestSnippet() routine.
162837*/
162838typedef struct SnippetIter SnippetIter;
162839typedef struct SnippetPhrase SnippetPhrase;
162840typedef struct SnippetFragment SnippetFragment;
162841
162842struct SnippetIter {
162843  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
162844  int iCol;                       /* Extract snippet from this column */
162845  int nSnippet;                   /* Requested snippet length (in tokens) */
162846  int nPhrase;                    /* Number of phrases in query */
162847  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
162848  int iCurrent;                   /* First token of current snippet */
162849};
162850
162851struct SnippetPhrase {
162852  int nToken;                     /* Number of tokens in phrase */
162853  char *pList;                    /* Pointer to start of phrase position list */
162854  int iHead;                      /* Next value in position list */
162855  char *pHead;                    /* Position list data following iHead */
162856  int iTail;                      /* Next value in trailing position list */
162857  char *pTail;                    /* Position list data following iTail */
162858};
162859
162860struct SnippetFragment {
162861  int iCol;                       /* Column snippet is extracted from */
162862  int iPos;                       /* Index of first token in snippet */
162863  u64 covered;                    /* Mask of query phrases covered */
162864  u64 hlmask;                     /* Mask of snippet terms to highlight */
162865};
162866
162867/*
162868** This type is used as an fts3ExprIterate() context object while
162869** accumulating the data returned by the matchinfo() function.
162870*/
162871typedef struct MatchInfo MatchInfo;
162872struct MatchInfo {
162873  Fts3Cursor *pCursor;            /* FTS3 Cursor */
162874  int nCol;                       /* Number of columns in table */
162875  int nPhrase;                    /* Number of matchable phrases in query */
162876  sqlite3_int64 nDoc;             /* Number of docs in database */
162877  char flag;
162878  u32 *aMatchinfo;                /* Pre-allocated buffer */
162879};
162880
162881/*
162882** An instance of this structure is used to manage a pair of buffers, each
162883** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
162884** for details.
162885*/
162886struct MatchinfoBuffer {
162887  u8 aRef[3];
162888  int nElem;
162889  int bGlobal;                    /* Set if global data is loaded */
162890  char *zMatchinfo;
162891  u32 aMatchinfo[1];
162892};
162893
162894
162895/*
162896** The snippet() and offsets() functions both return text values. An instance
162897** of the following structure is used to accumulate those values while the
162898** functions are running. See fts3StringAppend() for details.
162899*/
162900typedef struct StrBuffer StrBuffer;
162901struct StrBuffer {
162902  char *z;                        /* Pointer to buffer containing string */
162903  int n;                          /* Length of z in bytes (excl. nul-term) */
162904  int nAlloc;                     /* Allocated size of buffer z in bytes */
162905};
162906
162907
162908/*************************************************************************
162909** Start of MatchinfoBuffer code.
162910*/
162911
162912/*
162913** Allocate a two-slot MatchinfoBuffer object.
162914*/
162915static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
162916  MatchinfoBuffer *pRet;
162917  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
162918  int nStr = (int)strlen(zMatchinfo);
162919
162920  pRet = sqlite3_malloc(nByte + nStr+1);
162921  if( pRet ){
162922    memset(pRet, 0, nByte);
162923    pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
162924    pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
162925    pRet->nElem = nElem;
162926    pRet->zMatchinfo = ((char*)pRet) + nByte;
162927    memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
162928    pRet->aRef[0] = 1;
162929  }
162930
162931  return pRet;
162932}
162933
162934static void fts3MIBufferFree(void *p){
162935  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
162936
162937  assert( (u32*)p==&pBuf->aMatchinfo[1]
162938       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
162939  );
162940  if( (u32*)p==&pBuf->aMatchinfo[1] ){
162941    pBuf->aRef[1] = 0;
162942  }else{
162943    pBuf->aRef[2] = 0;
162944  }
162945
162946  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
162947    sqlite3_free(pBuf);
162948  }
162949}
162950
162951static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
162952  void (*xRet)(void*) = 0;
162953  u32 *aOut = 0;
162954
162955  if( p->aRef[1]==0 ){
162956    p->aRef[1] = 1;
162957    aOut = &p->aMatchinfo[1];
162958    xRet = fts3MIBufferFree;
162959  }
162960  else if( p->aRef[2]==0 ){
162961    p->aRef[2] = 1;
162962    aOut = &p->aMatchinfo[p->nElem+2];
162963    xRet = fts3MIBufferFree;
162964  }else{
162965    aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
162966    if( aOut ){
162967      xRet = sqlite3_free;
162968      if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
162969    }
162970  }
162971
162972  *paOut = aOut;
162973  return xRet;
162974}
162975
162976static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
162977  p->bGlobal = 1;
162978  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
162979}
162980
162981/*
162982** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
162983*/
162984SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
162985  if( p ){
162986    assert( p->aRef[0]==1 );
162987    p->aRef[0] = 0;
162988    if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
162989      sqlite3_free(p);
162990    }
162991  }
162992}
162993
162994/*
162995** End of MatchinfoBuffer code.
162996*************************************************************************/
162997
162998
162999/*
163000** This function is used to help iterate through a position-list. A position
163001** list is a list of unique integers, sorted from smallest to largest. Each
163002** element of the list is represented by an FTS3 varint that takes the value
163003** of the difference between the current element and the previous one plus
163004** two. For example, to store the position-list:
163005**
163006**     4 9 113
163007**
163008** the three varints:
163009**
163010**     6 7 106
163011**
163012** are encoded.
163013**
163014** When this function is called, *pp points to the start of an element of
163015** the list. *piPos contains the value of the previous entry in the list.
163016** After it returns, *piPos contains the value of the next element of the
163017** list and *pp is advanced to the following varint.
163018*/
163019static void fts3GetDeltaPosition(char **pp, int *piPos){
163020  int iVal;
163021  *pp += fts3GetVarint32(*pp, &iVal);
163022  *piPos += (iVal-2);
163023}
163024
163025/*
163026** Helper function for fts3ExprIterate() (see below).
163027*/
163028static int fts3ExprIterate2(
163029  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
163030  int *piPhrase,                  /* Pointer to phrase counter */
163031  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
163032  void *pCtx                      /* Second argument to pass to callback */
163033){
163034  int rc;                         /* Return code */
163035  int eType = pExpr->eType;     /* Type of expression node pExpr */
163036
163037  if( eType!=FTSQUERY_PHRASE ){
163038    assert( pExpr->pLeft && pExpr->pRight );
163039    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
163040    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
163041      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
163042    }
163043  }else{
163044    rc = x(pExpr, *piPhrase, pCtx);
163045    (*piPhrase)++;
163046  }
163047  return rc;
163048}
163049
163050/*
163051** Iterate through all phrase nodes in an FTS3 query, except those that
163052** are part of a sub-tree that is the right-hand-side of a NOT operator.
163053** For each phrase node found, the supplied callback function is invoked.
163054**
163055** If the callback function returns anything other than SQLITE_OK,
163056** the iteration is abandoned and the error code returned immediately.
163057** Otherwise, SQLITE_OK is returned after a callback has been made for
163058** all eligible phrase nodes.
163059*/
163060static int fts3ExprIterate(
163061  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
163062  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
163063  void *pCtx                      /* Second argument to pass to callback */
163064){
163065  int iPhrase = 0;                /* Variable used as the phrase counter */
163066  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
163067}
163068
163069
163070/*
163071** This is an fts3ExprIterate() callback used while loading the doclists
163072** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
163073** fts3ExprLoadDoclists().
163074*/
163075static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
163076  int rc = SQLITE_OK;
163077  Fts3Phrase *pPhrase = pExpr->pPhrase;
163078  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
163079
163080  UNUSED_PARAMETER(iPhrase);
163081
163082  p->nPhrase++;
163083  p->nToken += pPhrase->nToken;
163084
163085  return rc;
163086}
163087
163088/*
163089** Load the doclists for each phrase in the query associated with FTS3 cursor
163090** pCsr.
163091**
163092** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
163093** phrases in the expression (all phrases except those directly or
163094** indirectly descended from the right-hand-side of a NOT operator). If
163095** pnToken is not NULL, then it is set to the number of tokens in all
163096** matchable phrases of the expression.
163097*/
163098static int fts3ExprLoadDoclists(
163099  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
163100  int *pnPhrase,                  /* OUT: Number of phrases in query */
163101  int *pnToken                    /* OUT: Number of tokens in query */
163102){
163103  int rc;                         /* Return Code */
163104  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
163105  sCtx.pCsr = pCsr;
163106  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
163107  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
163108  if( pnToken ) *pnToken = sCtx.nToken;
163109  return rc;
163110}
163111
163112static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
163113  (*(int *)ctx)++;
163114  pExpr->iPhrase = iPhrase;
163115  return SQLITE_OK;
163116}
163117static int fts3ExprPhraseCount(Fts3Expr *pExpr){
163118  int nPhrase = 0;
163119  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
163120  return nPhrase;
163121}
163122
163123/*
163124** Advance the position list iterator specified by the first two
163125** arguments so that it points to the first element with a value greater
163126** than or equal to parameter iNext.
163127*/
163128static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
163129  char *pIter = *ppIter;
163130  if( pIter ){
163131    int iIter = *piIter;
163132
163133    while( iIter<iNext ){
163134      if( 0==(*pIter & 0xFE) ){
163135        iIter = -1;
163136        pIter = 0;
163137        break;
163138      }
163139      fts3GetDeltaPosition(&pIter, &iIter);
163140    }
163141
163142    *piIter = iIter;
163143    *ppIter = pIter;
163144  }
163145}
163146
163147/*
163148** Advance the snippet iterator to the next candidate snippet.
163149*/
163150static int fts3SnippetNextCandidate(SnippetIter *pIter){
163151  int i;                          /* Loop counter */
163152
163153  if( pIter->iCurrent<0 ){
163154    /* The SnippetIter object has just been initialized. The first snippet
163155    ** candidate always starts at offset 0 (even if this candidate has a
163156    ** score of 0.0).
163157    */
163158    pIter->iCurrent = 0;
163159
163160    /* Advance the 'head' iterator of each phrase to the first offset that
163161    ** is greater than or equal to (iNext+nSnippet).
163162    */
163163    for(i=0; i<pIter->nPhrase; i++){
163164      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163165      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
163166    }
163167  }else{
163168    int iStart;
163169    int iEnd = 0x7FFFFFFF;
163170
163171    for(i=0; i<pIter->nPhrase; i++){
163172      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163173      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
163174        iEnd = pPhrase->iHead;
163175      }
163176    }
163177    if( iEnd==0x7FFFFFFF ){
163178      return 1;
163179    }
163180
163181    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
163182    for(i=0; i<pIter->nPhrase; i++){
163183      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163184      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
163185      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
163186    }
163187  }
163188
163189  return 0;
163190}
163191
163192/*
163193** Retrieve information about the current candidate snippet of snippet
163194** iterator pIter.
163195*/
163196static void fts3SnippetDetails(
163197  SnippetIter *pIter,             /* Snippet iterator */
163198  u64 mCovered,                   /* Bitmask of phrases already covered */
163199  int *piToken,                   /* OUT: First token of proposed snippet */
163200  int *piScore,                   /* OUT: "Score" for this snippet */
163201  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
163202  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
163203){
163204  int iStart = pIter->iCurrent;   /* First token of snippet */
163205  int iScore = 0;                 /* Score of this snippet */
163206  int i;                          /* Loop counter */
163207  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
163208  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
163209
163210  for(i=0; i<pIter->nPhrase; i++){
163211    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
163212    if( pPhrase->pTail ){
163213      char *pCsr = pPhrase->pTail;
163214      int iCsr = pPhrase->iTail;
163215
163216      while( iCsr<(iStart+pIter->nSnippet) ){
163217        int j;
163218        u64 mPhrase = (u64)1 << i;
163219        u64 mPos = (u64)1 << (iCsr - iStart);
163220        assert( iCsr>=iStart );
163221        if( (mCover|mCovered)&mPhrase ){
163222          iScore++;
163223        }else{
163224          iScore += 1000;
163225        }
163226        mCover |= mPhrase;
163227
163228        for(j=0; j<pPhrase->nToken; j++){
163229          mHighlight |= (mPos>>j);
163230        }
163231
163232        if( 0==(*pCsr & 0x0FE) ) break;
163233        fts3GetDeltaPosition(&pCsr, &iCsr);
163234      }
163235    }
163236  }
163237
163238  /* Set the output variables before returning. */
163239  *piToken = iStart;
163240  *piScore = iScore;
163241  *pmCover = mCover;
163242  *pmHighlight = mHighlight;
163243}
163244
163245/*
163246** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
163247** Each invocation populates an element of the SnippetIter.aPhrase[] array.
163248*/
163249static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
163250  SnippetIter *p = (SnippetIter *)ctx;
163251  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
163252  char *pCsr;
163253  int rc;
163254
163255  pPhrase->nToken = pExpr->pPhrase->nToken;
163256  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
163257  assert( rc==SQLITE_OK || pCsr==0 );
163258  if( pCsr ){
163259    int iFirst = 0;
163260    pPhrase->pList = pCsr;
163261    fts3GetDeltaPosition(&pCsr, &iFirst);
163262    assert( iFirst>=0 );
163263    pPhrase->pHead = pCsr;
163264    pPhrase->pTail = pCsr;
163265    pPhrase->iHead = iFirst;
163266    pPhrase->iTail = iFirst;
163267  }else{
163268    assert( rc!=SQLITE_OK || (
163269       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
163270    ));
163271  }
163272
163273  return rc;
163274}
163275
163276/*
163277** Select the fragment of text consisting of nFragment contiguous tokens
163278** from column iCol that represent the "best" snippet. The best snippet
163279** is the snippet with the highest score, where scores are calculated
163280** by adding:
163281**
163282**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
163283**
163284**   (b) +1000 points for the first occurrence of each matchable phrase in
163285**       the snippet for which the corresponding mCovered bit is not set.
163286**
163287** The selected snippet parameters are stored in structure *pFragment before
163288** returning. The score of the selected snippet is stored in *piScore
163289** before returning.
163290*/
163291static int fts3BestSnippet(
163292  int nSnippet,                   /* Desired snippet length */
163293  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
163294  int iCol,                       /* Index of column to create snippet from */
163295  u64 mCovered,                   /* Mask of phrases already covered */
163296  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
163297  SnippetFragment *pFragment,     /* OUT: Best snippet found */
163298  int *piScore                    /* OUT: Score of snippet pFragment */
163299){
163300  int rc;                         /* Return Code */
163301  int nList;                      /* Number of phrases in expression */
163302  SnippetIter sIter;              /* Iterates through snippet candidates */
163303  int nByte;                      /* Number of bytes of space to allocate */
163304  int iBestScore = -1;            /* Best snippet score found so far */
163305  int i;                          /* Loop counter */
163306
163307  memset(&sIter, 0, sizeof(sIter));
163308
163309  /* Iterate through the phrases in the expression to count them. The same
163310  ** callback makes sure the doclists are loaded for each phrase.
163311  */
163312  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
163313  if( rc!=SQLITE_OK ){
163314    return rc;
163315  }
163316
163317  /* Now that it is known how many phrases there are, allocate and zero
163318  ** the required space using malloc().
163319  */
163320  nByte = sizeof(SnippetPhrase) * nList;
163321  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
163322  if( !sIter.aPhrase ){
163323    return SQLITE_NOMEM;
163324  }
163325  memset(sIter.aPhrase, 0, nByte);
163326
163327  /* Initialize the contents of the SnippetIter object. Then iterate through
163328  ** the set of phrases in the expression to populate the aPhrase[] array.
163329  */
163330  sIter.pCsr = pCsr;
163331  sIter.iCol = iCol;
163332  sIter.nSnippet = nSnippet;
163333  sIter.nPhrase = nList;
163334  sIter.iCurrent = -1;
163335  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
163336  if( rc==SQLITE_OK ){
163337
163338    /* Set the *pmSeen output variable. */
163339    for(i=0; i<nList; i++){
163340      if( sIter.aPhrase[i].pHead ){
163341        *pmSeen |= (u64)1 << i;
163342      }
163343    }
163344
163345    /* Loop through all candidate snippets. Store the best snippet in
163346     ** *pFragment. Store its associated 'score' in iBestScore.
163347     */
163348    pFragment->iCol = iCol;
163349    while( !fts3SnippetNextCandidate(&sIter) ){
163350      int iPos;
163351      int iScore;
163352      u64 mCover;
163353      u64 mHighlite;
163354      fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
163355      assert( iScore>=0 );
163356      if( iScore>iBestScore ){
163357        pFragment->iPos = iPos;
163358        pFragment->hlmask = mHighlite;
163359        pFragment->covered = mCover;
163360        iBestScore = iScore;
163361      }
163362    }
163363
163364    *piScore = iBestScore;
163365  }
163366  sqlite3_free(sIter.aPhrase);
163367  return rc;
163368}
163369
163370
163371/*
163372** Append a string to the string-buffer passed as the first argument.
163373**
163374** If nAppend is negative, then the length of the string zAppend is
163375** determined using strlen().
163376*/
163377static int fts3StringAppend(
163378  StrBuffer *pStr,                /* Buffer to append to */
163379  const char *zAppend,            /* Pointer to data to append to buffer */
163380  int nAppend                     /* Size of zAppend in bytes (or -1) */
163381){
163382  if( nAppend<0 ){
163383    nAppend = (int)strlen(zAppend);
163384  }
163385
163386  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
163387  ** to grow the buffer until so that it is big enough to accomadate the
163388  ** appended data.
163389  */
163390  if( pStr->n+nAppend+1>=pStr->nAlloc ){
163391    int nAlloc = pStr->nAlloc+nAppend+100;
163392    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
163393    if( !zNew ){
163394      return SQLITE_NOMEM;
163395    }
163396    pStr->z = zNew;
163397    pStr->nAlloc = nAlloc;
163398  }
163399  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
163400
163401  /* Append the data to the string buffer. */
163402  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
163403  pStr->n += nAppend;
163404  pStr->z[pStr->n] = '\0';
163405
163406  return SQLITE_OK;
163407}
163408
163409/*
163410** The fts3BestSnippet() function often selects snippets that end with a
163411** query term. That is, the final term of the snippet is always a term
163412** that requires highlighting. For example, if 'X' is a highlighted term
163413** and '.' is a non-highlighted term, BestSnippet() may select:
163414**
163415**     ........X.....X
163416**
163417** This function "shifts" the beginning of the snippet forward in the
163418** document so that there are approximately the same number of
163419** non-highlighted terms to the right of the final highlighted term as there
163420** are to the left of the first highlighted term. For example, to this:
163421**
163422**     ....X.....X....
163423**
163424** This is done as part of extracting the snippet text, not when selecting
163425** the snippet. Snippet selection is done based on doclists only, so there
163426** is no way for fts3BestSnippet() to know whether or not the document
163427** actually contains terms that follow the final highlighted term.
163428*/
163429static int fts3SnippetShift(
163430  Fts3Table *pTab,                /* FTS3 table snippet comes from */
163431  int iLangid,                    /* Language id to use in tokenizing */
163432  int nSnippet,                   /* Number of tokens desired for snippet */
163433  const char *zDoc,               /* Document text to extract snippet from */
163434  int nDoc,                       /* Size of buffer zDoc in bytes */
163435  int *piPos,                     /* IN/OUT: First token of snippet */
163436  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
163437){
163438  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
163439
163440  if( hlmask ){
163441    int nLeft;                    /* Tokens to the left of first highlight */
163442    int nRight;                   /* Tokens to the right of last highlight */
163443    int nDesired;                 /* Ideal number of tokens to shift forward */
163444
163445    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
163446    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
163447    nDesired = (nLeft-nRight)/2;
163448
163449    /* Ideally, the start of the snippet should be pushed forward in the
163450    ** document nDesired tokens. This block checks if there are actually
163451    ** nDesired tokens to the right of the snippet. If so, *piPos and
163452    ** *pHlMask are updated to shift the snippet nDesired tokens to the
163453    ** right. Otherwise, the snippet is shifted by the number of tokens
163454    ** available.
163455    */
163456    if( nDesired>0 ){
163457      int nShift;                 /* Number of tokens to shift snippet by */
163458      int iCurrent = 0;           /* Token counter */
163459      int rc;                     /* Return Code */
163460      sqlite3_tokenizer_module *pMod;
163461      sqlite3_tokenizer_cursor *pC;
163462      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
163463
163464      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
163465      ** or more tokens in zDoc/nDoc.
163466      */
163467      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
163468      if( rc!=SQLITE_OK ){
163469        return rc;
163470      }
163471      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
163472        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
163473        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
163474      }
163475      pMod->xClose(pC);
163476      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
163477
163478      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
163479      assert( nShift<=nDesired );
163480      if( nShift>0 ){
163481        *piPos += nShift;
163482        *pHlmask = hlmask >> nShift;
163483      }
163484    }
163485  }
163486  return SQLITE_OK;
163487}
163488
163489/*
163490** Extract the snippet text for fragment pFragment from cursor pCsr and
163491** append it to string buffer pOut.
163492*/
163493static int fts3SnippetText(
163494  Fts3Cursor *pCsr,               /* FTS3 Cursor */
163495  SnippetFragment *pFragment,     /* Snippet to extract */
163496  int iFragment,                  /* Fragment number */
163497  int isLast,                     /* True for final fragment in snippet */
163498  int nSnippet,                   /* Number of tokens in extracted snippet */
163499  const char *zOpen,              /* String inserted before highlighted term */
163500  const char *zClose,             /* String inserted after highlighted term */
163501  const char *zEllipsis,          /* String inserted between snippets */
163502  StrBuffer *pOut                 /* Write output here */
163503){
163504  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
163505  int rc;                         /* Return code */
163506  const char *zDoc;               /* Document text to extract snippet from */
163507  int nDoc;                       /* Size of zDoc in bytes */
163508  int iCurrent = 0;               /* Current token number of document */
163509  int iEnd = 0;                   /* Byte offset of end of current token */
163510  int isShiftDone = 0;            /* True after snippet is shifted */
163511  int iPos = pFragment->iPos;     /* First token of snippet */
163512  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
163513  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
163514  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
163515  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
163516
163517  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
163518  if( zDoc==0 ){
163519    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
163520      return SQLITE_NOMEM;
163521    }
163522    return SQLITE_OK;
163523  }
163524  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
163525
163526  /* Open a token cursor on the document. */
163527  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
163528  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
163529  if( rc!=SQLITE_OK ){
163530    return rc;
163531  }
163532
163533  while( rc==SQLITE_OK ){
163534    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
163535    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
163536    int iBegin = 0;               /* Offset in zDoc of start of token */
163537    int iFin = 0;                 /* Offset in zDoc of end of token */
163538    int isHighlight = 0;          /* True for highlighted terms */
163539
163540    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
163541    ** in the FTS code the variable that the third argument to xNext points to
163542    ** is initialized to zero before the first (*but not necessarily
163543    ** subsequent*) call to xNext(). This is done for a particular application
163544    ** that needs to know whether or not the tokenizer is being used for
163545    ** snippet generation or for some other purpose.
163546    **
163547    ** Extreme care is required when writing code to depend on this
163548    ** initialization. It is not a documented part of the tokenizer interface.
163549    ** If a tokenizer is used directly by any code outside of FTS, this
163550    ** convention might not be respected.  */
163551    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
163552    if( rc!=SQLITE_OK ){
163553      if( rc==SQLITE_DONE ){
163554        /* Special case - the last token of the snippet is also the last token
163555        ** of the column. Append any punctuation that occurred between the end
163556        ** of the previous token and the end of the document to the output.
163557        ** Then break out of the loop. */
163558        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
163559      }
163560      break;
163561    }
163562    if( iCurrent<iPos ){ continue; }
163563
163564    if( !isShiftDone ){
163565      int n = nDoc - iBegin;
163566      rc = fts3SnippetShift(
163567          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
163568      );
163569      isShiftDone = 1;
163570
163571      /* Now that the shift has been done, check if the initial "..." are
163572      ** required. They are required if (a) this is not the first fragment,
163573      ** or (b) this fragment does not begin at position 0 of its column.
163574      */
163575      if( rc==SQLITE_OK ){
163576        if( iPos>0 || iFragment>0 ){
163577          rc = fts3StringAppend(pOut, zEllipsis, -1);
163578        }else if( iBegin ){
163579          rc = fts3StringAppend(pOut, zDoc, iBegin);
163580        }
163581      }
163582      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
163583    }
163584
163585    if( iCurrent>=(iPos+nSnippet) ){
163586      if( isLast ){
163587        rc = fts3StringAppend(pOut, zEllipsis, -1);
163588      }
163589      break;
163590    }
163591
163592    /* Set isHighlight to true if this term should be highlighted. */
163593    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
163594
163595    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
163596    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
163597    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
163598    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
163599
163600    iEnd = iFin;
163601  }
163602
163603  pMod->xClose(pC);
163604  return rc;
163605}
163606
163607
163608/*
163609** This function is used to count the entries in a column-list (a
163610** delta-encoded list of term offsets within a single column of a single
163611** row). When this function is called, *ppCollist should point to the
163612** beginning of the first varint in the column-list (the varint that
163613** contains the position of the first matching term in the column data).
163614** Before returning, *ppCollist is set to point to the first byte after
163615** the last varint in the column-list (either the 0x00 signifying the end
163616** of the position-list, or the 0x01 that precedes the column number of
163617** the next column in the position-list).
163618**
163619** The number of elements in the column-list is returned.
163620*/
163621static int fts3ColumnlistCount(char **ppCollist){
163622  char *pEnd = *ppCollist;
163623  char c = 0;
163624  int nEntry = 0;
163625
163626  /* A column-list is terminated by either a 0x01 or 0x00. */
163627  while( 0xFE & (*pEnd | c) ){
163628    c = *pEnd++ & 0x80;
163629    if( !c ) nEntry++;
163630  }
163631
163632  *ppCollist = pEnd;
163633  return nEntry;
163634}
163635
163636/*
163637** This function gathers 'y' or 'b' data for a single phrase.
163638*/
163639static void fts3ExprLHits(
163640  Fts3Expr *pExpr,                /* Phrase expression node */
163641  MatchInfo *p                    /* Matchinfo context */
163642){
163643  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
163644  int iStart;
163645  Fts3Phrase *pPhrase = pExpr->pPhrase;
163646  char *pIter = pPhrase->doclist.pList;
163647  int iCol = 0;
163648
163649  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
163650  if( p->flag==FTS3_MATCHINFO_LHITS ){
163651    iStart = pExpr->iPhrase * p->nCol;
163652  }else{
163653    iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
163654  }
163655
163656  while( 1 ){
163657    int nHit = fts3ColumnlistCount(&pIter);
163658    if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
163659      if( p->flag==FTS3_MATCHINFO_LHITS ){
163660        p->aMatchinfo[iStart + iCol] = (u32)nHit;
163661      }else if( nHit ){
163662        p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
163663      }
163664    }
163665    assert( *pIter==0x00 || *pIter==0x01 );
163666    if( *pIter!=0x01 ) break;
163667    pIter++;
163668    pIter += fts3GetVarint32(pIter, &iCol);
163669  }
163670}
163671
163672/*
163673** Gather the results for matchinfo directives 'y' and 'b'.
163674*/
163675static void fts3ExprLHitGather(
163676  Fts3Expr *pExpr,
163677  MatchInfo *p
163678){
163679  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
163680  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
163681    if( pExpr->pLeft ){
163682      fts3ExprLHitGather(pExpr->pLeft, p);
163683      fts3ExprLHitGather(pExpr->pRight, p);
163684    }else{
163685      fts3ExprLHits(pExpr, p);
163686    }
163687  }
163688}
163689
163690/*
163691** fts3ExprIterate() callback used to collect the "global" matchinfo stats
163692** for a single query.
163693**
163694** fts3ExprIterate() callback to load the 'global' elements of a
163695** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
163696** of the matchinfo array that are constant for all rows returned by the
163697** current query.
163698**
163699** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
163700** function populates Matchinfo.aMatchinfo[] as follows:
163701**
163702**   for(iCol=0; iCol<nCol; iCol++){
163703**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
163704**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
163705**   }
163706**
163707** where X is the number of matches for phrase iPhrase is column iCol of all
163708** rows of the table. Y is the number of rows for which column iCol contains
163709** at least one instance of phrase iPhrase.
163710**
163711** If the phrase pExpr consists entirely of deferred tokens, then all X and
163712** Y values are set to nDoc, where nDoc is the number of documents in the
163713** file system. This is done because the full-text index doclist is required
163714** to calculate these values properly, and the full-text index doclist is
163715** not available for deferred tokens.
163716*/
163717static int fts3ExprGlobalHitsCb(
163718  Fts3Expr *pExpr,                /* Phrase expression node */
163719  int iPhrase,                    /* Phrase number (numbered from zero) */
163720  void *pCtx                      /* Pointer to MatchInfo structure */
163721){
163722  MatchInfo *p = (MatchInfo *)pCtx;
163723  return sqlite3Fts3EvalPhraseStats(
163724      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
163725  );
163726}
163727
163728/*
163729** fts3ExprIterate() callback used to collect the "local" part of the
163730** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
163731** array that are different for each row returned by the query.
163732*/
163733static int fts3ExprLocalHitsCb(
163734  Fts3Expr *pExpr,                /* Phrase expression node */
163735  int iPhrase,                    /* Phrase number */
163736  void *pCtx                      /* Pointer to MatchInfo structure */
163737){
163738  int rc = SQLITE_OK;
163739  MatchInfo *p = (MatchInfo *)pCtx;
163740  int iStart = iPhrase * p->nCol * 3;
163741  int i;
163742
163743  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
163744    char *pCsr;
163745    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
163746    if( pCsr ){
163747      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
163748    }else{
163749      p->aMatchinfo[iStart+i*3] = 0;
163750    }
163751  }
163752
163753  return rc;
163754}
163755
163756static int fts3MatchinfoCheck(
163757  Fts3Table *pTab,
163758  char cArg,
163759  char **pzErr
163760){
163761  if( (cArg==FTS3_MATCHINFO_NPHRASE)
163762   || (cArg==FTS3_MATCHINFO_NCOL)
163763   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
163764   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
163765   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
163766   || (cArg==FTS3_MATCHINFO_LCS)
163767   || (cArg==FTS3_MATCHINFO_HITS)
163768   || (cArg==FTS3_MATCHINFO_LHITS)
163769   || (cArg==FTS3_MATCHINFO_LHITS_BM)
163770  ){
163771    return SQLITE_OK;
163772  }
163773  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
163774  return SQLITE_ERROR;
163775}
163776
163777static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
163778  int nVal;                       /* Number of integers output by cArg */
163779
163780  switch( cArg ){
163781    case FTS3_MATCHINFO_NDOC:
163782    case FTS3_MATCHINFO_NPHRASE:
163783    case FTS3_MATCHINFO_NCOL:
163784      nVal = 1;
163785      break;
163786
163787    case FTS3_MATCHINFO_AVGLENGTH:
163788    case FTS3_MATCHINFO_LENGTH:
163789    case FTS3_MATCHINFO_LCS:
163790      nVal = pInfo->nCol;
163791      break;
163792
163793    case FTS3_MATCHINFO_LHITS:
163794      nVal = pInfo->nCol * pInfo->nPhrase;
163795      break;
163796
163797    case FTS3_MATCHINFO_LHITS_BM:
163798      nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
163799      break;
163800
163801    default:
163802      assert( cArg==FTS3_MATCHINFO_HITS );
163803      nVal = pInfo->nCol * pInfo->nPhrase * 3;
163804      break;
163805  }
163806
163807  return nVal;
163808}
163809
163810static int fts3MatchinfoSelectDoctotal(
163811  Fts3Table *pTab,
163812  sqlite3_stmt **ppStmt,
163813  sqlite3_int64 *pnDoc,
163814  const char **paLen
163815){
163816  sqlite3_stmt *pStmt;
163817  const char *a;
163818  sqlite3_int64 nDoc;
163819
163820  if( !*ppStmt ){
163821    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
163822    if( rc!=SQLITE_OK ) return rc;
163823  }
163824  pStmt = *ppStmt;
163825  assert( sqlite3_data_count(pStmt)==1 );
163826
163827  a = sqlite3_column_blob(pStmt, 0);
163828  a += sqlite3Fts3GetVarint(a, &nDoc);
163829  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
163830  *pnDoc = (u32)nDoc;
163831
163832  if( paLen ) *paLen = a;
163833  return SQLITE_OK;
163834}
163835
163836/*
163837** An instance of the following structure is used to store state while
163838** iterating through a multi-column position-list corresponding to the
163839** hits for a single phrase on a single row in order to calculate the
163840** values for a matchinfo() FTS3_MATCHINFO_LCS request.
163841*/
163842typedef struct LcsIterator LcsIterator;
163843struct LcsIterator {
163844  Fts3Expr *pExpr;                /* Pointer to phrase expression */
163845  int iPosOffset;                 /* Tokens count up to end of this phrase */
163846  char *pRead;                    /* Cursor used to iterate through aDoclist */
163847  int iPos;                       /* Current position */
163848};
163849
163850/*
163851** If LcsIterator.iCol is set to the following value, the iterator has
163852** finished iterating through all offsets for all columns.
163853*/
163854#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
163855
163856static int fts3MatchinfoLcsCb(
163857  Fts3Expr *pExpr,                /* Phrase expression node */
163858  int iPhrase,                    /* Phrase number (numbered from zero) */
163859  void *pCtx                      /* Pointer to MatchInfo structure */
163860){
163861  LcsIterator *aIter = (LcsIterator *)pCtx;
163862  aIter[iPhrase].pExpr = pExpr;
163863  return SQLITE_OK;
163864}
163865
163866/*
163867** Advance the iterator passed as an argument to the next position. Return
163868** 1 if the iterator is at EOF or if it now points to the start of the
163869** position list for the next column.
163870*/
163871static int fts3LcsIteratorAdvance(LcsIterator *pIter){
163872  char *pRead = pIter->pRead;
163873  sqlite3_int64 iRead;
163874  int rc = 0;
163875
163876  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
163877  if( iRead==0 || iRead==1 ){
163878    pRead = 0;
163879    rc = 1;
163880  }else{
163881    pIter->iPos += (int)(iRead-2);
163882  }
163883
163884  pIter->pRead = pRead;
163885  return rc;
163886}
163887
163888/*
163889** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
163890**
163891** If the call is successful, the longest-common-substring lengths for each
163892** column are written into the first nCol elements of the pInfo->aMatchinfo[]
163893** array before returning. SQLITE_OK is returned in this case.
163894**
163895** Otherwise, if an error occurs, an SQLite error code is returned and the
163896** data written to the first nCol elements of pInfo->aMatchinfo[] is
163897** undefined.
163898*/
163899static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
163900  LcsIterator *aIter;
163901  int i;
163902  int iCol;
163903  int nToken = 0;
163904
163905  /* Allocate and populate the array of LcsIterator objects. The array
163906  ** contains one element for each matchable phrase in the query.
163907  **/
163908  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
163909  if( !aIter ) return SQLITE_NOMEM;
163910  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
163911  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
163912
163913  for(i=0; i<pInfo->nPhrase; i++){
163914    LcsIterator *pIter = &aIter[i];
163915    nToken -= pIter->pExpr->pPhrase->nToken;
163916    pIter->iPosOffset = nToken;
163917  }
163918
163919  for(iCol=0; iCol<pInfo->nCol; iCol++){
163920    int nLcs = 0;                 /* LCS value for this column */
163921    int nLive = 0;                /* Number of iterators in aIter not at EOF */
163922
163923    for(i=0; i<pInfo->nPhrase; i++){
163924      int rc;
163925      LcsIterator *pIt = &aIter[i];
163926      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
163927      if( rc!=SQLITE_OK ) return rc;
163928      if( pIt->pRead ){
163929        pIt->iPos = pIt->iPosOffset;
163930        fts3LcsIteratorAdvance(&aIter[i]);
163931        nLive++;
163932      }
163933    }
163934
163935    while( nLive>0 ){
163936      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
163937      int nThisLcs = 0;           /* LCS for the current iterator positions */
163938
163939      for(i=0; i<pInfo->nPhrase; i++){
163940        LcsIterator *pIter = &aIter[i];
163941        if( pIter->pRead==0 ){
163942          /* This iterator is already at EOF for this column. */
163943          nThisLcs = 0;
163944        }else{
163945          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
163946            pAdv = pIter;
163947          }
163948          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
163949            nThisLcs++;
163950          }else{
163951            nThisLcs = 1;
163952          }
163953          if( nThisLcs>nLcs ) nLcs = nThisLcs;
163954        }
163955      }
163956      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
163957    }
163958
163959    pInfo->aMatchinfo[iCol] = nLcs;
163960  }
163961
163962  sqlite3_free(aIter);
163963  return SQLITE_OK;
163964}
163965
163966/*
163967** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
163968** be returned by the matchinfo() function. Argument zArg contains the
163969** format string passed as the second argument to matchinfo (or the
163970** default value "pcx" if no second argument was specified). The format
163971** string has already been validated and the pInfo->aMatchinfo[] array
163972** is guaranteed to be large enough for the output.
163973**
163974** If bGlobal is true, then populate all fields of the matchinfo() output.
163975** If it is false, then assume that those fields that do not change between
163976** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
163977** have already been populated.
163978**
163979** Return SQLITE_OK if successful, or an SQLite error code if an error
163980** occurs. If a value other than SQLITE_OK is returned, the state the
163981** pInfo->aMatchinfo[] buffer is left in is undefined.
163982*/
163983static int fts3MatchinfoValues(
163984  Fts3Cursor *pCsr,               /* FTS3 cursor object */
163985  int bGlobal,                    /* True to grab the global stats */
163986  MatchInfo *pInfo,               /* Matchinfo context object */
163987  const char *zArg                /* Matchinfo format string */
163988){
163989  int rc = SQLITE_OK;
163990  int i;
163991  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
163992  sqlite3_stmt *pSelect = 0;
163993
163994  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
163995    pInfo->flag = zArg[i];
163996    switch( zArg[i] ){
163997      case FTS3_MATCHINFO_NPHRASE:
163998        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
163999        break;
164000
164001      case FTS3_MATCHINFO_NCOL:
164002        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
164003        break;
164004
164005      case FTS3_MATCHINFO_NDOC:
164006        if( bGlobal ){
164007          sqlite3_int64 nDoc = 0;
164008          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
164009          pInfo->aMatchinfo[0] = (u32)nDoc;
164010        }
164011        break;
164012
164013      case FTS3_MATCHINFO_AVGLENGTH:
164014        if( bGlobal ){
164015          sqlite3_int64 nDoc;     /* Number of rows in table */
164016          const char *a;          /* Aggregate column length array */
164017
164018          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
164019          if( rc==SQLITE_OK ){
164020            int iCol;
164021            for(iCol=0; iCol<pInfo->nCol; iCol++){
164022              u32 iVal;
164023              sqlite3_int64 nToken;
164024              a += sqlite3Fts3GetVarint(a, &nToken);
164025              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
164026              pInfo->aMatchinfo[iCol] = iVal;
164027            }
164028          }
164029        }
164030        break;
164031
164032      case FTS3_MATCHINFO_LENGTH: {
164033        sqlite3_stmt *pSelectDocsize = 0;
164034        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
164035        if( rc==SQLITE_OK ){
164036          int iCol;
164037          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
164038          for(iCol=0; iCol<pInfo->nCol; iCol++){
164039            sqlite3_int64 nToken;
164040            a += sqlite3Fts3GetVarint(a, &nToken);
164041            pInfo->aMatchinfo[iCol] = (u32)nToken;
164042          }
164043        }
164044        sqlite3_reset(pSelectDocsize);
164045        break;
164046      }
164047
164048      case FTS3_MATCHINFO_LCS:
164049        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
164050        if( rc==SQLITE_OK ){
164051          rc = fts3MatchinfoLcs(pCsr, pInfo);
164052        }
164053        break;
164054
164055      case FTS3_MATCHINFO_LHITS_BM:
164056      case FTS3_MATCHINFO_LHITS: {
164057        int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
164058        memset(pInfo->aMatchinfo, 0, nZero);
164059        fts3ExprLHitGather(pCsr->pExpr, pInfo);
164060        break;
164061      }
164062
164063      default: {
164064        Fts3Expr *pExpr;
164065        assert( zArg[i]==FTS3_MATCHINFO_HITS );
164066        pExpr = pCsr->pExpr;
164067        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
164068        if( rc!=SQLITE_OK ) break;
164069        if( bGlobal ){
164070          if( pCsr->pDeferred ){
164071            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
164072            if( rc!=SQLITE_OK ) break;
164073          }
164074          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
164075          sqlite3Fts3EvalTestDeferred(pCsr, &rc);
164076          if( rc!=SQLITE_OK ) break;
164077        }
164078        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
164079        break;
164080      }
164081    }
164082
164083    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
164084  }
164085
164086  sqlite3_reset(pSelect);
164087  return rc;
164088}
164089
164090
164091/*
164092** Populate pCsr->aMatchinfo[] with data for the current row. The
164093** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
164094*/
164095static void fts3GetMatchinfo(
164096  sqlite3_context *pCtx,        /* Return results here */
164097  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
164098  const char *zArg                /* Second argument to matchinfo() function */
164099){
164100  MatchInfo sInfo;
164101  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164102  int rc = SQLITE_OK;
164103  int bGlobal = 0;                /* Collect 'global' stats as well as local */
164104
164105  u32 *aOut = 0;
164106  void (*xDestroyOut)(void*) = 0;
164107
164108  memset(&sInfo, 0, sizeof(MatchInfo));
164109  sInfo.pCursor = pCsr;
164110  sInfo.nCol = pTab->nColumn;
164111
164112  /* If there is cached matchinfo() data, but the format string for the
164113  ** cache does not match the format string for this request, discard
164114  ** the cached data. */
164115  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
164116    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
164117    pCsr->pMIBuffer = 0;
164118  }
164119
164120  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
164121  ** matchinfo function has been called for this query. In this case
164122  ** allocate the array used to accumulate the matchinfo data and
164123  ** initialize those elements that are constant for every row.
164124  */
164125  if( pCsr->pMIBuffer==0 ){
164126    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
164127    int i;                        /* Used to iterate through zArg */
164128
164129    /* Determine the number of phrases in the query */
164130    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
164131    sInfo.nPhrase = pCsr->nPhrase;
164132
164133    /* Determine the number of integers in the buffer returned by this call. */
164134    for(i=0; zArg[i]; i++){
164135      char *zErr = 0;
164136      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
164137        sqlite3_result_error(pCtx, zErr, -1);
164138        sqlite3_free(zErr);
164139        return;
164140      }
164141      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
164142    }
164143
164144    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
164145    pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
164146    if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
164147
164148    pCsr->isMatchinfoNeeded = 1;
164149    bGlobal = 1;
164150  }
164151
164152  if( rc==SQLITE_OK ){
164153    xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
164154    if( xDestroyOut==0 ){
164155      rc = SQLITE_NOMEM;
164156    }
164157  }
164158
164159  if( rc==SQLITE_OK ){
164160    sInfo.aMatchinfo = aOut;
164161    sInfo.nPhrase = pCsr->nPhrase;
164162    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
164163    if( bGlobal ){
164164      fts3MIBufferSetGlobal(pCsr->pMIBuffer);
164165    }
164166  }
164167
164168  if( rc!=SQLITE_OK ){
164169    sqlite3_result_error_code(pCtx, rc);
164170    if( xDestroyOut ) xDestroyOut(aOut);
164171  }else{
164172    int n = pCsr->pMIBuffer->nElem * sizeof(u32);
164173    sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
164174  }
164175}
164176
164177/*
164178** Implementation of snippet() function.
164179*/
164180SQLITE_PRIVATE void sqlite3Fts3Snippet(
164181  sqlite3_context *pCtx,          /* SQLite function call context */
164182  Fts3Cursor *pCsr,               /* Cursor object */
164183  const char *zStart,             /* Snippet start text - "<b>" */
164184  const char *zEnd,               /* Snippet end text - "</b>" */
164185  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
164186  int iCol,                       /* Extract snippet from this column */
164187  int nToken                      /* Approximate number of tokens in snippet */
164188){
164189  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164190  int rc = SQLITE_OK;
164191  int i;
164192  StrBuffer res = {0, 0, 0};
164193
164194  /* The returned text includes up to four fragments of text extracted from
164195  ** the data in the current row. The first iteration of the for(...) loop
164196  ** below attempts to locate a single fragment of text nToken tokens in
164197  ** size that contains at least one instance of all phrases in the query
164198  ** expression that appear in the current row. If such a fragment of text
164199  ** cannot be found, the second iteration of the loop attempts to locate
164200  ** a pair of fragments, and so on.
164201  */
164202  int nSnippet = 0;               /* Number of fragments in this snippet */
164203  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
164204  int nFToken = -1;               /* Number of tokens in each fragment */
164205
164206  if( !pCsr->pExpr ){
164207    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
164208    return;
164209  }
164210
164211  for(nSnippet=1; 1; nSnippet++){
164212
164213    int iSnip;                    /* Loop counter 0..nSnippet-1 */
164214    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
164215    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
164216
164217    if( nToken>=0 ){
164218      nFToken = (nToken+nSnippet-1) / nSnippet;
164219    }else{
164220      nFToken = -1 * nToken;
164221    }
164222
164223    for(iSnip=0; iSnip<nSnippet; iSnip++){
164224      int iBestScore = -1;        /* Best score of columns checked so far */
164225      int iRead;                  /* Used to iterate through columns */
164226      SnippetFragment *pFragment = &aSnippet[iSnip];
164227
164228      memset(pFragment, 0, sizeof(*pFragment));
164229
164230      /* Loop through all columns of the table being considered for snippets.
164231      ** If the iCol argument to this function was negative, this means all
164232      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
164233      */
164234      for(iRead=0; iRead<pTab->nColumn; iRead++){
164235        SnippetFragment sF = {0, 0, 0, 0};
164236        int iS = 0;
164237        if( iCol>=0 && iRead!=iCol ) continue;
164238
164239        /* Find the best snippet of nFToken tokens in column iRead. */
164240        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
164241        if( rc!=SQLITE_OK ){
164242          goto snippet_out;
164243        }
164244        if( iS>iBestScore ){
164245          *pFragment = sF;
164246          iBestScore = iS;
164247        }
164248      }
164249
164250      mCovered |= pFragment->covered;
164251    }
164252
164253    /* If all query phrases seen by fts3BestSnippet() are present in at least
164254    ** one of the nSnippet snippet fragments, break out of the loop.
164255    */
164256    assert( (mCovered&mSeen)==mCovered );
164257    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
164258  }
164259
164260  assert( nFToken>0 );
164261
164262  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
164263    rc = fts3SnippetText(pCsr, &aSnippet[i],
164264        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
164265    );
164266  }
164267
164268 snippet_out:
164269  sqlite3Fts3SegmentsClose(pTab);
164270  if( rc!=SQLITE_OK ){
164271    sqlite3_result_error_code(pCtx, rc);
164272    sqlite3_free(res.z);
164273  }else{
164274    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
164275  }
164276}
164277
164278
164279typedef struct TermOffset TermOffset;
164280typedef struct TermOffsetCtx TermOffsetCtx;
164281
164282struct TermOffset {
164283  char *pList;                    /* Position-list */
164284  int iPos;                       /* Position just read from pList */
164285  int iOff;                       /* Offset of this term from read positions */
164286};
164287
164288struct TermOffsetCtx {
164289  Fts3Cursor *pCsr;
164290  int iCol;                       /* Column of table to populate aTerm for */
164291  int iTerm;
164292  sqlite3_int64 iDocid;
164293  TermOffset *aTerm;
164294};
164295
164296/*
164297** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
164298*/
164299static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
164300  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
164301  int nTerm;                      /* Number of tokens in phrase */
164302  int iTerm;                      /* For looping through nTerm phrase terms */
164303  char *pList;                    /* Pointer to position list for phrase */
164304  int iPos = 0;                   /* First position in position-list */
164305  int rc;
164306
164307  UNUSED_PARAMETER(iPhrase);
164308  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
164309  nTerm = pExpr->pPhrase->nToken;
164310  if( pList ){
164311    fts3GetDeltaPosition(&pList, &iPos);
164312    assert( iPos>=0 );
164313  }
164314
164315  for(iTerm=0; iTerm<nTerm; iTerm++){
164316    TermOffset *pT = &p->aTerm[p->iTerm++];
164317    pT->iOff = nTerm-iTerm-1;
164318    pT->pList = pList;
164319    pT->iPos = iPos;
164320  }
164321
164322  return rc;
164323}
164324
164325/*
164326** Implementation of offsets() function.
164327*/
164328SQLITE_PRIVATE void sqlite3Fts3Offsets(
164329  sqlite3_context *pCtx,          /* SQLite function call context */
164330  Fts3Cursor *pCsr                /* Cursor object */
164331){
164332  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164333  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
164334  int rc;                         /* Return Code */
164335  int nToken;                     /* Number of tokens in query */
164336  int iCol;                       /* Column currently being processed */
164337  StrBuffer res = {0, 0, 0};      /* Result string */
164338  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
164339
164340  if( !pCsr->pExpr ){
164341    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
164342    return;
164343  }
164344
164345  memset(&sCtx, 0, sizeof(sCtx));
164346  assert( pCsr->isRequireSeek==0 );
164347
164348  /* Count the number of terms in the query */
164349  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
164350  if( rc!=SQLITE_OK ) goto offsets_out;
164351
164352  /* Allocate the array of TermOffset iterators. */
164353  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
164354  if( 0==sCtx.aTerm ){
164355    rc = SQLITE_NOMEM;
164356    goto offsets_out;
164357  }
164358  sCtx.iDocid = pCsr->iPrevId;
164359  sCtx.pCsr = pCsr;
164360
164361  /* Loop through the table columns, appending offset information to
164362  ** string-buffer res for each column.
164363  */
164364  for(iCol=0; iCol<pTab->nColumn; iCol++){
164365    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
164366    const char *ZDUMMY;           /* Dummy argument used with xNext() */
164367    int NDUMMY = 0;               /* Dummy argument used with xNext() */
164368    int iStart = 0;
164369    int iEnd = 0;
164370    int iCurrent = 0;
164371    const char *zDoc;
164372    int nDoc;
164373
164374    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
164375    ** no way that this operation can fail, so the return code from
164376    ** fts3ExprIterate() can be discarded.
164377    */
164378    sCtx.iCol = iCol;
164379    sCtx.iTerm = 0;
164380    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
164381
164382    /* Retreive the text stored in column iCol. If an SQL NULL is stored
164383    ** in column iCol, jump immediately to the next iteration of the loop.
164384    ** If an OOM occurs while retrieving the data (this can happen if SQLite
164385    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
164386    ** to the caller.
164387    */
164388    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
164389    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
164390    if( zDoc==0 ){
164391      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
164392        continue;
164393      }
164394      rc = SQLITE_NOMEM;
164395      goto offsets_out;
164396    }
164397
164398    /* Initialize a tokenizer iterator to iterate through column iCol. */
164399    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
164400        zDoc, nDoc, &pC
164401    );
164402    if( rc!=SQLITE_OK ) goto offsets_out;
164403
164404    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
164405    while( rc==SQLITE_OK ){
164406      int i;                      /* Used to loop through terms */
164407      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
164408      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
164409
164410      for(i=0; i<nToken; i++){
164411        TermOffset *pT = &sCtx.aTerm[i];
164412        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
164413          iMinPos = pT->iPos-pT->iOff;
164414          pTerm = pT;
164415        }
164416      }
164417
164418      if( !pTerm ){
164419        /* All offsets for this column have been gathered. */
164420        rc = SQLITE_DONE;
164421      }else{
164422        assert( iCurrent<=iMinPos );
164423        if( 0==(0xFE&*pTerm->pList) ){
164424          pTerm->pList = 0;
164425        }else{
164426          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
164427        }
164428        while( rc==SQLITE_OK && iCurrent<iMinPos ){
164429          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
164430        }
164431        if( rc==SQLITE_OK ){
164432          char aBuffer[64];
164433          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
164434              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
164435          );
164436          rc = fts3StringAppend(&res, aBuffer, -1);
164437        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
164438          rc = FTS_CORRUPT_VTAB;
164439        }
164440      }
164441    }
164442    if( rc==SQLITE_DONE ){
164443      rc = SQLITE_OK;
164444    }
164445
164446    pMod->xClose(pC);
164447    if( rc!=SQLITE_OK ) goto offsets_out;
164448  }
164449
164450 offsets_out:
164451  sqlite3_free(sCtx.aTerm);
164452  assert( rc!=SQLITE_DONE );
164453  sqlite3Fts3SegmentsClose(pTab);
164454  if( rc!=SQLITE_OK ){
164455    sqlite3_result_error_code(pCtx,  rc);
164456    sqlite3_free(res.z);
164457  }else{
164458    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
164459  }
164460  return;
164461}
164462
164463/*
164464** Implementation of matchinfo() function.
164465*/
164466SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
164467  sqlite3_context *pContext,      /* Function call context */
164468  Fts3Cursor *pCsr,               /* FTS3 table cursor */
164469  const char *zArg                /* Second arg to matchinfo() function */
164470){
164471  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
164472  const char *zFormat;
164473
164474  if( zArg ){
164475    zFormat = zArg;
164476  }else{
164477    zFormat = FTS3_MATCHINFO_DEFAULT;
164478  }
164479
164480  if( !pCsr->pExpr ){
164481    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
164482    return;
164483  }else{
164484    /* Retrieve matchinfo() data. */
164485    fts3GetMatchinfo(pContext, pCsr, zFormat);
164486    sqlite3Fts3SegmentsClose(pTab);
164487  }
164488}
164489
164490#endif
164491
164492/************** End of fts3_snippet.c ****************************************/
164493/************** Begin file fts3_unicode.c ************************************/
164494/*
164495** 2012 May 24
164496**
164497** The author disclaims copyright to this source code.  In place of
164498** a legal notice, here is a blessing:
164499**
164500**    May you do good and not evil.
164501**    May you find forgiveness for yourself and forgive others.
164502**    May you share freely, never taking more than you give.
164503**
164504******************************************************************************
164505**
164506** Implementation of the "unicode" full-text-search tokenizer.
164507*/
164508
164509#ifndef SQLITE_DISABLE_FTS3_UNICODE
164510
164511/* #include "fts3Int.h" */
164512#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
164513
164514/* #include <assert.h> */
164515/* #include <stdlib.h> */
164516/* #include <stdio.h> */
164517/* #include <string.h> */
164518
164519/* #include "fts3_tokenizer.h" */
164520
164521/*
164522** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
164523** from the sqlite3 source file utf.c. If this file is compiled as part
164524** of the amalgamation, they are not required.
164525*/
164526#ifndef SQLITE_AMALGAMATION
164527
164528static const unsigned char sqlite3Utf8Trans1[] = {
164529  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164530  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164531  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
164532  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
164533  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164534  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164535  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164536  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
164537};
164538
164539#define READ_UTF8(zIn, zTerm, c)                           \
164540  c = *(zIn++);                                            \
164541  if( c>=0xc0 ){                                           \
164542    c = sqlite3Utf8Trans1[c-0xc0];                         \
164543    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
164544      c = (c<<6) + (0x3f & *(zIn++));                      \
164545    }                                                      \
164546    if( c<0x80                                             \
164547        || (c&0xFFFFF800)==0xD800                          \
164548        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
164549  }
164550
164551#define WRITE_UTF8(zOut, c) {                          \
164552  if( c<0x00080 ){                                     \
164553    *zOut++ = (u8)(c&0xFF);                            \
164554  }                                                    \
164555  else if( c<0x00800 ){                                \
164556    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
164557    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
164558  }                                                    \
164559  else if( c<0x10000 ){                                \
164560    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
164561    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
164562    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
164563  }else{                                               \
164564    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
164565    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
164566    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
164567    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
164568  }                                                    \
164569}
164570
164571#endif /* ifndef SQLITE_AMALGAMATION */
164572
164573typedef struct unicode_tokenizer unicode_tokenizer;
164574typedef struct unicode_cursor unicode_cursor;
164575
164576struct unicode_tokenizer {
164577  sqlite3_tokenizer base;
164578  int bRemoveDiacritic;
164579  int nException;
164580  int *aiException;
164581};
164582
164583struct unicode_cursor {
164584  sqlite3_tokenizer_cursor base;
164585  const unsigned char *aInput;    /* Input text being tokenized */
164586  int nInput;                     /* Size of aInput[] in bytes */
164587  int iOff;                       /* Current offset within aInput[] */
164588  int iToken;                     /* Index of next token to be returned */
164589  char *zToken;                   /* storage for current token */
164590  int nAlloc;                     /* space allocated at zToken */
164591};
164592
164593
164594/*
164595** Destroy a tokenizer allocated by unicodeCreate().
164596*/
164597static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
164598  if( pTokenizer ){
164599    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
164600    sqlite3_free(p->aiException);
164601    sqlite3_free(p);
164602  }
164603  return SQLITE_OK;
164604}
164605
164606/*
164607** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
164608** statement has specified that the tokenizer for this table shall consider
164609** all characters in string zIn/nIn to be separators (if bAlnum==0) or
164610** token characters (if bAlnum==1).
164611**
164612** For each codepoint in the zIn/nIn string, this function checks if the
164613** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
164614** If so, no action is taken. Otherwise, the codepoint is added to the
164615** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
164616** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
164617** codepoints in the aiException[] array.
164618**
164619** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
164620** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
164621** It is not possible to change the behavior of the tokenizer with respect
164622** to these codepoints.
164623*/
164624static int unicodeAddExceptions(
164625  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
164626  int bAlnum,                     /* Replace Isalnum() return value with this */
164627  const char *zIn,                /* Array of characters to make exceptions */
164628  int nIn                         /* Length of z in bytes */
164629){
164630  const unsigned char *z = (const unsigned char *)zIn;
164631  const unsigned char *zTerm = &z[nIn];
164632  unsigned int iCode;
164633  int nEntry = 0;
164634
164635  assert( bAlnum==0 || bAlnum==1 );
164636
164637  while( z<zTerm ){
164638    READ_UTF8(z, zTerm, iCode);
164639    assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
164640    if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
164641     && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
164642    ){
164643      nEntry++;
164644    }
164645  }
164646
164647  if( nEntry ){
164648    int *aNew;                    /* New aiException[] array */
164649    int nNew;                     /* Number of valid entries in array aNew[] */
164650
164651    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
164652    if( aNew==0 ) return SQLITE_NOMEM;
164653    nNew = p->nException;
164654
164655    z = (const unsigned char *)zIn;
164656    while( z<zTerm ){
164657      READ_UTF8(z, zTerm, iCode);
164658      if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
164659       && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
164660      ){
164661        int i, j;
164662        for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
164663        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
164664        aNew[i] = (int)iCode;
164665        nNew++;
164666      }
164667    }
164668    p->aiException = aNew;
164669    p->nException = nNew;
164670  }
164671
164672  return SQLITE_OK;
164673}
164674
164675/*
164676** Return true if the p->aiException[] array contains the value iCode.
164677*/
164678static int unicodeIsException(unicode_tokenizer *p, int iCode){
164679  if( p->nException>0 ){
164680    int *a = p->aiException;
164681    int iLo = 0;
164682    int iHi = p->nException-1;
164683
164684    while( iHi>=iLo ){
164685      int iTest = (iHi + iLo) / 2;
164686      if( iCode==a[iTest] ){
164687        return 1;
164688      }else if( iCode>a[iTest] ){
164689        iLo = iTest+1;
164690      }else{
164691        iHi = iTest-1;
164692      }
164693    }
164694  }
164695
164696  return 0;
164697}
164698
164699/*
164700** Return true if, for the purposes of tokenization, codepoint iCode is
164701** considered a token character (not a separator).
164702*/
164703static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
164704  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
164705  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
164706}
164707
164708/*
164709** Create a new tokenizer instance.
164710*/
164711static int unicodeCreate(
164712  int nArg,                       /* Size of array argv[] */
164713  const char * const *azArg,      /* Tokenizer creation arguments */
164714  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
164715){
164716  unicode_tokenizer *pNew;        /* New tokenizer object */
164717  int i;
164718  int rc = SQLITE_OK;
164719
164720  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
164721  if( pNew==NULL ) return SQLITE_NOMEM;
164722  memset(pNew, 0, sizeof(unicode_tokenizer));
164723  pNew->bRemoveDiacritic = 1;
164724
164725  for(i=0; rc==SQLITE_OK && i<nArg; i++){
164726    const char *z = azArg[i];
164727    int n = (int)strlen(z);
164728
164729    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
164730      pNew->bRemoveDiacritic = 1;
164731    }
164732    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
164733      pNew->bRemoveDiacritic = 0;
164734    }
164735    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
164736      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
164737    }
164738    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
164739      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
164740    }
164741    else{
164742      /* Unrecognized argument */
164743      rc  = SQLITE_ERROR;
164744    }
164745  }
164746
164747  if( rc!=SQLITE_OK ){
164748    unicodeDestroy((sqlite3_tokenizer *)pNew);
164749    pNew = 0;
164750  }
164751  *pp = (sqlite3_tokenizer *)pNew;
164752  return rc;
164753}
164754
164755/*
164756** Prepare to begin tokenizing a particular string.  The input
164757** string to be tokenized is pInput[0..nBytes-1].  A cursor
164758** used to incrementally tokenize this string is returned in
164759** *ppCursor.
164760*/
164761static int unicodeOpen(
164762  sqlite3_tokenizer *p,           /* The tokenizer */
164763  const char *aInput,             /* Input string */
164764  int nInput,                     /* Size of string aInput in bytes */
164765  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
164766){
164767  unicode_cursor *pCsr;
164768
164769  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
164770  if( pCsr==0 ){
164771    return SQLITE_NOMEM;
164772  }
164773  memset(pCsr, 0, sizeof(unicode_cursor));
164774
164775  pCsr->aInput = (const unsigned char *)aInput;
164776  if( aInput==0 ){
164777    pCsr->nInput = 0;
164778  }else if( nInput<0 ){
164779    pCsr->nInput = (int)strlen(aInput);
164780  }else{
164781    pCsr->nInput = nInput;
164782  }
164783
164784  *pp = &pCsr->base;
164785  UNUSED_PARAMETER(p);
164786  return SQLITE_OK;
164787}
164788
164789/*
164790** Close a tokenization cursor previously opened by a call to
164791** simpleOpen() above.
164792*/
164793static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
164794  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
164795  sqlite3_free(pCsr->zToken);
164796  sqlite3_free(pCsr);
164797  return SQLITE_OK;
164798}
164799
164800/*
164801** Extract the next token from a tokenization cursor.  The cursor must
164802** have been opened by a prior call to simpleOpen().
164803*/
164804static int unicodeNext(
164805  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
164806  const char **paToken,           /* OUT: Token text */
164807  int *pnToken,                   /* OUT: Number of bytes at *paToken */
164808  int *piStart,                   /* OUT: Starting offset of token */
164809  int *piEnd,                     /* OUT: Ending offset of token */
164810  int *piPos                      /* OUT: Position integer of token */
164811){
164812  unicode_cursor *pCsr = (unicode_cursor *)pC;
164813  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
164814  unsigned int iCode = 0;
164815  char *zOut;
164816  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
164817  const unsigned char *zStart = z;
164818  const unsigned char *zEnd;
164819  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
164820
164821  /* Scan past any delimiter characters before the start of the next token.
164822  ** Return SQLITE_DONE early if this takes us all the way to the end of
164823  ** the input.  */
164824  while( z<zTerm ){
164825    READ_UTF8(z, zTerm, iCode);
164826    if( unicodeIsAlnum(p, (int)iCode) ) break;
164827    zStart = z;
164828  }
164829  if( zStart>=zTerm ) return SQLITE_DONE;
164830
164831  zOut = pCsr->zToken;
164832  do {
164833    int iOut;
164834
164835    /* Grow the output buffer if required. */
164836    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
164837      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
164838      if( !zNew ) return SQLITE_NOMEM;
164839      zOut = &zNew[zOut - pCsr->zToken];
164840      pCsr->zToken = zNew;
164841      pCsr->nAlloc += 64;
164842    }
164843
164844    /* Write the folded case of the last character read to the output */
164845    zEnd = z;
164846    iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
164847    if( iOut ){
164848      WRITE_UTF8(zOut, iOut);
164849    }
164850
164851    /* If the cursor is not at EOF, read the next character */
164852    if( z>=zTerm ) break;
164853    READ_UTF8(z, zTerm, iCode);
164854  }while( unicodeIsAlnum(p, (int)iCode)
164855       || sqlite3FtsUnicodeIsdiacritic((int)iCode)
164856  );
164857
164858  /* Set the output variables and return. */
164859  pCsr->iOff = (int)(z - pCsr->aInput);
164860  *paToken = pCsr->zToken;
164861  *pnToken = (int)(zOut - pCsr->zToken);
164862  *piStart = (int)(zStart - pCsr->aInput);
164863  *piEnd = (int)(zEnd - pCsr->aInput);
164864  *piPos = pCsr->iToken++;
164865  return SQLITE_OK;
164866}
164867
164868/*
164869** Set *ppModule to a pointer to the sqlite3_tokenizer_module
164870** structure for the unicode tokenizer.
164871*/
164872SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
164873  static const sqlite3_tokenizer_module module = {
164874    0,
164875    unicodeCreate,
164876    unicodeDestroy,
164877    unicodeOpen,
164878    unicodeClose,
164879    unicodeNext,
164880    0,
164881  };
164882  *ppModule = &module;
164883}
164884
164885#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
164886#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
164887
164888/************** End of fts3_unicode.c ****************************************/
164889/************** Begin file fts3_unicode2.c ***********************************/
164890/*
164891** 2012 May 25
164892**
164893** The author disclaims copyright to this source code.  In place of
164894** a legal notice, here is a blessing:
164895**
164896**    May you do good and not evil.
164897**    May you find forgiveness for yourself and forgive others.
164898**    May you share freely, never taking more than you give.
164899**
164900******************************************************************************
164901*/
164902
164903/*
164904** DO NOT EDIT THIS MACHINE GENERATED FILE.
164905*/
164906
164907#ifndef SQLITE_DISABLE_FTS3_UNICODE
164908#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
164909
164910/* #include <assert.h> */
164911
164912/*
164913** Return true if the argument corresponds to a unicode codepoint
164914** classified as either a letter or a number. Otherwise false.
164915**
164916** The results are undefined if the value passed to this function
164917** is less than zero.
164918*/
164919SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
164920  /* Each unsigned integer in the following array corresponds to a contiguous
164921  ** range of unicode codepoints that are not either letters or numbers (i.e.
164922  ** codepoints for which this function should return 0).
164923  **
164924  ** The most significant 22 bits in each 32-bit value contain the first
164925  ** codepoint in the range. The least significant 10 bits are used to store
164926  ** the size of the range (always at least 1). In other words, the value
164927  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
164928  ** C. It is not possible to represent a range larger than 1023 codepoints
164929  ** using this format.
164930  */
164931  static const unsigned int aEntry[] = {
164932    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
164933    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
164934    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
164935    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
164936    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
164937    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
164938    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
164939    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
164940    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
164941    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
164942    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
164943    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
164944    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
164945    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
164946    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
164947    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
164948    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
164949    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
164950    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
164951    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
164952    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
164953    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
164954    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
164955    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
164956    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
164957    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
164958    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
164959    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
164960    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
164961    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
164962    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
164963    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
164964    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
164965    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
164966    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
164967    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
164968    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
164969    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
164970    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
164971    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
164972    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
164973    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
164974    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
164975    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
164976    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
164977    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
164978    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
164979    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
164980    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
164981    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
164982    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
164983    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
164984    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
164985    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
164986    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
164987    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
164988    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
164989    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
164990    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
164991    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
164992    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
164993    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
164994    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
164995    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
164996    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
164997    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
164998    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
164999    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
165000    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
165001    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
165002    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
165003    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
165004    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
165005    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
165006    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
165007    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
165008    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
165009    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
165010    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
165011    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
165012    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
165013    0x380400F0,
165014  };
165015  static const unsigned int aAscii[4] = {
165016    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
165017  };
165018
165019  if( (unsigned int)c<128 ){
165020    return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
165021  }else if( (unsigned int)c<(1<<22) ){
165022    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
165023    int iRes = 0;
165024    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
165025    int iLo = 0;
165026    while( iHi>=iLo ){
165027      int iTest = (iHi + iLo) / 2;
165028      if( key >= aEntry[iTest] ){
165029        iRes = iTest;
165030        iLo = iTest+1;
165031      }else{
165032        iHi = iTest-1;
165033      }
165034    }
165035    assert( aEntry[0]<key );
165036    assert( key>=aEntry[iRes] );
165037    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
165038  }
165039  return 1;
165040}
165041
165042
165043/*
165044** If the argument is a codepoint corresponding to a lowercase letter
165045** in the ASCII range with a diacritic added, return the codepoint
165046** of the ASCII letter only. For example, if passed 235 - "LATIN
165047** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
165048** E"). The resuls of passing a codepoint that corresponds to an
165049** uppercase letter are undefined.
165050*/
165051static int remove_diacritic(int c){
165052  unsigned short aDia[] = {
165053        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
165054     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
165055     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
165056     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
165057     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
165058     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
165059     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
165060     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
165061    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
165062    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
165063    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
165064    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
165065    62924, 63050, 63082, 63274, 63390,
165066  };
165067  char aChar[] = {
165068    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
165069    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
165070    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
165071    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
165072    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
165073    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
165074    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
165075    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
165076    'e',  'i',  'o',  'u',  'y',
165077  };
165078
165079  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
165080  int iRes = 0;
165081  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
165082  int iLo = 0;
165083  while( iHi>=iLo ){
165084    int iTest = (iHi + iLo) / 2;
165085    if( key >= aDia[iTest] ){
165086      iRes = iTest;
165087      iLo = iTest+1;
165088    }else{
165089      iHi = iTest-1;
165090    }
165091  }
165092  assert( key>=aDia[iRes] );
165093  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
165094}
165095
165096
165097/*
165098** Return true if the argument interpreted as a unicode codepoint
165099** is a diacritical modifier character.
165100*/
165101SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
165102  unsigned int mask0 = 0x08029FDF;
165103  unsigned int mask1 = 0x000361F8;
165104  if( c<768 || c>817 ) return 0;
165105  return (c < 768+32) ?
165106      (mask0 & (1 << (c-768))) :
165107      (mask1 & (1 << (c-768-32)));
165108}
165109
165110
165111/*
165112** Interpret the argument as a unicode codepoint. If the codepoint
165113** is an upper case character that has a lower case equivalent,
165114** return the codepoint corresponding to the lower case version.
165115** Otherwise, return a copy of the argument.
165116**
165117** The results are undefined if the value passed to this function
165118** is less than zero.
165119*/
165120SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
165121  /* Each entry in the following array defines a rule for folding a range
165122  ** of codepoints to lower case. The rule applies to a range of nRange
165123  ** codepoints starting at codepoint iCode.
165124  **
165125  ** If the least significant bit in flags is clear, then the rule applies
165126  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
165127  ** need to be folded). Or, if it is set, then the rule only applies to
165128  ** every second codepoint in the range, starting with codepoint C.
165129  **
165130  ** The 7 most significant bits in flags are an index into the aiOff[]
165131  ** array. If a specific codepoint C does require folding, then its lower
165132  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
165133  **
165134  ** The contents of this array are generated by parsing the CaseFolding.txt
165135  ** file distributed as part of the "Unicode Character Database". See
165136  ** http://www.unicode.org for details.
165137  */
165138  static const struct TableEntry {
165139    unsigned short iCode;
165140    unsigned char flags;
165141    unsigned char nRange;
165142  } aEntry[] = {
165143    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
165144    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
165145    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
165146    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
165147    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
165148    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
165149    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
165150    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
165151    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
165152    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
165153    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
165154    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
165155    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
165156    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
165157    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
165158    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
165159    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
165160    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
165161    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
165162    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
165163    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
165164    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
165165    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
165166    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
165167    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
165168    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
165169    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
165170    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
165171    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
165172    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
165173    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
165174    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
165175    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
165176    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
165177    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
165178    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
165179    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
165180    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
165181    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
165182    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
165183    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
165184    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
165185    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
165186    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
165187    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
165188    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
165189    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
165190    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
165191    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
165192    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
165193    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
165194    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
165195    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
165196    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
165197    {65313, 14, 26},
165198  };
165199  static const unsigned short aiOff[] = {
165200   1,     2,     8,     15,    16,    26,    28,    32,
165201   37,    38,    40,    48,    63,    64,    69,    71,
165202   79,    80,    116,   202,   203,   205,   206,   207,
165203   209,   210,   211,   213,   214,   217,   218,   219,
165204   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
165205   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
165206   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
165207   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
165208   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
165209   65514, 65521, 65527, 65528, 65529,
165210  };
165211
165212  int ret = c;
165213
165214  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
165215
165216  if( c<128 ){
165217    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
165218  }else if( c<65536 ){
165219    const struct TableEntry *p;
165220    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
165221    int iLo = 0;
165222    int iRes = -1;
165223
165224    assert( c>aEntry[0].iCode );
165225    while( iHi>=iLo ){
165226      int iTest = (iHi + iLo) / 2;
165227      int cmp = (c - aEntry[iTest].iCode);
165228      if( cmp>=0 ){
165229        iRes = iTest;
165230        iLo = iTest+1;
165231      }else{
165232        iHi = iTest-1;
165233      }
165234    }
165235
165236    assert( iRes>=0 && c>=aEntry[iRes].iCode );
165237    p = &aEntry[iRes];
165238    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
165239      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
165240      assert( ret>0 );
165241    }
165242
165243    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
165244  }
165245
165246  else if( c>=66560 && c<66600 ){
165247    ret = c + 40;
165248  }
165249
165250  return ret;
165251}
165252#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
165253#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
165254
165255/************** End of fts3_unicode2.c ***************************************/
165256/************** Begin file rtree.c *******************************************/
165257/*
165258** 2001 September 15
165259**
165260** The author disclaims copyright to this source code.  In place of
165261** a legal notice, here is a blessing:
165262**
165263**    May you do good and not evil.
165264**    May you find forgiveness for yourself and forgive others.
165265**    May you share freely, never taking more than you give.
165266**
165267*************************************************************************
165268** This file contains code for implementations of the r-tree and r*-tree
165269** algorithms packaged as an SQLite virtual table module.
165270*/
165271
165272/*
165273** Database Format of R-Tree Tables
165274** --------------------------------
165275**
165276** The data structure for a single virtual r-tree table is stored in three
165277** native SQLite tables declared as follows. In each case, the '%' character
165278** in the table name is replaced with the user-supplied name of the r-tree
165279** table.
165280**
165281**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
165282**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
165283**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
165284**
165285** The data for each node of the r-tree structure is stored in the %_node
165286** table. For each node that is not the root node of the r-tree, there is
165287** an entry in the %_parent table associating the node with its parent.
165288** And for each row of data in the table, there is an entry in the %_rowid
165289** table that maps from the entries rowid to the id of the node that it
165290** is stored on.
165291**
165292** The root node of an r-tree always exists, even if the r-tree table is
165293** empty. The nodeno of the root node is always 1. All other nodes in the
165294** table must be the same size as the root node. The content of each node
165295** is formatted as follows:
165296**
165297**   1. If the node is the root node (node 1), then the first 2 bytes
165298**      of the node contain the tree depth as a big-endian integer.
165299**      For non-root nodes, the first 2 bytes are left unused.
165300**
165301**   2. The next 2 bytes contain the number of entries currently
165302**      stored in the node.
165303**
165304**   3. The remainder of the node contains the node entries. Each entry
165305**      consists of a single 8-byte integer followed by an even number
165306**      of 4-byte coordinates. For leaf nodes the integer is the rowid
165307**      of a record. For internal nodes it is the node number of a
165308**      child page.
165309*/
165310
165311#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
165312
165313#ifndef SQLITE_CORE
165314/*   #include "sqlite3ext.h" */
165315  SQLITE_EXTENSION_INIT1
165316#else
165317/*   #include "sqlite3.h" */
165318#endif
165319
165320/* #include <string.h> */
165321/* #include <assert.h> */
165322/* #include <stdio.h> */
165323
165324#ifndef SQLITE_AMALGAMATION
165325#include "sqlite3rtree.h"
165326typedef sqlite3_int64 i64;
165327typedef sqlite3_uint64 u64;
165328typedef unsigned char u8;
165329typedef unsigned short u16;
165330typedef unsigned int u32;
165331#endif
165332
165333/*  The following macro is used to suppress compiler warnings.
165334*/
165335#ifndef UNUSED_PARAMETER
165336# define UNUSED_PARAMETER(x) (void)(x)
165337#endif
165338
165339typedef struct Rtree Rtree;
165340typedef struct RtreeCursor RtreeCursor;
165341typedef struct RtreeNode RtreeNode;
165342typedef struct RtreeCell RtreeCell;
165343typedef struct RtreeConstraint RtreeConstraint;
165344typedef struct RtreeMatchArg RtreeMatchArg;
165345typedef struct RtreeGeomCallback RtreeGeomCallback;
165346typedef union RtreeCoord RtreeCoord;
165347typedef struct RtreeSearchPoint RtreeSearchPoint;
165348
165349/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
165350#define RTREE_MAX_DIMENSIONS 5
165351
165352/* Size of hash table Rtree.aHash. This hash table is not expected to
165353** ever contain very many entries, so a fixed number of buckets is
165354** used.
165355*/
165356#define HASHSIZE 97
165357
165358/* The xBestIndex method of this virtual table requires an estimate of
165359** the number of rows in the virtual table to calculate the costs of
165360** various strategies. If possible, this estimate is loaded from the
165361** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
165362** Otherwise, if no sqlite_stat1 entry is available, use
165363** RTREE_DEFAULT_ROWEST.
165364*/
165365#define RTREE_DEFAULT_ROWEST 1048576
165366#define RTREE_MIN_ROWEST         100
165367
165368/*
165369** An rtree virtual-table object.
165370*/
165371struct Rtree {
165372  sqlite3_vtab base;          /* Base class.  Must be first */
165373  sqlite3 *db;                /* Host database connection */
165374  int iNodeSize;              /* Size in bytes of each node in the node table */
165375  u8 nDim;                    /* Number of dimensions */
165376  u8 nDim2;                   /* Twice the number of dimensions */
165377  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
165378  u8 nBytesPerCell;           /* Bytes consumed per cell */
165379  u8 inWrTrans;               /* True if inside write transaction */
165380  int iDepth;                 /* Current depth of the r-tree structure */
165381  char *zDb;                  /* Name of database containing r-tree table */
165382  char *zName;                /* Name of r-tree table */
165383  u32 nBusy;                  /* Current number of users of this structure */
165384  i64 nRowEst;                /* Estimated number of rows in this table */
165385  u32 nCursor;                /* Number of open cursors */
165386
165387  /* List of nodes removed during a CondenseTree operation. List is
165388  ** linked together via the pointer normally used for hash chains -
165389  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
165390  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
165391  */
165392  RtreeNode *pDeleted;
165393  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
165394
165395  /* Blob I/O on xxx_node */
165396  sqlite3_blob *pNodeBlob;
165397
165398  /* Statements to read/write/delete a record from xxx_node */
165399  sqlite3_stmt *pWriteNode;
165400  sqlite3_stmt *pDeleteNode;
165401
165402  /* Statements to read/write/delete a record from xxx_rowid */
165403  sqlite3_stmt *pReadRowid;
165404  sqlite3_stmt *pWriteRowid;
165405  sqlite3_stmt *pDeleteRowid;
165406
165407  /* Statements to read/write/delete a record from xxx_parent */
165408  sqlite3_stmt *pReadParent;
165409  sqlite3_stmt *pWriteParent;
165410  sqlite3_stmt *pDeleteParent;
165411
165412  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
165413};
165414
165415/* Possible values for Rtree.eCoordType: */
165416#define RTREE_COORD_REAL32 0
165417#define RTREE_COORD_INT32  1
165418
165419/*
165420** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
165421** only deal with integer coordinates.  No floating point operations
165422** will be done.
165423*/
165424#ifdef SQLITE_RTREE_INT_ONLY
165425  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
165426  typedef int RtreeValue;                  /* Low accuracy coordinate */
165427# define RTREE_ZERO 0
165428#else
165429  typedef double RtreeDValue;              /* High accuracy coordinate */
165430  typedef float RtreeValue;                /* Low accuracy coordinate */
165431# define RTREE_ZERO 0.0
165432#endif
165433
165434/*
165435** When doing a search of an r-tree, instances of the following structure
165436** record intermediate results from the tree walk.
165437**
165438** The id is always a node-id.  For iLevel>=1 the id is the node-id of
165439** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
165440** the id is of the parent node and the cell that RtreeSearchPoint
165441** represents is the iCell-th entry in the parent node.
165442*/
165443struct RtreeSearchPoint {
165444  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
165445  sqlite3_int64 id;      /* Node ID */
165446  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
165447  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
165448  u8 iCell;              /* Cell index within the node */
165449};
165450
165451/*
165452** The minimum number of cells allowed for a node is a third of the
165453** maximum. In Gutman's notation:
165454**
165455**     m = M/3
165456**
165457** If an R*-tree "Reinsert" operation is required, the same number of
165458** cells are removed from the overfull node and reinserted into the tree.
165459*/
165460#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
165461#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
165462#define RTREE_MAXCELLS 51
165463
165464/*
165465** The smallest possible node-size is (512-64)==448 bytes. And the largest
165466** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
165467** Therefore all non-root nodes must contain at least 3 entries. Since
165468** 2^40 is greater than 2^64, an r-tree structure always has a depth of
165469** 40 or less.
165470*/
165471#define RTREE_MAX_DEPTH 40
165472
165473
165474/*
165475** Number of entries in the cursor RtreeNode cache.  The first entry is
165476** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
165477** entries cache the RtreeNode for the first elements of the priority queue.
165478*/
165479#define RTREE_CACHE_SZ  5
165480
165481/*
165482** An rtree cursor object.
165483*/
165484struct RtreeCursor {
165485  sqlite3_vtab_cursor base;         /* Base class.  Must be first */
165486  u8 atEOF;                         /* True if at end of search */
165487  u8 bPoint;                        /* True if sPoint is valid */
165488  int iStrategy;                    /* Copy of idxNum search parameter */
165489  int nConstraint;                  /* Number of entries in aConstraint */
165490  RtreeConstraint *aConstraint;     /* Search constraints. */
165491  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
165492  int nPoint;                       /* Number of slots used in aPoint[] */
165493  int mxLevel;                      /* iLevel value for root of the tree */
165494  RtreeSearchPoint *aPoint;         /* Priority queue for search points */
165495  RtreeSearchPoint sPoint;          /* Cached next search point */
165496  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
165497  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
165498};
165499
165500/* Return the Rtree of a RtreeCursor */
165501#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
165502
165503/*
165504** A coordinate can be either a floating point number or a integer.  All
165505** coordinates within a single R-Tree are always of the same time.
165506*/
165507union RtreeCoord {
165508  RtreeValue f;      /* Floating point value */
165509  int i;             /* Integer value */
165510  u32 u;             /* Unsigned for byte-order conversions */
165511};
165512
165513/*
165514** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
165515** formatted as a RtreeDValue (double or int64). This macro assumes that local
165516** variable pRtree points to the Rtree structure associated with the
165517** RtreeCoord.
165518*/
165519#ifdef SQLITE_RTREE_INT_ONLY
165520# define DCOORD(coord) ((RtreeDValue)coord.i)
165521#else
165522# define DCOORD(coord) (                           \
165523    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
165524      ((double)coord.f) :                           \
165525      ((double)coord.i)                             \
165526  )
165527#endif
165528
165529/*
165530** A search constraint.
165531*/
165532struct RtreeConstraint {
165533  int iCoord;                     /* Index of constrained coordinate */
165534  int op;                         /* Constraining operation */
165535  union {
165536    RtreeDValue rValue;             /* Constraint value. */
165537    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
165538    int (*xQueryFunc)(sqlite3_rtree_query_info*);
165539  } u;
165540  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
165541};
165542
165543/* Possible values for RtreeConstraint.op */
165544#define RTREE_EQ    0x41  /* A */
165545#define RTREE_LE    0x42  /* B */
165546#define RTREE_LT    0x43  /* C */
165547#define RTREE_GE    0x44  /* D */
165548#define RTREE_GT    0x45  /* E */
165549#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
165550#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
165551
165552
165553/*
165554** An rtree structure node.
165555*/
165556struct RtreeNode {
165557  RtreeNode *pParent;         /* Parent node */
165558  i64 iNode;                  /* The node number */
165559  int nRef;                   /* Number of references to this node */
165560  int isDirty;                /* True if the node needs to be written to disk */
165561  u8 *zData;                  /* Content of the node, as should be on disk */
165562  RtreeNode *pNext;           /* Next node in this hash collision chain */
165563};
165564
165565/* Return the number of cells in a node  */
165566#define NCELL(pNode) readInt16(&(pNode)->zData[2])
165567
165568/*
165569** A single cell from a node, deserialized
165570*/
165571struct RtreeCell {
165572  i64 iRowid;                                 /* Node or entry ID */
165573  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
165574};
165575
165576
165577/*
165578** This object becomes the sqlite3_user_data() for the SQL functions
165579** that are created by sqlite3_rtree_geometry_callback() and
165580** sqlite3_rtree_query_callback() and which appear on the right of MATCH
165581** operators in order to constrain a search.
165582**
165583** xGeom and xQueryFunc are the callback functions.  Exactly one of
165584** xGeom and xQueryFunc fields is non-NULL, depending on whether the
165585** SQL function was created using sqlite3_rtree_geometry_callback() or
165586** sqlite3_rtree_query_callback().
165587**
165588** This object is deleted automatically by the destructor mechanism in
165589** sqlite3_create_function_v2().
165590*/
165591struct RtreeGeomCallback {
165592  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
165593  int (*xQueryFunc)(sqlite3_rtree_query_info*);
165594  void (*xDestructor)(void*);
165595  void *pContext;
165596};
165597
165598/*
165599** An instance of this structure (in the form of a BLOB) is returned by
165600** the SQL functions that sqlite3_rtree_geometry_callback() and
165601** sqlite3_rtree_query_callback() create, and is read as the right-hand
165602** operand to the MATCH operator of an R-Tree.
165603*/
165604struct RtreeMatchArg {
165605  u32 iSize;                  /* Size of this object */
165606  RtreeGeomCallback cb;       /* Info about the callback functions */
165607  int nParam;                 /* Number of parameters to the SQL function */
165608  sqlite3_value **apSqlParam; /* Original SQL parameter values */
165609  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
165610};
165611
165612#ifndef MAX
165613# define MAX(x,y) ((x) < (y) ? (y) : (x))
165614#endif
165615#ifndef MIN
165616# define MIN(x,y) ((x) > (y) ? (y) : (x))
165617#endif
165618
165619/* What version of GCC is being used.  0 means GCC is not being used .
165620** Note that the GCC_VERSION macro will also be set correctly when using
165621** clang, since clang works hard to be gcc compatible.  So the gcc
165622** optimizations will also work when compiling with clang.
165623*/
165624#ifndef GCC_VERSION
165625#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
165626# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
165627#else
165628# define GCC_VERSION 0
165629#endif
165630#endif
165631
165632/* The testcase() macro should already be defined in the amalgamation.  If
165633** it is not, make it a no-op.
165634*/
165635#ifndef SQLITE_AMALGAMATION
165636# define testcase(X)
165637#endif
165638
165639/*
165640** Macros to determine whether the machine is big or little endian,
165641** and whether or not that determination is run-time or compile-time.
165642**
165643** For best performance, an attempt is made to guess at the byte-order
165644** using C-preprocessor macros.  If that is unsuccessful, or if
165645** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
165646** at run-time.
165647*/
165648#ifndef SQLITE_BYTEORDER
165649#if defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
165650    defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
165651    defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
165652    defined(__arm__)
165653# define SQLITE_BYTEORDER    1234
165654#elif defined(sparc)    || defined(__ppc__)
165655# define SQLITE_BYTEORDER    4321
165656#else
165657# define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
165658#endif
165659#endif
165660
165661
165662/* What version of MSVC is being used.  0 means MSVC is not being used */
165663#ifndef MSVC_VERSION
165664#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
165665# define MSVC_VERSION _MSC_VER
165666#else
165667# define MSVC_VERSION 0
165668#endif
165669#endif
165670
165671/*
165672** Functions to deserialize a 16 bit integer, 32 bit real number and
165673** 64 bit integer. The deserialized value is returned.
165674*/
165675static int readInt16(u8 *p){
165676  return (p[0]<<8) + p[1];
165677}
165678static void readCoord(u8 *p, RtreeCoord *pCoord){
165679  assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
165680#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
165681  pCoord->u = _byteswap_ulong(*(u32*)p);
165682#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
165683  pCoord->u = __builtin_bswap32(*(u32*)p);
165684#elif SQLITE_BYTEORDER==4321
165685  pCoord->u = *(u32*)p;
165686#else
165687  pCoord->u = (
165688    (((u32)p[0]) << 24) +
165689    (((u32)p[1]) << 16) +
165690    (((u32)p[2]) <<  8) +
165691    (((u32)p[3]) <<  0)
165692  );
165693#endif
165694}
165695static i64 readInt64(u8 *p){
165696#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
165697  u64 x;
165698  memcpy(&x, p, 8);
165699  return (i64)_byteswap_uint64(x);
165700#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
165701  u64 x;
165702  memcpy(&x, p, 8);
165703  return (i64)__builtin_bswap64(x);
165704#elif SQLITE_BYTEORDER==4321
165705  i64 x;
165706  memcpy(&x, p, 8);
165707  return x;
165708#else
165709  return (i64)(
165710    (((u64)p[0]) << 56) +
165711    (((u64)p[1]) << 48) +
165712    (((u64)p[2]) << 40) +
165713    (((u64)p[3]) << 32) +
165714    (((u64)p[4]) << 24) +
165715    (((u64)p[5]) << 16) +
165716    (((u64)p[6]) <<  8) +
165717    (((u64)p[7]) <<  0)
165718  );
165719#endif
165720}
165721
165722/*
165723** Functions to serialize a 16 bit integer, 32 bit real number and
165724** 64 bit integer. The value returned is the number of bytes written
165725** to the argument buffer (always 2, 4 and 8 respectively).
165726*/
165727static void writeInt16(u8 *p, int i){
165728  p[0] = (i>> 8)&0xFF;
165729  p[1] = (i>> 0)&0xFF;
165730}
165731static int writeCoord(u8 *p, RtreeCoord *pCoord){
165732  u32 i;
165733  assert( ((((char*)p) - (char*)0)&3)==0 );  /* p is always 4-byte aligned */
165734  assert( sizeof(RtreeCoord)==4 );
165735  assert( sizeof(u32)==4 );
165736#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
165737  i = __builtin_bswap32(pCoord->u);
165738  memcpy(p, &i, 4);
165739#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
165740  i = _byteswap_ulong(pCoord->u);
165741  memcpy(p, &i, 4);
165742#elif SQLITE_BYTEORDER==4321
165743  i = pCoord->u;
165744  memcpy(p, &i, 4);
165745#else
165746  i = pCoord->u;
165747  p[0] = (i>>24)&0xFF;
165748  p[1] = (i>>16)&0xFF;
165749  p[2] = (i>> 8)&0xFF;
165750  p[3] = (i>> 0)&0xFF;
165751#endif
165752  return 4;
165753}
165754static int writeInt64(u8 *p, i64 i){
165755#if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
165756  i = (i64)__builtin_bswap64((u64)i);
165757  memcpy(p, &i, 8);
165758#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
165759  i = (i64)_byteswap_uint64((u64)i);
165760  memcpy(p, &i, 8);
165761#elif SQLITE_BYTEORDER==4321
165762  memcpy(p, &i, 8);
165763#else
165764  p[0] = (i>>56)&0xFF;
165765  p[1] = (i>>48)&0xFF;
165766  p[2] = (i>>40)&0xFF;
165767  p[3] = (i>>32)&0xFF;
165768  p[4] = (i>>24)&0xFF;
165769  p[5] = (i>>16)&0xFF;
165770  p[6] = (i>> 8)&0xFF;
165771  p[7] = (i>> 0)&0xFF;
165772#endif
165773  return 8;
165774}
165775
165776/*
165777** Increment the reference count of node p.
165778*/
165779static void nodeReference(RtreeNode *p){
165780  if( p ){
165781    p->nRef++;
165782  }
165783}
165784
165785/*
165786** Clear the content of node p (set all bytes to 0x00).
165787*/
165788static void nodeZero(Rtree *pRtree, RtreeNode *p){
165789  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
165790  p->isDirty = 1;
165791}
165792
165793/*
165794** Given a node number iNode, return the corresponding key to use
165795** in the Rtree.aHash table.
165796*/
165797static int nodeHash(i64 iNode){
165798  return iNode % HASHSIZE;
165799}
165800
165801/*
165802** Search the node hash table for node iNode. If found, return a pointer
165803** to it. Otherwise, return 0.
165804*/
165805static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
165806  RtreeNode *p;
165807  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
165808  return p;
165809}
165810
165811/*
165812** Add node pNode to the node hash table.
165813*/
165814static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
165815  int iHash;
165816  assert( pNode->pNext==0 );
165817  iHash = nodeHash(pNode->iNode);
165818  pNode->pNext = pRtree->aHash[iHash];
165819  pRtree->aHash[iHash] = pNode;
165820}
165821
165822/*
165823** Remove node pNode from the node hash table.
165824*/
165825static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
165826  RtreeNode **pp;
165827  if( pNode->iNode!=0 ){
165828    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
165829    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
165830    *pp = pNode->pNext;
165831    pNode->pNext = 0;
165832  }
165833}
165834
165835/*
165836** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
165837** indicating that node has not yet been assigned a node number. It is
165838** assigned a node number when nodeWrite() is called to write the
165839** node contents out to the database.
165840*/
165841static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
165842  RtreeNode *pNode;
165843  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
165844  if( pNode ){
165845    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
165846    pNode->zData = (u8 *)&pNode[1];
165847    pNode->nRef = 1;
165848    pNode->pParent = pParent;
165849    pNode->isDirty = 1;
165850    nodeReference(pParent);
165851  }
165852  return pNode;
165853}
165854
165855/*
165856** Clear the Rtree.pNodeBlob object
165857*/
165858static void nodeBlobReset(Rtree *pRtree){
165859  if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
165860    sqlite3_blob *pBlob = pRtree->pNodeBlob;
165861    pRtree->pNodeBlob = 0;
165862    sqlite3_blob_close(pBlob);
165863  }
165864}
165865
165866/*
165867** Obtain a reference to an r-tree node.
165868*/
165869static int nodeAcquire(
165870  Rtree *pRtree,             /* R-tree structure */
165871  i64 iNode,                 /* Node number to load */
165872  RtreeNode *pParent,        /* Either the parent node or NULL */
165873  RtreeNode **ppNode         /* OUT: Acquired node */
165874){
165875  int rc = SQLITE_OK;
165876  RtreeNode *pNode = 0;
165877
165878  /* Check if the requested node is already in the hash table. If so,
165879  ** increase its reference count and return it.
165880  */
165881  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
165882    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
165883    if( pParent && !pNode->pParent ){
165884      nodeReference(pParent);
165885      pNode->pParent = pParent;
165886    }
165887    pNode->nRef++;
165888    *ppNode = pNode;
165889    return SQLITE_OK;
165890  }
165891
165892  if( pRtree->pNodeBlob ){
165893    sqlite3_blob *pBlob = pRtree->pNodeBlob;
165894    pRtree->pNodeBlob = 0;
165895    rc = sqlite3_blob_reopen(pBlob, iNode);
165896    pRtree->pNodeBlob = pBlob;
165897    if( rc ){
165898      nodeBlobReset(pRtree);
165899      if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
165900    }
165901  }
165902  if( pRtree->pNodeBlob==0 ){
165903    char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
165904    if( zTab==0 ) return SQLITE_NOMEM;
165905    rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
165906                           &pRtree->pNodeBlob);
165907    sqlite3_free(zTab);
165908  }
165909  if( rc ){
165910    nodeBlobReset(pRtree);
165911    *ppNode = 0;
165912    /* If unable to open an sqlite3_blob on the desired row, that can only
165913    ** be because the shadow tables hold erroneous data. */
165914    if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
165915  }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
165916    pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
165917    if( !pNode ){
165918      rc = SQLITE_NOMEM;
165919    }else{
165920      pNode->pParent = pParent;
165921      pNode->zData = (u8 *)&pNode[1];
165922      pNode->nRef = 1;
165923      pNode->iNode = iNode;
165924      pNode->isDirty = 0;
165925      pNode->pNext = 0;
165926      rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
165927                             pRtree->iNodeSize, 0);
165928      nodeReference(pParent);
165929    }
165930  }
165931
165932  /* If the root node was just loaded, set pRtree->iDepth to the height
165933  ** of the r-tree structure. A height of zero means all data is stored on
165934  ** the root node. A height of one means the children of the root node
165935  ** are the leaves, and so on. If the depth as specified on the root node
165936  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
165937  */
165938  if( pNode && iNode==1 ){
165939    pRtree->iDepth = readInt16(pNode->zData);
165940    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
165941      rc = SQLITE_CORRUPT_VTAB;
165942    }
165943  }
165944
165945  /* If no error has occurred so far, check if the "number of entries"
165946  ** field on the node is too large. If so, set the return code to
165947  ** SQLITE_CORRUPT_VTAB.
165948  */
165949  if( pNode && rc==SQLITE_OK ){
165950    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
165951      rc = SQLITE_CORRUPT_VTAB;
165952    }
165953  }
165954
165955  if( rc==SQLITE_OK ){
165956    if( pNode!=0 ){
165957      nodeHashInsert(pRtree, pNode);
165958    }else{
165959      rc = SQLITE_CORRUPT_VTAB;
165960    }
165961    *ppNode = pNode;
165962  }else{
165963    sqlite3_free(pNode);
165964    *ppNode = 0;
165965  }
165966
165967  return rc;
165968}
165969
165970/*
165971** Overwrite cell iCell of node pNode with the contents of pCell.
165972*/
165973static void nodeOverwriteCell(
165974  Rtree *pRtree,             /* The overall R-Tree */
165975  RtreeNode *pNode,          /* The node into which the cell is to be written */
165976  RtreeCell *pCell,          /* The cell to write */
165977  int iCell                  /* Index into pNode into which pCell is written */
165978){
165979  int ii;
165980  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
165981  p += writeInt64(p, pCell->iRowid);
165982  for(ii=0; ii<pRtree->nDim2; ii++){
165983    p += writeCoord(p, &pCell->aCoord[ii]);
165984  }
165985  pNode->isDirty = 1;
165986}
165987
165988/*
165989** Remove the cell with index iCell from node pNode.
165990*/
165991static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
165992  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
165993  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
165994  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
165995  memmove(pDst, pSrc, nByte);
165996  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
165997  pNode->isDirty = 1;
165998}
165999
166000/*
166001** Insert the contents of cell pCell into node pNode. If the insert
166002** is successful, return SQLITE_OK.
166003**
166004** If there is not enough free space in pNode, return SQLITE_FULL.
166005*/
166006static int nodeInsertCell(
166007  Rtree *pRtree,                /* The overall R-Tree */
166008  RtreeNode *pNode,             /* Write new cell into this node */
166009  RtreeCell *pCell              /* The cell to be inserted */
166010){
166011  int nCell;                    /* Current number of cells in pNode */
166012  int nMaxCell;                 /* Maximum number of cells for pNode */
166013
166014  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
166015  nCell = NCELL(pNode);
166016
166017  assert( nCell<=nMaxCell );
166018  if( nCell<nMaxCell ){
166019    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
166020    writeInt16(&pNode->zData[2], nCell+1);
166021    pNode->isDirty = 1;
166022  }
166023
166024  return (nCell==nMaxCell);
166025}
166026
166027/*
166028** If the node is dirty, write it out to the database.
166029*/
166030static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
166031  int rc = SQLITE_OK;
166032  if( pNode->isDirty ){
166033    sqlite3_stmt *p = pRtree->pWriteNode;
166034    if( pNode->iNode ){
166035      sqlite3_bind_int64(p, 1, pNode->iNode);
166036    }else{
166037      sqlite3_bind_null(p, 1);
166038    }
166039    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
166040    sqlite3_step(p);
166041    pNode->isDirty = 0;
166042    rc = sqlite3_reset(p);
166043    if( pNode->iNode==0 && rc==SQLITE_OK ){
166044      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
166045      nodeHashInsert(pRtree, pNode);
166046    }
166047  }
166048  return rc;
166049}
166050
166051/*
166052** Release a reference to a node. If the node is dirty and the reference
166053** count drops to zero, the node data is written to the database.
166054*/
166055static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
166056  int rc = SQLITE_OK;
166057  if( pNode ){
166058    assert( pNode->nRef>0 );
166059    pNode->nRef--;
166060    if( pNode->nRef==0 ){
166061      if( pNode->iNode==1 ){
166062        pRtree->iDepth = -1;
166063      }
166064      if( pNode->pParent ){
166065        rc = nodeRelease(pRtree, pNode->pParent);
166066      }
166067      if( rc==SQLITE_OK ){
166068        rc = nodeWrite(pRtree, pNode);
166069      }
166070      nodeHashDelete(pRtree, pNode);
166071      sqlite3_free(pNode);
166072    }
166073  }
166074  return rc;
166075}
166076
166077/*
166078** Return the 64-bit integer value associated with cell iCell of
166079** node pNode. If pNode is a leaf node, this is a rowid. If it is
166080** an internal node, then the 64-bit integer is a child page number.
166081*/
166082static i64 nodeGetRowid(
166083  Rtree *pRtree,       /* The overall R-Tree */
166084  RtreeNode *pNode,    /* The node from which to extract the ID */
166085  int iCell            /* The cell index from which to extract the ID */
166086){
166087  assert( iCell<NCELL(pNode) );
166088  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
166089}
166090
166091/*
166092** Return coordinate iCoord from cell iCell in node pNode.
166093*/
166094static void nodeGetCoord(
166095  Rtree *pRtree,               /* The overall R-Tree */
166096  RtreeNode *pNode,            /* The node from which to extract a coordinate */
166097  int iCell,                   /* The index of the cell within the node */
166098  int iCoord,                  /* Which coordinate to extract */
166099  RtreeCoord *pCoord           /* OUT: Space to write result to */
166100){
166101  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
166102}
166103
166104/*
166105** Deserialize cell iCell of node pNode. Populate the structure pointed
166106** to by pCell with the results.
166107*/
166108static void nodeGetCell(
166109  Rtree *pRtree,               /* The overall R-Tree */
166110  RtreeNode *pNode,            /* The node containing the cell to be read */
166111  int iCell,                   /* Index of the cell within the node */
166112  RtreeCell *pCell             /* OUT: Write the cell contents here */
166113){
166114  u8 *pData;
166115  RtreeCoord *pCoord;
166116  int ii = 0;
166117  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
166118  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
166119  pCoord = pCell->aCoord;
166120  do{
166121    readCoord(pData, &pCoord[ii]);
166122    readCoord(pData+4, &pCoord[ii+1]);
166123    pData += 8;
166124    ii += 2;
166125  }while( ii<pRtree->nDim2 );
166126}
166127
166128
166129/* Forward declaration for the function that does the work of
166130** the virtual table module xCreate() and xConnect() methods.
166131*/
166132static int rtreeInit(
166133  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
166134);
166135
166136/*
166137** Rtree virtual table module xCreate method.
166138*/
166139static int rtreeCreate(
166140  sqlite3 *db,
166141  void *pAux,
166142  int argc, const char *const*argv,
166143  sqlite3_vtab **ppVtab,
166144  char **pzErr
166145){
166146  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
166147}
166148
166149/*
166150** Rtree virtual table module xConnect method.
166151*/
166152static int rtreeConnect(
166153  sqlite3 *db,
166154  void *pAux,
166155  int argc, const char *const*argv,
166156  sqlite3_vtab **ppVtab,
166157  char **pzErr
166158){
166159  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
166160}
166161
166162/*
166163** Increment the r-tree reference count.
166164*/
166165static void rtreeReference(Rtree *pRtree){
166166  pRtree->nBusy++;
166167}
166168
166169/*
166170** Decrement the r-tree reference count. When the reference count reaches
166171** zero the structure is deleted.
166172*/
166173static void rtreeRelease(Rtree *pRtree){
166174  pRtree->nBusy--;
166175  if( pRtree->nBusy==0 ){
166176    pRtree->inWrTrans = 0;
166177    pRtree->nCursor = 0;
166178    nodeBlobReset(pRtree);
166179    sqlite3_finalize(pRtree->pWriteNode);
166180    sqlite3_finalize(pRtree->pDeleteNode);
166181    sqlite3_finalize(pRtree->pReadRowid);
166182    sqlite3_finalize(pRtree->pWriteRowid);
166183    sqlite3_finalize(pRtree->pDeleteRowid);
166184    sqlite3_finalize(pRtree->pReadParent);
166185    sqlite3_finalize(pRtree->pWriteParent);
166186    sqlite3_finalize(pRtree->pDeleteParent);
166187    sqlite3_free(pRtree);
166188  }
166189}
166190
166191/*
166192** Rtree virtual table module xDisconnect method.
166193*/
166194static int rtreeDisconnect(sqlite3_vtab *pVtab){
166195  rtreeRelease((Rtree *)pVtab);
166196  return SQLITE_OK;
166197}
166198
166199/*
166200** Rtree virtual table module xDestroy method.
166201*/
166202static int rtreeDestroy(sqlite3_vtab *pVtab){
166203  Rtree *pRtree = (Rtree *)pVtab;
166204  int rc;
166205  char *zCreate = sqlite3_mprintf(
166206    "DROP TABLE '%q'.'%q_node';"
166207    "DROP TABLE '%q'.'%q_rowid';"
166208    "DROP TABLE '%q'.'%q_parent';",
166209    pRtree->zDb, pRtree->zName,
166210    pRtree->zDb, pRtree->zName,
166211    pRtree->zDb, pRtree->zName
166212  );
166213  if( !zCreate ){
166214    rc = SQLITE_NOMEM;
166215  }else{
166216    nodeBlobReset(pRtree);
166217    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
166218    sqlite3_free(zCreate);
166219  }
166220  if( rc==SQLITE_OK ){
166221    rtreeRelease(pRtree);
166222  }
166223
166224  return rc;
166225}
166226
166227/*
166228** Rtree virtual table module xOpen method.
166229*/
166230static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
166231  int rc = SQLITE_NOMEM;
166232  Rtree *pRtree = (Rtree *)pVTab;
166233  RtreeCursor *pCsr;
166234
166235  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
166236  if( pCsr ){
166237    memset(pCsr, 0, sizeof(RtreeCursor));
166238    pCsr->base.pVtab = pVTab;
166239    rc = SQLITE_OK;
166240    pRtree->nCursor++;
166241  }
166242  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
166243
166244  return rc;
166245}
166246
166247
166248/*
166249** Free the RtreeCursor.aConstraint[] array and its contents.
166250*/
166251static void freeCursorConstraints(RtreeCursor *pCsr){
166252  if( pCsr->aConstraint ){
166253    int i;                        /* Used to iterate through constraint array */
166254    for(i=0; i<pCsr->nConstraint; i++){
166255      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
166256      if( pInfo ){
166257        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
166258        sqlite3_free(pInfo);
166259      }
166260    }
166261    sqlite3_free(pCsr->aConstraint);
166262    pCsr->aConstraint = 0;
166263  }
166264}
166265
166266/*
166267** Rtree virtual table module xClose method.
166268*/
166269static int rtreeClose(sqlite3_vtab_cursor *cur){
166270  Rtree *pRtree = (Rtree *)(cur->pVtab);
166271  int ii;
166272  RtreeCursor *pCsr = (RtreeCursor *)cur;
166273  assert( pRtree->nCursor>0 );
166274  freeCursorConstraints(pCsr);
166275  sqlite3_free(pCsr->aPoint);
166276  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
166277  sqlite3_free(pCsr);
166278  pRtree->nCursor--;
166279  nodeBlobReset(pRtree);
166280  return SQLITE_OK;
166281}
166282
166283/*
166284** Rtree virtual table module xEof method.
166285**
166286** Return non-zero if the cursor does not currently point to a valid
166287** record (i.e if the scan has finished), or zero otherwise.
166288*/
166289static int rtreeEof(sqlite3_vtab_cursor *cur){
166290  RtreeCursor *pCsr = (RtreeCursor *)cur;
166291  return pCsr->atEOF;
166292}
166293
166294/*
166295** Convert raw bits from the on-disk RTree record into a coordinate value.
166296** The on-disk format is big-endian and needs to be converted for little-
166297** endian platforms.  The on-disk record stores integer coordinates if
166298** eInt is true and it stores 32-bit floating point records if eInt is
166299** false.  a[] is the four bytes of the on-disk record to be decoded.
166300** Store the results in "r".
166301**
166302** There are five versions of this macro.  The last one is generic.  The
166303** other four are various architectures-specific optimizations.
166304*/
166305#if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
166306#define RTREE_DECODE_COORD(eInt, a, r) {                        \
166307    RtreeCoord c;    /* Coordinate decoded */                   \
166308    c.u = _byteswap_ulong(*(u32*)a);                            \
166309    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166310}
166311#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
166312#define RTREE_DECODE_COORD(eInt, a, r) {                        \
166313    RtreeCoord c;    /* Coordinate decoded */                   \
166314    c.u = __builtin_bswap32(*(u32*)a);                          \
166315    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166316}
166317#elif SQLITE_BYTEORDER==1234
166318#define RTREE_DECODE_COORD(eInt, a, r) {                        \
166319    RtreeCoord c;    /* Coordinate decoded */                   \
166320    memcpy(&c.u,a,4);                                           \
166321    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
166322          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
166323    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166324}
166325#elif SQLITE_BYTEORDER==4321
166326#define RTREE_DECODE_COORD(eInt, a, r) {                        \
166327    RtreeCoord c;    /* Coordinate decoded */                   \
166328    memcpy(&c.u,a,4);                                           \
166329    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166330}
166331#else
166332#define RTREE_DECODE_COORD(eInt, a, r) {                        \
166333    RtreeCoord c;    /* Coordinate decoded */                   \
166334    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
166335           +((u32)a[2]<<8) + a[3];                              \
166336    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
166337}
166338#endif
166339
166340/*
166341** Check the RTree node or entry given by pCellData and p against the MATCH
166342** constraint pConstraint.
166343*/
166344static int rtreeCallbackConstraint(
166345  RtreeConstraint *pConstraint,  /* The constraint to test */
166346  int eInt,                      /* True if RTree holding integer coordinates */
166347  u8 *pCellData,                 /* Raw cell content */
166348  RtreeSearchPoint *pSearch,     /* Container of this cell */
166349  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
166350  int *peWithin                  /* OUT: visibility of the cell */
166351){
166352  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
166353  int nCoord = pInfo->nCoord;                           /* No. of coordinates */
166354  int rc;                                             /* Callback return code */
166355  RtreeCoord c;                                       /* Translator union */
166356  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
166357
166358  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
166359  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
166360
166361  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
166362    pInfo->iRowid = readInt64(pCellData);
166363  }
166364  pCellData += 8;
166365#ifndef SQLITE_RTREE_INT_ONLY
166366  if( eInt==0 ){
166367    switch( nCoord ){
166368      case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.f;
166369                readCoord(pCellData+32, &c); aCoord[8] = c.f;
166370      case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.f;
166371                readCoord(pCellData+24, &c); aCoord[6] = c.f;
166372      case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.f;
166373                readCoord(pCellData+16, &c); aCoord[4] = c.f;
166374      case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.f;
166375                readCoord(pCellData+8,  &c); aCoord[2] = c.f;
166376      default:  readCoord(pCellData+4,  &c); aCoord[1] = c.f;
166377                readCoord(pCellData,    &c); aCoord[0] = c.f;
166378    }
166379  }else
166380#endif
166381  {
166382    switch( nCoord ){
166383      case 10:  readCoord(pCellData+36, &c); aCoord[9] = c.i;
166384                readCoord(pCellData+32, &c); aCoord[8] = c.i;
166385      case 8:   readCoord(pCellData+28, &c); aCoord[7] = c.i;
166386                readCoord(pCellData+24, &c); aCoord[6] = c.i;
166387      case 6:   readCoord(pCellData+20, &c); aCoord[5] = c.i;
166388                readCoord(pCellData+16, &c); aCoord[4] = c.i;
166389      case 4:   readCoord(pCellData+12, &c); aCoord[3] = c.i;
166390                readCoord(pCellData+8,  &c); aCoord[2] = c.i;
166391      default:  readCoord(pCellData+4,  &c); aCoord[1] = c.i;
166392                readCoord(pCellData,    &c); aCoord[0] = c.i;
166393    }
166394  }
166395  if( pConstraint->op==RTREE_MATCH ){
166396    int eWithin = 0;
166397    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
166398                              nCoord, aCoord, &eWithin);
166399    if( eWithin==0 ) *peWithin = NOT_WITHIN;
166400    *prScore = RTREE_ZERO;
166401  }else{
166402    pInfo->aCoord = aCoord;
166403    pInfo->iLevel = pSearch->iLevel - 1;
166404    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
166405    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
166406    rc = pConstraint->u.xQueryFunc(pInfo);
166407    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
166408    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
166409      *prScore = pInfo->rScore;
166410    }
166411  }
166412  return rc;
166413}
166414
166415/*
166416** Check the internal RTree node given by pCellData against constraint p.
166417** If this constraint cannot be satisfied by any child within the node,
166418** set *peWithin to NOT_WITHIN.
166419*/
166420static void rtreeNonleafConstraint(
166421  RtreeConstraint *p,        /* The constraint to test */
166422  int eInt,                  /* True if RTree holds integer coordinates */
166423  u8 *pCellData,             /* Raw cell content as appears on disk */
166424  int *peWithin              /* Adjust downward, as appropriate */
166425){
166426  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
166427
166428  /* p->iCoord might point to either a lower or upper bound coordinate
166429  ** in a coordinate pair.  But make pCellData point to the lower bound.
166430  */
166431  pCellData += 8 + 4*(p->iCoord&0xfe);
166432
166433  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
166434      || p->op==RTREE_GT || p->op==RTREE_EQ );
166435  assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
166436  switch( p->op ){
166437    case RTREE_LE:
166438    case RTREE_LT:
166439    case RTREE_EQ:
166440      RTREE_DECODE_COORD(eInt, pCellData, val);
166441      /* val now holds the lower bound of the coordinate pair */
166442      if( p->u.rValue>=val ) return;
166443      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
166444      /* Fall through for the RTREE_EQ case */
166445
166446    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
166447      pCellData += 4;
166448      RTREE_DECODE_COORD(eInt, pCellData, val);
166449      /* val now holds the upper bound of the coordinate pair */
166450      if( p->u.rValue<=val ) return;
166451  }
166452  *peWithin = NOT_WITHIN;
166453}
166454
166455/*
166456** Check the leaf RTree cell given by pCellData against constraint p.
166457** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
166458** If the constraint is satisfied, leave *peWithin unchanged.
166459**
166460** The constraint is of the form:  xN op $val
166461**
166462** The op is given by p->op.  The xN is p->iCoord-th coordinate in
166463** pCellData.  $val is given by p->u.rValue.
166464*/
166465static void rtreeLeafConstraint(
166466  RtreeConstraint *p,        /* The constraint to test */
166467  int eInt,                  /* True if RTree holds integer coordinates */
166468  u8 *pCellData,             /* Raw cell content as appears on disk */
166469  int *peWithin              /* Adjust downward, as appropriate */
166470){
166471  RtreeDValue xN;      /* Coordinate value converted to a double */
166472
166473  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
166474      || p->op==RTREE_GT || p->op==RTREE_EQ );
166475  pCellData += 8 + p->iCoord*4;
166476  assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
166477  RTREE_DECODE_COORD(eInt, pCellData, xN);
166478  switch( p->op ){
166479    case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
166480    case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
166481    case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
166482    case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
166483    default:       if( xN == p->u.rValue ) return;  break;
166484  }
166485  *peWithin = NOT_WITHIN;
166486}
166487
166488/*
166489** One of the cells in node pNode is guaranteed to have a 64-bit
166490** integer value equal to iRowid. Return the index of this cell.
166491*/
166492static int nodeRowidIndex(
166493  Rtree *pRtree,
166494  RtreeNode *pNode,
166495  i64 iRowid,
166496  int *piIndex
166497){
166498  int ii;
166499  int nCell = NCELL(pNode);
166500  assert( nCell<200 );
166501  for(ii=0; ii<nCell; ii++){
166502    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
166503      *piIndex = ii;
166504      return SQLITE_OK;
166505    }
166506  }
166507  return SQLITE_CORRUPT_VTAB;
166508}
166509
166510/*
166511** Return the index of the cell containing a pointer to node pNode
166512** in its parent. If pNode is the root node, return -1.
166513*/
166514static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
166515  RtreeNode *pParent = pNode->pParent;
166516  if( pParent ){
166517    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
166518  }
166519  *piIndex = -1;
166520  return SQLITE_OK;
166521}
166522
166523/*
166524** Compare two search points.  Return negative, zero, or positive if the first
166525** is less than, equal to, or greater than the second.
166526**
166527** The rScore is the primary key.  Smaller rScore values come first.
166528** If the rScore is a tie, then use iLevel as the tie breaker with smaller
166529** iLevel values coming first.  In this way, if rScore is the same for all
166530** SearchPoints, then iLevel becomes the deciding factor and the result
166531** is a depth-first search, which is the desired default behavior.
166532*/
166533static int rtreeSearchPointCompare(
166534  const RtreeSearchPoint *pA,
166535  const RtreeSearchPoint *pB
166536){
166537  if( pA->rScore<pB->rScore ) return -1;
166538  if( pA->rScore>pB->rScore ) return +1;
166539  if( pA->iLevel<pB->iLevel ) return -1;
166540  if( pA->iLevel>pB->iLevel ) return +1;
166541  return 0;
166542}
166543
166544/*
166545** Interchange two search points in a cursor.
166546*/
166547static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
166548  RtreeSearchPoint t = p->aPoint[i];
166549  assert( i<j );
166550  p->aPoint[i] = p->aPoint[j];
166551  p->aPoint[j] = t;
166552  i++; j++;
166553  if( i<RTREE_CACHE_SZ ){
166554    if( j>=RTREE_CACHE_SZ ){
166555      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
166556      p->aNode[i] = 0;
166557    }else{
166558      RtreeNode *pTemp = p->aNode[i];
166559      p->aNode[i] = p->aNode[j];
166560      p->aNode[j] = pTemp;
166561    }
166562  }
166563}
166564
166565/*
166566** Return the search point with the lowest current score.
166567*/
166568static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
166569  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
166570}
166571
166572/*
166573** Get the RtreeNode for the search point with the lowest score.
166574*/
166575static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
166576  sqlite3_int64 id;
166577  int ii = 1 - pCur->bPoint;
166578  assert( ii==0 || ii==1 );
166579  assert( pCur->bPoint || pCur->nPoint );
166580  if( pCur->aNode[ii]==0 ){
166581    assert( pRC!=0 );
166582    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
166583    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
166584  }
166585  return pCur->aNode[ii];
166586}
166587
166588/*
166589** Push a new element onto the priority queue
166590*/
166591static RtreeSearchPoint *rtreeEnqueue(
166592  RtreeCursor *pCur,    /* The cursor */
166593  RtreeDValue rScore,   /* Score for the new search point */
166594  u8 iLevel             /* Level for the new search point */
166595){
166596  int i, j;
166597  RtreeSearchPoint *pNew;
166598  if( pCur->nPoint>=pCur->nPointAlloc ){
166599    int nNew = pCur->nPointAlloc*2 + 8;
166600    pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
166601    if( pNew==0 ) return 0;
166602    pCur->aPoint = pNew;
166603    pCur->nPointAlloc = nNew;
166604  }
166605  i = pCur->nPoint++;
166606  pNew = pCur->aPoint + i;
166607  pNew->rScore = rScore;
166608  pNew->iLevel = iLevel;
166609  assert( iLevel<=RTREE_MAX_DEPTH );
166610  while( i>0 ){
166611    RtreeSearchPoint *pParent;
166612    j = (i-1)/2;
166613    pParent = pCur->aPoint + j;
166614    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
166615    rtreeSearchPointSwap(pCur, j, i);
166616    i = j;
166617    pNew = pParent;
166618  }
166619  return pNew;
166620}
166621
166622/*
166623** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
166624** NULL if malloc fails.
166625*/
166626static RtreeSearchPoint *rtreeSearchPointNew(
166627  RtreeCursor *pCur,    /* The cursor */
166628  RtreeDValue rScore,   /* Score for the new search point */
166629  u8 iLevel             /* Level for the new search point */
166630){
166631  RtreeSearchPoint *pNew, *pFirst;
166632  pFirst = rtreeSearchPointFirst(pCur);
166633  pCur->anQueue[iLevel]++;
166634  if( pFirst==0
166635   || pFirst->rScore>rScore
166636   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
166637  ){
166638    if( pCur->bPoint ){
166639      int ii;
166640      pNew = rtreeEnqueue(pCur, rScore, iLevel);
166641      if( pNew==0 ) return 0;
166642      ii = (int)(pNew - pCur->aPoint) + 1;
166643      if( ii<RTREE_CACHE_SZ ){
166644        assert( pCur->aNode[ii]==0 );
166645        pCur->aNode[ii] = pCur->aNode[0];
166646       }else{
166647        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
166648      }
166649      pCur->aNode[0] = 0;
166650      *pNew = pCur->sPoint;
166651    }
166652    pCur->sPoint.rScore = rScore;
166653    pCur->sPoint.iLevel = iLevel;
166654    pCur->bPoint = 1;
166655    return &pCur->sPoint;
166656  }else{
166657    return rtreeEnqueue(pCur, rScore, iLevel);
166658  }
166659}
166660
166661#if 0
166662/* Tracing routines for the RtreeSearchPoint queue */
166663static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
166664  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
166665  printf(" %d.%05lld.%02d %g %d",
166666    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
166667  );
166668  idx++;
166669  if( idx<RTREE_CACHE_SZ ){
166670    printf(" %p\n", pCur->aNode[idx]);
166671  }else{
166672    printf("\n");
166673  }
166674}
166675static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
166676  int ii;
166677  printf("=== %9s ", zPrefix);
166678  if( pCur->bPoint ){
166679    tracePoint(&pCur->sPoint, -1, pCur);
166680  }
166681  for(ii=0; ii<pCur->nPoint; ii++){
166682    if( ii>0 || pCur->bPoint ) printf("              ");
166683    tracePoint(&pCur->aPoint[ii], ii, pCur);
166684  }
166685}
166686# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
166687#else
166688# define RTREE_QUEUE_TRACE(A,B)   /* no-op */
166689#endif
166690
166691/* Remove the search point with the lowest current score.
166692*/
166693static void rtreeSearchPointPop(RtreeCursor *p){
166694  int i, j, k, n;
166695  i = 1 - p->bPoint;
166696  assert( i==0 || i==1 );
166697  if( p->aNode[i] ){
166698    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
166699    p->aNode[i] = 0;
166700  }
166701  if( p->bPoint ){
166702    p->anQueue[p->sPoint.iLevel]--;
166703    p->bPoint = 0;
166704  }else if( p->nPoint ){
166705    p->anQueue[p->aPoint[0].iLevel]--;
166706    n = --p->nPoint;
166707    p->aPoint[0] = p->aPoint[n];
166708    if( n<RTREE_CACHE_SZ-1 ){
166709      p->aNode[1] = p->aNode[n+1];
166710      p->aNode[n+1] = 0;
166711    }
166712    i = 0;
166713    while( (j = i*2+1)<n ){
166714      k = j+1;
166715      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
166716        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
166717          rtreeSearchPointSwap(p, i, k);
166718          i = k;
166719        }else{
166720          break;
166721        }
166722      }else{
166723        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
166724          rtreeSearchPointSwap(p, i, j);
166725          i = j;
166726        }else{
166727          break;
166728        }
166729      }
166730    }
166731  }
166732}
166733
166734
166735/*
166736** Continue the search on cursor pCur until the front of the queue
166737** contains an entry suitable for returning as a result-set row,
166738** or until the RtreeSearchPoint queue is empty, indicating that the
166739** query has completed.
166740*/
166741static int rtreeStepToLeaf(RtreeCursor *pCur){
166742  RtreeSearchPoint *p;
166743  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
166744  RtreeNode *pNode;
166745  int eWithin;
166746  int rc = SQLITE_OK;
166747  int nCell;
166748  int nConstraint = pCur->nConstraint;
166749  int ii;
166750  int eInt;
166751  RtreeSearchPoint x;
166752
166753  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
166754  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
166755    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
166756    if( rc ) return rc;
166757    nCell = NCELL(pNode);
166758    assert( nCell<200 );
166759    while( p->iCell<nCell ){
166760      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
166761      u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
166762      eWithin = FULLY_WITHIN;
166763      for(ii=0; ii<nConstraint; ii++){
166764        RtreeConstraint *pConstraint = pCur->aConstraint + ii;
166765        if( pConstraint->op>=RTREE_MATCH ){
166766          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
166767                                       &rScore, &eWithin);
166768          if( rc ) return rc;
166769        }else if( p->iLevel==1 ){
166770          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
166771        }else{
166772          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
166773        }
166774        if( eWithin==NOT_WITHIN ) break;
166775      }
166776      p->iCell++;
166777      if( eWithin==NOT_WITHIN ) continue;
166778      x.iLevel = p->iLevel - 1;
166779      if( x.iLevel ){
166780        x.id = readInt64(pCellData);
166781        x.iCell = 0;
166782      }else{
166783        x.id = p->id;
166784        x.iCell = p->iCell - 1;
166785      }
166786      if( p->iCell>=nCell ){
166787        RTREE_QUEUE_TRACE(pCur, "POP-S:");
166788        rtreeSearchPointPop(pCur);
166789      }
166790      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
166791      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
166792      if( p==0 ) return SQLITE_NOMEM;
166793      p->eWithin = (u8)eWithin;
166794      p->id = x.id;
166795      p->iCell = x.iCell;
166796      RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
166797      break;
166798    }
166799    if( p->iCell>=nCell ){
166800      RTREE_QUEUE_TRACE(pCur, "POP-Se:");
166801      rtreeSearchPointPop(pCur);
166802    }
166803  }
166804  pCur->atEOF = p==0;
166805  return SQLITE_OK;
166806}
166807
166808/*
166809** Rtree virtual table module xNext method.
166810*/
166811static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
166812  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
166813  int rc = SQLITE_OK;
166814
166815  /* Move to the next entry that matches the configured constraints. */
166816  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
166817  rtreeSearchPointPop(pCsr);
166818  rc = rtreeStepToLeaf(pCsr);
166819  return rc;
166820}
166821
166822/*
166823** Rtree virtual table module xRowid method.
166824*/
166825static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
166826  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
166827  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
166828  int rc = SQLITE_OK;
166829  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
166830  if( rc==SQLITE_OK && p ){
166831    *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
166832  }
166833  return rc;
166834}
166835
166836/*
166837** Rtree virtual table module xColumn method.
166838*/
166839static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
166840  Rtree *pRtree = (Rtree *)cur->pVtab;
166841  RtreeCursor *pCsr = (RtreeCursor *)cur;
166842  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
166843  RtreeCoord c;
166844  int rc = SQLITE_OK;
166845  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
166846
166847  if( rc ) return rc;
166848  if( p==0 ) return SQLITE_OK;
166849  if( i==0 ){
166850    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
166851  }else{
166852    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
166853#ifndef SQLITE_RTREE_INT_ONLY
166854    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
166855      sqlite3_result_double(ctx, c.f);
166856    }else
166857#endif
166858    {
166859      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
166860      sqlite3_result_int(ctx, c.i);
166861    }
166862  }
166863  return SQLITE_OK;
166864}
166865
166866/*
166867** Use nodeAcquire() to obtain the leaf node containing the record with
166868** rowid iRowid. If successful, set *ppLeaf to point to the node and
166869** return SQLITE_OK. If there is no such record in the table, set
166870** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
166871** to zero and return an SQLite error code.
166872*/
166873static int findLeafNode(
166874  Rtree *pRtree,              /* RTree to search */
166875  i64 iRowid,                 /* The rowid searching for */
166876  RtreeNode **ppLeaf,         /* Write the node here */
166877  sqlite3_int64 *piNode       /* Write the node-id here */
166878){
166879  int rc;
166880  *ppLeaf = 0;
166881  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
166882  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
166883    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
166884    if( piNode ) *piNode = iNode;
166885    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
166886    sqlite3_reset(pRtree->pReadRowid);
166887  }else{
166888    rc = sqlite3_reset(pRtree->pReadRowid);
166889  }
166890  return rc;
166891}
166892
166893/*
166894** This function is called to configure the RtreeConstraint object passed
166895** as the second argument for a MATCH constraint. The value passed as the
166896** first argument to this function is the right-hand operand to the MATCH
166897** operator.
166898*/
166899static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
166900  RtreeMatchArg *pBlob, *pSrc;       /* BLOB returned by geometry function */
166901  sqlite3_rtree_query_info *pInfo;   /* Callback information */
166902
166903  pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
166904  if( pSrc==0 ) return SQLITE_ERROR;
166905  pInfo = (sqlite3_rtree_query_info*)
166906                sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
166907  if( !pInfo ) return SQLITE_NOMEM;
166908  memset(pInfo, 0, sizeof(*pInfo));
166909  pBlob = (RtreeMatchArg*)&pInfo[1];
166910  memcpy(pBlob, pSrc, pSrc->iSize);
166911  pInfo->pContext = pBlob->cb.pContext;
166912  pInfo->nParam = pBlob->nParam;
166913  pInfo->aParam = pBlob->aParam;
166914  pInfo->apSqlParam = pBlob->apSqlParam;
166915
166916  if( pBlob->cb.xGeom ){
166917    pCons->u.xGeom = pBlob->cb.xGeom;
166918  }else{
166919    pCons->op = RTREE_QUERY;
166920    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
166921  }
166922  pCons->pInfo = pInfo;
166923  return SQLITE_OK;
166924}
166925
166926/*
166927** Rtree virtual table module xFilter method.
166928*/
166929static int rtreeFilter(
166930  sqlite3_vtab_cursor *pVtabCursor,
166931  int idxNum, const char *idxStr,
166932  int argc, sqlite3_value **argv
166933){
166934  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
166935  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
166936  RtreeNode *pRoot = 0;
166937  int ii;
166938  int rc = SQLITE_OK;
166939  int iCell = 0;
166940
166941  rtreeReference(pRtree);
166942
166943  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
166944  freeCursorConstraints(pCsr);
166945  sqlite3_free(pCsr->aPoint);
166946  memset(pCsr, 0, sizeof(RtreeCursor));
166947  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
166948
166949  pCsr->iStrategy = idxNum;
166950  if( idxNum==1 ){
166951    /* Special case - lookup by rowid. */
166952    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
166953    RtreeSearchPoint *p;     /* Search point for the leaf */
166954    i64 iRowid = sqlite3_value_int64(argv[0]);
166955    i64 iNode = 0;
166956    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
166957    if( rc==SQLITE_OK && pLeaf!=0 ){
166958      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
166959      assert( p!=0 );  /* Always returns pCsr->sPoint */
166960      pCsr->aNode[0] = pLeaf;
166961      p->id = iNode;
166962      p->eWithin = PARTLY_WITHIN;
166963      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
166964      p->iCell = (u8)iCell;
166965      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
166966    }else{
166967      pCsr->atEOF = 1;
166968    }
166969  }else{
166970    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
166971    ** with the configured constraints.
166972    */
166973    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
166974    if( rc==SQLITE_OK && argc>0 ){
166975      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
166976      pCsr->nConstraint = argc;
166977      if( !pCsr->aConstraint ){
166978        rc = SQLITE_NOMEM;
166979      }else{
166980        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
166981        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
166982        assert( (idxStr==0 && argc==0)
166983                || (idxStr && (int)strlen(idxStr)==argc*2) );
166984        for(ii=0; ii<argc; ii++){
166985          RtreeConstraint *p = &pCsr->aConstraint[ii];
166986          p->op = idxStr[ii*2];
166987          p->iCoord = idxStr[ii*2+1]-'0';
166988          if( p->op>=RTREE_MATCH ){
166989            /* A MATCH operator. The right-hand-side must be a blob that
166990            ** can be cast into an RtreeMatchArg object. One created using
166991            ** an sqlite3_rtree_geometry_callback() SQL user function.
166992            */
166993            rc = deserializeGeometry(argv[ii], p);
166994            if( rc!=SQLITE_OK ){
166995              break;
166996            }
166997            p->pInfo->nCoord = pRtree->nDim2;
166998            p->pInfo->anQueue = pCsr->anQueue;
166999            p->pInfo->mxLevel = pRtree->iDepth + 1;
167000          }else{
167001#ifdef SQLITE_RTREE_INT_ONLY
167002            p->u.rValue = sqlite3_value_int64(argv[ii]);
167003#else
167004            p->u.rValue = sqlite3_value_double(argv[ii]);
167005#endif
167006          }
167007        }
167008      }
167009    }
167010    if( rc==SQLITE_OK ){
167011      RtreeSearchPoint *pNew;
167012      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
167013      if( pNew==0 ) return SQLITE_NOMEM;
167014      pNew->id = 1;
167015      pNew->iCell = 0;
167016      pNew->eWithin = PARTLY_WITHIN;
167017      assert( pCsr->bPoint==1 );
167018      pCsr->aNode[0] = pRoot;
167019      pRoot = 0;
167020      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
167021      rc = rtreeStepToLeaf(pCsr);
167022    }
167023  }
167024
167025  nodeRelease(pRtree, pRoot);
167026  rtreeRelease(pRtree);
167027  return rc;
167028}
167029
167030/*
167031** Rtree virtual table module xBestIndex method. There are three
167032** table scan strategies to choose from (in order from most to
167033** least desirable):
167034**
167035**   idxNum     idxStr        Strategy
167036**   ------------------------------------------------
167037**     1        Unused        Direct lookup by rowid.
167038**     2        See below     R-tree query or full-table scan.
167039**   ------------------------------------------------
167040**
167041** If strategy 1 is used, then idxStr is not meaningful. If strategy
167042** 2 is used, idxStr is formatted to contain 2 bytes for each
167043** constraint used. The first two bytes of idxStr correspond to
167044** the constraint in sqlite3_index_info.aConstraintUsage[] with
167045** (argvIndex==1) etc.
167046**
167047** The first of each pair of bytes in idxStr identifies the constraint
167048** operator as follows:
167049**
167050**   Operator    Byte Value
167051**   ----------------------
167052**      =        0x41 ('A')
167053**     <=        0x42 ('B')
167054**      <        0x43 ('C')
167055**     >=        0x44 ('D')
167056**      >        0x45 ('E')
167057**   MATCH       0x46 ('F')
167058**   ----------------------
167059**
167060** The second of each pair of bytes identifies the coordinate column
167061** to which the constraint applies. The leftmost coordinate column
167062** is 'a', the second from the left 'b' etc.
167063*/
167064static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
167065  Rtree *pRtree = (Rtree*)tab;
167066  int rc = SQLITE_OK;
167067  int ii;
167068  int bMatch = 0;                 /* True if there exists a MATCH constraint */
167069  i64 nRow;                       /* Estimated rows returned by this scan */
167070
167071  int iIdx = 0;
167072  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
167073  memset(zIdxStr, 0, sizeof(zIdxStr));
167074
167075  /* Check if there exists a MATCH constraint - even an unusable one. If there
167076  ** is, do not consider the lookup-by-rowid plan as using such a plan would
167077  ** require the VDBE to evaluate the MATCH constraint, which is not currently
167078  ** possible. */
167079  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
167080    if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
167081      bMatch = 1;
167082    }
167083  }
167084
167085  assert( pIdxInfo->idxStr==0 );
167086  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
167087    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
167088
167089    if( bMatch==0 && p->usable
167090     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
167091    ){
167092      /* We have an equality constraint on the rowid. Use strategy 1. */
167093      int jj;
167094      for(jj=0; jj<ii; jj++){
167095        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
167096        pIdxInfo->aConstraintUsage[jj].omit = 0;
167097      }
167098      pIdxInfo->idxNum = 1;
167099      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
167100      pIdxInfo->aConstraintUsage[jj].omit = 1;
167101
167102      /* This strategy involves a two rowid lookups on an B-Tree structures
167103      ** and then a linear search of an R-Tree node. This should be
167104      ** considered almost as quick as a direct rowid lookup (for which
167105      ** sqlite uses an internal cost of 0.0). It is expected to return
167106      ** a single row.
167107      */
167108      pIdxInfo->estimatedCost = 30.0;
167109      pIdxInfo->estimatedRows = 1;
167110      return SQLITE_OK;
167111    }
167112
167113    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
167114      u8 op;
167115      switch( p->op ){
167116        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
167117        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
167118        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
167119        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
167120        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
167121        default:
167122          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
167123          op = RTREE_MATCH;
167124          break;
167125      }
167126      zIdxStr[iIdx++] = op;
167127      zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
167128      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
167129      pIdxInfo->aConstraintUsage[ii].omit = 1;
167130    }
167131  }
167132
167133  pIdxInfo->idxNum = 2;
167134  pIdxInfo->needToFreeIdxStr = 1;
167135  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
167136    return SQLITE_NOMEM;
167137  }
167138
167139  nRow = pRtree->nRowEst >> (iIdx/2);
167140  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
167141  pIdxInfo->estimatedRows = nRow;
167142
167143  return rc;
167144}
167145
167146/*
167147** Return the N-dimensional volumn of the cell stored in *p.
167148*/
167149static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
167150  RtreeDValue area = (RtreeDValue)1;
167151  assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
167152#ifndef SQLITE_RTREE_INT_ONLY
167153  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
167154    switch( pRtree->nDim ){
167155      case 5:  area  = p->aCoord[9].f - p->aCoord[8].f;
167156      case 4:  area *= p->aCoord[7].f - p->aCoord[6].f;
167157      case 3:  area *= p->aCoord[5].f - p->aCoord[4].f;
167158      case 2:  area *= p->aCoord[3].f - p->aCoord[2].f;
167159      default: area *= p->aCoord[1].f - p->aCoord[0].f;
167160    }
167161  }else
167162#endif
167163  {
167164    switch( pRtree->nDim ){
167165      case 5:  area  = p->aCoord[9].i - p->aCoord[8].i;
167166      case 4:  area *= p->aCoord[7].i - p->aCoord[6].i;
167167      case 3:  area *= p->aCoord[5].i - p->aCoord[4].i;
167168      case 2:  area *= p->aCoord[3].i - p->aCoord[2].i;
167169      default: area *= p->aCoord[1].i - p->aCoord[0].i;
167170    }
167171  }
167172  return area;
167173}
167174
167175/*
167176** Return the margin length of cell p. The margin length is the sum
167177** of the objects size in each dimension.
167178*/
167179static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
167180  RtreeDValue margin = 0;
167181  int ii = pRtree->nDim2 - 2;
167182  do{
167183    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
167184    ii -= 2;
167185  }while( ii>=0 );
167186  return margin;
167187}
167188
167189/*
167190** Store the union of cells p1 and p2 in p1.
167191*/
167192static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
167193  int ii = 0;
167194  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
167195    do{
167196      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
167197      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
167198      ii += 2;
167199    }while( ii<pRtree->nDim2 );
167200  }else{
167201    do{
167202      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
167203      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
167204      ii += 2;
167205    }while( ii<pRtree->nDim2 );
167206  }
167207}
167208
167209/*
167210** Return true if the area covered by p2 is a subset of the area covered
167211** by p1. False otherwise.
167212*/
167213static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
167214  int ii;
167215  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
167216  for(ii=0; ii<pRtree->nDim2; ii+=2){
167217    RtreeCoord *a1 = &p1->aCoord[ii];
167218    RtreeCoord *a2 = &p2->aCoord[ii];
167219    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
167220     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
167221    ){
167222      return 0;
167223    }
167224  }
167225  return 1;
167226}
167227
167228/*
167229** Return the amount cell p would grow by if it were unioned with pCell.
167230*/
167231static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
167232  RtreeDValue area;
167233  RtreeCell cell;
167234  memcpy(&cell, p, sizeof(RtreeCell));
167235  area = cellArea(pRtree, &cell);
167236  cellUnion(pRtree, &cell, pCell);
167237  return (cellArea(pRtree, &cell)-area);
167238}
167239
167240static RtreeDValue cellOverlap(
167241  Rtree *pRtree,
167242  RtreeCell *p,
167243  RtreeCell *aCell,
167244  int nCell
167245){
167246  int ii;
167247  RtreeDValue overlap = RTREE_ZERO;
167248  for(ii=0; ii<nCell; ii++){
167249    int jj;
167250    RtreeDValue o = (RtreeDValue)1;
167251    for(jj=0; jj<pRtree->nDim2; jj+=2){
167252      RtreeDValue x1, x2;
167253      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
167254      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
167255      if( x2<x1 ){
167256        o = (RtreeDValue)0;
167257        break;
167258      }else{
167259        o = o * (x2-x1);
167260      }
167261    }
167262    overlap += o;
167263  }
167264  return overlap;
167265}
167266
167267
167268/*
167269** This function implements the ChooseLeaf algorithm from Gutman[84].
167270** ChooseSubTree in r*tree terminology.
167271*/
167272static int ChooseLeaf(
167273  Rtree *pRtree,               /* Rtree table */
167274  RtreeCell *pCell,            /* Cell to insert into rtree */
167275  int iHeight,                 /* Height of sub-tree rooted at pCell */
167276  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
167277){
167278  int rc;
167279  int ii;
167280  RtreeNode *pNode;
167281  rc = nodeAcquire(pRtree, 1, 0, &pNode);
167282
167283  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
167284    int iCell;
167285    sqlite3_int64 iBest = 0;
167286
167287    RtreeDValue fMinGrowth = RTREE_ZERO;
167288    RtreeDValue fMinArea = RTREE_ZERO;
167289
167290    int nCell = NCELL(pNode);
167291    RtreeCell cell;
167292    RtreeNode *pChild;
167293
167294    RtreeCell *aCell = 0;
167295
167296    /* Select the child node which will be enlarged the least if pCell
167297    ** is inserted into it. Resolve ties by choosing the entry with
167298    ** the smallest area.
167299    */
167300    for(iCell=0; iCell<nCell; iCell++){
167301      int bBest = 0;
167302      RtreeDValue growth;
167303      RtreeDValue area;
167304      nodeGetCell(pRtree, pNode, iCell, &cell);
167305      growth = cellGrowth(pRtree, &cell, pCell);
167306      area = cellArea(pRtree, &cell);
167307      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
167308        bBest = 1;
167309      }
167310      if( bBest ){
167311        fMinGrowth = growth;
167312        fMinArea = area;
167313        iBest = cell.iRowid;
167314      }
167315    }
167316
167317    sqlite3_free(aCell);
167318    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
167319    nodeRelease(pRtree, pNode);
167320    pNode = pChild;
167321  }
167322
167323  *ppLeaf = pNode;
167324  return rc;
167325}
167326
167327/*
167328** A cell with the same content as pCell has just been inserted into
167329** the node pNode. This function updates the bounding box cells in
167330** all ancestor elements.
167331*/
167332static int AdjustTree(
167333  Rtree *pRtree,                    /* Rtree table */
167334  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
167335  RtreeCell *pCell                  /* This cell was just inserted */
167336){
167337  RtreeNode *p = pNode;
167338  while( p->pParent ){
167339    RtreeNode *pParent = p->pParent;
167340    RtreeCell cell;
167341    int iCell;
167342
167343    if( nodeParentIndex(pRtree, p, &iCell) ){
167344      return SQLITE_CORRUPT_VTAB;
167345    }
167346
167347    nodeGetCell(pRtree, pParent, iCell, &cell);
167348    if( !cellContains(pRtree, &cell, pCell) ){
167349      cellUnion(pRtree, &cell, pCell);
167350      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
167351    }
167352
167353    p = pParent;
167354  }
167355  return SQLITE_OK;
167356}
167357
167358/*
167359** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
167360*/
167361static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
167362  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
167363  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
167364  sqlite3_step(pRtree->pWriteRowid);
167365  return sqlite3_reset(pRtree->pWriteRowid);
167366}
167367
167368/*
167369** Write mapping (iNode->iPar) to the <rtree>_parent table.
167370*/
167371static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
167372  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
167373  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
167374  sqlite3_step(pRtree->pWriteParent);
167375  return sqlite3_reset(pRtree->pWriteParent);
167376}
167377
167378static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
167379
167380
167381/*
167382** Arguments aIdx, aDistance and aSpare all point to arrays of size
167383** nIdx. The aIdx array contains the set of integers from 0 to
167384** (nIdx-1) in no particular order. This function sorts the values
167385** in aIdx according to the indexed values in aDistance. For
167386** example, assuming the inputs:
167387**
167388**   aIdx      = { 0,   1,   2,   3 }
167389**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
167390**
167391** this function sets the aIdx array to contain:
167392**
167393**   aIdx      = { 0,   1,   2,   3 }
167394**
167395** The aSpare array is used as temporary working space by the
167396** sorting algorithm.
167397*/
167398static void SortByDistance(
167399  int *aIdx,
167400  int nIdx,
167401  RtreeDValue *aDistance,
167402  int *aSpare
167403){
167404  if( nIdx>1 ){
167405    int iLeft = 0;
167406    int iRight = 0;
167407
167408    int nLeft = nIdx/2;
167409    int nRight = nIdx-nLeft;
167410    int *aLeft = aIdx;
167411    int *aRight = &aIdx[nLeft];
167412
167413    SortByDistance(aLeft, nLeft, aDistance, aSpare);
167414    SortByDistance(aRight, nRight, aDistance, aSpare);
167415
167416    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
167417    aLeft = aSpare;
167418
167419    while( iLeft<nLeft || iRight<nRight ){
167420      if( iLeft==nLeft ){
167421        aIdx[iLeft+iRight] = aRight[iRight];
167422        iRight++;
167423      }else if( iRight==nRight ){
167424        aIdx[iLeft+iRight] = aLeft[iLeft];
167425        iLeft++;
167426      }else{
167427        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
167428        RtreeDValue fRight = aDistance[aRight[iRight]];
167429        if( fLeft<fRight ){
167430          aIdx[iLeft+iRight] = aLeft[iLeft];
167431          iLeft++;
167432        }else{
167433          aIdx[iLeft+iRight] = aRight[iRight];
167434          iRight++;
167435        }
167436      }
167437    }
167438
167439#if 0
167440    /* Check that the sort worked */
167441    {
167442      int jj;
167443      for(jj=1; jj<nIdx; jj++){
167444        RtreeDValue left = aDistance[aIdx[jj-1]];
167445        RtreeDValue right = aDistance[aIdx[jj]];
167446        assert( left<=right );
167447      }
167448    }
167449#endif
167450  }
167451}
167452
167453/*
167454** Arguments aIdx, aCell and aSpare all point to arrays of size
167455** nIdx. The aIdx array contains the set of integers from 0 to
167456** (nIdx-1) in no particular order. This function sorts the values
167457** in aIdx according to dimension iDim of the cells in aCell. The
167458** minimum value of dimension iDim is considered first, the
167459** maximum used to break ties.
167460**
167461** The aSpare array is used as temporary working space by the
167462** sorting algorithm.
167463*/
167464static void SortByDimension(
167465  Rtree *pRtree,
167466  int *aIdx,
167467  int nIdx,
167468  int iDim,
167469  RtreeCell *aCell,
167470  int *aSpare
167471){
167472  if( nIdx>1 ){
167473
167474    int iLeft = 0;
167475    int iRight = 0;
167476
167477    int nLeft = nIdx/2;
167478    int nRight = nIdx-nLeft;
167479    int *aLeft = aIdx;
167480    int *aRight = &aIdx[nLeft];
167481
167482    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
167483    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
167484
167485    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
167486    aLeft = aSpare;
167487    while( iLeft<nLeft || iRight<nRight ){
167488      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
167489      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
167490      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
167491      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
167492      if( (iLeft!=nLeft) && ((iRight==nRight)
167493       || (xleft1<xright1)
167494       || (xleft1==xright1 && xleft2<xright2)
167495      )){
167496        aIdx[iLeft+iRight] = aLeft[iLeft];
167497        iLeft++;
167498      }else{
167499        aIdx[iLeft+iRight] = aRight[iRight];
167500        iRight++;
167501      }
167502    }
167503
167504#if 0
167505    /* Check that the sort worked */
167506    {
167507      int jj;
167508      for(jj=1; jj<nIdx; jj++){
167509        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
167510        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
167511        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
167512        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
167513        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
167514      }
167515    }
167516#endif
167517  }
167518}
167519
167520/*
167521** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
167522*/
167523static int splitNodeStartree(
167524  Rtree *pRtree,
167525  RtreeCell *aCell,
167526  int nCell,
167527  RtreeNode *pLeft,
167528  RtreeNode *pRight,
167529  RtreeCell *pBboxLeft,
167530  RtreeCell *pBboxRight
167531){
167532  int **aaSorted;
167533  int *aSpare;
167534  int ii;
167535
167536  int iBestDim = 0;
167537  int iBestSplit = 0;
167538  RtreeDValue fBestMargin = RTREE_ZERO;
167539
167540  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
167541
167542  aaSorted = (int **)sqlite3_malloc(nByte);
167543  if( !aaSorted ){
167544    return SQLITE_NOMEM;
167545  }
167546
167547  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
167548  memset(aaSorted, 0, nByte);
167549  for(ii=0; ii<pRtree->nDim; ii++){
167550    int jj;
167551    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
167552    for(jj=0; jj<nCell; jj++){
167553      aaSorted[ii][jj] = jj;
167554    }
167555    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
167556  }
167557
167558  for(ii=0; ii<pRtree->nDim; ii++){
167559    RtreeDValue margin = RTREE_ZERO;
167560    RtreeDValue fBestOverlap = RTREE_ZERO;
167561    RtreeDValue fBestArea = RTREE_ZERO;
167562    int iBestLeft = 0;
167563    int nLeft;
167564
167565    for(
167566      nLeft=RTREE_MINCELLS(pRtree);
167567      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
167568      nLeft++
167569    ){
167570      RtreeCell left;
167571      RtreeCell right;
167572      int kk;
167573      RtreeDValue overlap;
167574      RtreeDValue area;
167575
167576      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
167577      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
167578      for(kk=1; kk<(nCell-1); kk++){
167579        if( kk<nLeft ){
167580          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
167581        }else{
167582          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
167583        }
167584      }
167585      margin += cellMargin(pRtree, &left);
167586      margin += cellMargin(pRtree, &right);
167587      overlap = cellOverlap(pRtree, &left, &right, 1);
167588      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
167589      if( (nLeft==RTREE_MINCELLS(pRtree))
167590       || (overlap<fBestOverlap)
167591       || (overlap==fBestOverlap && area<fBestArea)
167592      ){
167593        iBestLeft = nLeft;
167594        fBestOverlap = overlap;
167595        fBestArea = area;
167596      }
167597    }
167598
167599    if( ii==0 || margin<fBestMargin ){
167600      iBestDim = ii;
167601      fBestMargin = margin;
167602      iBestSplit = iBestLeft;
167603    }
167604  }
167605
167606  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
167607  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
167608  for(ii=0; ii<nCell; ii++){
167609    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
167610    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
167611    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
167612    nodeInsertCell(pRtree, pTarget, pCell);
167613    cellUnion(pRtree, pBbox, pCell);
167614  }
167615
167616  sqlite3_free(aaSorted);
167617  return SQLITE_OK;
167618}
167619
167620
167621static int updateMapping(
167622  Rtree *pRtree,
167623  i64 iRowid,
167624  RtreeNode *pNode,
167625  int iHeight
167626){
167627  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
167628  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
167629  if( iHeight>0 ){
167630    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
167631    if( pChild ){
167632      nodeRelease(pRtree, pChild->pParent);
167633      nodeReference(pNode);
167634      pChild->pParent = pNode;
167635    }
167636  }
167637  return xSetMapping(pRtree, iRowid, pNode->iNode);
167638}
167639
167640static int SplitNode(
167641  Rtree *pRtree,
167642  RtreeNode *pNode,
167643  RtreeCell *pCell,
167644  int iHeight
167645){
167646  int i;
167647  int newCellIsRight = 0;
167648
167649  int rc = SQLITE_OK;
167650  int nCell = NCELL(pNode);
167651  RtreeCell *aCell;
167652  int *aiUsed;
167653
167654  RtreeNode *pLeft = 0;
167655  RtreeNode *pRight = 0;
167656
167657  RtreeCell leftbbox;
167658  RtreeCell rightbbox;
167659
167660  /* Allocate an array and populate it with a copy of pCell and
167661  ** all cells from node pLeft. Then zero the original node.
167662  */
167663  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
167664  if( !aCell ){
167665    rc = SQLITE_NOMEM;
167666    goto splitnode_out;
167667  }
167668  aiUsed = (int *)&aCell[nCell+1];
167669  memset(aiUsed, 0, sizeof(int)*(nCell+1));
167670  for(i=0; i<nCell; i++){
167671    nodeGetCell(pRtree, pNode, i, &aCell[i]);
167672  }
167673  nodeZero(pRtree, pNode);
167674  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
167675  nCell++;
167676
167677  if( pNode->iNode==1 ){
167678    pRight = nodeNew(pRtree, pNode);
167679    pLeft = nodeNew(pRtree, pNode);
167680    pRtree->iDepth++;
167681    pNode->isDirty = 1;
167682    writeInt16(pNode->zData, pRtree->iDepth);
167683  }else{
167684    pLeft = pNode;
167685    pRight = nodeNew(pRtree, pLeft->pParent);
167686    nodeReference(pLeft);
167687  }
167688
167689  if( !pLeft || !pRight ){
167690    rc = SQLITE_NOMEM;
167691    goto splitnode_out;
167692  }
167693
167694  memset(pLeft->zData, 0, pRtree->iNodeSize);
167695  memset(pRight->zData, 0, pRtree->iNodeSize);
167696
167697  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
167698                         &leftbbox, &rightbbox);
167699  if( rc!=SQLITE_OK ){
167700    goto splitnode_out;
167701  }
167702
167703  /* Ensure both child nodes have node numbers assigned to them by calling
167704  ** nodeWrite(). Node pRight always needs a node number, as it was created
167705  ** by nodeNew() above. But node pLeft sometimes already has a node number.
167706  ** In this case avoid the all to nodeWrite().
167707  */
167708  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
167709   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
167710  ){
167711    goto splitnode_out;
167712  }
167713
167714  rightbbox.iRowid = pRight->iNode;
167715  leftbbox.iRowid = pLeft->iNode;
167716
167717  if( pNode->iNode==1 ){
167718    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
167719    if( rc!=SQLITE_OK ){
167720      goto splitnode_out;
167721    }
167722  }else{
167723    RtreeNode *pParent = pLeft->pParent;
167724    int iCell;
167725    rc = nodeParentIndex(pRtree, pLeft, &iCell);
167726    if( rc==SQLITE_OK ){
167727      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
167728      rc = AdjustTree(pRtree, pParent, &leftbbox);
167729    }
167730    if( rc!=SQLITE_OK ){
167731      goto splitnode_out;
167732    }
167733  }
167734  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
167735    goto splitnode_out;
167736  }
167737
167738  for(i=0; i<NCELL(pRight); i++){
167739    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
167740    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
167741    if( iRowid==pCell->iRowid ){
167742      newCellIsRight = 1;
167743    }
167744    if( rc!=SQLITE_OK ){
167745      goto splitnode_out;
167746    }
167747  }
167748  if( pNode->iNode==1 ){
167749    for(i=0; i<NCELL(pLeft); i++){
167750      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
167751      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
167752      if( rc!=SQLITE_OK ){
167753        goto splitnode_out;
167754      }
167755    }
167756  }else if( newCellIsRight==0 ){
167757    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
167758  }
167759
167760  if( rc==SQLITE_OK ){
167761    rc = nodeRelease(pRtree, pRight);
167762    pRight = 0;
167763  }
167764  if( rc==SQLITE_OK ){
167765    rc = nodeRelease(pRtree, pLeft);
167766    pLeft = 0;
167767  }
167768
167769splitnode_out:
167770  nodeRelease(pRtree, pRight);
167771  nodeRelease(pRtree, pLeft);
167772  sqlite3_free(aCell);
167773  return rc;
167774}
167775
167776/*
167777** If node pLeaf is not the root of the r-tree and its pParent pointer is
167778** still NULL, load all ancestor nodes of pLeaf into memory and populate
167779** the pLeaf->pParent chain all the way up to the root node.
167780**
167781** This operation is required when a row is deleted (or updated - an update
167782** is implemented as a delete followed by an insert). SQLite provides the
167783** rowid of the row to delete, which can be used to find the leaf on which
167784** the entry resides (argument pLeaf). Once the leaf is located, this
167785** function is called to determine its ancestry.
167786*/
167787static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
167788  int rc = SQLITE_OK;
167789  RtreeNode *pChild = pLeaf;
167790  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
167791    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
167792    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
167793    rc = sqlite3_step(pRtree->pReadParent);
167794    if( rc==SQLITE_ROW ){
167795      RtreeNode *pTest;           /* Used to test for reference loops */
167796      i64 iNode;                  /* Node number of parent node */
167797
167798      /* Before setting pChild->pParent, test that we are not creating a
167799      ** loop of references (as we would if, say, pChild==pParent). We don't
167800      ** want to do this as it leads to a memory leak when trying to delete
167801      ** the referenced counted node structures.
167802      */
167803      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
167804      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
167805      if( !pTest ){
167806        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
167807      }
167808    }
167809    rc = sqlite3_reset(pRtree->pReadParent);
167810    if( rc==SQLITE_OK ) rc = rc2;
167811    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
167812    pChild = pChild->pParent;
167813  }
167814  return rc;
167815}
167816
167817static int deleteCell(Rtree *, RtreeNode *, int, int);
167818
167819static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
167820  int rc;
167821  int rc2;
167822  RtreeNode *pParent = 0;
167823  int iCell;
167824
167825  assert( pNode->nRef==1 );
167826
167827  /* Remove the entry in the parent cell. */
167828  rc = nodeParentIndex(pRtree, pNode, &iCell);
167829  if( rc==SQLITE_OK ){
167830    pParent = pNode->pParent;
167831    pNode->pParent = 0;
167832    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
167833  }
167834  rc2 = nodeRelease(pRtree, pParent);
167835  if( rc==SQLITE_OK ){
167836    rc = rc2;
167837  }
167838  if( rc!=SQLITE_OK ){
167839    return rc;
167840  }
167841
167842  /* Remove the xxx_node entry. */
167843  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
167844  sqlite3_step(pRtree->pDeleteNode);
167845  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
167846    return rc;
167847  }
167848
167849  /* Remove the xxx_parent entry. */
167850  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
167851  sqlite3_step(pRtree->pDeleteParent);
167852  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
167853    return rc;
167854  }
167855
167856  /* Remove the node from the in-memory hash table and link it into
167857  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
167858  */
167859  nodeHashDelete(pRtree, pNode);
167860  pNode->iNode = iHeight;
167861  pNode->pNext = pRtree->pDeleted;
167862  pNode->nRef++;
167863  pRtree->pDeleted = pNode;
167864
167865  return SQLITE_OK;
167866}
167867
167868static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
167869  RtreeNode *pParent = pNode->pParent;
167870  int rc = SQLITE_OK;
167871  if( pParent ){
167872    int ii;
167873    int nCell = NCELL(pNode);
167874    RtreeCell box;                            /* Bounding box for pNode */
167875    nodeGetCell(pRtree, pNode, 0, &box);
167876    for(ii=1; ii<nCell; ii++){
167877      RtreeCell cell;
167878      nodeGetCell(pRtree, pNode, ii, &cell);
167879      cellUnion(pRtree, &box, &cell);
167880    }
167881    box.iRowid = pNode->iNode;
167882    rc = nodeParentIndex(pRtree, pNode, &ii);
167883    if( rc==SQLITE_OK ){
167884      nodeOverwriteCell(pRtree, pParent, &box, ii);
167885      rc = fixBoundingBox(pRtree, pParent);
167886    }
167887  }
167888  return rc;
167889}
167890
167891/*
167892** Delete the cell at index iCell of node pNode. After removing the
167893** cell, adjust the r-tree data structure if required.
167894*/
167895static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
167896  RtreeNode *pParent;
167897  int rc;
167898
167899  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
167900    return rc;
167901  }
167902
167903  /* Remove the cell from the node. This call just moves bytes around
167904  ** the in-memory node image, so it cannot fail.
167905  */
167906  nodeDeleteCell(pRtree, pNode, iCell);
167907
167908  /* If the node is not the tree root and now has less than the minimum
167909  ** number of cells, remove it from the tree. Otherwise, update the
167910  ** cell in the parent node so that it tightly contains the updated
167911  ** node.
167912  */
167913  pParent = pNode->pParent;
167914  assert( pParent || pNode->iNode==1 );
167915  if( pParent ){
167916    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
167917      rc = removeNode(pRtree, pNode, iHeight);
167918    }else{
167919      rc = fixBoundingBox(pRtree, pNode);
167920    }
167921  }
167922
167923  return rc;
167924}
167925
167926static int Reinsert(
167927  Rtree *pRtree,
167928  RtreeNode *pNode,
167929  RtreeCell *pCell,
167930  int iHeight
167931){
167932  int *aOrder;
167933  int *aSpare;
167934  RtreeCell *aCell;
167935  RtreeDValue *aDistance;
167936  int nCell;
167937  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
167938  int iDim;
167939  int ii;
167940  int rc = SQLITE_OK;
167941  int n;
167942
167943  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
167944
167945  nCell = NCELL(pNode)+1;
167946  n = (nCell+1)&(~1);
167947
167948  /* Allocate the buffers used by this operation. The allocation is
167949  ** relinquished before this function returns.
167950  */
167951  aCell = (RtreeCell *)sqlite3_malloc(n * (
167952    sizeof(RtreeCell)     +         /* aCell array */
167953    sizeof(int)           +         /* aOrder array */
167954    sizeof(int)           +         /* aSpare array */
167955    sizeof(RtreeDValue)             /* aDistance array */
167956  ));
167957  if( !aCell ){
167958    return SQLITE_NOMEM;
167959  }
167960  aOrder    = (int *)&aCell[n];
167961  aSpare    = (int *)&aOrder[n];
167962  aDistance = (RtreeDValue *)&aSpare[n];
167963
167964  for(ii=0; ii<nCell; ii++){
167965    if( ii==(nCell-1) ){
167966      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
167967    }else{
167968      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
167969    }
167970    aOrder[ii] = ii;
167971    for(iDim=0; iDim<pRtree->nDim; iDim++){
167972      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
167973      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
167974    }
167975  }
167976  for(iDim=0; iDim<pRtree->nDim; iDim++){
167977    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
167978  }
167979
167980  for(ii=0; ii<nCell; ii++){
167981    aDistance[ii] = RTREE_ZERO;
167982    for(iDim=0; iDim<pRtree->nDim; iDim++){
167983      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
167984                               DCOORD(aCell[ii].aCoord[iDim*2]));
167985      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
167986    }
167987  }
167988
167989  SortByDistance(aOrder, nCell, aDistance, aSpare);
167990  nodeZero(pRtree, pNode);
167991
167992  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
167993    RtreeCell *p = &aCell[aOrder[ii]];
167994    nodeInsertCell(pRtree, pNode, p);
167995    if( p->iRowid==pCell->iRowid ){
167996      if( iHeight==0 ){
167997        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
167998      }else{
167999        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
168000      }
168001    }
168002  }
168003  if( rc==SQLITE_OK ){
168004    rc = fixBoundingBox(pRtree, pNode);
168005  }
168006  for(; rc==SQLITE_OK && ii<nCell; ii++){
168007    /* Find a node to store this cell in. pNode->iNode currently contains
168008    ** the height of the sub-tree headed by the cell.
168009    */
168010    RtreeNode *pInsert;
168011    RtreeCell *p = &aCell[aOrder[ii]];
168012    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
168013    if( rc==SQLITE_OK ){
168014      int rc2;
168015      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
168016      rc2 = nodeRelease(pRtree, pInsert);
168017      if( rc==SQLITE_OK ){
168018        rc = rc2;
168019      }
168020    }
168021  }
168022
168023  sqlite3_free(aCell);
168024  return rc;
168025}
168026
168027/*
168028** Insert cell pCell into node pNode. Node pNode is the head of a
168029** subtree iHeight high (leaf nodes have iHeight==0).
168030*/
168031static int rtreeInsertCell(
168032  Rtree *pRtree,
168033  RtreeNode *pNode,
168034  RtreeCell *pCell,
168035  int iHeight
168036){
168037  int rc = SQLITE_OK;
168038  if( iHeight>0 ){
168039    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
168040    if( pChild ){
168041      nodeRelease(pRtree, pChild->pParent);
168042      nodeReference(pNode);
168043      pChild->pParent = pNode;
168044    }
168045  }
168046  if( nodeInsertCell(pRtree, pNode, pCell) ){
168047    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
168048      rc = SplitNode(pRtree, pNode, pCell, iHeight);
168049    }else{
168050      pRtree->iReinsertHeight = iHeight;
168051      rc = Reinsert(pRtree, pNode, pCell, iHeight);
168052    }
168053  }else{
168054    rc = AdjustTree(pRtree, pNode, pCell);
168055    if( rc==SQLITE_OK ){
168056      if( iHeight==0 ){
168057        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
168058      }else{
168059        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
168060      }
168061    }
168062  }
168063  return rc;
168064}
168065
168066static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
168067  int ii;
168068  int rc = SQLITE_OK;
168069  int nCell = NCELL(pNode);
168070
168071  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
168072    RtreeNode *pInsert;
168073    RtreeCell cell;
168074    nodeGetCell(pRtree, pNode, ii, &cell);
168075
168076    /* Find a node to store this cell in. pNode->iNode currently contains
168077    ** the height of the sub-tree headed by the cell.
168078    */
168079    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
168080    if( rc==SQLITE_OK ){
168081      int rc2;
168082      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
168083      rc2 = nodeRelease(pRtree, pInsert);
168084      if( rc==SQLITE_OK ){
168085        rc = rc2;
168086      }
168087    }
168088  }
168089  return rc;
168090}
168091
168092/*
168093** Select a currently unused rowid for a new r-tree record.
168094*/
168095static int newRowid(Rtree *pRtree, i64 *piRowid){
168096  int rc;
168097  sqlite3_bind_null(pRtree->pWriteRowid, 1);
168098  sqlite3_bind_null(pRtree->pWriteRowid, 2);
168099  sqlite3_step(pRtree->pWriteRowid);
168100  rc = sqlite3_reset(pRtree->pWriteRowid);
168101  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
168102  return rc;
168103}
168104
168105/*
168106** Remove the entry with rowid=iDelete from the r-tree structure.
168107*/
168108static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
168109  int rc;                         /* Return code */
168110  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
168111  int iCell;                      /* Index of iDelete cell in pLeaf */
168112  RtreeNode *pRoot;               /* Root node of rtree structure */
168113
168114
168115  /* Obtain a reference to the root node to initialize Rtree.iDepth */
168116  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
168117
168118  /* Obtain a reference to the leaf node that contains the entry
168119  ** about to be deleted.
168120  */
168121  if( rc==SQLITE_OK ){
168122    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
168123  }
168124
168125  /* Delete the cell in question from the leaf node. */
168126  if( rc==SQLITE_OK ){
168127    int rc2;
168128    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
168129    if( rc==SQLITE_OK ){
168130      rc = deleteCell(pRtree, pLeaf, iCell, 0);
168131    }
168132    rc2 = nodeRelease(pRtree, pLeaf);
168133    if( rc==SQLITE_OK ){
168134      rc = rc2;
168135    }
168136  }
168137
168138  /* Delete the corresponding entry in the <rtree>_rowid table. */
168139  if( rc==SQLITE_OK ){
168140    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
168141    sqlite3_step(pRtree->pDeleteRowid);
168142    rc = sqlite3_reset(pRtree->pDeleteRowid);
168143  }
168144
168145  /* Check if the root node now has exactly one child. If so, remove
168146  ** it, schedule the contents of the child for reinsertion and
168147  ** reduce the tree height by one.
168148  **
168149  ** This is equivalent to copying the contents of the child into
168150  ** the root node (the operation that Gutman's paper says to perform
168151  ** in this scenario).
168152  */
168153  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
168154    int rc2;
168155    RtreeNode *pChild;
168156    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
168157    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
168158    if( rc==SQLITE_OK ){
168159      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
168160    }
168161    rc2 = nodeRelease(pRtree, pChild);
168162    if( rc==SQLITE_OK ) rc = rc2;
168163    if( rc==SQLITE_OK ){
168164      pRtree->iDepth--;
168165      writeInt16(pRoot->zData, pRtree->iDepth);
168166      pRoot->isDirty = 1;
168167    }
168168  }
168169
168170  /* Re-insert the contents of any underfull nodes removed from the tree. */
168171  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
168172    if( rc==SQLITE_OK ){
168173      rc = reinsertNodeContent(pRtree, pLeaf);
168174    }
168175    pRtree->pDeleted = pLeaf->pNext;
168176    sqlite3_free(pLeaf);
168177  }
168178
168179  /* Release the reference to the root node. */
168180  if( rc==SQLITE_OK ){
168181    rc = nodeRelease(pRtree, pRoot);
168182  }else{
168183    nodeRelease(pRtree, pRoot);
168184  }
168185
168186  return rc;
168187}
168188
168189/*
168190** Rounding constants for float->double conversion.
168191*/
168192#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
168193#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
168194
168195#if !defined(SQLITE_RTREE_INT_ONLY)
168196/*
168197** Convert an sqlite3_value into an RtreeValue (presumably a float)
168198** while taking care to round toward negative or positive, respectively.
168199*/
168200static RtreeValue rtreeValueDown(sqlite3_value *v){
168201  double d = sqlite3_value_double(v);
168202  float f = (float)d;
168203  if( f>d ){
168204    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
168205  }
168206  return f;
168207}
168208static RtreeValue rtreeValueUp(sqlite3_value *v){
168209  double d = sqlite3_value_double(v);
168210  float f = (float)d;
168211  if( f<d ){
168212    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
168213  }
168214  return f;
168215}
168216#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
168217
168218/*
168219** A constraint has failed while inserting a row into an rtree table.
168220** Assuming no OOM error occurs, this function sets the error message
168221** (at pRtree->base.zErrMsg) to an appropriate value and returns
168222** SQLITE_CONSTRAINT.
168223**
168224** Parameter iCol is the index of the leftmost column involved in the
168225** constraint failure. If it is 0, then the constraint that failed is
168226** the unique constraint on the id column. Otherwise, it is the rtree
168227** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
168228**
168229** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
168230*/
168231static int rtreeConstraintError(Rtree *pRtree, int iCol){
168232  sqlite3_stmt *pStmt = 0;
168233  char *zSql;
168234  int rc;
168235
168236  assert( iCol==0 || iCol%2 );
168237  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
168238  if( zSql ){
168239    rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
168240  }else{
168241    rc = SQLITE_NOMEM;
168242  }
168243  sqlite3_free(zSql);
168244
168245  if( rc==SQLITE_OK ){
168246    if( iCol==0 ){
168247      const char *zCol = sqlite3_column_name(pStmt, 0);
168248      pRtree->base.zErrMsg = sqlite3_mprintf(
168249          "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
168250      );
168251    }else{
168252      const char *zCol1 = sqlite3_column_name(pStmt, iCol);
168253      const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
168254      pRtree->base.zErrMsg = sqlite3_mprintf(
168255          "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
168256      );
168257    }
168258  }
168259
168260  sqlite3_finalize(pStmt);
168261  return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
168262}
168263
168264
168265
168266/*
168267** The xUpdate method for rtree module virtual tables.
168268*/
168269static int rtreeUpdate(
168270  sqlite3_vtab *pVtab,
168271  int nData,
168272  sqlite3_value **azData,
168273  sqlite_int64 *pRowid
168274){
168275  Rtree *pRtree = (Rtree *)pVtab;
168276  int rc = SQLITE_OK;
168277  RtreeCell cell;                 /* New cell to insert if nData>1 */
168278  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
168279
168280  rtreeReference(pRtree);
168281  assert(nData>=1);
168282
168283  cell.iRowid = 0;  /* Used only to suppress a compiler warning */
168284
168285  /* Constraint handling. A write operation on an r-tree table may return
168286  ** SQLITE_CONSTRAINT for two reasons:
168287  **
168288  **   1. A duplicate rowid value, or
168289  **   2. The supplied data violates the "x2>=x1" constraint.
168290  **
168291  ** In the first case, if the conflict-handling mode is REPLACE, then
168292  ** the conflicting row can be removed before proceeding. In the second
168293  ** case, SQLITE_CONSTRAINT must be returned regardless of the
168294  ** conflict-handling mode specified by the user.
168295  */
168296  if( nData>1 ){
168297    int ii;
168298
168299    /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
168300    **
168301    ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
168302    ** with "column" that are interpreted as table constraints.
168303    ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
168304    ** This problem was discovered after years of use, so we silently ignore
168305    ** these kinds of misdeclared tables to avoid breaking any legacy.
168306    */
168307    assert( nData<=(pRtree->nDim2 + 3) );
168308
168309#ifndef SQLITE_RTREE_INT_ONLY
168310    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
168311      for(ii=0; ii<nData-4; ii+=2){
168312        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
168313        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
168314        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
168315          rc = rtreeConstraintError(pRtree, ii+1);
168316          goto constraint;
168317        }
168318      }
168319    }else
168320#endif
168321    {
168322      for(ii=0; ii<nData-4; ii+=2){
168323        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
168324        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
168325        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
168326          rc = rtreeConstraintError(pRtree, ii+1);
168327          goto constraint;
168328        }
168329      }
168330    }
168331
168332    /* If a rowid value was supplied, check if it is already present in
168333    ** the table. If so, the constraint has failed. */
168334    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
168335      cell.iRowid = sqlite3_value_int64(azData[2]);
168336      if( sqlite3_value_type(azData[0])==SQLITE_NULL
168337       || sqlite3_value_int64(azData[0])!=cell.iRowid
168338      ){
168339        int steprc;
168340        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
168341        steprc = sqlite3_step(pRtree->pReadRowid);
168342        rc = sqlite3_reset(pRtree->pReadRowid);
168343        if( SQLITE_ROW==steprc ){
168344          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
168345            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
168346          }else{
168347            rc = rtreeConstraintError(pRtree, 0);
168348            goto constraint;
168349          }
168350        }
168351      }
168352      bHaveRowid = 1;
168353    }
168354  }
168355
168356  /* If azData[0] is not an SQL NULL value, it is the rowid of a
168357  ** record to delete from the r-tree table. The following block does
168358  ** just that.
168359  */
168360  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
168361    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
168362  }
168363
168364  /* If the azData[] array contains more than one element, elements
168365  ** (azData[2]..azData[argc-1]) contain a new record to insert into
168366  ** the r-tree structure.
168367  */
168368  if( rc==SQLITE_OK && nData>1 ){
168369    /* Insert the new record into the r-tree */
168370    RtreeNode *pLeaf = 0;
168371
168372    /* Figure out the rowid of the new row. */
168373    if( bHaveRowid==0 ){
168374      rc = newRowid(pRtree, &cell.iRowid);
168375    }
168376    *pRowid = cell.iRowid;
168377
168378    if( rc==SQLITE_OK ){
168379      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
168380    }
168381    if( rc==SQLITE_OK ){
168382      int rc2;
168383      pRtree->iReinsertHeight = -1;
168384      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
168385      rc2 = nodeRelease(pRtree, pLeaf);
168386      if( rc==SQLITE_OK ){
168387        rc = rc2;
168388      }
168389    }
168390  }
168391
168392constraint:
168393  rtreeRelease(pRtree);
168394  return rc;
168395}
168396
168397/*
168398** Called when a transaction starts.
168399*/
168400static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
168401  Rtree *pRtree = (Rtree *)pVtab;
168402  assert( pRtree->inWrTrans==0 );
168403  pRtree->inWrTrans++;
168404  return SQLITE_OK;
168405}
168406
168407/*
168408** Called when a transaction completes (either by COMMIT or ROLLBACK).
168409** The sqlite3_blob object should be released at this point.
168410*/
168411static int rtreeEndTransaction(sqlite3_vtab *pVtab){
168412  Rtree *pRtree = (Rtree *)pVtab;
168413  pRtree->inWrTrans = 0;
168414  nodeBlobReset(pRtree);
168415  return SQLITE_OK;
168416}
168417
168418/*
168419** The xRename method for rtree module virtual tables.
168420*/
168421static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
168422  Rtree *pRtree = (Rtree *)pVtab;
168423  int rc = SQLITE_NOMEM;
168424  char *zSql = sqlite3_mprintf(
168425    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
168426    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
168427    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
168428    , pRtree->zDb, pRtree->zName, zNewName
168429    , pRtree->zDb, pRtree->zName, zNewName
168430    , pRtree->zDb, pRtree->zName, zNewName
168431  );
168432  if( zSql ){
168433    nodeBlobReset(pRtree);
168434    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
168435    sqlite3_free(zSql);
168436  }
168437  return rc;
168438}
168439
168440/*
168441** The xSavepoint method.
168442**
168443** This module does not need to do anything to support savepoints. However,
168444** it uses this hook to close any open blob handle. This is done because a
168445** DROP TABLE command - which fortunately always opens a savepoint - cannot
168446** succeed if there are any open blob handles. i.e. if the blob handle were
168447** not closed here, the following would fail:
168448**
168449**   BEGIN;
168450**     INSERT INTO rtree...
168451**     DROP TABLE <tablename>;    -- Would fail with SQLITE_LOCKED
168452**   COMMIT;
168453*/
168454static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
168455  Rtree *pRtree = (Rtree *)pVtab;
168456  int iwt = pRtree->inWrTrans;
168457  UNUSED_PARAMETER(iSavepoint);
168458  pRtree->inWrTrans = 0;
168459  nodeBlobReset(pRtree);
168460  pRtree->inWrTrans = iwt;
168461  return SQLITE_OK;
168462}
168463
168464/*
168465** This function populates the pRtree->nRowEst variable with an estimate
168466** of the number of rows in the virtual table. If possible, this is based
168467** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
168468*/
168469static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
168470  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
168471  char *zSql;
168472  sqlite3_stmt *p;
168473  int rc;
168474  i64 nRow = 0;
168475
168476  rc = sqlite3_table_column_metadata(
168477      db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
168478  );
168479  if( rc!=SQLITE_OK ){
168480    pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
168481    return rc==SQLITE_ERROR ? SQLITE_OK : rc;
168482  }
168483  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
168484  if( zSql==0 ){
168485    rc = SQLITE_NOMEM;
168486  }else{
168487    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
168488    if( rc==SQLITE_OK ){
168489      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
168490      rc = sqlite3_finalize(p);
168491    }else if( rc!=SQLITE_NOMEM ){
168492      rc = SQLITE_OK;
168493    }
168494
168495    if( rc==SQLITE_OK ){
168496      if( nRow==0 ){
168497        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
168498      }else{
168499        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
168500      }
168501    }
168502    sqlite3_free(zSql);
168503  }
168504
168505  return rc;
168506}
168507
168508static sqlite3_module rtreeModule = {
168509  2,                          /* iVersion */
168510  rtreeCreate,                /* xCreate - create a table */
168511  rtreeConnect,               /* xConnect - connect to an existing table */
168512  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
168513  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
168514  rtreeDestroy,               /* xDestroy - Drop a table */
168515  rtreeOpen,                  /* xOpen - open a cursor */
168516  rtreeClose,                 /* xClose - close a cursor */
168517  rtreeFilter,                /* xFilter - configure scan constraints */
168518  rtreeNext,                  /* xNext - advance a cursor */
168519  rtreeEof,                   /* xEof */
168520  rtreeColumn,                /* xColumn - read data */
168521  rtreeRowid,                 /* xRowid - read data */
168522  rtreeUpdate,                /* xUpdate - write data */
168523  rtreeBeginTransaction,      /* xBegin - begin transaction */
168524  rtreeEndTransaction,        /* xSync - sync transaction */
168525  rtreeEndTransaction,        /* xCommit - commit transaction */
168526  rtreeEndTransaction,        /* xRollback - rollback transaction */
168527  0,                          /* xFindFunction - function overloading */
168528  rtreeRename,                /* xRename - rename the table */
168529  rtreeSavepoint,             /* xSavepoint */
168530  0,                          /* xRelease */
168531  0,                          /* xRollbackTo */
168532};
168533
168534static int rtreeSqlInit(
168535  Rtree *pRtree,
168536  sqlite3 *db,
168537  const char *zDb,
168538  const char *zPrefix,
168539  int isCreate
168540){
168541  int rc = SQLITE_OK;
168542
168543  #define N_STATEMENT 8
168544  static const char *azSql[N_STATEMENT] = {
168545    /* Write the xxx_node table */
168546    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
168547    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
168548
168549    /* Read and write the xxx_rowid table */
168550    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
168551    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
168552    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
168553
168554    /* Read and write the xxx_parent table */
168555    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
168556    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
168557    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
168558  };
168559  sqlite3_stmt **appStmt[N_STATEMENT];
168560  int i;
168561
168562  pRtree->db = db;
168563
168564  if( isCreate ){
168565    char *zCreate = sqlite3_mprintf(
168566"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
168567"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
168568"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
168569                                  " parentnode INTEGER);"
168570"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
168571      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
168572    );
168573    if( !zCreate ){
168574      return SQLITE_NOMEM;
168575    }
168576    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
168577    sqlite3_free(zCreate);
168578    if( rc!=SQLITE_OK ){
168579      return rc;
168580    }
168581  }
168582
168583  appStmt[0] = &pRtree->pWriteNode;
168584  appStmt[1] = &pRtree->pDeleteNode;
168585  appStmt[2] = &pRtree->pReadRowid;
168586  appStmt[3] = &pRtree->pWriteRowid;
168587  appStmt[4] = &pRtree->pDeleteRowid;
168588  appStmt[5] = &pRtree->pReadParent;
168589  appStmt[6] = &pRtree->pWriteParent;
168590  appStmt[7] = &pRtree->pDeleteParent;
168591
168592  rc = rtreeQueryStat1(db, pRtree);
168593  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
168594    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
168595    if( zSql ){
168596      rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
168597                              appStmt[i], 0);
168598    }else{
168599      rc = SQLITE_NOMEM;
168600    }
168601    sqlite3_free(zSql);
168602  }
168603
168604  return rc;
168605}
168606
168607/*
168608** The second argument to this function contains the text of an SQL statement
168609** that returns a single integer value. The statement is compiled and executed
168610** using database connection db. If successful, the integer value returned
168611** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
168612** code is returned and the value of *piVal after returning is not defined.
168613*/
168614static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
168615  int rc = SQLITE_NOMEM;
168616  if( zSql ){
168617    sqlite3_stmt *pStmt = 0;
168618    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
168619    if( rc==SQLITE_OK ){
168620      if( SQLITE_ROW==sqlite3_step(pStmt) ){
168621        *piVal = sqlite3_column_int(pStmt, 0);
168622      }
168623      rc = sqlite3_finalize(pStmt);
168624    }
168625  }
168626  return rc;
168627}
168628
168629/*
168630** This function is called from within the xConnect() or xCreate() method to
168631** determine the node-size used by the rtree table being created or connected
168632** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
168633** Otherwise, an SQLite error code is returned.
168634**
168635** If this function is being called as part of an xConnect(), then the rtree
168636** table already exists. In this case the node-size is determined by inspecting
168637** the root node of the tree.
168638**
168639** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
168640** This ensures that each node is stored on a single database page. If the
168641** database page-size is so large that more than RTREE_MAXCELLS entries
168642** would fit in a single node, use a smaller node-size.
168643*/
168644static int getNodeSize(
168645  sqlite3 *db,                    /* Database handle */
168646  Rtree *pRtree,                  /* Rtree handle */
168647  int isCreate,                   /* True for xCreate, false for xConnect */
168648  char **pzErr                    /* OUT: Error message, if any */
168649){
168650  int rc;
168651  char *zSql;
168652  if( isCreate ){
168653    int iPageSize = 0;
168654    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
168655    rc = getIntFromStmt(db, zSql, &iPageSize);
168656    if( rc==SQLITE_OK ){
168657      pRtree->iNodeSize = iPageSize-64;
168658      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
168659        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
168660      }
168661    }else{
168662      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
168663    }
168664  }else{
168665    zSql = sqlite3_mprintf(
168666        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
168667        pRtree->zDb, pRtree->zName
168668    );
168669    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
168670    if( rc!=SQLITE_OK ){
168671      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
168672    }else if( pRtree->iNodeSize<(512-64) ){
168673      rc = SQLITE_CORRUPT;
168674      *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
168675                               pRtree->zName);
168676    }
168677  }
168678
168679  sqlite3_free(zSql);
168680  return rc;
168681}
168682
168683/*
168684** This function is the implementation of both the xConnect and xCreate
168685** methods of the r-tree virtual table.
168686**
168687**   argv[0]   -> module name
168688**   argv[1]   -> database name
168689**   argv[2]   -> table name
168690**   argv[...] -> column names...
168691*/
168692static int rtreeInit(
168693  sqlite3 *db,                        /* Database connection */
168694  void *pAux,                         /* One of the RTREE_COORD_* constants */
168695  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
168696  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
168697  char **pzErr,                       /* OUT: Error message, if any */
168698  int isCreate                        /* True for xCreate, false for xConnect */
168699){
168700  int rc = SQLITE_OK;
168701  Rtree *pRtree;
168702  int nDb;              /* Length of string argv[1] */
168703  int nName;            /* Length of string argv[2] */
168704  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
168705
168706  const char *aErrMsg[] = {
168707    0,                                                    /* 0 */
168708    "Wrong number of columns for an rtree table",         /* 1 */
168709    "Too few columns for an rtree table",                 /* 2 */
168710    "Too many columns for an rtree table"                 /* 3 */
168711  };
168712
168713  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
168714  if( aErrMsg[iErr] ){
168715    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
168716    return SQLITE_ERROR;
168717  }
168718
168719  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
168720
168721  /* Allocate the sqlite3_vtab structure */
168722  nDb = (int)strlen(argv[1]);
168723  nName = (int)strlen(argv[2]);
168724  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
168725  if( !pRtree ){
168726    return SQLITE_NOMEM;
168727  }
168728  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
168729  pRtree->nBusy = 1;
168730  pRtree->base.pModule = &rtreeModule;
168731  pRtree->zDb = (char *)&pRtree[1];
168732  pRtree->zName = &pRtree->zDb[nDb+1];
168733  pRtree->nDim = (u8)((argc-4)/2);
168734  pRtree->nDim2 = pRtree->nDim*2;
168735  pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
168736  pRtree->eCoordType = (u8)eCoordType;
168737  memcpy(pRtree->zDb, argv[1], nDb);
168738  memcpy(pRtree->zName, argv[2], nName);
168739
168740  /* Figure out the node size to use. */
168741  rc = getNodeSize(db, pRtree, isCreate, pzErr);
168742
168743  /* Create/Connect to the underlying relational database schema. If
168744  ** that is successful, call sqlite3_declare_vtab() to configure
168745  ** the r-tree table schema.
168746  */
168747  if( rc==SQLITE_OK ){
168748    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
168749      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
168750    }else{
168751      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
168752      char *zTmp;
168753      int ii;
168754      for(ii=4; zSql && ii<argc; ii++){
168755        zTmp = zSql;
168756        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
168757        sqlite3_free(zTmp);
168758      }
168759      if( zSql ){
168760        zTmp = zSql;
168761        zSql = sqlite3_mprintf("%s);", zTmp);
168762        sqlite3_free(zTmp);
168763      }
168764      if( !zSql ){
168765        rc = SQLITE_NOMEM;
168766      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
168767        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
168768      }
168769      sqlite3_free(zSql);
168770    }
168771  }
168772
168773  if( rc==SQLITE_OK ){
168774    *ppVtab = (sqlite3_vtab *)pRtree;
168775  }else{
168776    assert( *ppVtab==0 );
168777    assert( pRtree->nBusy==1 );
168778    rtreeRelease(pRtree);
168779  }
168780  return rc;
168781}
168782
168783
168784/*
168785** Implementation of a scalar function that decodes r-tree nodes to
168786** human readable strings. This can be used for debugging and analysis.
168787**
168788** The scalar function takes two arguments: (1) the number of dimensions
168789** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
168790** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
168791** deserialize all nodes, a statement like:
168792**
168793**   SELECT rtreenode(2, data) FROM rt_node;
168794**
168795** The human readable string takes the form of a Tcl list with one
168796** entry for each cell in the r-tree node. Each entry is itself a
168797** list, containing the 8-byte rowid/pageno followed by the
168798** <num-dimension>*2 coordinates.
168799*/
168800static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
168801  char *zText = 0;
168802  RtreeNode node;
168803  Rtree tree;
168804  int ii;
168805
168806  UNUSED_PARAMETER(nArg);
168807  memset(&node, 0, sizeof(RtreeNode));
168808  memset(&tree, 0, sizeof(Rtree));
168809  tree.nDim = (u8)sqlite3_value_int(apArg[0]);
168810  tree.nDim2 = tree.nDim*2;
168811  tree.nBytesPerCell = 8 + 8 * tree.nDim;
168812  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
168813
168814  for(ii=0; ii<NCELL(&node); ii++){
168815    char zCell[512];
168816    int nCell = 0;
168817    RtreeCell cell;
168818    int jj;
168819
168820    nodeGetCell(&tree, &node, ii, &cell);
168821    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
168822    nCell = (int)strlen(zCell);
168823    for(jj=0; jj<tree.nDim2; jj++){
168824#ifndef SQLITE_RTREE_INT_ONLY
168825      sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
168826                       (double)cell.aCoord[jj].f);
168827#else
168828      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
168829                       cell.aCoord[jj].i);
168830#endif
168831      nCell = (int)strlen(zCell);
168832    }
168833
168834    if( zText ){
168835      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
168836      sqlite3_free(zText);
168837      zText = zTextNew;
168838    }else{
168839      zText = sqlite3_mprintf("{%s}", zCell);
168840    }
168841  }
168842
168843  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
168844}
168845
168846/* This routine implements an SQL function that returns the "depth" parameter
168847** from the front of a blob that is an r-tree node.  For example:
168848**
168849**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
168850**
168851** The depth value is 0 for all nodes other than the root node, and the root
168852** node always has nodeno=1, so the example above is the primary use for this
168853** routine.  This routine is intended for testing and analysis only.
168854*/
168855static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
168856  UNUSED_PARAMETER(nArg);
168857  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
168858   || sqlite3_value_bytes(apArg[0])<2
168859  ){
168860    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
168861  }else{
168862    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
168863    sqlite3_result_int(ctx, readInt16(zBlob));
168864  }
168865}
168866
168867/*
168868** Register the r-tree module with database handle db. This creates the
168869** virtual table module "rtree" and the debugging/analysis scalar
168870** function "rtreenode".
168871*/
168872SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
168873  const int utf8 = SQLITE_UTF8;
168874  int rc;
168875
168876  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
168877  if( rc==SQLITE_OK ){
168878    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
168879  }
168880  if( rc==SQLITE_OK ){
168881#ifdef SQLITE_RTREE_INT_ONLY
168882    void *c = (void *)RTREE_COORD_INT32;
168883#else
168884    void *c = (void *)RTREE_COORD_REAL32;
168885#endif
168886    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
168887  }
168888  if( rc==SQLITE_OK ){
168889    void *c = (void *)RTREE_COORD_INT32;
168890    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
168891  }
168892
168893  return rc;
168894}
168895
168896/*
168897** This routine deletes the RtreeGeomCallback object that was attached
168898** one of the SQL functions create by sqlite3_rtree_geometry_callback()
168899** or sqlite3_rtree_query_callback().  In other words, this routine is the
168900** destructor for an RtreeGeomCallback objecct.  This routine is called when
168901** the corresponding SQL function is deleted.
168902*/
168903static void rtreeFreeCallback(void *p){
168904  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
168905  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
168906  sqlite3_free(p);
168907}
168908
168909/*
168910** This routine frees the BLOB that is returned by geomCallback().
168911*/
168912static void rtreeMatchArgFree(void *pArg){
168913  int i;
168914  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
168915  for(i=0; i<p->nParam; i++){
168916    sqlite3_value_free(p->apSqlParam[i]);
168917  }
168918  sqlite3_free(p);
168919}
168920
168921/*
168922** Each call to sqlite3_rtree_geometry_callback() or
168923** sqlite3_rtree_query_callback() creates an ordinary SQLite
168924** scalar function that is implemented by this routine.
168925**
168926** All this function does is construct an RtreeMatchArg object that
168927** contains the geometry-checking callback routines and a list of
168928** parameters to this function, then return that RtreeMatchArg object
168929** as a BLOB.
168930**
168931** The R-Tree MATCH operator will read the returned BLOB, deserialize
168932** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
168933** out which elements of the R-Tree should be returned by the query.
168934*/
168935static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
168936  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
168937  RtreeMatchArg *pBlob;
168938  int nBlob;
168939  int memErr = 0;
168940
168941  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
168942           + nArg*sizeof(sqlite3_value*);
168943  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
168944  if( !pBlob ){
168945    sqlite3_result_error_nomem(ctx);
168946  }else{
168947    int i;
168948    pBlob->iSize = nBlob;
168949    pBlob->cb = pGeomCtx[0];
168950    pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
168951    pBlob->nParam = nArg;
168952    for(i=0; i<nArg; i++){
168953      pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
168954      if( pBlob->apSqlParam[i]==0 ) memErr = 1;
168955#ifdef SQLITE_RTREE_INT_ONLY
168956      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
168957#else
168958      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
168959#endif
168960    }
168961    if( memErr ){
168962      sqlite3_result_error_nomem(ctx);
168963      rtreeMatchArgFree(pBlob);
168964    }else{
168965      sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
168966    }
168967  }
168968}
168969
168970/*
168971** Register a new geometry function for use with the r-tree MATCH operator.
168972*/
168973SQLITE_API int sqlite3_rtree_geometry_callback(
168974  sqlite3 *db,                  /* Register SQL function on this connection */
168975  const char *zGeom,            /* Name of the new SQL function */
168976  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
168977  void *pContext                /* Extra data associated with the callback */
168978){
168979  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
168980
168981  /* Allocate and populate the context object. */
168982  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
168983  if( !pGeomCtx ) return SQLITE_NOMEM;
168984  pGeomCtx->xGeom = xGeom;
168985  pGeomCtx->xQueryFunc = 0;
168986  pGeomCtx->xDestructor = 0;
168987  pGeomCtx->pContext = pContext;
168988  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
168989      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
168990  );
168991}
168992
168993/*
168994** Register a new 2nd-generation geometry function for use with the
168995** r-tree MATCH operator.
168996*/
168997SQLITE_API int sqlite3_rtree_query_callback(
168998  sqlite3 *db,                 /* Register SQL function on this connection */
168999  const char *zQueryFunc,      /* Name of new SQL function */
169000  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
169001  void *pContext,              /* Extra data passed into the callback */
169002  void (*xDestructor)(void*)   /* Destructor for the extra data */
169003){
169004  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
169005
169006  /* Allocate and populate the context object. */
169007  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
169008  if( !pGeomCtx ) return SQLITE_NOMEM;
169009  pGeomCtx->xGeom = 0;
169010  pGeomCtx->xQueryFunc = xQueryFunc;
169011  pGeomCtx->xDestructor = xDestructor;
169012  pGeomCtx->pContext = pContext;
169013  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
169014      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
169015  );
169016}
169017
169018#if !SQLITE_CORE
169019#ifdef _WIN32
169020__declspec(dllexport)
169021#endif
169022SQLITE_API int sqlite3_rtree_init(
169023  sqlite3 *db,
169024  char **pzErrMsg,
169025  const sqlite3_api_routines *pApi
169026){
169027  SQLITE_EXTENSION_INIT2(pApi)
169028  return sqlite3RtreeInit(db);
169029}
169030#endif
169031
169032#endif
169033
169034/************** End of rtree.c ***********************************************/
169035/************** Begin file icu.c *********************************************/
169036/*
169037** 2007 May 6
169038**
169039** The author disclaims copyright to this source code.  In place of
169040** a legal notice, here is a blessing:
169041**
169042**    May you do good and not evil.
169043**    May you find forgiveness for yourself and forgive others.
169044**    May you share freely, never taking more than you give.
169045**
169046*************************************************************************
169047** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
169048**
169049** This file implements an integration between the ICU library
169050** ("International Components for Unicode", an open-source library
169051** for handling unicode data) and SQLite. The integration uses
169052** ICU to provide the following to SQLite:
169053**
169054**   * An implementation of the SQL regexp() function (and hence REGEXP
169055**     operator) using the ICU uregex_XX() APIs.
169056**
169057**   * Implementations of the SQL scalar upper() and lower() functions
169058**     for case mapping.
169059**
169060**   * Integration of ICU and SQLite collation sequences.
169061**
169062**   * An implementation of the LIKE operator that uses ICU to
169063**     provide case-independent matching.
169064*/
169065
169066#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
169067
169068/* Include ICU headers */
169069#include <unicode/utypes.h>
169070#include <unicode/uregex.h>
169071#include <unicode/ustring.h>
169072#include <unicode/ucol.h>
169073
169074/* #include <assert.h> */
169075
169076#ifndef SQLITE_CORE
169077/*   #include "sqlite3ext.h" */
169078  SQLITE_EXTENSION_INIT1
169079#else
169080/*   #include "sqlite3.h" */
169081#endif
169082
169083/*
169084** Maximum length (in bytes) of the pattern in a LIKE or GLOB
169085** operator.
169086*/
169087#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
169088# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
169089#endif
169090
169091/*
169092** Version of sqlite3_free() that is always a function, never a macro.
169093*/
169094static void xFree(void *p){
169095  sqlite3_free(p);
169096}
169097
169098/*
169099** This lookup table is used to help decode the first byte of
169100** a multi-byte UTF8 character. It is copied here from SQLite source
169101** code file utf8.c.
169102*/
169103static const unsigned char icuUtf8Trans1[] = {
169104  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169105  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
169106  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
169107  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
169108  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169109  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
169110  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
169111  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
169112};
169113
169114#define SQLITE_ICU_READ_UTF8(zIn, c)                       \
169115  c = *(zIn++);                                            \
169116  if( c>=0xc0 ){                                           \
169117    c = icuUtf8Trans1[c-0xc0];                             \
169118    while( (*zIn & 0xc0)==0x80 ){                          \
169119      c = (c<<6) + (0x3f & *(zIn++));                      \
169120    }                                                      \
169121  }
169122
169123#define SQLITE_ICU_SKIP_UTF8(zIn)                          \
169124  assert( *zIn );                                          \
169125  if( *(zIn++)>=0xc0 ){                                    \
169126    while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
169127  }
169128
169129
169130/*
169131** Compare two UTF-8 strings for equality where the first string is
169132** a "LIKE" expression. Return true (1) if they are the same and
169133** false (0) if they are different.
169134*/
169135static int icuLikeCompare(
169136  const uint8_t *zPattern,   /* LIKE pattern */
169137  const uint8_t *zString,    /* The UTF-8 string to compare against */
169138  const UChar32 uEsc         /* The escape character */
169139){
169140  static const int MATCH_ONE = (UChar32)'_';
169141  static const int MATCH_ALL = (UChar32)'%';
169142
169143  int prevEscape = 0;     /* True if the previous character was uEsc */
169144
169145  while( 1 ){
169146
169147    /* Read (and consume) the next character from the input pattern. */
169148    UChar32 uPattern;
169149    SQLITE_ICU_READ_UTF8(zPattern, uPattern);
169150    if( uPattern==0 ) break;
169151
169152    /* There are now 4 possibilities:
169153    **
169154    **     1. uPattern is an unescaped match-all character "%",
169155    **     2. uPattern is an unescaped match-one character "_",
169156    **     3. uPattern is an unescaped escape character, or
169157    **     4. uPattern is to be handled as an ordinary character
169158    */
169159    if( !prevEscape && uPattern==MATCH_ALL ){
169160      /* Case 1. */
169161      uint8_t c;
169162
169163      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
169164      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
169165      ** test string.
169166      */
169167      while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
169168        if( c==MATCH_ONE ){
169169          if( *zString==0 ) return 0;
169170          SQLITE_ICU_SKIP_UTF8(zString);
169171        }
169172        zPattern++;
169173      }
169174
169175      if( *zPattern==0 ) return 1;
169176
169177      while( *zString ){
169178        if( icuLikeCompare(zPattern, zString, uEsc) ){
169179          return 1;
169180        }
169181        SQLITE_ICU_SKIP_UTF8(zString);
169182      }
169183      return 0;
169184
169185    }else if( !prevEscape && uPattern==MATCH_ONE ){
169186      /* Case 2. */
169187      if( *zString==0 ) return 0;
169188      SQLITE_ICU_SKIP_UTF8(zString);
169189
169190    }else if( !prevEscape && uPattern==uEsc){
169191      /* Case 3. */
169192      prevEscape = 1;
169193
169194    }else{
169195      /* Case 4. */
169196      UChar32 uString;
169197      SQLITE_ICU_READ_UTF8(zString, uString);
169198      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
169199      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
169200      if( uString!=uPattern ){
169201        return 0;
169202      }
169203      prevEscape = 0;
169204    }
169205  }
169206
169207  return *zString==0;
169208}
169209
169210/*
169211** Implementation of the like() SQL function.  This function implements
169212** the build-in LIKE operator.  The first argument to the function is the
169213** pattern and the second argument is the string.  So, the SQL statements:
169214**
169215**       A LIKE B
169216**
169217** is implemented as like(B, A). If there is an escape character E,
169218**
169219**       A LIKE B ESCAPE E
169220**
169221** is mapped to like(B, A, E).
169222*/
169223static void icuLikeFunc(
169224  sqlite3_context *context,
169225  int argc,
169226  sqlite3_value **argv
169227){
169228  const unsigned char *zA = sqlite3_value_text(argv[0]);
169229  const unsigned char *zB = sqlite3_value_text(argv[1]);
169230  UChar32 uEsc = 0;
169231
169232  /* Limit the length of the LIKE or GLOB pattern to avoid problems
169233  ** of deep recursion and N*N behavior in patternCompare().
169234  */
169235  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
169236    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
169237    return;
169238  }
169239
169240
169241  if( argc==3 ){
169242    /* The escape character string must consist of a single UTF-8 character.
169243    ** Otherwise, return an error.
169244    */
169245    int nE= sqlite3_value_bytes(argv[2]);
169246    const unsigned char *zE = sqlite3_value_text(argv[2]);
169247    int i = 0;
169248    if( zE==0 ) return;
169249    U8_NEXT(zE, i, nE, uEsc);
169250    if( i!=nE){
169251      sqlite3_result_error(context,
169252          "ESCAPE expression must be a single character", -1);
169253      return;
169254    }
169255  }
169256
169257  if( zA && zB ){
169258    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
169259  }
169260}
169261
169262/*
169263** This function is called when an ICU function called from within
169264** the implementation of an SQL scalar function returns an error.
169265**
169266** The scalar function context passed as the first argument is
169267** loaded with an error message based on the following two args.
169268*/
169269static void icuFunctionError(
169270  sqlite3_context *pCtx,       /* SQLite scalar function context */
169271  const char *zName,           /* Name of ICU function that failed */
169272  UErrorCode e                 /* Error code returned by ICU function */
169273){
169274  char zBuf[128];
169275  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
169276  zBuf[127] = '\0';
169277  sqlite3_result_error(pCtx, zBuf, -1);
169278}
169279
169280/*
169281** Function to delete compiled regexp objects. Registered as
169282** a destructor function with sqlite3_set_auxdata().
169283*/
169284static void icuRegexpDelete(void *p){
169285  URegularExpression *pExpr = (URegularExpression *)p;
169286  uregex_close(pExpr);
169287}
169288
169289/*
169290** Implementation of SQLite REGEXP operator. This scalar function takes
169291** two arguments. The first is a regular expression pattern to compile
169292** the second is a string to match against that pattern. If either
169293** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
169294** is 1 if the string matches the pattern, or 0 otherwise.
169295**
169296** SQLite maps the regexp() function to the regexp() operator such
169297** that the following two are equivalent:
169298**
169299**     zString REGEXP zPattern
169300**     regexp(zPattern, zString)
169301**
169302** Uses the following ICU regexp APIs:
169303**
169304**     uregex_open()
169305**     uregex_matches()
169306**     uregex_close()
169307*/
169308static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
169309  UErrorCode status = U_ZERO_ERROR;
169310  URegularExpression *pExpr;
169311  UBool res;
169312  const UChar *zString = sqlite3_value_text16(apArg[1]);
169313
169314  (void)nArg;  /* Unused parameter */
169315
169316  /* If the left hand side of the regexp operator is NULL,
169317  ** then the result is also NULL.
169318  */
169319  if( !zString ){
169320    return;
169321  }
169322
169323  pExpr = sqlite3_get_auxdata(p, 0);
169324  if( !pExpr ){
169325    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
169326    if( !zPattern ){
169327      return;
169328    }
169329    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
169330
169331    if( U_SUCCESS(status) ){
169332      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
169333    }else{
169334      assert(!pExpr);
169335      icuFunctionError(p, "uregex_open", status);
169336      return;
169337    }
169338  }
169339
169340  /* Configure the text that the regular expression operates on. */
169341  uregex_setText(pExpr, zString, -1, &status);
169342  if( !U_SUCCESS(status) ){
169343    icuFunctionError(p, "uregex_setText", status);
169344    return;
169345  }
169346
169347  /* Attempt the match */
169348  res = uregex_matches(pExpr, 0, &status);
169349  if( !U_SUCCESS(status) ){
169350    icuFunctionError(p, "uregex_matches", status);
169351    return;
169352  }
169353
169354  /* Set the text that the regular expression operates on to a NULL
169355  ** pointer. This is not really necessary, but it is tidier than
169356  ** leaving the regular expression object configured with an invalid
169357  ** pointer after this function returns.
169358  */
169359  uregex_setText(pExpr, 0, 0, &status);
169360
169361  /* Return 1 or 0. */
169362  sqlite3_result_int(p, res ? 1 : 0);
169363}
169364
169365/*
169366** Implementations of scalar functions for case mapping - upper() and
169367** lower(). Function upper() converts its input to upper-case (ABC).
169368** Function lower() converts to lower-case (abc).
169369**
169370** ICU provides two types of case mapping, "general" case mapping and
169371** "language specific". Refer to ICU documentation for the differences
169372** between the two.
169373**
169374** To utilise "general" case mapping, the upper() or lower() scalar
169375** functions are invoked with one argument:
169376**
169377**     upper('ABC') -> 'abc'
169378**     lower('abc') -> 'ABC'
169379**
169380** To access ICU "language specific" case mapping, upper() or lower()
169381** should be invoked with two arguments. The second argument is the name
169382** of the locale to use. Passing an empty string ("") or SQL NULL value
169383** as the second argument is the same as invoking the 1 argument version
169384** of upper() or lower().
169385**
169386**     lower('I', 'en_us') -> 'i'
169387**     lower('I', 'tr_tr') -> '\u131' (small dotless i)
169388**
169389** http://www.icu-project.org/userguide/posix.html#case_mappings
169390*/
169391static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
169392  const UChar *zInput;            /* Pointer to input string */
169393  UChar *zOutput = 0;             /* Pointer to output buffer */
169394  int nInput;                     /* Size of utf-16 input string in bytes */
169395  int nOut;                       /* Size of output buffer in bytes */
169396  int cnt;
169397  int bToUpper;                   /* True for toupper(), false for tolower() */
169398  UErrorCode status;
169399  const char *zLocale = 0;
169400
169401  assert(nArg==1 || nArg==2);
169402  bToUpper = (sqlite3_user_data(p)!=0);
169403  if( nArg==2 ){
169404    zLocale = (const char *)sqlite3_value_text(apArg[1]);
169405  }
169406
169407  zInput = sqlite3_value_text16(apArg[0]);
169408  if( !zInput ){
169409    return;
169410  }
169411  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
169412  if( nOut==0 ){
169413    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
169414    return;
169415  }
169416
169417  for(cnt=0; cnt<2; cnt++){
169418    UChar *zNew = sqlite3_realloc(zOutput, nOut);
169419    if( zNew==0 ){
169420      sqlite3_free(zOutput);
169421      sqlite3_result_error_nomem(p);
169422      return;
169423    }
169424    zOutput = zNew;
169425    status = U_ZERO_ERROR;
169426    if( bToUpper ){
169427      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
169428    }else{
169429      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
169430    }
169431
169432    if( U_SUCCESS(status) ){
169433      sqlite3_result_text16(p, zOutput, nOut, xFree);
169434    }else if( status==U_BUFFER_OVERFLOW_ERROR ){
169435      assert( cnt==0 );
169436      continue;
169437    }else{
169438      icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
169439    }
169440    return;
169441  }
169442  assert( 0 );     /* Unreachable */
169443}
169444
169445/*
169446** Collation sequence destructor function. The pCtx argument points to
169447** a UCollator structure previously allocated using ucol_open().
169448*/
169449static void icuCollationDel(void *pCtx){
169450  UCollator *p = (UCollator *)pCtx;
169451  ucol_close(p);
169452}
169453
169454/*
169455** Collation sequence comparison function. The pCtx argument points to
169456** a UCollator structure previously allocated using ucol_open().
169457*/
169458static int icuCollationColl(
169459  void *pCtx,
169460  int nLeft,
169461  const void *zLeft,
169462  int nRight,
169463  const void *zRight
169464){
169465  UCollationResult res;
169466  UCollator *p = (UCollator *)pCtx;
169467  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
169468  switch( res ){
169469    case UCOL_LESS:    return -1;
169470    case UCOL_GREATER: return +1;
169471    case UCOL_EQUAL:   return 0;
169472  }
169473  assert(!"Unexpected return value from ucol_strcoll()");
169474  return 0;
169475}
169476
169477/*
169478** Implementation of the scalar function icu_load_collation().
169479**
169480** This scalar function is used to add ICU collation based collation
169481** types to an SQLite database connection. It is intended to be called
169482** as follows:
169483**
169484**     SELECT icu_load_collation(<locale>, <collation-name>);
169485**
169486** Where <locale> is a string containing an ICU locale identifier (i.e.
169487** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
169488** collation sequence to create.
169489*/
169490static void icuLoadCollation(
169491  sqlite3_context *p,
169492  int nArg,
169493  sqlite3_value **apArg
169494){
169495  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
169496  UErrorCode status = U_ZERO_ERROR;
169497  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
169498  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
169499  UCollator *pUCollator;    /* ICU library collation object */
169500  int rc;                   /* Return code from sqlite3_create_collation_x() */
169501
169502  assert(nArg==2);
169503  (void)nArg; /* Unused parameter */
169504  zLocale = (const char *)sqlite3_value_text(apArg[0]);
169505  zName = (const char *)sqlite3_value_text(apArg[1]);
169506
169507  if( !zLocale || !zName ){
169508    return;
169509  }
169510
169511  pUCollator = ucol_open(zLocale, &status);
169512  if( !U_SUCCESS(status) ){
169513    icuFunctionError(p, "ucol_open", status);
169514    return;
169515  }
169516  assert(p);
169517
169518  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
169519      icuCollationColl, icuCollationDel
169520  );
169521  if( rc!=SQLITE_OK ){
169522    ucol_close(pUCollator);
169523    sqlite3_result_error(p, "Error registering collation function", -1);
169524  }
169525}
169526
169527/*
169528** Register the ICU extension functions with database db.
169529*/
169530SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
169531  static const struct IcuScalar {
169532    const char *zName;                        /* Function name */
169533    unsigned char nArg;                       /* Number of arguments */
169534    unsigned short enc;                       /* Optimal text encoding */
169535    unsigned char iContext;                   /* sqlite3_user_data() context */
169536    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
169537  } scalars[] = {
169538    {"icu_load_collation",  2, SQLITE_UTF8,                1, icuLoadCollation},
169539    {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC,         0, icuRegexpFunc},
169540    {"lower",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
169541    {"lower",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
169542    {"upper",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
169543    {"upper",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
169544    {"lower",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
169545    {"lower",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
169546    {"upper",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
169547    {"upper",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
169548    {"like",   2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
169549    {"like",   3, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
169550  };
169551  int rc = SQLITE_OK;
169552  int i;
169553
169554
169555  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
169556    const struct IcuScalar *p = &scalars[i];
169557    rc = sqlite3_create_function(
169558        db, p->zName, p->nArg, p->enc,
169559        p->iContext ? (void*)db : (void*)0,
169560        p->xFunc, 0, 0
169561    );
169562  }
169563
169564  return rc;
169565}
169566
169567#if !SQLITE_CORE
169568#ifdef _WIN32
169569__declspec(dllexport)
169570#endif
169571SQLITE_API int sqlite3_icu_init(
169572  sqlite3 *db,
169573  char **pzErrMsg,
169574  const sqlite3_api_routines *pApi
169575){
169576  SQLITE_EXTENSION_INIT2(pApi)
169577  return sqlite3IcuInit(db);
169578}
169579#endif
169580
169581#endif
169582
169583/************** End of icu.c *************************************************/
169584/************** Begin file fts3_icu.c ****************************************/
169585/*
169586** 2007 June 22
169587**
169588** The author disclaims copyright to this source code.  In place of
169589** a legal notice, here is a blessing:
169590**
169591**    May you do good and not evil.
169592**    May you find forgiveness for yourself and forgive others.
169593**    May you share freely, never taking more than you give.
169594**
169595*************************************************************************
169596** This file implements a tokenizer for fts3 based on the ICU library.
169597*/
169598/* #include "fts3Int.h" */
169599#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
169600#ifdef SQLITE_ENABLE_ICU
169601
169602/* #include <assert.h> */
169603/* #include <string.h> */
169604/* #include "fts3_tokenizer.h" */
169605
169606#include <unicode/ubrk.h>
169607/* #include <unicode/ucol.h> */
169608/* #include <unicode/ustring.h> */
169609#include <unicode/utf16.h>
169610
169611typedef struct IcuTokenizer IcuTokenizer;
169612typedef struct IcuCursor IcuCursor;
169613
169614struct IcuTokenizer {
169615  sqlite3_tokenizer base;
169616  char *zLocale;
169617};
169618
169619struct IcuCursor {
169620  sqlite3_tokenizer_cursor base;
169621
169622  UBreakIterator *pIter;      /* ICU break-iterator object */
169623  int nChar;                  /* Number of UChar elements in pInput */
169624  UChar *aChar;               /* Copy of input using utf-16 encoding */
169625  int *aOffset;               /* Offsets of each character in utf-8 input */
169626
169627  int nBuffer;
169628  char *zBuffer;
169629
169630  int iToken;
169631};
169632
169633/*
169634** Create a new tokenizer instance.
169635*/
169636static int icuCreate(
169637  int argc,                            /* Number of entries in argv[] */
169638  const char * const *argv,            /* Tokenizer creation arguments */
169639  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
169640){
169641  IcuTokenizer *p;
169642  int n = 0;
169643
169644  if( argc>0 ){
169645    n = strlen(argv[0])+1;
169646  }
169647  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
169648  if( !p ){
169649    return SQLITE_NOMEM;
169650  }
169651  memset(p, 0, sizeof(IcuTokenizer));
169652
169653  if( n ){
169654    p->zLocale = (char *)&p[1];
169655    memcpy(p->zLocale, argv[0], n);
169656  }
169657
169658  *ppTokenizer = (sqlite3_tokenizer *)p;
169659
169660  return SQLITE_OK;
169661}
169662
169663/*
169664** Destroy a tokenizer
169665*/
169666static int icuDestroy(sqlite3_tokenizer *pTokenizer){
169667  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
169668  sqlite3_free(p);
169669  return SQLITE_OK;
169670}
169671
169672/*
169673** Prepare to begin tokenizing a particular string.  The input
169674** string to be tokenized is pInput[0..nBytes-1].  A cursor
169675** used to incrementally tokenize this string is returned in
169676** *ppCursor.
169677*/
169678static int icuOpen(
169679  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
169680  const char *zInput,                    /* Input string */
169681  int nInput,                            /* Length of zInput in bytes */
169682  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
169683){
169684  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
169685  IcuCursor *pCsr;
169686
169687  const int32_t opt = U_FOLD_CASE_DEFAULT;
169688  UErrorCode status = U_ZERO_ERROR;
169689  int nChar;
169690
169691  UChar32 c;
169692  int iInput = 0;
169693  int iOut = 0;
169694
169695  *ppCursor = 0;
169696
169697  if( zInput==0 ){
169698    nInput = 0;
169699    zInput = "";
169700  }else if( nInput<0 ){
169701    nInput = strlen(zInput);
169702  }
169703  nChar = nInput+1;
169704  pCsr = (IcuCursor *)sqlite3_malloc(
169705      sizeof(IcuCursor) +                /* IcuCursor */
169706      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
169707      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
169708  );
169709  if( !pCsr ){
169710    return SQLITE_NOMEM;
169711  }
169712  memset(pCsr, 0, sizeof(IcuCursor));
169713  pCsr->aChar = (UChar *)&pCsr[1];
169714  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
169715
169716  pCsr->aOffset[iOut] = iInput;
169717  U8_NEXT(zInput, iInput, nInput, c);
169718  while( c>0 ){
169719    int isError = 0;
169720    c = u_foldCase(c, opt);
169721    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
169722    if( isError ){
169723      sqlite3_free(pCsr);
169724      return SQLITE_ERROR;
169725    }
169726    pCsr->aOffset[iOut] = iInput;
169727
169728    if( iInput<nInput ){
169729      U8_NEXT(zInput, iInput, nInput, c);
169730    }else{
169731      c = 0;
169732    }
169733  }
169734
169735  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
169736  if( !U_SUCCESS(status) ){
169737    sqlite3_free(pCsr);
169738    return SQLITE_ERROR;
169739  }
169740  pCsr->nChar = iOut;
169741
169742  ubrk_first(pCsr->pIter);
169743  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
169744  return SQLITE_OK;
169745}
169746
169747/*
169748** Close a tokenization cursor previously opened by a call to icuOpen().
169749*/
169750static int icuClose(sqlite3_tokenizer_cursor *pCursor){
169751  IcuCursor *pCsr = (IcuCursor *)pCursor;
169752  ubrk_close(pCsr->pIter);
169753  sqlite3_free(pCsr->zBuffer);
169754  sqlite3_free(pCsr);
169755  return SQLITE_OK;
169756}
169757
169758/*
169759** Extract the next token from a tokenization cursor.
169760*/
169761static int icuNext(
169762  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
169763  const char **ppToken,               /* OUT: *ppToken is the token text */
169764  int *pnBytes,                       /* OUT: Number of bytes in token */
169765  int *piStartOffset,                 /* OUT: Starting offset of token */
169766  int *piEndOffset,                   /* OUT: Ending offset of token */
169767  int *piPosition                     /* OUT: Position integer of token */
169768){
169769  IcuCursor *pCsr = (IcuCursor *)pCursor;
169770
169771  int iStart = 0;
169772  int iEnd = 0;
169773  int nByte = 0;
169774
169775  while( iStart==iEnd ){
169776    UChar32 c;
169777
169778    iStart = ubrk_current(pCsr->pIter);
169779    iEnd = ubrk_next(pCsr->pIter);
169780    if( iEnd==UBRK_DONE ){
169781      return SQLITE_DONE;
169782    }
169783
169784    while( iStart<iEnd ){
169785      int iWhite = iStart;
169786      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
169787      if( u_isspace(c) ){
169788        iStart = iWhite;
169789      }else{
169790        break;
169791      }
169792    }
169793    assert(iStart<=iEnd);
169794  }
169795
169796  do {
169797    UErrorCode status = U_ZERO_ERROR;
169798    if( nByte ){
169799      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
169800      if( !zNew ){
169801        return SQLITE_NOMEM;
169802      }
169803      pCsr->zBuffer = zNew;
169804      pCsr->nBuffer = nByte;
169805    }
169806
169807    u_strToUTF8(
169808        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
169809        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
169810        &status                                  /* Output success/failure */
169811    );
169812  } while( nByte>pCsr->nBuffer );
169813
169814  *ppToken = pCsr->zBuffer;
169815  *pnBytes = nByte;
169816  *piStartOffset = pCsr->aOffset[iStart];
169817  *piEndOffset = pCsr->aOffset[iEnd];
169818  *piPosition = pCsr->iToken++;
169819
169820  return SQLITE_OK;
169821}
169822
169823/*
169824** The set of routines that implement the simple tokenizer
169825*/
169826static const sqlite3_tokenizer_module icuTokenizerModule = {
169827  0,                           /* iVersion    */
169828  icuCreate,                   /* xCreate     */
169829  icuDestroy,                  /* xCreate     */
169830  icuOpen,                     /* xOpen       */
169831  icuClose,                    /* xClose      */
169832  icuNext,                     /* xNext       */
169833  0,                           /* xLanguageid */
169834};
169835
169836/*
169837** Set *ppModule to point at the implementation of the ICU tokenizer.
169838*/
169839SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
169840  sqlite3_tokenizer_module const**ppModule
169841){
169842  *ppModule = &icuTokenizerModule;
169843}
169844
169845#endif /* defined(SQLITE_ENABLE_ICU) */
169846#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
169847
169848/************** End of fts3_icu.c ********************************************/
169849/************** Begin file sqlite3rbu.c **************************************/
169850/*
169851** 2014 August 30
169852**
169853** The author disclaims copyright to this source code.  In place of
169854** a legal notice, here is a blessing:
169855**
169856**    May you do good and not evil.
169857**    May you find forgiveness for yourself and forgive others.
169858**    May you share freely, never taking more than you give.
169859**
169860*************************************************************************
169861**
169862**
169863** OVERVIEW
169864**
169865**  The RBU extension requires that the RBU update be packaged as an
169866**  SQLite database. The tables it expects to find are described in
169867**  sqlite3rbu.h.  Essentially, for each table xyz in the target database
169868**  that the user wishes to write to, a corresponding data_xyz table is
169869**  created in the RBU database and populated with one row for each row to
169870**  update, insert or delete from the target table.
169871**
169872**  The update proceeds in three stages:
169873**
169874**  1) The database is updated. The modified database pages are written
169875**     to a *-oal file. A *-oal file is just like a *-wal file, except
169876**     that it is named "<database>-oal" instead of "<database>-wal".
169877**     Because regular SQLite clients do not look for file named
169878**     "<database>-oal", they go on using the original database in
169879**     rollback mode while the *-oal file is being generated.
169880**
169881**     During this stage RBU does not update the database by writing
169882**     directly to the target tables. Instead it creates "imposter"
169883**     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
169884**     to update each b-tree individually. All updates required by each
169885**     b-tree are completed before moving on to the next, and all
169886**     updates are done in sorted key order.
169887**
169888**  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
169889**     location using a call to rename(2). Before doing this the RBU
169890**     module takes an EXCLUSIVE lock on the database file, ensuring
169891**     that there are no other active readers.
169892**
169893**     Once the EXCLUSIVE lock is released, any other database readers
169894**     detect the new *-wal file and read the database in wal mode. At
169895**     this point they see the new version of the database - including
169896**     the updates made as part of the RBU update.
169897**
169898**  3) The new *-wal file is checkpointed. This proceeds in the same way
169899**     as a regular database checkpoint, except that a single frame is
169900**     checkpointed each time sqlite3rbu_step() is called. If the RBU
169901**     handle is closed before the entire *-wal file is checkpointed,
169902**     the checkpoint progress is saved in the RBU database and the
169903**     checkpoint can be resumed by another RBU client at some point in
169904**     the future.
169905**
169906** POTENTIAL PROBLEMS
169907**
169908**  The rename() call might not be portable. And RBU is not currently
169909**  syncing the directory after renaming the file.
169910**
169911**  When state is saved, any commit to the *-oal file and the commit to
169912**  the RBU update database are not atomic. So if the power fails at the
169913**  wrong moment they might get out of sync. As the main database will be
169914**  committed before the RBU update database this will likely either just
169915**  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
169916**  constraint violations).
169917**
169918**  If some client does modify the target database mid RBU update, or some
169919**  other error occurs, the RBU extension will keep throwing errors. It's
169920**  not really clear how to get out of this state. The system could just
169921**  by delete the RBU update database and *-oal file and have the device
169922**  download the update again and start over.
169923**
169924**  At present, for an UPDATE, both the new.* and old.* records are
169925**  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
169926**  fields are collected.  This means we're probably writing a lot more
169927**  data to disk when saving the state of an ongoing update to the RBU
169928**  update database than is strictly necessary.
169929**
169930*/
169931
169932/* #include <assert.h> */
169933/* #include <string.h> */
169934/* #include <stdio.h> */
169935
169936/* #include "sqlite3.h" */
169937
169938#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
169939/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
169940/************** Begin file sqlite3rbu.h **************************************/
169941/*
169942** 2014 August 30
169943**
169944** The author disclaims copyright to this source code.  In place of
169945** a legal notice, here is a blessing:
169946**
169947**    May you do good and not evil.
169948**    May you find forgiveness for yourself and forgive others.
169949**    May you share freely, never taking more than you give.
169950**
169951*************************************************************************
169952**
169953** This file contains the public interface for the RBU extension.
169954*/
169955
169956/*
169957** SUMMARY
169958**
169959** Writing a transaction containing a large number of operations on
169960** b-tree indexes that are collectively larger than the available cache
169961** memory can be very inefficient.
169962**
169963** The problem is that in order to update a b-tree, the leaf page (at least)
169964** containing the entry being inserted or deleted must be modified. If the
169965** working set of leaves is larger than the available cache memory, then a
169966** single leaf that is modified more than once as part of the transaction
169967** may be loaded from or written to the persistent media multiple times.
169968** Additionally, because the index updates are likely to be applied in
169969** random order, access to pages within the database is also likely to be in
169970** random order, which is itself quite inefficient.
169971**
169972** One way to improve the situation is to sort the operations on each index
169973** by index key before applying them to the b-tree. This leads to an IO
169974** pattern that resembles a single linear scan through the index b-tree,
169975** and all but guarantees each modified leaf page is loaded and stored
169976** exactly once. SQLite uses this trick to improve the performance of
169977** CREATE INDEX commands. This extension allows it to be used to improve
169978** the performance of large transactions on existing databases.
169979**
169980** Additionally, this extension allows the work involved in writing the
169981** large transaction to be broken down into sub-transactions performed
169982** sequentially by separate processes. This is useful if the system cannot
169983** guarantee that a single update process will run for long enough to apply
169984** the entire update, for example because the update is being applied on a
169985** mobile device that is frequently rebooted. Even after the writer process
169986** has committed one or more sub-transactions, other database clients continue
169987** to read from the original database snapshot. In other words, partially
169988** applied transactions are not visible to other clients.
169989**
169990** "RBU" stands for "Resumable Bulk Update". As in a large database update
169991** transmitted via a wireless network to a mobile device. A transaction
169992** applied using this extension is hence refered to as an "RBU update".
169993**
169994**
169995** LIMITATIONS
169996**
169997** An "RBU update" transaction is subject to the following limitations:
169998**
169999**   * The transaction must consist of INSERT, UPDATE and DELETE operations
170000**     only.
170001**
170002**   * INSERT statements may not use any default values.
170003**
170004**   * UPDATE and DELETE statements must identify their target rows by
170005**     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
170006**     KEY fields may not be updated or deleted. If the table being written
170007**     has no PRIMARY KEY, affected rows must be identified by rowid.
170008**
170009**   * UPDATE statements may not modify PRIMARY KEY columns.
170010**
170011**   * No triggers will be fired.
170012**
170013**   * No foreign key violations are detected or reported.
170014**
170015**   * CHECK constraints are not enforced.
170016**
170017**   * No constraint handling mode except for "OR ROLLBACK" is supported.
170018**
170019**
170020** PREPARATION
170021**
170022** An "RBU update" is stored as a separate SQLite database. A database
170023** containing an RBU update is an "RBU database". For each table in the
170024** target database to be updated, the RBU database should contain a table
170025** named "data_<target name>" containing the same set of columns as the
170026** target table, and one more - "rbu_control". The data_% table should
170027** have no PRIMARY KEY or UNIQUE constraints, but each column should have
170028** the same type as the corresponding column in the target database.
170029** The "rbu_control" column should have no type at all. For example, if
170030** the target database contains:
170031**
170032**   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
170033**
170034** Then the RBU database should contain:
170035**
170036**   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
170037**
170038** The order of the columns in the data_% table does not matter.
170039**
170040** Instead of a regular table, the RBU database may also contain virtual
170041** tables or view named using the data_<target> naming scheme.
170042**
170043** Instead of the plain data_<target> naming scheme, RBU database tables
170044** may also be named data<integer>_<target>, where <integer> is any sequence
170045** of zero or more numeric characters (0-9). This can be significant because
170046** tables within the RBU database are always processed in order sorted by
170047** name. By judicious selection of the <integer> portion of the names
170048** of the RBU tables the user can therefore control the order in which they
170049** are processed. This can be useful, for example, to ensure that "external
170050** content" FTS4 tables are updated before their underlying content tables.
170051**
170052** If the target database table is a virtual table or a table that has no
170053** PRIMARY KEY declaration, the data_% table must also contain a column
170054** named "rbu_rowid". This column is mapped to the tables implicit primary
170055** key column - "rowid". Virtual tables for which the "rowid" column does
170056** not function like a primary key value cannot be updated using RBU. For
170057** example, if the target db contains either of the following:
170058**
170059**   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
170060**   CREATE TABLE x1(a, b)
170061**
170062** then the RBU database should contain:
170063**
170064**   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
170065**
170066** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
170067** target table must be present in the input table. For virtual tables,
170068** hidden columns are optional - they are updated by RBU if present in
170069** the input table, or not otherwise. For example, to write to an fts4
170070** table with a hidden languageid column such as:
170071**
170072**   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
170073**
170074** Either of the following input table schemas may be used:
170075**
170076**   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
170077**   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
170078**
170079** For each row to INSERT into the target database as part of the RBU
170080** update, the corresponding data_% table should contain a single record
170081** with the "rbu_control" column set to contain integer value 0. The
170082** other columns should be set to the values that make up the new record
170083** to insert.
170084**
170085** If the target database table has an INTEGER PRIMARY KEY, it is not
170086** possible to insert a NULL value into the IPK column. Attempting to
170087** do so results in an SQLITE_MISMATCH error.
170088**
170089** For each row to DELETE from the target database as part of the RBU
170090** update, the corresponding data_% table should contain a single record
170091** with the "rbu_control" column set to contain integer value 1. The
170092** real primary key values of the row to delete should be stored in the
170093** corresponding columns of the data_% table. The values stored in the
170094** other columns are not used.
170095**
170096** For each row to UPDATE from the target database as part of the RBU
170097** update, the corresponding data_% table should contain a single record
170098** with the "rbu_control" column set to contain a value of type text.
170099** The real primary key values identifying the row to update should be
170100** stored in the corresponding columns of the data_% table row, as should
170101** the new values of all columns being update. The text value in the
170102** "rbu_control" column must contain the same number of characters as
170103** there are columns in the target database table, and must consist entirely
170104** of 'x' and '.' characters (or in some special cases 'd' - see below). For
170105** each column that is being updated, the corresponding character is set to
170106** 'x'. For those that remain as they are, the corresponding character of the
170107** rbu_control value should be set to '.'. For example, given the tables
170108** above, the update statement:
170109**
170110**   UPDATE t1 SET c = 'usa' WHERE a = 4;
170111**
170112** is represented by the data_t1 row created by:
170113**
170114**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
170115**
170116** Instead of an 'x' character, characters of the rbu_control value specified
170117** for UPDATEs may also be set to 'd'. In this case, instead of updating the
170118** target table with the value stored in the corresponding data_% column, the
170119** user-defined SQL function "rbu_delta()" is invoked and the result stored in
170120** the target table column. rbu_delta() is invoked with two arguments - the
170121** original value currently stored in the target table column and the
170122** value specified in the data_xxx table.
170123**
170124** For example, this row:
170125**
170126**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
170127**
170128** is similar to an UPDATE statement such as:
170129**
170130**   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
170131**
170132** Finally, if an 'f' character appears in place of a 'd' or 's' in an
170133** ota_control string, the contents of the data_xxx table column is assumed
170134** to be a "fossil delta" - a patch to be applied to a blob value in the
170135** format used by the fossil source-code management system. In this case
170136** the existing value within the target database table must be of type BLOB.
170137** It is replaced by the result of applying the specified fossil delta to
170138** itself.
170139**
170140** If the target database table is a virtual table or a table with no PRIMARY
170141** KEY, the rbu_control value should not include a character corresponding
170142** to the rbu_rowid value. For example, this:
170143**
170144**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
170145**       VALUES(NULL, 'usa', 12, '.x');
170146**
170147** causes a result similar to:
170148**
170149**   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
170150**
170151** The data_xxx tables themselves should have no PRIMARY KEY declarations.
170152** However, RBU is more efficient if reading the rows in from each data_xxx
170153** table in "rowid" order is roughly the same as reading them sorted by
170154** the PRIMARY KEY of the corresponding target database table. In other
170155** words, rows should be sorted using the destination table PRIMARY KEY
170156** fields before they are inserted into the data_xxx tables.
170157**
170158** USAGE
170159**
170160** The API declared below allows an application to apply an RBU update
170161** stored on disk to an existing target database. Essentially, the
170162** application:
170163**
170164**     1) Opens an RBU handle using the sqlite3rbu_open() function.
170165**
170166**     2) Registers any required virtual table modules with the database
170167**        handle returned by sqlite3rbu_db(). Also, if required, register
170168**        the rbu_delta() implementation.
170169**
170170**     3) Calls the sqlite3rbu_step() function one or more times on
170171**        the new handle. Each call to sqlite3rbu_step() performs a single
170172**        b-tree operation, so thousands of calls may be required to apply
170173**        a complete update.
170174**
170175**     4) Calls sqlite3rbu_close() to close the RBU update handle. If
170176**        sqlite3rbu_step() has been called enough times to completely
170177**        apply the update to the target database, then the RBU database
170178**        is marked as fully applied. Otherwise, the state of the RBU
170179**        update application is saved in the RBU database for later
170180**        resumption.
170181**
170182** See comments below for more detail on APIs.
170183**
170184** If an update is only partially applied to the target database by the
170185** time sqlite3rbu_close() is called, various state information is saved
170186** within the RBU database. This allows subsequent processes to automatically
170187** resume the RBU update from where it left off.
170188**
170189** To remove all RBU extension state information, returning an RBU database
170190** to its original contents, it is sufficient to drop all tables that begin
170191** with the prefix "rbu_"
170192**
170193** DATABASE LOCKING
170194**
170195** An RBU update may not be applied to a database in WAL mode. Attempting
170196** to do so is an error (SQLITE_ERROR).
170197**
170198** While an RBU handle is open, a SHARED lock may be held on the target
170199** database file. This means it is possible for other clients to read the
170200** database, but not to write it.
170201**
170202** If an RBU update is started and then suspended before it is completed,
170203** then an external client writes to the database, then attempting to resume
170204** the suspended RBU update is also an error (SQLITE_BUSY).
170205*/
170206
170207#ifndef _SQLITE3RBU_H
170208#define _SQLITE3RBU_H
170209
170210/* #include "sqlite3.h"              ** Required for error code definitions ** */
170211
170212#if 0
170213extern "C" {
170214#endif
170215
170216typedef struct sqlite3rbu sqlite3rbu;
170217
170218/*
170219** Open an RBU handle.
170220**
170221** Argument zTarget is the path to the target database. Argument zRbu is
170222** the path to the RBU database. Each call to this function must be matched
170223** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
170224** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
170225** or zRbu begin with "file:", it will be interpreted as an SQLite
170226** database URI, not a regular file name.
170227**
170228** If the zState argument is passed a NULL value, the RBU extension stores
170229** the current state of the update (how many rows have been updated, which
170230** indexes are yet to be updated etc.) within the RBU database itself. This
170231** can be convenient, as it means that the RBU application does not need to
170232** organize removing a separate state file after the update is concluded.
170233** Or, if zState is non-NULL, it must be a path to a database file in which
170234** the RBU extension can store the state of the update.
170235**
170236** When resuming an RBU update, the zState argument must be passed the same
170237** value as when the RBU update was started.
170238**
170239** Once the RBU update is finished, the RBU extension does not
170240** automatically remove any zState database file, even if it created it.
170241**
170242** By default, RBU uses the default VFS to access the files on disk. To
170243** use a VFS other than the default, an SQLite "file:" URI containing a
170244** "vfs=..." option may be passed as the zTarget option.
170245**
170246** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
170247** SQLite's built-in VFSs, including the multiplexor VFS. However it does
170248** not work out of the box with zipvfs. Refer to the comment describing
170249** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
170250*/
170251SQLITE_API sqlite3rbu *sqlite3rbu_open(
170252  const char *zTarget,
170253  const char *zRbu,
170254  const char *zState
170255);
170256
170257/*
170258** Open an RBU handle to perform an RBU vacuum on database file zTarget.
170259** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
170260** that it can be suspended and resumed like an RBU update.
170261**
170262** The second argument to this function identifies a database in which
170263** to store the state of the RBU vacuum operation if it is suspended. The
170264** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
170265** operation, the state database should either not exist or be empty
170266** (contain no tables). If an RBU vacuum is suspended by calling
170267** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
170268** returned SQLITE_DONE, the vacuum state is stored in the state database.
170269** The vacuum can be resumed by calling this function to open a new RBU
170270** handle specifying the same target and state databases.
170271**
170272** If the second argument passed to this function is NULL, then the
170273** name of the state database is "<database>-vacuum", where <database>
170274** is the name of the target database file. In this case, on UNIX, if the
170275** state database is not already present in the file-system, it is created
170276** with the same permissions as the target db is made.
170277**
170278** This function does not delete the state database after an RBU vacuum
170279** is completed, even if it created it. However, if the call to
170280** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
170281** of the state tables within the state database are zeroed. This way,
170282** the next call to sqlite3rbu_vacuum() opens a handle that starts a
170283** new RBU vacuum operation.
170284**
170285** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
170286** describing the sqlite3rbu_create_vfs() API function below for
170287** a description of the complications associated with using RBU with
170288** zipvfs databases.
170289*/
170290SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
170291  const char *zTarget,
170292  const char *zState
170293);
170294
170295/*
170296** Internally, each RBU connection uses a separate SQLite database
170297** connection to access the target and rbu update databases. This
170298** API allows the application direct access to these database handles.
170299**
170300** The first argument passed to this function must be a valid, open, RBU
170301** handle. The second argument should be passed zero to access the target
170302** database handle, or non-zero to access the rbu update database handle.
170303** Accessing the underlying database handles may be useful in the
170304** following scenarios:
170305**
170306**   * If any target tables are virtual tables, it may be necessary to
170307**     call sqlite3_create_module() on the target database handle to
170308**     register the required virtual table implementations.
170309**
170310**   * If the data_xxx tables in the RBU source database are virtual
170311**     tables, the application may need to call sqlite3_create_module() on
170312**     the rbu update db handle to any required virtual table
170313**     implementations.
170314**
170315**   * If the application uses the "rbu_delta()" feature described above,
170316**     it must use sqlite3_create_function() or similar to register the
170317**     rbu_delta() implementation with the target database handle.
170318**
170319** If an error has occurred, either while opening or stepping the RBU object,
170320** this function may return NULL. The error code and message may be collected
170321** when sqlite3rbu_close() is called.
170322**
170323** Database handles returned by this function remain valid until the next
170324** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
170325*/
170326SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
170327
170328/*
170329** Do some work towards applying the RBU update to the target db.
170330**
170331** Return SQLITE_DONE if the update has been completely applied, or
170332** SQLITE_OK if no error occurs but there remains work to do to apply
170333** the RBU update. If an error does occur, some other error code is
170334** returned.
170335**
170336** Once a call to sqlite3rbu_step() has returned a value other than
170337** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
170338** that immediately return the same value.
170339*/
170340SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
170341
170342/*
170343** Force RBU to save its state to disk.
170344**
170345** If a power failure or application crash occurs during an update, following
170346** system recovery RBU may resume the update from the point at which the state
170347** was last saved. In other words, from the most recent successful call to
170348** sqlite3rbu_close() or this function.
170349**
170350** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
170351*/
170352SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
170353
170354/*
170355** Close an RBU handle.
170356**
170357** If the RBU update has been completely applied, mark the RBU database
170358** as fully applied. Otherwise, assuming no error has occurred, save the
170359** current state of the RBU update appliation to the RBU database.
170360**
170361** If an error has already occurred as part of an sqlite3rbu_step()
170362** or sqlite3rbu_open() call, or if one occurs within this function, an
170363** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
170364** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
170365** English language error message. It is the responsibility of the caller to
170366** eventually free any such buffer using sqlite3_free().
170367**
170368** Otherwise, if no error occurs, this function returns SQLITE_OK if the
170369** update has been partially applied, or SQLITE_DONE if it has been
170370** completely applied.
170371*/
170372SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
170373
170374/*
170375** Return the total number of key-value operations (inserts, deletes or
170376** updates) that have been performed on the target database since the
170377** current RBU update was started.
170378*/
170379SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
170380
170381/*
170382** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
170383** progress indications for the two stages of an RBU update. This API may
170384** be useful for driving GUI progress indicators and similar.
170385**
170386** An RBU update is divided into two stages:
170387**
170388**   * Stage 1, in which changes are accumulated in an oal/wal file, and
170389**   * Stage 2, in which the contents of the wal file are copied into the
170390**     main database.
170391**
170392** The update is visible to non-RBU clients during stage 2. During stage 1
170393** non-RBU reader clients may see the original database.
170394**
170395** If this API is called during stage 2 of the update, output variable
170396** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
170397** to a value between 0 and 10000 to indicate the permyriadage progress of
170398** stage 2. A value of 5000 indicates that stage 2 is half finished,
170399** 9000 indicates that it is 90% finished, and so on.
170400**
170401** If this API is called during stage 1 of the update, output variable
170402** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
170403** value to which (*pnOne) is set depends on whether or not the RBU
170404** database contains an "rbu_count" table. The rbu_count table, if it
170405** exists, must contain the same columns as the following:
170406**
170407**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
170408**
170409** There must be one row in the table for each source (data_xxx) table within
170410** the RBU database. The 'tbl' column should contain the name of the source
170411** table. The 'cnt' column should contain the number of rows within the
170412** source table.
170413**
170414** If the rbu_count table is present and populated correctly and this
170415** API is called during stage 1, the *pnOne output variable is set to the
170416** permyriadage progress of the same stage. If the rbu_count table does
170417** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
170418** table exists but is not correctly populated, the value of the *pnOne
170419** output variable during stage 1 is undefined.
170420*/
170421SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
170422
170423/*
170424** Obtain an indication as to the current stage of an RBU update or vacuum.
170425** This function always returns one of the SQLITE_RBU_STATE_XXX constants
170426** defined in this file. Return values should be interpreted as follows:
170427**
170428** SQLITE_RBU_STATE_OAL:
170429**   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
170430**   may either add further data to the *-oal file, or compute data that will
170431**   be added by a subsequent call.
170432**
170433** SQLITE_RBU_STATE_MOVE:
170434**   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
170435**   will move the *-oal file to the equivalent *-wal path. If the current
170436**   operation is an RBU update, then the updated version of the database
170437**   file will become visible to ordinary SQLite clients following the next
170438**   call to sqlite3rbu_step().
170439**
170440** SQLITE_RBU_STATE_CHECKPOINT:
170441**   RBU is currently performing an incremental checkpoint. The next call to
170442**   sqlite3rbu_step() will copy a page of data from the *-wal file into
170443**   the target database file.
170444**
170445** SQLITE_RBU_STATE_DONE:
170446**   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
170447**   will immediately return SQLITE_DONE.
170448**
170449** SQLITE_RBU_STATE_ERROR:
170450**   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
170451**   immediately return the SQLite error code associated with the error.
170452*/
170453#define SQLITE_RBU_STATE_OAL        1
170454#define SQLITE_RBU_STATE_MOVE       2
170455#define SQLITE_RBU_STATE_CHECKPOINT 3
170456#define SQLITE_RBU_STATE_DONE       4
170457#define SQLITE_RBU_STATE_ERROR      5
170458
170459SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
170460
170461/*
170462** Create an RBU VFS named zName that accesses the underlying file-system
170463** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
170464** then the new RBU VFS uses the default system VFS to access the file-system.
170465** The new object is registered as a non-default VFS with SQLite before
170466** returning.
170467**
170468** Part of the RBU implementation uses a custom VFS object. Usually, this
170469** object is created and deleted automatically by RBU.
170470**
170471** The exception is for applications that also use zipvfs. In this case,
170472** the custom VFS must be explicitly created by the user before the RBU
170473** handle is opened. The RBU VFS should be installed so that the zipvfs
170474** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
170475** (for example multiplexor) to access the file-system. For example,
170476** to assemble an RBU enabled VFS stack that uses both zipvfs and
170477** multiplexor (error checking omitted):
170478**
170479**     // Create a VFS named "multiplex" (not the default).
170480**     sqlite3_multiplex_initialize(0, 0);
170481**
170482**     // Create an rbu VFS named "rbu" that uses multiplexor. If the
170483**     // second argument were replaced with NULL, the "rbu" VFS would
170484**     // access the file-system via the system default VFS, bypassing the
170485**     // multiplexor.
170486**     sqlite3rbu_create_vfs("rbu", "multiplex");
170487**
170488**     // Create a zipvfs VFS named "zipvfs" that uses rbu.
170489**     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
170490**
170491**     // Make zipvfs the default VFS.
170492**     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
170493**
170494** Because the default VFS created above includes a RBU functionality, it
170495** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
170496** that does not include the RBU layer results in an error.
170497**
170498** The overhead of adding the "rbu" VFS to the system is negligible for
170499** non-RBU users. There is no harm in an application accessing the
170500** file-system via "rbu" all the time, even if it only uses RBU functionality
170501** occasionally.
170502*/
170503SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
170504
170505/*
170506** Deregister and destroy an RBU vfs created by an earlier call to
170507** sqlite3rbu_create_vfs().
170508**
170509** VFS objects are not reference counted. If a VFS object is destroyed
170510** before all database handles that use it have been closed, the results
170511** are undefined.
170512*/
170513SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
170514
170515#if 0
170516}  /* end of the 'extern "C"' block */
170517#endif
170518
170519#endif /* _SQLITE3RBU_H */
170520
170521/************** End of sqlite3rbu.h ******************************************/
170522/************** Continuing where we left off in sqlite3rbu.c *****************/
170523
170524#if defined(_WIN32_WCE)
170525/* #include "windows.h" */
170526#endif
170527
170528/* Maximum number of prepared UPDATE statements held by this module */
170529#define SQLITE_RBU_UPDATE_CACHESIZE 16
170530
170531/*
170532** Swap two objects of type TYPE.
170533*/
170534#if !defined(SQLITE_AMALGAMATION)
170535# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
170536#endif
170537
170538/*
170539** The rbu_state table is used to save the state of a partially applied
170540** update so that it can be resumed later. The table consists of integer
170541** keys mapped to values as follows:
170542**
170543** RBU_STATE_STAGE:
170544**   May be set to integer values 1, 2, 4 or 5. As follows:
170545**       1: the *-rbu file is currently under construction.
170546**       2: the *-rbu file has been constructed, but not yet moved
170547**          to the *-wal path.
170548**       4: the checkpoint is underway.
170549**       5: the rbu update has been checkpointed.
170550**
170551** RBU_STATE_TBL:
170552**   Only valid if STAGE==1. The target database name of the table
170553**   currently being written.
170554**
170555** RBU_STATE_IDX:
170556**   Only valid if STAGE==1. The target database name of the index
170557**   currently being written, or NULL if the main table is currently being
170558**   updated.
170559**
170560** RBU_STATE_ROW:
170561**   Only valid if STAGE==1. Number of rows already processed for the current
170562**   table/index.
170563**
170564** RBU_STATE_PROGRESS:
170565**   Trbul number of sqlite3rbu_step() calls made so far as part of this
170566**   rbu update.
170567**
170568** RBU_STATE_CKPT:
170569**   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
170570**   header created by recovering the *-wal file. This is used to detect
170571**   cases when another client appends frames to the *-wal file in the
170572**   middle of an incremental checkpoint (an incremental checkpoint cannot
170573**   be continued if this happens).
170574**
170575** RBU_STATE_COOKIE:
170576**   Valid if STAGE==1. The current change-counter cookie value in the
170577**   target db file.
170578**
170579** RBU_STATE_OALSZ:
170580**   Valid if STAGE==1. The size in bytes of the *-oal file.
170581*/
170582#define RBU_STATE_STAGE        1
170583#define RBU_STATE_TBL          2
170584#define RBU_STATE_IDX          3
170585#define RBU_STATE_ROW          4
170586#define RBU_STATE_PROGRESS     5
170587#define RBU_STATE_CKPT         6
170588#define RBU_STATE_COOKIE       7
170589#define RBU_STATE_OALSZ        8
170590#define RBU_STATE_PHASEONESTEP 9
170591
170592#define RBU_STAGE_OAL         1
170593#define RBU_STAGE_MOVE        2
170594#define RBU_STAGE_CAPTURE     3
170595#define RBU_STAGE_CKPT        4
170596#define RBU_STAGE_DONE        5
170597
170598
170599#define RBU_CREATE_STATE \
170600  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
170601
170602typedef struct RbuFrame RbuFrame;
170603typedef struct RbuObjIter RbuObjIter;
170604typedef struct RbuState RbuState;
170605typedef struct rbu_vfs rbu_vfs;
170606typedef struct rbu_file rbu_file;
170607typedef struct RbuUpdateStmt RbuUpdateStmt;
170608
170609#if !defined(SQLITE_AMALGAMATION)
170610typedef unsigned int u32;
170611typedef unsigned short u16;
170612typedef unsigned char u8;
170613typedef sqlite3_int64 i64;
170614#endif
170615
170616/*
170617** These values must match the values defined in wal.c for the equivalent
170618** locks. These are not magic numbers as they are part of the SQLite file
170619** format.
170620*/
170621#define WAL_LOCK_WRITE  0
170622#define WAL_LOCK_CKPT   1
170623#define WAL_LOCK_READ0  3
170624
170625#define SQLITE_FCNTL_RBUCNT    5149216
170626
170627/*
170628** A structure to store values read from the rbu_state table in memory.
170629*/
170630struct RbuState {
170631  int eStage;
170632  char *zTbl;
170633  char *zIdx;
170634  i64 iWalCksum;
170635  int nRow;
170636  i64 nProgress;
170637  u32 iCookie;
170638  i64 iOalSz;
170639  i64 nPhaseOneStep;
170640};
170641
170642struct RbuUpdateStmt {
170643  char *zMask;                    /* Copy of update mask used with pUpdate */
170644  sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
170645  RbuUpdateStmt *pNext;
170646};
170647
170648/*
170649** An iterator of this type is used to iterate through all objects in
170650** the target database that require updating. For each such table, the
170651** iterator visits, in order:
170652**
170653**     * the table itself,
170654**     * each index of the table (zero or more points to visit), and
170655**     * a special "cleanup table" state.
170656**
170657** abIndexed:
170658**   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
170659**   it points to an array of flags nTblCol elements in size. The flag is
170660**   set for each column that is either a part of the PK or a part of an
170661**   index. Or clear otherwise.
170662**
170663*/
170664struct RbuObjIter {
170665  sqlite3_stmt *pTblIter;         /* Iterate through tables */
170666  sqlite3_stmt *pIdxIter;         /* Index iterator */
170667  int nTblCol;                    /* Size of azTblCol[] array */
170668  char **azTblCol;                /* Array of unquoted target column names */
170669  char **azTblType;               /* Array of target column types */
170670  int *aiSrcOrder;                /* src table col -> target table col */
170671  u8 *abTblPk;                    /* Array of flags, set on target PK columns */
170672  u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
170673  u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
170674  int eType;                      /* Table type - an RBU_PK_XXX value */
170675
170676  /* Output variables. zTbl==0 implies EOF. */
170677  int bCleanup;                   /* True in "cleanup" state */
170678  const char *zTbl;               /* Name of target db table */
170679  const char *zDataTbl;           /* Name of rbu db table (or null) */
170680  const char *zIdx;               /* Name of target db index (or null) */
170681  int iTnum;                      /* Root page of current object */
170682  int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
170683  int bUnique;                    /* Current index is unique */
170684  int nIndex;                     /* Number of aux. indexes on table zTbl */
170685
170686  /* Statements created by rbuObjIterPrepareAll() */
170687  int nCol;                       /* Number of columns in current object */
170688  sqlite3_stmt *pSelect;          /* Source data */
170689  sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
170690  sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
170691  sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
170692
170693  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
170694  RbuUpdateStmt *pRbuUpdate;
170695};
170696
170697/*
170698** Values for RbuObjIter.eType
170699**
170700**     0: Table does not exist (error)
170701**     1: Table has an implicit rowid.
170702**     2: Table has an explicit IPK column.
170703**     3: Table has an external PK index.
170704**     4: Table is WITHOUT ROWID.
170705**     5: Table is a virtual table.
170706*/
170707#define RBU_PK_NOTABLE        0
170708#define RBU_PK_NONE           1
170709#define RBU_PK_IPK            2
170710#define RBU_PK_EXTERNAL       3
170711#define RBU_PK_WITHOUT_ROWID  4
170712#define RBU_PK_VTAB           5
170713
170714
170715/*
170716** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
170717** one of the following operations.
170718*/
170719#define RBU_INSERT     1          /* Insert on a main table b-tree */
170720#define RBU_DELETE     2          /* Delete a row from a main table b-tree */
170721#define RBU_REPLACE    3          /* Delete and then insert a row */
170722#define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
170723#define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
170724
170725#define RBU_UPDATE     6          /* Update a row in a main table b-tree */
170726
170727/*
170728** A single step of an incremental checkpoint - frame iWalFrame of the wal
170729** file should be copied to page iDbPage of the database file.
170730*/
170731struct RbuFrame {
170732  u32 iDbPage;
170733  u32 iWalFrame;
170734};
170735
170736/*
170737** RBU handle.
170738**
170739** nPhaseOneStep:
170740**   If the RBU database contains an rbu_count table, this value is set to
170741**   a running estimate of the number of b-tree operations required to
170742**   finish populating the *-oal file. This allows the sqlite3_bp_progress()
170743**   API to calculate the permyriadage progress of populating the *-oal file
170744**   using the formula:
170745**
170746**     permyriadage = (10000 * nProgress) / nPhaseOneStep
170747**
170748**   nPhaseOneStep is initialized to the sum of:
170749**
170750**     nRow * (nIndex + 1)
170751**
170752**   for all source tables in the RBU database, where nRow is the number
170753**   of rows in the source table and nIndex the number of indexes on the
170754**   corresponding target database table.
170755**
170756**   This estimate is accurate if the RBU update consists entirely of
170757**   INSERT operations. However, it is inaccurate if:
170758**
170759**     * the RBU update contains any UPDATE operations. If the PK specified
170760**       for an UPDATE operation does not exist in the target table, then
170761**       no b-tree operations are required on index b-trees. Or if the
170762**       specified PK does exist, then (nIndex*2) such operations are
170763**       required (one delete and one insert on each index b-tree).
170764**
170765**     * the RBU update contains any DELETE operations for which the specified
170766**       PK does not exist. In this case no operations are required on index
170767**       b-trees.
170768**
170769**     * the RBU update contains REPLACE operations. These are similar to
170770**       UPDATE operations.
170771**
170772**   nPhaseOneStep is updated to account for the conditions above during the
170773**   first pass of each source table. The updated nPhaseOneStep value is
170774**   stored in the rbu_state table if the RBU update is suspended.
170775*/
170776struct sqlite3rbu {
170777  int eStage;                     /* Value of RBU_STATE_STAGE field */
170778  sqlite3 *dbMain;                /* target database handle */
170779  sqlite3 *dbRbu;                 /* rbu database handle */
170780  char *zTarget;                  /* Path to target db */
170781  char *zRbu;                     /* Path to rbu db */
170782  char *zState;                   /* Path to state db (or NULL if zRbu) */
170783  char zStateDb[5];               /* Db name for state ("stat" or "main") */
170784  int rc;                         /* Value returned by last rbu_step() call */
170785  char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
170786  int nStep;                      /* Rows processed for current object */
170787  int nProgress;                  /* Rows processed for all objects */
170788  RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
170789  const char *zVfsName;           /* Name of automatically created rbu vfs */
170790  rbu_file *pTargetFd;            /* File handle open on target db */
170791  int nPagePerSector;             /* Pages per sector for pTargetFd */
170792  i64 iOalSz;
170793  i64 nPhaseOneStep;
170794
170795  /* The following state variables are used as part of the incremental
170796  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
170797  ** function rbuSetupCheckpoint() for details.  */
170798  u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
170799  u32 mLock;
170800  int nFrame;                     /* Entries in aFrame[] array */
170801  int nFrameAlloc;                /* Allocated size of aFrame[] array */
170802  RbuFrame *aFrame;
170803  int pgsz;
170804  u8 *aBuf;
170805  i64 iWalCksum;
170806
170807  /* Used in RBU vacuum mode only */
170808  int nRbu;                       /* Number of RBU VFS in the stack */
170809  rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
170810};
170811
170812/*
170813** An rbu VFS is implemented using an instance of this structure.
170814*/
170815struct rbu_vfs {
170816  sqlite3_vfs base;               /* rbu VFS shim methods */
170817  sqlite3_vfs *pRealVfs;          /* Underlying VFS */
170818  sqlite3_mutex *mutex;           /* Mutex to protect pMain */
170819  rbu_file *pMain;                /* Linked list of main db files */
170820};
170821
170822/*
170823** Each file opened by an rbu VFS is represented by an instance of
170824** the following structure.
170825*/
170826struct rbu_file {
170827  sqlite3_file base;              /* sqlite3_file methods */
170828  sqlite3_file *pReal;            /* Underlying file handle */
170829  rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
170830  sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
170831
170832  int openFlags;                  /* Flags this file was opened with */
170833  u32 iCookie;                    /* Cookie value for main db files */
170834  u8 iWriteVer;                   /* "write-version" value for main db files */
170835  u8 bNolock;                     /* True to fail EXCLUSIVE locks */
170836
170837  int nShm;                       /* Number of entries in apShm[] array */
170838  char **apShm;                   /* Array of mmap'd *-shm regions */
170839  char *zDel;                     /* Delete this when closing file */
170840
170841  const char *zWal;               /* Wal filename for this main db file */
170842  rbu_file *pWalFd;               /* Wal file descriptor for this main db */
170843  rbu_file *pMainNext;            /* Next MAIN_DB file */
170844};
170845
170846/*
170847** True for an RBU vacuum handle, or false otherwise.
170848*/
170849#define rbuIsVacuum(p) ((p)->zTarget==0)
170850
170851
170852/*************************************************************************
170853** The following three functions, found below:
170854**
170855**   rbuDeltaGetInt()
170856**   rbuDeltaChecksum()
170857**   rbuDeltaApply()
170858**
170859** are lifted from the fossil source code (http://fossil-scm.org). They
170860** are used to implement the scalar SQL function rbu_fossil_delta().
170861*/
170862
170863/*
170864** Read bytes from *pz and convert them into a positive integer.  When
170865** finished, leave *pz pointing to the first character past the end of
170866** the integer.  The *pLen parameter holds the length of the string
170867** in *pz and is decremented once for each character in the integer.
170868*/
170869static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
170870  static const signed char zValue[] = {
170871    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
170872    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
170873    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
170874     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
170875    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
170876    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
170877    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
170878    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
170879  };
170880  unsigned int v = 0;
170881  int c;
170882  unsigned char *z = (unsigned char*)*pz;
170883  unsigned char *zStart = z;
170884  while( (c = zValue[0x7f&*(z++)])>=0 ){
170885     v = (v<<6) + c;
170886  }
170887  z--;
170888  *pLen -= z - zStart;
170889  *pz = (char*)z;
170890  return v;
170891}
170892
170893/*
170894** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
170895*/
170896static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
170897  const unsigned char *z = (const unsigned char *)zIn;
170898  unsigned sum0 = 0;
170899  unsigned sum1 = 0;
170900  unsigned sum2 = 0;
170901  unsigned sum3 = 0;
170902  while(N >= 16){
170903    sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
170904    sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
170905    sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
170906    sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
170907    z += 16;
170908    N -= 16;
170909  }
170910  while(N >= 4){
170911    sum0 += z[0];
170912    sum1 += z[1];
170913    sum2 += z[2];
170914    sum3 += z[3];
170915    z += 4;
170916    N -= 4;
170917  }
170918  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
170919  switch(N){
170920    case 3:   sum3 += (z[2] << 8);
170921    case 2:   sum3 += (z[1] << 16);
170922    case 1:   sum3 += (z[0] << 24);
170923    default:  ;
170924  }
170925  return sum3;
170926}
170927
170928/*
170929** Apply a delta.
170930**
170931** The output buffer should be big enough to hold the whole output
170932** file and a NUL terminator at the end.  The delta_output_size()
170933** routine will determine this size for you.
170934**
170935** The delta string should be null-terminated.  But the delta string
170936** may contain embedded NUL characters (if the input and output are
170937** binary files) so we also have to pass in the length of the delta in
170938** the lenDelta parameter.
170939**
170940** This function returns the size of the output file in bytes (excluding
170941** the final NUL terminator character).  Except, if the delta string is
170942** malformed or intended for use with a source file other than zSrc,
170943** then this routine returns -1.
170944**
170945** Refer to the delta_create() documentation above for a description
170946** of the delta file format.
170947*/
170948static int rbuDeltaApply(
170949  const char *zSrc,      /* The source or pattern file */
170950  int lenSrc,            /* Length of the source file */
170951  const char *zDelta,    /* Delta to apply to the pattern */
170952  int lenDelta,          /* Length of the delta */
170953  char *zOut             /* Write the output into this preallocated buffer */
170954){
170955  unsigned int limit;
170956  unsigned int total = 0;
170957#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
170958  char *zOrigOut = zOut;
170959#endif
170960
170961  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
170962  if( *zDelta!='\n' ){
170963    /* ERROR: size integer not terminated by "\n" */
170964    return -1;
170965  }
170966  zDelta++; lenDelta--;
170967  while( *zDelta && lenDelta>0 ){
170968    unsigned int cnt, ofst;
170969    cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
170970    switch( zDelta[0] ){
170971      case '@': {
170972        zDelta++; lenDelta--;
170973        ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
170974        if( lenDelta>0 && zDelta[0]!=',' ){
170975          /* ERROR: copy command not terminated by ',' */
170976          return -1;
170977        }
170978        zDelta++; lenDelta--;
170979        total += cnt;
170980        if( total>limit ){
170981          /* ERROR: copy exceeds output file size */
170982          return -1;
170983        }
170984        if( (int)(ofst+cnt) > lenSrc ){
170985          /* ERROR: copy extends past end of input */
170986          return -1;
170987        }
170988        memcpy(zOut, &zSrc[ofst], cnt);
170989        zOut += cnt;
170990        break;
170991      }
170992      case ':': {
170993        zDelta++; lenDelta--;
170994        total += cnt;
170995        if( total>limit ){
170996          /* ERROR:  insert command gives an output larger than predicted */
170997          return -1;
170998        }
170999        if( (int)cnt>lenDelta ){
171000          /* ERROR: insert count exceeds size of delta */
171001          return -1;
171002        }
171003        memcpy(zOut, zDelta, cnt);
171004        zOut += cnt;
171005        zDelta += cnt;
171006        lenDelta -= cnt;
171007        break;
171008      }
171009      case ';': {
171010        zDelta++; lenDelta--;
171011        zOut[0] = 0;
171012#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
171013        if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
171014          /* ERROR:  bad checksum */
171015          return -1;
171016        }
171017#endif
171018        if( total!=limit ){
171019          /* ERROR: generated size does not match predicted size */
171020          return -1;
171021        }
171022        return total;
171023      }
171024      default: {
171025        /* ERROR: unknown delta operator */
171026        return -1;
171027      }
171028    }
171029  }
171030  /* ERROR: unterminated delta */
171031  return -1;
171032}
171033
171034static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
171035  int size;
171036  size = rbuDeltaGetInt(&zDelta, &lenDelta);
171037  if( *zDelta!='\n' ){
171038    /* ERROR: size integer not terminated by "\n" */
171039    return -1;
171040  }
171041  return size;
171042}
171043
171044/*
171045** End of code taken from fossil.
171046*************************************************************************/
171047
171048/*
171049** Implementation of SQL scalar function rbu_fossil_delta().
171050**
171051** This function applies a fossil delta patch to a blob. Exactly two
171052** arguments must be passed to this function. The first is the blob to
171053** patch and the second the patch to apply. If no error occurs, this
171054** function returns the patched blob.
171055*/
171056static void rbuFossilDeltaFunc(
171057  sqlite3_context *context,
171058  int argc,
171059  sqlite3_value **argv
171060){
171061  const char *aDelta;
171062  int nDelta;
171063  const char *aOrig;
171064  int nOrig;
171065
171066  int nOut;
171067  int nOut2;
171068  char *aOut;
171069
171070  assert( argc==2 );
171071
171072  nOrig = sqlite3_value_bytes(argv[0]);
171073  aOrig = (const char*)sqlite3_value_blob(argv[0]);
171074  nDelta = sqlite3_value_bytes(argv[1]);
171075  aDelta = (const char*)sqlite3_value_blob(argv[1]);
171076
171077  /* Figure out the size of the output */
171078  nOut = rbuDeltaOutputSize(aDelta, nDelta);
171079  if( nOut<0 ){
171080    sqlite3_result_error(context, "corrupt fossil delta", -1);
171081    return;
171082  }
171083
171084  aOut = sqlite3_malloc(nOut+1);
171085  if( aOut==0 ){
171086    sqlite3_result_error_nomem(context);
171087  }else{
171088    nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
171089    if( nOut2!=nOut ){
171090      sqlite3_result_error(context, "corrupt fossil delta", -1);
171091    }else{
171092      sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
171093    }
171094  }
171095}
171096
171097
171098/*
171099** Prepare the SQL statement in buffer zSql against database handle db.
171100** If successful, set *ppStmt to point to the new statement and return
171101** SQLITE_OK.
171102**
171103** Otherwise, if an error does occur, set *ppStmt to NULL and return
171104** an SQLite error code. Additionally, set output variable *pzErrmsg to
171105** point to a buffer containing an error message. It is the responsibility
171106** of the caller to (eventually) free this buffer using sqlite3_free().
171107*/
171108static int prepareAndCollectError(
171109  sqlite3 *db,
171110  sqlite3_stmt **ppStmt,
171111  char **pzErrmsg,
171112  const char *zSql
171113){
171114  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
171115  if( rc!=SQLITE_OK ){
171116    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
171117    *ppStmt = 0;
171118  }
171119  return rc;
171120}
171121
171122/*
171123** Reset the SQL statement passed as the first argument. Return a copy
171124** of the value returned by sqlite3_reset().
171125**
171126** If an error has occurred, then set *pzErrmsg to point to a buffer
171127** containing an error message. It is the responsibility of the caller
171128** to eventually free this buffer using sqlite3_free().
171129*/
171130static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
171131  int rc = sqlite3_reset(pStmt);
171132  if( rc!=SQLITE_OK ){
171133    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
171134  }
171135  return rc;
171136}
171137
171138/*
171139** Unless it is NULL, argument zSql points to a buffer allocated using
171140** sqlite3_malloc containing an SQL statement. This function prepares the SQL
171141** statement against database db and frees the buffer. If statement
171142** compilation is successful, *ppStmt is set to point to the new statement
171143** handle and SQLITE_OK is returned.
171144**
171145** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
171146** returned. In this case, *pzErrmsg may also be set to point to an error
171147** message. It is the responsibility of the caller to free this error message
171148** buffer using sqlite3_free().
171149**
171150** If argument zSql is NULL, this function assumes that an OOM has occurred.
171151** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
171152*/
171153static int prepareFreeAndCollectError(
171154  sqlite3 *db,
171155  sqlite3_stmt **ppStmt,
171156  char **pzErrmsg,
171157  char *zSql
171158){
171159  int rc;
171160  assert( *pzErrmsg==0 );
171161  if( zSql==0 ){
171162    rc = SQLITE_NOMEM;
171163    *ppStmt = 0;
171164  }else{
171165    rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
171166    sqlite3_free(zSql);
171167  }
171168  return rc;
171169}
171170
171171/*
171172** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
171173** by an earlier call to rbuObjIterCacheTableInfo().
171174*/
171175static void rbuObjIterFreeCols(RbuObjIter *pIter){
171176  int i;
171177  for(i=0; i<pIter->nTblCol; i++){
171178    sqlite3_free(pIter->azTblCol[i]);
171179    sqlite3_free(pIter->azTblType[i]);
171180  }
171181  sqlite3_free(pIter->azTblCol);
171182  pIter->azTblCol = 0;
171183  pIter->azTblType = 0;
171184  pIter->aiSrcOrder = 0;
171185  pIter->abTblPk = 0;
171186  pIter->abNotNull = 0;
171187  pIter->nTblCol = 0;
171188  pIter->eType = 0;               /* Invalid value */
171189}
171190
171191/*
171192** Finalize all statements and free all allocations that are specific to
171193** the current object (table/index pair).
171194*/
171195static void rbuObjIterClearStatements(RbuObjIter *pIter){
171196  RbuUpdateStmt *pUp;
171197
171198  sqlite3_finalize(pIter->pSelect);
171199  sqlite3_finalize(pIter->pInsert);
171200  sqlite3_finalize(pIter->pDelete);
171201  sqlite3_finalize(pIter->pTmpInsert);
171202  pUp = pIter->pRbuUpdate;
171203  while( pUp ){
171204    RbuUpdateStmt *pTmp = pUp->pNext;
171205    sqlite3_finalize(pUp->pUpdate);
171206    sqlite3_free(pUp);
171207    pUp = pTmp;
171208  }
171209
171210  pIter->pSelect = 0;
171211  pIter->pInsert = 0;
171212  pIter->pDelete = 0;
171213  pIter->pRbuUpdate = 0;
171214  pIter->pTmpInsert = 0;
171215  pIter->nCol = 0;
171216}
171217
171218/*
171219** Clean up any resources allocated as part of the iterator object passed
171220** as the only argument.
171221*/
171222static void rbuObjIterFinalize(RbuObjIter *pIter){
171223  rbuObjIterClearStatements(pIter);
171224  sqlite3_finalize(pIter->pTblIter);
171225  sqlite3_finalize(pIter->pIdxIter);
171226  rbuObjIterFreeCols(pIter);
171227  memset(pIter, 0, sizeof(RbuObjIter));
171228}
171229
171230/*
171231** Advance the iterator to the next position.
171232**
171233** If no error occurs, SQLITE_OK is returned and the iterator is left
171234** pointing to the next entry. Otherwise, an error code and message is
171235** left in the RBU handle passed as the first argument. A copy of the
171236** error code is returned.
171237*/
171238static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
171239  int rc = p->rc;
171240  if( rc==SQLITE_OK ){
171241
171242    /* Free any SQLite statements used while processing the previous object */
171243    rbuObjIterClearStatements(pIter);
171244    if( pIter->zIdx==0 ){
171245      rc = sqlite3_exec(p->dbMain,
171246          "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
171247          "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
171248          "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
171249          "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
171250          , 0, 0, &p->zErrmsg
171251      );
171252    }
171253
171254    if( rc==SQLITE_OK ){
171255      if( pIter->bCleanup ){
171256        rbuObjIterFreeCols(pIter);
171257        pIter->bCleanup = 0;
171258        rc = sqlite3_step(pIter->pTblIter);
171259        if( rc!=SQLITE_ROW ){
171260          rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
171261          pIter->zTbl = 0;
171262        }else{
171263          pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
171264          pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
171265          rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
171266        }
171267      }else{
171268        if( pIter->zIdx==0 ){
171269          sqlite3_stmt *pIdx = pIter->pIdxIter;
171270          rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
171271        }
171272        if( rc==SQLITE_OK ){
171273          rc = sqlite3_step(pIter->pIdxIter);
171274          if( rc!=SQLITE_ROW ){
171275            rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
171276            pIter->bCleanup = 1;
171277            pIter->zIdx = 0;
171278          }else{
171279            pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
171280            pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
171281            pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
171282            rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
171283          }
171284        }
171285      }
171286    }
171287  }
171288
171289  if( rc!=SQLITE_OK ){
171290    rbuObjIterFinalize(pIter);
171291    p->rc = rc;
171292  }
171293  return rc;
171294}
171295
171296
171297/*
171298** The implementation of the rbu_target_name() SQL function. This function
171299** accepts one or two arguments. The first argument is the name of a table -
171300** the name of a table in the RBU database.  The second, if it is present, is 1
171301** for a view or 0 for a table.
171302**
171303** For a non-vacuum RBU handle, if the table name matches the pattern:
171304**
171305**     data[0-9]_<name>
171306**
171307** where <name> is any sequence of 1 or more characters, <name> is returned.
171308** Otherwise, if the only argument does not match the above pattern, an SQL
171309** NULL is returned.
171310**
171311**     "data_t1"     -> "t1"
171312**     "data0123_t2" -> "t2"
171313**     "dataAB_t3"   -> NULL
171314**
171315** For an rbu vacuum handle, a copy of the first argument is returned if
171316** the second argument is either missing or 0 (not a view).
171317*/
171318static void rbuTargetNameFunc(
171319  sqlite3_context *pCtx,
171320  int argc,
171321  sqlite3_value **argv
171322){
171323  sqlite3rbu *p = sqlite3_user_data(pCtx);
171324  const char *zIn;
171325  assert( argc==1 || argc==2 );
171326
171327  zIn = (const char*)sqlite3_value_text(argv[0]);
171328  if( zIn ){
171329    if( rbuIsVacuum(p) ){
171330      if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
171331        sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
171332      }
171333    }else{
171334      if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
171335        int i;
171336        for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
171337        if( zIn[i]=='_' && zIn[i+1] ){
171338          sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
171339        }
171340      }
171341    }
171342  }
171343}
171344
171345/*
171346** Initialize the iterator structure passed as the second argument.
171347**
171348** If no error occurs, SQLITE_OK is returned and the iterator is left
171349** pointing to the first entry. Otherwise, an error code and message is
171350** left in the RBU handle passed as the first argument. A copy of the
171351** error code is returned.
171352*/
171353static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
171354  int rc;
171355  memset(pIter, 0, sizeof(RbuObjIter));
171356
171357  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
171358    sqlite3_mprintf(
171359      "SELECT rbu_target_name(name, type='view') AS target, name "
171360      "FROM sqlite_master "
171361      "WHERE type IN ('table', 'view') AND target IS NOT NULL "
171362      " %s "
171363      "ORDER BY name"
171364  , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
171365
171366  if( rc==SQLITE_OK ){
171367    rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
171368        "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
171369        "  FROM main.sqlite_master "
171370        "  WHERE type='index' AND tbl_name = ?"
171371    );
171372  }
171373
171374  pIter->bCleanup = 1;
171375  p->rc = rc;
171376  return rbuObjIterNext(p, pIter);
171377}
171378
171379/*
171380** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
171381** an error code is stored in the RBU handle passed as the first argument.
171382**
171383** If an error has already occurred (p->rc is already set to something other
171384** than SQLITE_OK), then this function returns NULL without modifying the
171385** stored error code. In this case it still calls sqlite3_free() on any
171386** printf() parameters associated with %z conversions.
171387*/
171388static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
171389  char *zSql = 0;
171390  va_list ap;
171391  va_start(ap, zFmt);
171392  zSql = sqlite3_vmprintf(zFmt, ap);
171393  if( p->rc==SQLITE_OK ){
171394    if( zSql==0 ) p->rc = SQLITE_NOMEM;
171395  }else{
171396    sqlite3_free(zSql);
171397    zSql = 0;
171398  }
171399  va_end(ap);
171400  return zSql;
171401}
171402
171403/*
171404** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
171405** arguments are the usual subsitution values. This function performs
171406** the printf() style substitutions and executes the result as an SQL
171407** statement on the RBU handles database.
171408**
171409** If an error occurs, an error code and error message is stored in the
171410** RBU handle. If an error has already occurred when this function is
171411** called, it is a no-op.
171412*/
171413static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
171414  va_list ap;
171415  char *zSql;
171416  va_start(ap, zFmt);
171417  zSql = sqlite3_vmprintf(zFmt, ap);
171418  if( p->rc==SQLITE_OK ){
171419    if( zSql==0 ){
171420      p->rc = SQLITE_NOMEM;
171421    }else{
171422      p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
171423    }
171424  }
171425  sqlite3_free(zSql);
171426  va_end(ap);
171427  return p->rc;
171428}
171429
171430/*
171431** Attempt to allocate and return a pointer to a zeroed block of nByte
171432** bytes.
171433**
171434** If an error (i.e. an OOM condition) occurs, return NULL and leave an
171435** error code in the rbu handle passed as the first argument. Or, if an
171436** error has already occurred when this function is called, return NULL
171437** immediately without attempting the allocation or modifying the stored
171438** error code.
171439*/
171440static void *rbuMalloc(sqlite3rbu *p, int nByte){
171441  void *pRet = 0;
171442  if( p->rc==SQLITE_OK ){
171443    assert( nByte>0 );
171444    pRet = sqlite3_malloc64(nByte);
171445    if( pRet==0 ){
171446      p->rc = SQLITE_NOMEM;
171447    }else{
171448      memset(pRet, 0, nByte);
171449    }
171450  }
171451  return pRet;
171452}
171453
171454
171455/*
171456** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
171457** there is room for at least nCol elements. If an OOM occurs, store an
171458** error code in the RBU handle passed as the first argument.
171459*/
171460static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
171461  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
171462  char **azNew;
171463
171464  azNew = (char**)rbuMalloc(p, nByte);
171465  if( azNew ){
171466    pIter->azTblCol = azNew;
171467    pIter->azTblType = &azNew[nCol];
171468    pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
171469    pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
171470    pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
171471    pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
171472  }
171473}
171474
171475/*
171476** The first argument must be a nul-terminated string. This function
171477** returns a copy of the string in memory obtained from sqlite3_malloc().
171478** It is the responsibility of the caller to eventually free this memory
171479** using sqlite3_free().
171480**
171481** If an OOM condition is encountered when attempting to allocate memory,
171482** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
171483** if the allocation succeeds, (*pRc) is left unchanged.
171484*/
171485static char *rbuStrndup(const char *zStr, int *pRc){
171486  char *zRet = 0;
171487
171488  assert( *pRc==SQLITE_OK );
171489  if( zStr ){
171490    size_t nCopy = strlen(zStr) + 1;
171491    zRet = (char*)sqlite3_malloc64(nCopy);
171492    if( zRet ){
171493      memcpy(zRet, zStr, nCopy);
171494    }else{
171495      *pRc = SQLITE_NOMEM;
171496    }
171497  }
171498
171499  return zRet;
171500}
171501
171502/*
171503** Finalize the statement passed as the second argument.
171504**
171505** If the sqlite3_finalize() call indicates that an error occurs, and the
171506** rbu handle error code is not already set, set the error code and error
171507** message accordingly.
171508*/
171509static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
171510  sqlite3 *db = sqlite3_db_handle(pStmt);
171511  int rc = sqlite3_finalize(pStmt);
171512  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
171513    p->rc = rc;
171514    p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
171515  }
171516}
171517
171518/* Determine the type of a table.
171519**
171520**   peType is of type (int*), a pointer to an output parameter of type
171521**   (int). This call sets the output parameter as follows, depending
171522**   on the type of the table specified by parameters dbName and zTbl.
171523**
171524**     RBU_PK_NOTABLE:       No such table.
171525**     RBU_PK_NONE:          Table has an implicit rowid.
171526**     RBU_PK_IPK:           Table has an explicit IPK column.
171527**     RBU_PK_EXTERNAL:      Table has an external PK index.
171528**     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
171529**     RBU_PK_VTAB:          Table is a virtual table.
171530**
171531**   Argument *piPk is also of type (int*), and also points to an output
171532**   parameter. Unless the table has an external primary key index
171533**   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
171534**   if the table does have an external primary key index, then *piPk
171535**   is set to the root page number of the primary key index before
171536**   returning.
171537**
171538** ALGORITHM:
171539**
171540**   if( no entry exists in sqlite_master ){
171541**     return RBU_PK_NOTABLE
171542**   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
171543**     return RBU_PK_VTAB
171544**   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
171545**     if( the index that is the pk exists in sqlite_master ){
171546**       *piPK = rootpage of that index.
171547**       return RBU_PK_EXTERNAL
171548**     }else{
171549**       return RBU_PK_WITHOUT_ROWID
171550**     }
171551**   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
171552**     return RBU_PK_IPK
171553**   }else{
171554**     return RBU_PK_NONE
171555**   }
171556*/
171557static void rbuTableType(
171558  sqlite3rbu *p,
171559  const char *zTab,
171560  int *peType,
171561  int *piTnum,
171562  int *piPk
171563){
171564  /*
171565  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
171566  ** 1) PRAGMA index_list = ?
171567  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
171568  ** 3) PRAGMA table_info = ?
171569  */
171570  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
171571
171572  *peType = RBU_PK_NOTABLE;
171573  *piPk = 0;
171574
171575  assert( p->rc==SQLITE_OK );
171576  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
171577    sqlite3_mprintf(
171578          "SELECT (sql LIKE 'create virtual%%'), rootpage"
171579          "  FROM sqlite_master"
171580          " WHERE name=%Q", zTab
171581  ));
171582  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
171583    /* Either an error, or no such table. */
171584    goto rbuTableType_end;
171585  }
171586  if( sqlite3_column_int(aStmt[0], 0) ){
171587    *peType = RBU_PK_VTAB;                     /* virtual table */
171588    goto rbuTableType_end;
171589  }
171590  *piTnum = sqlite3_column_int(aStmt[0], 1);
171591
171592  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
171593    sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
171594  );
171595  if( p->rc ) goto rbuTableType_end;
171596  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
171597    const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
171598    const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
171599    if( zOrig && zIdx && zOrig[0]=='p' ){
171600      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
171601          sqlite3_mprintf(
171602            "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
171603      ));
171604      if( p->rc==SQLITE_OK ){
171605        if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
171606          *piPk = sqlite3_column_int(aStmt[2], 0);
171607          *peType = RBU_PK_EXTERNAL;
171608        }else{
171609          *peType = RBU_PK_WITHOUT_ROWID;
171610        }
171611      }
171612      goto rbuTableType_end;
171613    }
171614  }
171615
171616  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
171617    sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
171618  );
171619  if( p->rc==SQLITE_OK ){
171620    while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
171621      if( sqlite3_column_int(aStmt[3],5)>0 ){
171622        *peType = RBU_PK_IPK;                /* explicit IPK column */
171623        goto rbuTableType_end;
171624      }
171625    }
171626    *peType = RBU_PK_NONE;
171627  }
171628
171629rbuTableType_end: {
171630    unsigned int i;
171631    for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
171632      rbuFinalize(p, aStmt[i]);
171633    }
171634  }
171635}
171636
171637/*
171638** This is a helper function for rbuObjIterCacheTableInfo(). It populates
171639** the pIter->abIndexed[] array.
171640*/
171641static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
171642  sqlite3_stmt *pList = 0;
171643  int bIndex = 0;
171644
171645  if( p->rc==SQLITE_OK ){
171646    memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
171647    p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
171648        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
171649    );
171650  }
171651
171652  pIter->nIndex = 0;
171653  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
171654    const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
171655    sqlite3_stmt *pXInfo = 0;
171656    if( zIdx==0 ) break;
171657    p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
171658        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
171659    );
171660    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
171661      int iCid = sqlite3_column_int(pXInfo, 1);
171662      if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
171663    }
171664    rbuFinalize(p, pXInfo);
171665    bIndex = 1;
171666    pIter->nIndex++;
171667  }
171668
171669  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
171670    /* "PRAGMA index_list" includes the main PK b-tree */
171671    pIter->nIndex--;
171672  }
171673
171674  rbuFinalize(p, pList);
171675  if( bIndex==0 ) pIter->abIndexed = 0;
171676}
171677
171678
171679/*
171680** If they are not already populated, populate the pIter->azTblCol[],
171681** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
171682** the table (not index) that the iterator currently points to.
171683**
171684** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
171685** an error does occur, an error code and error message are also left in
171686** the RBU handle.
171687*/
171688static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
171689  if( pIter->azTblCol==0 ){
171690    sqlite3_stmt *pStmt = 0;
171691    int nCol = 0;
171692    int i;                        /* for() loop iterator variable */
171693    int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
171694    int iOrder = 0;
171695    int iTnum = 0;
171696
171697    /* Figure out the type of table this step will deal with. */
171698    assert( pIter->eType==0 );
171699    rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
171700    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
171701      p->rc = SQLITE_ERROR;
171702      p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
171703    }
171704    if( p->rc ) return p->rc;
171705    if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
171706
171707    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
171708         || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
171709         || pIter->eType==RBU_PK_VTAB
171710    );
171711
171712    /* Populate the azTblCol[] and nTblCol variables based on the columns
171713    ** of the input table. Ignore any input table columns that begin with
171714    ** "rbu_".  */
171715    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
171716        sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
171717    );
171718    if( p->rc==SQLITE_OK ){
171719      nCol = sqlite3_column_count(pStmt);
171720      rbuAllocateIterArrays(p, pIter, nCol);
171721    }
171722    for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
171723      const char *zName = (const char*)sqlite3_column_name(pStmt, i);
171724      if( sqlite3_strnicmp("rbu_", zName, 4) ){
171725        char *zCopy = rbuStrndup(zName, &p->rc);
171726        pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
171727        pIter->azTblCol[pIter->nTblCol++] = zCopy;
171728      }
171729      else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
171730        bRbuRowid = 1;
171731      }
171732    }
171733    sqlite3_finalize(pStmt);
171734    pStmt = 0;
171735
171736    if( p->rc==SQLITE_OK
171737     && rbuIsVacuum(p)==0
171738     && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
171739    ){
171740      p->rc = SQLITE_ERROR;
171741      p->zErrmsg = sqlite3_mprintf(
171742          "table %q %s rbu_rowid column", pIter->zDataTbl,
171743          (bRbuRowid ? "may not have" : "requires")
171744      );
171745    }
171746
171747    /* Check that all non-HIDDEN columns in the destination table are also
171748    ** present in the input table. Populate the abTblPk[], azTblType[] and
171749    ** aiTblOrder[] arrays at the same time.  */
171750    if( p->rc==SQLITE_OK ){
171751      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
171752          sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
171753      );
171754    }
171755    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
171756      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
171757      if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
171758      for(i=iOrder; i<pIter->nTblCol; i++){
171759        if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
171760      }
171761      if( i==pIter->nTblCol ){
171762        p->rc = SQLITE_ERROR;
171763        p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
171764            pIter->zDataTbl, zName
171765        );
171766      }else{
171767        int iPk = sqlite3_column_int(pStmt, 5);
171768        int bNotNull = sqlite3_column_int(pStmt, 3);
171769        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
171770
171771        if( i!=iOrder ){
171772          SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
171773          SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
171774        }
171775
171776        pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
171777        pIter->abTblPk[iOrder] = (iPk!=0);
171778        pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
171779        iOrder++;
171780      }
171781    }
171782
171783    rbuFinalize(p, pStmt);
171784    rbuObjIterCacheIndexedCols(p, pIter);
171785    assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
171786    assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
171787  }
171788
171789  return p->rc;
171790}
171791
171792/*
171793** This function constructs and returns a pointer to a nul-terminated
171794** string containing some SQL clause or list based on one or more of the
171795** column names currently stored in the pIter->azTblCol[] array.
171796*/
171797static char *rbuObjIterGetCollist(
171798  sqlite3rbu *p,                  /* RBU object */
171799  RbuObjIter *pIter               /* Object iterator for column names */
171800){
171801  char *zList = 0;
171802  const char *zSep = "";
171803  int i;
171804  for(i=0; i<pIter->nTblCol; i++){
171805    const char *z = pIter->azTblCol[i];
171806    zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
171807    zSep = ", ";
171808  }
171809  return zList;
171810}
171811
171812/*
171813** This function is used to create a SELECT list (the list of SQL
171814** expressions that follows a SELECT keyword) for a SELECT statement
171815** used to read from an data_xxx or rbu_tmp_xxx table while updating the
171816** index object currently indicated by the iterator object passed as the
171817** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
171818** to obtain the required information.
171819**
171820** If the index is of the following form:
171821**
171822**   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
171823**
171824** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
171825** "ipk", the returned string is:
171826**
171827**   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
171828**
171829** As well as the returned string, three other malloc'd strings are
171830** returned via output parameters. As follows:
171831**
171832**   pzImposterCols: ...
171833**   pzImposterPk: ...
171834**   pzWhere: ...
171835*/
171836static char *rbuObjIterGetIndexCols(
171837  sqlite3rbu *p,                  /* RBU object */
171838  RbuObjIter *pIter,              /* Object iterator for column names */
171839  char **pzImposterCols,          /* OUT: Columns for imposter table */
171840  char **pzImposterPk,            /* OUT: Imposter PK clause */
171841  char **pzWhere,                 /* OUT: WHERE clause */
171842  int *pnBind                     /* OUT: Trbul number of columns */
171843){
171844  int rc = p->rc;                 /* Error code */
171845  int rc2;                        /* sqlite3_finalize() return code */
171846  char *zRet = 0;                 /* String to return */
171847  char *zImpCols = 0;             /* String to return via *pzImposterCols */
171848  char *zImpPK = 0;               /* String to return via *pzImposterPK */
171849  char *zWhere = 0;               /* String to return via *pzWhere */
171850  int nBind = 0;                  /* Value to return via *pnBind */
171851  const char *zCom = "";          /* Set to ", " later on */
171852  const char *zAnd = "";          /* Set to " AND " later on */
171853  sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
171854
171855  if( rc==SQLITE_OK ){
171856    assert( p->zErrmsg==0 );
171857    rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
171858        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
171859    );
171860  }
171861
171862  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
171863    int iCid = sqlite3_column_int(pXInfo, 1);
171864    int bDesc = sqlite3_column_int(pXInfo, 3);
171865    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
171866    const char *zCol;
171867    const char *zType;
171868
171869    if( iCid<0 ){
171870      /* An integer primary key. If the table has an explicit IPK, use
171871      ** its name. Otherwise, use "rbu_rowid".  */
171872      if( pIter->eType==RBU_PK_IPK ){
171873        int i;
171874        for(i=0; pIter->abTblPk[i]==0; i++);
171875        assert( i<pIter->nTblCol );
171876        zCol = pIter->azTblCol[i];
171877      }else if( rbuIsVacuum(p) ){
171878        zCol = "_rowid_";
171879      }else{
171880        zCol = "rbu_rowid";
171881      }
171882      zType = "INTEGER";
171883    }else{
171884      zCol = pIter->azTblCol[iCid];
171885      zType = pIter->azTblType[iCid];
171886    }
171887
171888    zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
171889    if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
171890      const char *zOrder = (bDesc ? " DESC" : "");
171891      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
171892          zImpPK, zCom, nBind, zCol, zOrder
171893      );
171894    }
171895    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
171896        zImpCols, zCom, nBind, zCol, zType, zCollate
171897    );
171898    zWhere = sqlite3_mprintf(
171899        "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
171900    );
171901    if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
171902    zCom = ", ";
171903    zAnd = " AND ";
171904    nBind++;
171905  }
171906
171907  rc2 = sqlite3_finalize(pXInfo);
171908  if( rc==SQLITE_OK ) rc = rc2;
171909
171910  if( rc!=SQLITE_OK ){
171911    sqlite3_free(zRet);
171912    sqlite3_free(zImpCols);
171913    sqlite3_free(zImpPK);
171914    sqlite3_free(zWhere);
171915    zRet = 0;
171916    zImpCols = 0;
171917    zImpPK = 0;
171918    zWhere = 0;
171919    p->rc = rc;
171920  }
171921
171922  *pzImposterCols = zImpCols;
171923  *pzImposterPk = zImpPK;
171924  *pzWhere = zWhere;
171925  *pnBind = nBind;
171926  return zRet;
171927}
171928
171929/*
171930** Assuming the current table columns are "a", "b" and "c", and the zObj
171931** paramter is passed "old", return a string of the form:
171932**
171933**     "old.a, old.b, old.b"
171934**
171935** With the column names escaped.
171936**
171937** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
171938** the text ", old._rowid_" to the returned value.
171939*/
171940static char *rbuObjIterGetOldlist(
171941  sqlite3rbu *p,
171942  RbuObjIter *pIter,
171943  const char *zObj
171944){
171945  char *zList = 0;
171946  if( p->rc==SQLITE_OK && pIter->abIndexed ){
171947    const char *zS = "";
171948    int i;
171949    for(i=0; i<pIter->nTblCol; i++){
171950      if( pIter->abIndexed[i] ){
171951        const char *zCol = pIter->azTblCol[i];
171952        zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
171953      }else{
171954        zList = sqlite3_mprintf("%z%sNULL", zList, zS);
171955      }
171956      zS = ", ";
171957      if( zList==0 ){
171958        p->rc = SQLITE_NOMEM;
171959        break;
171960      }
171961    }
171962
171963    /* For a table with implicit rowids, append "old._rowid_" to the list. */
171964    if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
171965      zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
171966    }
171967  }
171968  return zList;
171969}
171970
171971/*
171972** Return an expression that can be used in a WHERE clause to match the
171973** primary key of the current table. For example, if the table is:
171974**
171975**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
171976**
171977** Return the string:
171978**
171979**   "b = ?1 AND c = ?2"
171980*/
171981static char *rbuObjIterGetWhere(
171982  sqlite3rbu *p,
171983  RbuObjIter *pIter
171984){
171985  char *zList = 0;
171986  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
171987    zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
171988  }else if( pIter->eType==RBU_PK_EXTERNAL ){
171989    const char *zSep = "";
171990    int i;
171991    for(i=0; i<pIter->nTblCol; i++){
171992      if( pIter->abTblPk[i] ){
171993        zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
171994        zSep = " AND ";
171995      }
171996    }
171997    zList = rbuMPrintf(p,
171998        "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
171999    );
172000
172001  }else{
172002    const char *zSep = "";
172003    int i;
172004    for(i=0; i<pIter->nTblCol; i++){
172005      if( pIter->abTblPk[i] ){
172006        const char *zCol = pIter->azTblCol[i];
172007        zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
172008        zSep = " AND ";
172009      }
172010    }
172011  }
172012  return zList;
172013}
172014
172015/*
172016** The SELECT statement iterating through the keys for the current object
172017** (p->objiter.pSelect) currently points to a valid row. However, there
172018** is something wrong with the rbu_control value in the rbu_control value
172019** stored in the (p->nCol+1)'th column. Set the error code and error message
172020** of the RBU handle to something reflecting this.
172021*/
172022static void rbuBadControlError(sqlite3rbu *p){
172023  p->rc = SQLITE_ERROR;
172024  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
172025}
172026
172027
172028/*
172029** Return a nul-terminated string containing the comma separated list of
172030** assignments that should be included following the "SET" keyword of
172031** an UPDATE statement used to update the table object that the iterator
172032** passed as the second argument currently points to if the rbu_control
172033** column of the data_xxx table entry is set to zMask.
172034**
172035** The memory for the returned string is obtained from sqlite3_malloc().
172036** It is the responsibility of the caller to eventually free it using
172037** sqlite3_free().
172038**
172039** If an OOM error is encountered when allocating space for the new
172040** string, an error code is left in the rbu handle passed as the first
172041** argument and NULL is returned. Or, if an error has already occurred
172042** when this function is called, NULL is returned immediately, without
172043** attempting the allocation or modifying the stored error code.
172044*/
172045static char *rbuObjIterGetSetlist(
172046  sqlite3rbu *p,
172047  RbuObjIter *pIter,
172048  const char *zMask
172049){
172050  char *zList = 0;
172051  if( p->rc==SQLITE_OK ){
172052    int i;
172053
172054    if( (int)strlen(zMask)!=pIter->nTblCol ){
172055      rbuBadControlError(p);
172056    }else{
172057      const char *zSep = "";
172058      for(i=0; i<pIter->nTblCol; i++){
172059        char c = zMask[pIter->aiSrcOrder[i]];
172060        if( c=='x' ){
172061          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
172062              zList, zSep, pIter->azTblCol[i], i+1
172063          );
172064          zSep = ", ";
172065        }
172066        else if( c=='d' ){
172067          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
172068              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
172069          );
172070          zSep = ", ";
172071        }
172072        else if( c=='f' ){
172073          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
172074              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
172075          );
172076          zSep = ", ";
172077        }
172078      }
172079    }
172080  }
172081  return zList;
172082}
172083
172084/*
172085** Return a nul-terminated string consisting of nByte comma separated
172086** "?" expressions. For example, if nByte is 3, return a pointer to
172087** a buffer containing the string "?,?,?".
172088**
172089** The memory for the returned string is obtained from sqlite3_malloc().
172090** It is the responsibility of the caller to eventually free it using
172091** sqlite3_free().
172092**
172093** If an OOM error is encountered when allocating space for the new
172094** string, an error code is left in the rbu handle passed as the first
172095** argument and NULL is returned. Or, if an error has already occurred
172096** when this function is called, NULL is returned immediately, without
172097** attempting the allocation or modifying the stored error code.
172098*/
172099static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
172100  char *zRet = 0;
172101  int nByte = nBind*2 + 1;
172102
172103  zRet = (char*)rbuMalloc(p, nByte);
172104  if( zRet ){
172105    int i;
172106    for(i=0; i<nBind; i++){
172107      zRet[i*2] = '?';
172108      zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
172109    }
172110  }
172111  return zRet;
172112}
172113
172114/*
172115** The iterator currently points to a table (not index) of type
172116** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
172117** declaration for the corresponding imposter table. For example,
172118** if the iterator points to a table created as:
172119**
172120**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
172121**
172122** this function returns:
172123**
172124**   PRIMARY KEY("b", "a" DESC)
172125*/
172126static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
172127  char *z = 0;
172128  assert( pIter->zIdx==0 );
172129  if( p->rc==SQLITE_OK ){
172130    const char *zSep = "PRIMARY KEY(";
172131    sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
172132    sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
172133
172134    p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
172135        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
172136    );
172137    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
172138      const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
172139      if( zOrig && strcmp(zOrig, "pk")==0 ){
172140        const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
172141        if( zIdx ){
172142          p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172143              sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
172144          );
172145        }
172146        break;
172147      }
172148    }
172149    rbuFinalize(p, pXList);
172150
172151    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172152      if( sqlite3_column_int(pXInfo, 5) ){
172153        /* int iCid = sqlite3_column_int(pXInfo, 0); */
172154        const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
172155        const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
172156        z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
172157        zSep = ", ";
172158      }
172159    }
172160    z = rbuMPrintf(p, "%z)", z);
172161    rbuFinalize(p, pXInfo);
172162  }
172163  return z;
172164}
172165
172166/*
172167** This function creates the second imposter table used when writing to
172168** a table b-tree where the table has an external primary key. If the
172169** iterator passed as the second argument does not currently point to
172170** a table (not index) with an external primary key, this function is a
172171** no-op.
172172**
172173** Assuming the iterator does point to a table with an external PK, this
172174** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
172175** used to access that PK index. For example, if the target table is
172176** declared as follows:
172177**
172178**   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
172179**
172180** then the imposter table schema is:
172181**
172182**   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
172183**
172184*/
172185static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
172186  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
172187    int tnum = pIter->iPkTnum;    /* Root page of PK index */
172188    sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
172189    const char *zIdx = 0;         /* Name of PK index */
172190    sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
172191    const char *zComma = "";
172192    char *zCols = 0;              /* Used to build up list of table cols */
172193    char *zPk = 0;                /* Used to build up table PK declaration */
172194
172195    /* Figure out the name of the primary key index for the current table.
172196    ** This is needed for the argument to "PRAGMA index_xinfo". Set
172197    ** zIdx to point to a nul-terminated string containing this name. */
172198    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
172199        "SELECT name FROM sqlite_master WHERE rootpage = ?"
172200    );
172201    if( p->rc==SQLITE_OK ){
172202      sqlite3_bind_int(pQuery, 1, tnum);
172203      if( SQLITE_ROW==sqlite3_step(pQuery) ){
172204        zIdx = (const char*)sqlite3_column_text(pQuery, 0);
172205      }
172206    }
172207    if( zIdx ){
172208      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
172209          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
172210      );
172211    }
172212    rbuFinalize(p, pQuery);
172213
172214    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
172215      int bKey = sqlite3_column_int(pXInfo, 5);
172216      if( bKey ){
172217        int iCid = sqlite3_column_int(pXInfo, 1);
172218        int bDesc = sqlite3_column_int(pXInfo, 3);
172219        const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
172220        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
172221            iCid, pIter->azTblType[iCid], zCollate
172222        );
172223        zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
172224        zComma = ", ";
172225      }
172226    }
172227    zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
172228    rbuFinalize(p, pXInfo);
172229
172230    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
172231    rbuMPrintfExec(p, p->dbMain,
172232        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
172233        zCols, zPk
172234    );
172235    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172236  }
172237}
172238
172239/*
172240** If an error has already occurred when this function is called, it
172241** immediately returns zero (without doing any work). Or, if an error
172242** occurs during the execution of this function, it sets the error code
172243** in the sqlite3rbu object indicated by the first argument and returns
172244** zero.
172245**
172246** The iterator passed as the second argument is guaranteed to point to
172247** a table (not an index) when this function is called. This function
172248** attempts to create any imposter table required to write to the main
172249** table b-tree of the table before returning. Non-zero is returned if
172250** an imposter table are created, or zero otherwise.
172251**
172252** An imposter table is required in all cases except RBU_PK_VTAB. Only
172253** virtual tables are written to directly. The imposter table has the
172254** same schema as the actual target table (less any UNIQUE constraints).
172255** More precisely, the "same schema" means the same columns, types,
172256** collation sequences. For tables that do not have an external PRIMARY
172257** KEY, it also means the same PRIMARY KEY declaration.
172258*/
172259static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
172260  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
172261    int tnum = pIter->iTnum;
172262    const char *zComma = "";
172263    char *zSql = 0;
172264    int iCol;
172265    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
172266
172267    for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
172268      const char *zPk = "";
172269      const char *zCol = pIter->azTblCol[iCol];
172270      const char *zColl = 0;
172271
172272      p->rc = sqlite3_table_column_metadata(
172273          p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
172274      );
172275
172276      if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
172277        /* If the target table column is an "INTEGER PRIMARY KEY", add
172278        ** "PRIMARY KEY" to the imposter table column declaration. */
172279        zPk = "PRIMARY KEY ";
172280      }
172281      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
172282          zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
172283          (pIter->abNotNull[iCol] ? " NOT NULL" : "")
172284      );
172285      zComma = ", ";
172286    }
172287
172288    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
172289      char *zPk = rbuWithoutRowidPK(p, pIter);
172290      if( zPk ){
172291        zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
172292      }
172293    }
172294
172295    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
172296    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
172297        pIter->zTbl, zSql,
172298        (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
172299    );
172300    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172301  }
172302}
172303
172304/*
172305** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
172306** Specifically a statement of the form:
172307**
172308**     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
172309**
172310** The number of bound variables is equal to the number of columns in
172311** the target table, plus one (for the rbu_control column), plus one more
172312** (for the rbu_rowid column) if the target table is an implicit IPK or
172313** virtual table.
172314*/
172315static void rbuObjIterPrepareTmpInsert(
172316  sqlite3rbu *p,
172317  RbuObjIter *pIter,
172318  const char *zCollist,
172319  const char *zRbuRowid
172320){
172321  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
172322  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
172323  if( zBind ){
172324    assert( pIter->pTmpInsert==0 );
172325    p->rc = prepareFreeAndCollectError(
172326        p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
172327          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
172328          p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
172329    ));
172330  }
172331}
172332
172333static void rbuTmpInsertFunc(
172334  sqlite3_context *pCtx,
172335  int nVal,
172336  sqlite3_value **apVal
172337){
172338  sqlite3rbu *p = sqlite3_user_data(pCtx);
172339  int rc = SQLITE_OK;
172340  int i;
172341
172342  assert( sqlite3_value_int(apVal[0])!=0
172343      || p->objiter.eType==RBU_PK_EXTERNAL
172344      || p->objiter.eType==RBU_PK_NONE
172345  );
172346  if( sqlite3_value_int(apVal[0])!=0 ){
172347    p->nPhaseOneStep += p->objiter.nIndex;
172348  }
172349
172350  for(i=0; rc==SQLITE_OK && i<nVal; i++){
172351    rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
172352  }
172353  if( rc==SQLITE_OK ){
172354    sqlite3_step(p->objiter.pTmpInsert);
172355    rc = sqlite3_reset(p->objiter.pTmpInsert);
172356  }
172357
172358  if( rc!=SQLITE_OK ){
172359    sqlite3_result_error_code(pCtx, rc);
172360  }
172361}
172362
172363/*
172364** Ensure that the SQLite statement handles required to update the
172365** target database object currently indicated by the iterator passed
172366** as the second argument are available.
172367*/
172368static int rbuObjIterPrepareAll(
172369  sqlite3rbu *p,
172370  RbuObjIter *pIter,
172371  int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
172372){
172373  assert( pIter->bCleanup==0 );
172374  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
172375    const int tnum = pIter->iTnum;
172376    char *zCollist = 0;           /* List of indexed columns */
172377    char **pz = &p->zErrmsg;
172378    const char *zIdx = pIter->zIdx;
172379    char *zLimit = 0;
172380
172381    if( nOffset ){
172382      zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
172383      if( !zLimit ) p->rc = SQLITE_NOMEM;
172384    }
172385
172386    if( zIdx ){
172387      const char *zTbl = pIter->zTbl;
172388      char *zImposterCols = 0;    /* Columns for imposter table */
172389      char *zImposterPK = 0;      /* Primary key declaration for imposter */
172390      char *zWhere = 0;           /* WHERE clause on PK columns */
172391      char *zBind = 0;
172392      int nBind = 0;
172393
172394      assert( pIter->eType!=RBU_PK_VTAB );
172395      zCollist = rbuObjIterGetIndexCols(
172396          p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
172397      );
172398      zBind = rbuObjIterGetBindlist(p, nBind);
172399
172400      /* Create the imposter table used to write to this index. */
172401      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
172402      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
172403      rbuMPrintfExec(p, p->dbMain,
172404          "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
172405          zTbl, zImposterCols, zImposterPK
172406      );
172407      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
172408
172409      /* Create the statement to insert index entries */
172410      pIter->nCol = nBind;
172411      if( p->rc==SQLITE_OK ){
172412        p->rc = prepareFreeAndCollectError(
172413            p->dbMain, &pIter->pInsert, &p->zErrmsg,
172414          sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
172415        );
172416      }
172417
172418      /* And to delete index entries */
172419      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
172420        p->rc = prepareFreeAndCollectError(
172421            p->dbMain, &pIter->pDelete, &p->zErrmsg,
172422          sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
172423        );
172424      }
172425
172426      /* Create the SELECT statement to read keys in sorted order */
172427      if( p->rc==SQLITE_OK ){
172428        char *zSql;
172429        if( rbuIsVacuum(p) ){
172430          zSql = sqlite3_mprintf(
172431              "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
172432              zCollist,
172433              pIter->zDataTbl,
172434              zCollist, zLimit
172435          );
172436        }else
172437
172438        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172439          zSql = sqlite3_mprintf(
172440              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
172441              zCollist, p->zStateDb, pIter->zDataTbl,
172442              zCollist, zLimit
172443          );
172444        }else{
172445          zSql = sqlite3_mprintf(
172446              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
172447              "UNION ALL "
172448              "SELECT %s, rbu_control FROM '%q' "
172449              "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
172450              "ORDER BY %s%s",
172451              zCollist, p->zStateDb, pIter->zDataTbl,
172452              zCollist, pIter->zDataTbl,
172453              zCollist, zLimit
172454          );
172455        }
172456        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
172457      }
172458
172459      sqlite3_free(zImposterCols);
172460      sqlite3_free(zImposterPK);
172461      sqlite3_free(zWhere);
172462      sqlite3_free(zBind);
172463    }else{
172464      int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
172465                    ||(pIter->eType==RBU_PK_NONE)
172466                    ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
172467      const char *zTbl = pIter->zTbl;       /* Table this step applies to */
172468      const char *zWrite;                   /* Imposter table name */
172469
172470      char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
172471      char *zWhere = rbuObjIterGetWhere(p, pIter);
172472      char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
172473      char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
172474
172475      zCollist = rbuObjIterGetCollist(p, pIter);
172476      pIter->nCol = pIter->nTblCol;
172477
172478      /* Create the imposter table or tables (if required). */
172479      rbuCreateImposterTable(p, pIter);
172480      rbuCreateImposterTable2(p, pIter);
172481      zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
172482
172483      /* Create the INSERT statement to write to the target PK b-tree */
172484      if( p->rc==SQLITE_OK ){
172485        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
172486            sqlite3_mprintf(
172487              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
172488              zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
172489            )
172490        );
172491      }
172492
172493      /* Create the DELETE statement to write to the target PK b-tree.
172494      ** Because it only performs INSERT operations, this is not required for
172495      ** an rbu vacuum handle.  */
172496      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
172497        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
172498            sqlite3_mprintf(
172499              "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
172500            )
172501        );
172502      }
172503
172504      if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
172505        const char *zRbuRowid = "";
172506        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172507          zRbuRowid = ", rbu_rowid";
172508        }
172509
172510        /* Create the rbu_tmp_xxx table and the triggers to populate it. */
172511        rbuMPrintfExec(p, p->dbRbu,
172512            "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
172513            "SELECT *%s FROM '%q' WHERE 0;"
172514            , p->zStateDb, pIter->zDataTbl
172515            , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
172516            , pIter->zDataTbl
172517        );
172518
172519        rbuMPrintfExec(p, p->dbMain,
172520            "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
172521            "BEGIN "
172522            "  SELECT rbu_tmp_insert(3, %s);"
172523            "END;"
172524
172525            "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
172526            "BEGIN "
172527            "  SELECT rbu_tmp_insert(3, %s);"
172528            "END;"
172529
172530            "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
172531            "BEGIN "
172532            "  SELECT rbu_tmp_insert(4, %s);"
172533            "END;",
172534            zWrite, zTbl, zOldlist,
172535            zWrite, zTbl, zOldlist,
172536            zWrite, zTbl, zNewlist
172537        );
172538
172539        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
172540          rbuMPrintfExec(p, p->dbMain,
172541              "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
172542              "BEGIN "
172543              "  SELECT rbu_tmp_insert(0, %s);"
172544              "END;",
172545              zWrite, zTbl, zNewlist
172546          );
172547        }
172548
172549        rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
172550      }
172551
172552      /* Create the SELECT statement to read keys from data_xxx */
172553      if( p->rc==SQLITE_OK ){
172554        const char *zRbuRowid = "";
172555        if( bRbuRowid ){
172556          zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
172557        }
172558        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
172559            sqlite3_mprintf(
172560              "SELECT %s,%s rbu_control%s FROM '%q'%s",
172561              zCollist,
172562              (rbuIsVacuum(p) ? "0 AS " : ""),
172563              zRbuRowid,
172564              pIter->zDataTbl, zLimit
172565            )
172566        );
172567      }
172568
172569      sqlite3_free(zWhere);
172570      sqlite3_free(zOldlist);
172571      sqlite3_free(zNewlist);
172572      sqlite3_free(zBindings);
172573    }
172574    sqlite3_free(zCollist);
172575    sqlite3_free(zLimit);
172576  }
172577
172578  return p->rc;
172579}
172580
172581/*
172582** Set output variable *ppStmt to point to an UPDATE statement that may
172583** be used to update the imposter table for the main table b-tree of the
172584** table object that pIter currently points to, assuming that the
172585** rbu_control column of the data_xyz table contains zMask.
172586**
172587** If the zMask string does not specify any columns to update, then this
172588** is not an error. Output variable *ppStmt is set to NULL in this case.
172589*/
172590static int rbuGetUpdateStmt(
172591  sqlite3rbu *p,                  /* RBU handle */
172592  RbuObjIter *pIter,              /* Object iterator */
172593  const char *zMask,              /* rbu_control value ('x.x.') */
172594  sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
172595){
172596  RbuUpdateStmt **pp;
172597  RbuUpdateStmt *pUp = 0;
172598  int nUp = 0;
172599
172600  /* In case an error occurs */
172601  *ppStmt = 0;
172602
172603  /* Search for an existing statement. If one is found, shift it to the front
172604  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
172605  ** to the number of statements currently in the cache and pUp to the
172606  ** last object in the list.  */
172607  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
172608    pUp = *pp;
172609    if( strcmp(pUp->zMask, zMask)==0 ){
172610      *pp = pUp->pNext;
172611      pUp->pNext = pIter->pRbuUpdate;
172612      pIter->pRbuUpdate = pUp;
172613      *ppStmt = pUp->pUpdate;
172614      return SQLITE_OK;
172615    }
172616    nUp++;
172617  }
172618  assert( pUp==0 || pUp->pNext==0 );
172619
172620  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
172621    for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
172622    *pp = 0;
172623    sqlite3_finalize(pUp->pUpdate);
172624    pUp->pUpdate = 0;
172625  }else{
172626    pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
172627  }
172628
172629  if( pUp ){
172630    char *zWhere = rbuObjIterGetWhere(p, pIter);
172631    char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
172632    char *zUpdate = 0;
172633
172634    pUp->zMask = (char*)&pUp[1];
172635    memcpy(pUp->zMask, zMask, pIter->nTblCol);
172636    pUp->pNext = pIter->pRbuUpdate;
172637    pIter->pRbuUpdate = pUp;
172638
172639    if( zSet ){
172640      const char *zPrefix = "";
172641
172642      if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
172643      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
172644          zPrefix, pIter->zTbl, zSet, zWhere
172645      );
172646      p->rc = prepareFreeAndCollectError(
172647          p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
172648      );
172649      *ppStmt = pUp->pUpdate;
172650    }
172651    sqlite3_free(zWhere);
172652    sqlite3_free(zSet);
172653  }
172654
172655  return p->rc;
172656}
172657
172658static sqlite3 *rbuOpenDbhandle(
172659  sqlite3rbu *p,
172660  const char *zName,
172661  int bUseVfs
172662){
172663  sqlite3 *db = 0;
172664  if( p->rc==SQLITE_OK ){
172665    const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
172666    p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
172667    if( p->rc ){
172668      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
172669      sqlite3_close(db);
172670      db = 0;
172671    }
172672  }
172673  return db;
172674}
172675
172676/*
172677** Free an RbuState object allocated by rbuLoadState().
172678*/
172679static void rbuFreeState(RbuState *p){
172680  if( p ){
172681    sqlite3_free(p->zTbl);
172682    sqlite3_free(p->zIdx);
172683    sqlite3_free(p);
172684  }
172685}
172686
172687/*
172688** Allocate an RbuState object and load the contents of the rbu_state
172689** table into it. Return a pointer to the new object. It is the
172690** responsibility of the caller to eventually free the object using
172691** sqlite3_free().
172692**
172693** If an error occurs, leave an error code and message in the rbu handle
172694** and return NULL.
172695*/
172696static RbuState *rbuLoadState(sqlite3rbu *p){
172697  RbuState *pRet = 0;
172698  sqlite3_stmt *pStmt = 0;
172699  int rc;
172700  int rc2;
172701
172702  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
172703  if( pRet==0 ) return 0;
172704
172705  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
172706      sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
172707  );
172708  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
172709    switch( sqlite3_column_int(pStmt, 0) ){
172710      case RBU_STATE_STAGE:
172711        pRet->eStage = sqlite3_column_int(pStmt, 1);
172712        if( pRet->eStage!=RBU_STAGE_OAL
172713         && pRet->eStage!=RBU_STAGE_MOVE
172714         && pRet->eStage!=RBU_STAGE_CKPT
172715        ){
172716          p->rc = SQLITE_CORRUPT;
172717        }
172718        break;
172719
172720      case RBU_STATE_TBL:
172721        pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
172722        break;
172723
172724      case RBU_STATE_IDX:
172725        pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
172726        break;
172727
172728      case RBU_STATE_ROW:
172729        pRet->nRow = sqlite3_column_int(pStmt, 1);
172730        break;
172731
172732      case RBU_STATE_PROGRESS:
172733        pRet->nProgress = sqlite3_column_int64(pStmt, 1);
172734        break;
172735
172736      case RBU_STATE_CKPT:
172737        pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
172738        break;
172739
172740      case RBU_STATE_COOKIE:
172741        pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
172742        break;
172743
172744      case RBU_STATE_OALSZ:
172745        pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
172746        break;
172747
172748      case RBU_STATE_PHASEONESTEP:
172749        pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
172750        break;
172751
172752      default:
172753        rc = SQLITE_CORRUPT;
172754        break;
172755    }
172756  }
172757  rc2 = sqlite3_finalize(pStmt);
172758  if( rc==SQLITE_OK ) rc = rc2;
172759
172760  p->rc = rc;
172761  return pRet;
172762}
172763
172764
172765/*
172766** Open the database handle and attach the RBU database as "rbu". If an
172767** error occurs, leave an error code and message in the RBU handle.
172768*/
172769static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
172770  assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
172771  assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
172772
172773  /* Open the RBU database */
172774  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
172775
172776  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
172777    sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
172778    if( p->zState==0 ){
172779      const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
172780      p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
172781    }
172782  }
172783
172784  /* If using separate RBU and state databases, attach the state database to
172785  ** the RBU db handle now.  */
172786  if( p->zState ){
172787    rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
172788    memcpy(p->zStateDb, "stat", 4);
172789  }else{
172790    memcpy(p->zStateDb, "main", 4);
172791  }
172792
172793#if 0
172794  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
172795    p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
172796  }
172797#endif
172798
172799  /* If it has not already been created, create the rbu_state table */
172800  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
172801
172802#if 0
172803  if( rbuIsVacuum(p) ){
172804    if( p->rc==SQLITE_OK ){
172805      int rc2;
172806      int bOk = 0;
172807      sqlite3_stmt *pCnt = 0;
172808      p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
172809          "SELECT count(*) FROM stat.sqlite_master"
172810      );
172811      if( p->rc==SQLITE_OK
172812       && sqlite3_step(pCnt)==SQLITE_ROW
172813       && 1==sqlite3_column_int(pCnt, 0)
172814      ){
172815        bOk = 1;
172816      }
172817      rc2 = sqlite3_finalize(pCnt);
172818      if( p->rc==SQLITE_OK ) p->rc = rc2;
172819
172820      if( p->rc==SQLITE_OK && bOk==0 ){
172821        p->rc = SQLITE_ERROR;
172822        p->zErrmsg = sqlite3_mprintf("invalid state database");
172823      }
172824
172825      if( p->rc==SQLITE_OK ){
172826        p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
172827      }
172828    }
172829  }
172830#endif
172831
172832  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
172833    int bOpen = 0;
172834    int rc;
172835    p->nRbu = 0;
172836    p->pRbuFd = 0;
172837    rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
172838    if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
172839    if( p->eStage>=RBU_STAGE_MOVE ){
172840      bOpen = 1;
172841    }else{
172842      RbuState *pState = rbuLoadState(p);
172843      if( pState ){
172844        bOpen = (pState->eStage>=RBU_STAGE_MOVE);
172845        rbuFreeState(pState);
172846      }
172847    }
172848    if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
172849  }
172850
172851  p->eStage = 0;
172852  if( p->rc==SQLITE_OK && p->dbMain==0 ){
172853    if( !rbuIsVacuum(p) ){
172854      p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
172855    }else if( p->pRbuFd->pWalFd ){
172856      if( pbRetry ){
172857        p->pRbuFd->bNolock = 0;
172858        sqlite3_close(p->dbRbu);
172859        sqlite3_close(p->dbMain);
172860        p->dbMain = 0;
172861        p->dbRbu = 0;
172862        *pbRetry = 1;
172863        return;
172864      }
172865      p->rc = SQLITE_ERROR;
172866      p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
172867    }else{
172868      char *zTarget;
172869      char *zExtra = 0;
172870      if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
172871        zExtra = &p->zRbu[5];
172872        while( *zExtra ){
172873          if( *zExtra++=='?' ) break;
172874        }
172875        if( *zExtra=='\0' ) zExtra = 0;
172876      }
172877
172878      zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
172879          sqlite3_db_filename(p->dbRbu, "main"),
172880          (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
172881      );
172882
172883      if( zTarget==0 ){
172884        p->rc = SQLITE_NOMEM;
172885        return;
172886      }
172887      p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
172888      sqlite3_free(zTarget);
172889    }
172890  }
172891
172892  if( p->rc==SQLITE_OK ){
172893    p->rc = sqlite3_create_function(p->dbMain,
172894        "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
172895    );
172896  }
172897
172898  if( p->rc==SQLITE_OK ){
172899    p->rc = sqlite3_create_function(p->dbMain,
172900        "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
172901    );
172902  }
172903
172904  if( p->rc==SQLITE_OK ){
172905    p->rc = sqlite3_create_function(p->dbRbu,
172906        "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
172907    );
172908  }
172909
172910  if( p->rc==SQLITE_OK ){
172911    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
172912  }
172913  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
172914
172915  /* Mark the database file just opened as an RBU target database. If
172916  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
172917  ** This is an error.  */
172918  if( p->rc==SQLITE_OK ){
172919    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
172920  }
172921
172922  if( p->rc==SQLITE_NOTFOUND ){
172923    p->rc = SQLITE_ERROR;
172924    p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
172925  }
172926}
172927
172928/*
172929** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
172930** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
172931**
172932** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
172933** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
172934** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
172935** three characters, then shorten the suffix on z[] to be the last three
172936** characters of the original suffix.
172937**
172938** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
172939** do the suffix shortening regardless of URI parameter.
172940**
172941** Examples:
172942**
172943**     test.db-journal    =>   test.nal
172944**     test.db-wal        =>   test.wal
172945**     test.db-shm        =>   test.shm
172946**     test.db-mj7f3319fa =>   test.9fa
172947*/
172948static void rbuFileSuffix3(const char *zBase, char *z){
172949#ifdef SQLITE_ENABLE_8_3_NAMES
172950#if SQLITE_ENABLE_8_3_NAMES<2
172951  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
172952#endif
172953  {
172954    int i, sz;
172955    sz = (int)strlen(z)&0xffffff;
172956    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
172957    if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
172958  }
172959#endif
172960}
172961
172962/*
172963** Return the current wal-index header checksum for the target database
172964** as a 64-bit integer.
172965**
172966** The checksum is store in the first page of xShmMap memory as an 8-byte
172967** blob starting at byte offset 40.
172968*/
172969static i64 rbuShmChecksum(sqlite3rbu *p){
172970  i64 iRet = 0;
172971  if( p->rc==SQLITE_OK ){
172972    sqlite3_file *pDb = p->pTargetFd->pReal;
172973    u32 volatile *ptr;
172974    p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
172975    if( p->rc==SQLITE_OK ){
172976      iRet = ((i64)ptr[10] << 32) + ptr[11];
172977    }
172978  }
172979  return iRet;
172980}
172981
172982/*
172983** This function is called as part of initializing or reinitializing an
172984** incremental checkpoint.
172985**
172986** It populates the sqlite3rbu.aFrame[] array with the set of
172987** (wal frame -> db page) copy operations required to checkpoint the
172988** current wal file, and obtains the set of shm locks required to safely
172989** perform the copy operations directly on the file-system.
172990**
172991** If argument pState is not NULL, then the incremental checkpoint is
172992** being resumed. In this case, if the checksum of the wal-index-header
172993** following recovery is not the same as the checksum saved in the RbuState
172994** object, then the rbu handle is set to DONE state. This occurs if some
172995** other client appends a transaction to the wal file in the middle of
172996** an incremental checkpoint.
172997*/
172998static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
172999
173000  /* If pState is NULL, then the wal file may not have been opened and
173001  ** recovered. Running a read-statement here to ensure that doing so
173002  ** does not interfere with the "capture" process below.  */
173003  if( pState==0 ){
173004    p->eStage = 0;
173005    if( p->rc==SQLITE_OK ){
173006      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
173007    }
173008  }
173009
173010  /* Assuming no error has occurred, run a "restart" checkpoint with the
173011  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
173012  ** special behaviour in the rbu VFS:
173013  **
173014  **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
173015  **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
173016  **     proceed with running a passive checkpoint instead of failing).
173017  **
173018  **   * Attempts to read from the *-wal file or write to the database file
173019  **     do not perform any IO. Instead, the frame/page combinations that
173020  **     would be read/written are recorded in the sqlite3rbu.aFrame[]
173021  **     array.
173022  **
173023  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
173024  **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
173025  **     no-ops. These locks will not be released until the connection
173026  **     is closed.
173027  **
173028  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL
173029  **     error.
173030  **
173031  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
173032  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
173033  ** array populated with a set of (frame -> page) mappings. Because the
173034  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
173035  ** data from the wal file into the database file according to the
173036  ** contents of aFrame[].
173037  */
173038  if( p->rc==SQLITE_OK ){
173039    int rc2;
173040    p->eStage = RBU_STAGE_CAPTURE;
173041    rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
173042    if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
173043  }
173044
173045  if( p->rc==SQLITE_OK && p->nFrame>0 ){
173046    p->eStage = RBU_STAGE_CKPT;
173047    p->nStep = (pState ? pState->nRow : 0);
173048    p->aBuf = rbuMalloc(p, p->pgsz);
173049    p->iWalCksum = rbuShmChecksum(p);
173050  }
173051
173052  if( p->rc==SQLITE_OK ){
173053    if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
173054      p->rc = SQLITE_DONE;
173055      p->eStage = RBU_STAGE_DONE;
173056    }else{
173057      int nSectorSize;
173058      sqlite3_file *pDb = p->pTargetFd->pReal;
173059      sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
173060      assert( p->nPagePerSector==0 );
173061      nSectorSize = pDb->pMethods->xSectorSize(pDb);
173062      if( nSectorSize>p->pgsz ){
173063        p->nPagePerSector = nSectorSize / p->pgsz;
173064      }else{
173065        p->nPagePerSector = 1;
173066      }
173067
173068      /* Call xSync() on the wal file. This causes SQLite to sync the
173069      ** directory in which the target database and the wal file reside, in
173070      ** case it has not been synced since the rename() call in
173071      ** rbuMoveOalFile(). */
173072      p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
173073    }
173074  }
173075}
173076
173077/*
173078** Called when iAmt bytes are read from offset iOff of the wal file while
173079** the rbu object is in capture mode. Record the frame number of the frame
173080** being read in the aFrame[] array.
173081*/
173082static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
173083  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
173084  u32 iFrame;
173085
173086  if( pRbu->mLock!=mReq ){
173087    pRbu->rc = SQLITE_BUSY;
173088    return SQLITE_INTERNAL;
173089  }
173090
173091  pRbu->pgsz = iAmt;
173092  if( pRbu->nFrame==pRbu->nFrameAlloc ){
173093    int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
173094    RbuFrame *aNew;
173095    aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
173096    if( aNew==0 ) return SQLITE_NOMEM;
173097    pRbu->aFrame = aNew;
173098    pRbu->nFrameAlloc = nNew;
173099  }
173100
173101  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
173102  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
173103  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
173104  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
173105  pRbu->nFrame++;
173106  return SQLITE_OK;
173107}
173108
173109/*
173110** Called when a page of data is written to offset iOff of the database
173111** file while the rbu handle is in capture mode. Record the page number
173112** of the page being written in the aFrame[] array.
173113*/
173114static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
173115  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
173116  return SQLITE_OK;
173117}
173118
173119/*
173120** This is called as part of an incremental checkpoint operation. Copy
173121** a single frame of data from the wal file into the database file, as
173122** indicated by the RbuFrame object.
173123*/
173124static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
173125  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
173126  sqlite3_file *pDb = p->pTargetFd->pReal;
173127  i64 iOff;
173128
173129  assert( p->rc==SQLITE_OK );
173130  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
173131  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
173132  if( p->rc ) return;
173133
173134  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
173135  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
173136}
173137
173138
173139/*
173140** Take an EXCLUSIVE lock on the database file.
173141*/
173142static void rbuLockDatabase(sqlite3rbu *p){
173143  sqlite3_file *pReal = p->pTargetFd->pReal;
173144  assert( p->rc==SQLITE_OK );
173145  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
173146  if( p->rc==SQLITE_OK ){
173147    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
173148  }
173149}
173150
173151#if defined(_WIN32_WCE)
173152static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
173153  int nChar;
173154  LPWSTR zWideFilename;
173155
173156  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
173157  if( nChar==0 ){
173158    return 0;
173159  }
173160  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
173161  if( zWideFilename==0 ){
173162    return 0;
173163  }
173164  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
173165  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
173166                                nChar);
173167  if( nChar==0 ){
173168    sqlite3_free(zWideFilename);
173169    zWideFilename = 0;
173170  }
173171  return zWideFilename;
173172}
173173#endif
173174
173175/*
173176** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
173177** on the database file. This proc moves the *-oal file to the *-wal path,
173178** then reopens the database file (this time in vanilla, non-oal, WAL mode).
173179** If an error occurs, leave an error code and error message in the rbu
173180** handle.
173181*/
173182static void rbuMoveOalFile(sqlite3rbu *p){
173183  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
173184  const char *zMove = zBase;
173185  char *zOal;
173186  char *zWal;
173187
173188  if( rbuIsVacuum(p) ){
173189    zMove = sqlite3_db_filename(p->dbRbu, "main");
173190  }
173191  zOal = sqlite3_mprintf("%s-oal", zMove);
173192  zWal = sqlite3_mprintf("%s-wal", zMove);
173193
173194  assert( p->eStage==RBU_STAGE_MOVE );
173195  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
173196  if( zWal==0 || zOal==0 ){
173197    p->rc = SQLITE_NOMEM;
173198  }else{
173199    /* Move the *-oal file to *-wal. At this point connection p->db is
173200    ** holding a SHARED lock on the target database file (because it is
173201    ** in WAL mode). So no other connection may be writing the db.
173202    **
173203    ** In order to ensure that there are no database readers, an EXCLUSIVE
173204    ** lock is obtained here before the *-oal is moved to *-wal.
173205    */
173206    rbuLockDatabase(p);
173207    if( p->rc==SQLITE_OK ){
173208      rbuFileSuffix3(zBase, zWal);
173209      rbuFileSuffix3(zBase, zOal);
173210
173211      /* Re-open the databases. */
173212      rbuObjIterFinalize(&p->objiter);
173213      sqlite3_close(p->dbRbu);
173214      sqlite3_close(p->dbMain);
173215      p->dbMain = 0;
173216      p->dbRbu = 0;
173217
173218#if defined(_WIN32_WCE)
173219      {
173220        LPWSTR zWideOal;
173221        LPWSTR zWideWal;
173222
173223        zWideOal = rbuWinUtf8ToUnicode(zOal);
173224        if( zWideOal ){
173225          zWideWal = rbuWinUtf8ToUnicode(zWal);
173226          if( zWideWal ){
173227            if( MoveFileW(zWideOal, zWideWal) ){
173228              p->rc = SQLITE_OK;
173229            }else{
173230              p->rc = SQLITE_IOERR;
173231            }
173232            sqlite3_free(zWideWal);
173233          }else{
173234            p->rc = SQLITE_IOERR_NOMEM;
173235          }
173236          sqlite3_free(zWideOal);
173237        }else{
173238          p->rc = SQLITE_IOERR_NOMEM;
173239        }
173240      }
173241#else
173242      p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
173243#endif
173244
173245      if( p->rc==SQLITE_OK ){
173246        rbuOpenDatabase(p, 0);
173247        rbuSetupCheckpoint(p, 0);
173248      }
173249    }
173250  }
173251
173252  sqlite3_free(zWal);
173253  sqlite3_free(zOal);
173254}
173255
173256/*
173257** The SELECT statement iterating through the keys for the current object
173258** (p->objiter.pSelect) currently points to a valid row. This function
173259** determines the type of operation requested by this row and returns
173260** one of the following values to indicate the result:
173261**
173262**     * RBU_INSERT
173263**     * RBU_DELETE
173264**     * RBU_IDX_DELETE
173265**     * RBU_UPDATE
173266**
173267** If RBU_UPDATE is returned, then output variable *pzMask is set to
173268** point to the text value indicating the columns to update.
173269**
173270** If the rbu_control field contains an invalid value, an error code and
173271** message are left in the RBU handle and zero returned.
173272*/
173273static int rbuStepType(sqlite3rbu *p, const char **pzMask){
173274  int iCol = p->objiter.nCol;     /* Index of rbu_control column */
173275  int res = 0;                    /* Return value */
173276
173277  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
173278    case SQLITE_INTEGER: {
173279      int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
173280      switch( iVal ){
173281        case 0: res = RBU_INSERT;     break;
173282        case 1: res = RBU_DELETE;     break;
173283        case 2: res = RBU_REPLACE;    break;
173284        case 3: res = RBU_IDX_DELETE; break;
173285        case 4: res = RBU_IDX_INSERT; break;
173286      }
173287      break;
173288    }
173289
173290    case SQLITE_TEXT: {
173291      const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
173292      if( z==0 ){
173293        p->rc = SQLITE_NOMEM;
173294      }else{
173295        *pzMask = (const char*)z;
173296      }
173297      res = RBU_UPDATE;
173298
173299      break;
173300    }
173301
173302    default:
173303      break;
173304  }
173305
173306  if( res==0 ){
173307    rbuBadControlError(p);
173308  }
173309  return res;
173310}
173311
173312#ifdef SQLITE_DEBUG
173313/*
173314** Assert that column iCol of statement pStmt is named zName.
173315*/
173316static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
173317  const char *zCol = sqlite3_column_name(pStmt, iCol);
173318  assert( 0==sqlite3_stricmp(zName, zCol) );
173319}
173320#else
173321# define assertColumnName(x,y,z)
173322#endif
173323
173324/*
173325** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
173326** RBU_IDX_DELETE. This function performs the work of a single
173327** sqlite3rbu_step() call for the type of operation specified by eType.
173328*/
173329static void rbuStepOneOp(sqlite3rbu *p, int eType){
173330  RbuObjIter *pIter = &p->objiter;
173331  sqlite3_value *pVal;
173332  sqlite3_stmt *pWriter;
173333  int i;
173334
173335  assert( p->rc==SQLITE_OK );
173336  assert( eType!=RBU_DELETE || pIter->zIdx==0 );
173337  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
173338       || eType==RBU_INSERT || eType==RBU_IDX_INSERT
173339  );
173340
173341  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
173342  ** statement below does actually delete a row, nPhaseOneStep will be
173343  ** incremented by the same amount when SQL function rbu_tmp_insert()
173344  ** is invoked by the trigger.  */
173345  if( eType==RBU_DELETE ){
173346    p->nPhaseOneStep -= p->objiter.nIndex;
173347  }
173348
173349  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
173350    pWriter = pIter->pDelete;
173351  }else{
173352    pWriter = pIter->pInsert;
173353  }
173354
173355  for(i=0; i<pIter->nCol; i++){
173356    /* If this is an INSERT into a table b-tree and the table has an
173357    ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
173358    ** to write a NULL into the IPK column. That is not permitted.  */
173359    if( eType==RBU_INSERT
173360     && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
173361     && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
173362    ){
173363      p->rc = SQLITE_MISMATCH;
173364      p->zErrmsg = sqlite3_mprintf("datatype mismatch");
173365      return;
173366    }
173367
173368    if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
173369      continue;
173370    }
173371
173372    pVal = sqlite3_column_value(pIter->pSelect, i);
173373    p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
173374    if( p->rc ) return;
173375  }
173376  if( pIter->zIdx==0 ){
173377    if( pIter->eType==RBU_PK_VTAB
173378     || pIter->eType==RBU_PK_NONE
173379     || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
173380    ){
173381      /* For a virtual table, or a table with no primary key, the
173382      ** SELECT statement is:
173383      **
173384      **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
173385      **
173386      ** Hence column_value(pIter->nCol+1).
173387      */
173388      assertColumnName(pIter->pSelect, pIter->nCol+1,
173389          rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
173390      );
173391      pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
173392      p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
173393    }
173394  }
173395  if( p->rc==SQLITE_OK ){
173396    sqlite3_step(pWriter);
173397    p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
173398  }
173399}
173400
173401/*
173402** This function does the work for an sqlite3rbu_step() call.
173403**
173404** The object-iterator (p->objiter) currently points to a valid object,
173405** and the input cursor (p->objiter.pSelect) currently points to a valid
173406** input row. Perform whatever processing is required and return.
173407**
173408** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
173409** and message is left in the RBU handle and a copy of the error code
173410** returned.
173411*/
173412static int rbuStep(sqlite3rbu *p){
173413  RbuObjIter *pIter = &p->objiter;
173414  const char *zMask = 0;
173415  int eType = rbuStepType(p, &zMask);
173416
173417  if( eType ){
173418    assert( eType==RBU_INSERT     || eType==RBU_DELETE
173419         || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
173420         || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
173421    );
173422    assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
173423
173424    if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
173425      rbuBadControlError(p);
173426    }
173427    else if( eType==RBU_REPLACE ){
173428      if( pIter->zIdx==0 ){
173429        p->nPhaseOneStep += p->objiter.nIndex;
173430        rbuStepOneOp(p, RBU_DELETE);
173431      }
173432      if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
173433    }
173434    else if( eType!=RBU_UPDATE ){
173435      rbuStepOneOp(p, eType);
173436    }
173437    else{
173438      sqlite3_value *pVal;
173439      sqlite3_stmt *pUpdate = 0;
173440      assert( eType==RBU_UPDATE );
173441      p->nPhaseOneStep -= p->objiter.nIndex;
173442      rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
173443      if( pUpdate ){
173444        int i;
173445        for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
173446          char c = zMask[pIter->aiSrcOrder[i]];
173447          pVal = sqlite3_column_value(pIter->pSelect, i);
173448          if( pIter->abTblPk[i] || c!='.' ){
173449            p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
173450          }
173451        }
173452        if( p->rc==SQLITE_OK
173453         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
173454        ){
173455          /* Bind the rbu_rowid value to column _rowid_ */
173456          assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
173457          pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
173458          p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
173459        }
173460        if( p->rc==SQLITE_OK ){
173461          sqlite3_step(pUpdate);
173462          p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
173463        }
173464      }
173465    }
173466  }
173467  return p->rc;
173468}
173469
173470/*
173471** Increment the schema cookie of the main database opened by p->dbMain.
173472**
173473** Or, if this is an RBU vacuum, set the schema cookie of the main db
173474** opened by p->dbMain to one more than the schema cookie of the main
173475** db opened by p->dbRbu.
173476*/
173477static void rbuIncrSchemaCookie(sqlite3rbu *p){
173478  if( p->rc==SQLITE_OK ){
173479    sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
173480    int iCookie = 1000000;
173481    sqlite3_stmt *pStmt;
173482
173483    p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
173484        "PRAGMA schema_version"
173485    );
173486    if( p->rc==SQLITE_OK ){
173487      /* Coverage: it may be that this sqlite3_step() cannot fail. There
173488      ** is already a transaction open, so the prepared statement cannot
173489      ** throw an SQLITE_SCHEMA exception. The only database page the
173490      ** statement reads is page 1, which is guaranteed to be in the cache.
173491      ** And no memory allocations are required.  */
173492      if( SQLITE_ROW==sqlite3_step(pStmt) ){
173493        iCookie = sqlite3_column_int(pStmt, 0);
173494      }
173495      rbuFinalize(p, pStmt);
173496    }
173497    if( p->rc==SQLITE_OK ){
173498      rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
173499    }
173500  }
173501}
173502
173503/*
173504** Update the contents of the rbu_state table within the rbu database. The
173505** value stored in the RBU_STATE_STAGE column is eStage. All other values
173506** are determined by inspecting the rbu handle passed as the first argument.
173507*/
173508static void rbuSaveState(sqlite3rbu *p, int eStage){
173509  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
173510    sqlite3_stmt *pInsert = 0;
173511    rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
173512    int rc;
173513
173514    assert( p->zErrmsg==0 );
173515    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
173516        sqlite3_mprintf(
173517          "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
173518          "(%d, %d), "
173519          "(%d, %Q), "
173520          "(%d, %Q), "
173521          "(%d, %d), "
173522          "(%d, %d), "
173523          "(%d, %lld), "
173524          "(%d, %lld), "
173525          "(%d, %lld), "
173526          "(%d, %lld) ",
173527          p->zStateDb,
173528          RBU_STATE_STAGE, eStage,
173529          RBU_STATE_TBL, p->objiter.zTbl,
173530          RBU_STATE_IDX, p->objiter.zIdx,
173531          RBU_STATE_ROW, p->nStep,
173532          RBU_STATE_PROGRESS, p->nProgress,
173533          RBU_STATE_CKPT, p->iWalCksum,
173534          RBU_STATE_COOKIE, (i64)pFd->iCookie,
173535          RBU_STATE_OALSZ, p->iOalSz,
173536          RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
173537      )
173538    );
173539    assert( pInsert==0 || rc==SQLITE_OK );
173540
173541    if( rc==SQLITE_OK ){
173542      sqlite3_step(pInsert);
173543      rc = sqlite3_finalize(pInsert);
173544    }
173545    if( rc!=SQLITE_OK ) p->rc = rc;
173546  }
173547}
173548
173549
173550/*
173551** The second argument passed to this function is the name of a PRAGMA
173552** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
173553** This function executes the following on sqlite3rbu.dbRbu:
173554**
173555**   "PRAGMA main.$zPragma"
173556**
173557** where $zPragma is the string passed as the second argument, then
173558** on sqlite3rbu.dbMain:
173559**
173560**   "PRAGMA main.$zPragma = $val"
173561**
173562** where $val is the value returned by the first PRAGMA invocation.
173563**
173564** In short, it copies the value  of the specified PRAGMA setting from
173565** dbRbu to dbMain.
173566*/
173567static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
173568  if( p->rc==SQLITE_OK ){
173569    sqlite3_stmt *pPragma = 0;
173570    p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
173571        sqlite3_mprintf("PRAGMA main.%s", zPragma)
173572    );
173573    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
173574      p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
173575          zPragma, sqlite3_column_int(pPragma, 0)
173576      );
173577    }
173578    rbuFinalize(p, pPragma);
173579  }
173580}
173581
173582/*
173583** The RBU handle passed as the only argument has just been opened and
173584** the state database is empty. If this RBU handle was opened for an
173585** RBU vacuum operation, create the schema in the target db.
173586*/
173587static void rbuCreateTargetSchema(sqlite3rbu *p){
173588  sqlite3_stmt *pSql = 0;
173589  sqlite3_stmt *pInsert = 0;
173590
173591  assert( rbuIsVacuum(p) );
173592  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
173593  if( p->rc==SQLITE_OK ){
173594    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
173595      "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
173596      " AND name!='sqlite_sequence' "
173597      " ORDER BY type DESC"
173598    );
173599  }
173600
173601  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
173602    const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
173603    p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
173604  }
173605  rbuFinalize(p, pSql);
173606  if( p->rc!=SQLITE_OK ) return;
173607
173608  if( p->rc==SQLITE_OK ){
173609    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
173610        "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
173611    );
173612  }
173613
173614  if( p->rc==SQLITE_OK ){
173615    p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
173616        "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
173617    );
173618  }
173619
173620  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
173621    int i;
173622    for(i=0; i<5; i++){
173623      sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
173624    }
173625    sqlite3_step(pInsert);
173626    p->rc = sqlite3_reset(pInsert);
173627  }
173628  if( p->rc==SQLITE_OK ){
173629    p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
173630  }
173631
173632  rbuFinalize(p, pSql);
173633  rbuFinalize(p, pInsert);
173634}
173635
173636/*
173637** Step the RBU object.
173638*/
173639SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
173640  if( p ){
173641    switch( p->eStage ){
173642      case RBU_STAGE_OAL: {
173643        RbuObjIter *pIter = &p->objiter;
173644
173645        /* If this is an RBU vacuum operation and the state table was empty
173646        ** when this handle was opened, create the target database schema. */
173647        if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
173648          rbuCreateTargetSchema(p);
173649          rbuCopyPragma(p, "user_version");
173650          rbuCopyPragma(p, "application_id");
173651        }
173652
173653        while( p->rc==SQLITE_OK && pIter->zTbl ){
173654
173655          if( pIter->bCleanup ){
173656            /* Clean up the rbu_tmp_xxx table for the previous table. It
173657            ** cannot be dropped as there are currently active SQL statements.
173658            ** But the contents can be deleted.  */
173659            if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
173660              rbuMPrintfExec(p, p->dbRbu,
173661                  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
173662              );
173663            }
173664          }else{
173665            rbuObjIterPrepareAll(p, pIter, 0);
173666
173667            /* Advance to the next row to process. */
173668            if( p->rc==SQLITE_OK ){
173669              int rc = sqlite3_step(pIter->pSelect);
173670              if( rc==SQLITE_ROW ){
173671                p->nProgress++;
173672                p->nStep++;
173673                return rbuStep(p);
173674              }
173675              p->rc = sqlite3_reset(pIter->pSelect);
173676              p->nStep = 0;
173677            }
173678          }
173679
173680          rbuObjIterNext(p, pIter);
173681        }
173682
173683        if( p->rc==SQLITE_OK ){
173684          assert( pIter->zTbl==0 );
173685          rbuSaveState(p, RBU_STAGE_MOVE);
173686          rbuIncrSchemaCookie(p);
173687          if( p->rc==SQLITE_OK ){
173688            p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
173689          }
173690          if( p->rc==SQLITE_OK ){
173691            p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
173692          }
173693          p->eStage = RBU_STAGE_MOVE;
173694        }
173695        break;
173696      }
173697
173698      case RBU_STAGE_MOVE: {
173699        if( p->rc==SQLITE_OK ){
173700          rbuMoveOalFile(p);
173701          p->nProgress++;
173702        }
173703        break;
173704      }
173705
173706      case RBU_STAGE_CKPT: {
173707        if( p->rc==SQLITE_OK ){
173708          if( p->nStep>=p->nFrame ){
173709            sqlite3_file *pDb = p->pTargetFd->pReal;
173710
173711            /* Sync the db file */
173712            p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
173713
173714            /* Update nBackfill */
173715            if( p->rc==SQLITE_OK ){
173716              void volatile *ptr;
173717              p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
173718              if( p->rc==SQLITE_OK ){
173719                ((u32 volatile*)ptr)[24] = p->iMaxFrame;
173720              }
173721            }
173722
173723            if( p->rc==SQLITE_OK ){
173724              p->eStage = RBU_STAGE_DONE;
173725              p->rc = SQLITE_DONE;
173726            }
173727          }else{
173728            /* At one point the following block copied a single frame from the
173729            ** wal file to the database file. So that one call to sqlite3rbu_step()
173730            ** checkpointed a single frame.
173731            **
173732            ** However, if the sector-size is larger than the page-size, and the
173733            ** application calls sqlite3rbu_savestate() or close() immediately
173734            ** after this step, then rbu_step() again, then a power failure occurs,
173735            ** then the database page written here may be damaged. Work around
173736            ** this by checkpointing frames until the next page in the aFrame[]
173737            ** lies on a different disk sector to the current one. */
173738            u32 iSector;
173739            do{
173740              RbuFrame *pFrame = &p->aFrame[p->nStep];
173741              iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
173742              rbuCheckpointFrame(p, pFrame);
173743              p->nStep++;
173744            }while( p->nStep<p->nFrame
173745                 && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
173746                 && p->rc==SQLITE_OK
173747            );
173748          }
173749          p->nProgress++;
173750        }
173751        break;
173752      }
173753
173754      default:
173755        break;
173756    }
173757    return p->rc;
173758  }else{
173759    return SQLITE_NOMEM;
173760  }
173761}
173762
173763/*
173764** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
173765** otherwise. Either or both argument may be NULL. Two NULL values are
173766** considered equal, and NULL is considered distinct from all other values.
173767*/
173768static int rbuStrCompare(const char *z1, const char *z2){
173769  if( z1==0 && z2==0 ) return 0;
173770  if( z1==0 || z2==0 ) return 1;
173771  return (sqlite3_stricmp(z1, z2)!=0);
173772}
173773
173774/*
173775** This function is called as part of sqlite3rbu_open() when initializing
173776** an rbu handle in OAL stage. If the rbu update has not started (i.e.
173777** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
173778** things so that the next call to sqlite3rbu_step() continues on from
173779** where the previous rbu handle left off.
173780**
173781** If an error occurs, an error code and error message are left in the
173782** rbu handle passed as the first argument.
173783*/
173784static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
173785  assert( p->rc==SQLITE_OK );
173786  if( pState->zTbl ){
173787    RbuObjIter *pIter = &p->objiter;
173788    int rc = SQLITE_OK;
173789
173790    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
173791       || rbuStrCompare(pIter->zIdx, pState->zIdx)
173792       || rbuStrCompare(pIter->zTbl, pState->zTbl)
173793    )){
173794      rc = rbuObjIterNext(p, pIter);
173795    }
173796
173797    if( rc==SQLITE_OK && !pIter->zTbl ){
173798      rc = SQLITE_ERROR;
173799      p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
173800    }
173801
173802    if( rc==SQLITE_OK ){
173803      p->nStep = pState->nRow;
173804      rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
173805    }
173806
173807    p->rc = rc;
173808  }
173809}
173810
173811/*
173812** If there is a "*-oal" file in the file-system corresponding to the
173813** target database in the file-system, delete it. If an error occurs,
173814** leave an error code and error message in the rbu handle.
173815*/
173816static void rbuDeleteOalFile(sqlite3rbu *p){
173817  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
173818  if( zOal ){
173819    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
173820    assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
173821    pVfs->xDelete(pVfs, zOal, 0);
173822    sqlite3_free(zOal);
173823  }
173824}
173825
173826/*
173827** Allocate a private rbu VFS for the rbu handle passed as the only
173828** argument. This VFS will be used unless the call to sqlite3rbu_open()
173829** specified a URI with a vfs=? option in place of a target database
173830** file name.
173831*/
173832static void rbuCreateVfs(sqlite3rbu *p){
173833  int rnd;
173834  char zRnd[64];
173835
173836  assert( p->rc==SQLITE_OK );
173837  sqlite3_randomness(sizeof(int), (void*)&rnd);
173838  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
173839  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
173840  if( p->rc==SQLITE_OK ){
173841    sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
173842    assert( pVfs );
173843    p->zVfsName = pVfs->zName;
173844  }
173845}
173846
173847/*
173848** Destroy the private VFS created for the rbu handle passed as the only
173849** argument by an earlier call to rbuCreateVfs().
173850*/
173851static void rbuDeleteVfs(sqlite3rbu *p){
173852  if( p->zVfsName ){
173853    sqlite3rbu_destroy_vfs(p->zVfsName);
173854    p->zVfsName = 0;
173855  }
173856}
173857
173858/*
173859** This user-defined SQL function is invoked with a single argument - the
173860** name of a table expected to appear in the target database. It returns
173861** the number of auxilliary indexes on the table.
173862*/
173863static void rbuIndexCntFunc(
173864  sqlite3_context *pCtx,
173865  int nVal,
173866  sqlite3_value **apVal
173867){
173868  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
173869  sqlite3_stmt *pStmt = 0;
173870  char *zErrmsg = 0;
173871  int rc;
173872
173873  assert( nVal==1 );
173874
173875  rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
173876      sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
173877        "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
173878  );
173879  if( rc!=SQLITE_OK ){
173880    sqlite3_result_error(pCtx, zErrmsg, -1);
173881  }else{
173882    int nIndex = 0;
173883    if( SQLITE_ROW==sqlite3_step(pStmt) ){
173884      nIndex = sqlite3_column_int(pStmt, 0);
173885    }
173886    rc = sqlite3_finalize(pStmt);
173887    if( rc==SQLITE_OK ){
173888      sqlite3_result_int(pCtx, nIndex);
173889    }else{
173890      sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
173891    }
173892  }
173893
173894  sqlite3_free(zErrmsg);
173895}
173896
173897/*
173898** If the RBU database contains the rbu_count table, use it to initialize
173899** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
173900** is assumed to contain the same columns as:
173901**
173902**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
173903**
173904** There should be one row in the table for each data_xxx table in the
173905** database. The 'tbl' column should contain the name of a data_xxx table,
173906** and the cnt column the number of rows it contains.
173907**
173908** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
173909** for all rows in the rbu_count table, where nIndex is the number of
173910** indexes on the corresponding target database table.
173911*/
173912static void rbuInitPhaseOneSteps(sqlite3rbu *p){
173913  if( p->rc==SQLITE_OK ){
173914    sqlite3_stmt *pStmt = 0;
173915    int bExists = 0;                /* True if rbu_count exists */
173916
173917    p->nPhaseOneStep = -1;
173918
173919    p->rc = sqlite3_create_function(p->dbRbu,
173920        "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
173921    );
173922
173923    /* Check for the rbu_count table. If it does not exist, or if an error
173924    ** occurs, nPhaseOneStep will be left set to -1. */
173925    if( p->rc==SQLITE_OK ){
173926      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
173927          "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
173928      );
173929    }
173930    if( p->rc==SQLITE_OK ){
173931      if( SQLITE_ROW==sqlite3_step(pStmt) ){
173932        bExists = 1;
173933      }
173934      p->rc = sqlite3_finalize(pStmt);
173935    }
173936
173937    if( p->rc==SQLITE_OK && bExists ){
173938      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
173939          "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
173940          "FROM rbu_count"
173941      );
173942      if( p->rc==SQLITE_OK ){
173943        if( SQLITE_ROW==sqlite3_step(pStmt) ){
173944          p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
173945        }
173946        p->rc = sqlite3_finalize(pStmt);
173947      }
173948    }
173949  }
173950}
173951
173952
173953static sqlite3rbu *openRbuHandle(
173954  const char *zTarget,
173955  const char *zRbu,
173956  const char *zState
173957){
173958  sqlite3rbu *p;
173959  size_t nTarget = zTarget ? strlen(zTarget) : 0;
173960  size_t nRbu = strlen(zRbu);
173961  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
173962
173963  p = (sqlite3rbu*)sqlite3_malloc64(nByte);
173964  if( p ){
173965    RbuState *pState = 0;
173966
173967    /* Create the custom VFS. */
173968    memset(p, 0, sizeof(sqlite3rbu));
173969    rbuCreateVfs(p);
173970
173971    /* Open the target, RBU and state databases */
173972    if( p->rc==SQLITE_OK ){
173973      char *pCsr = (char*)&p[1];
173974      int bRetry = 0;
173975      if( zTarget ){
173976        p->zTarget = pCsr;
173977        memcpy(p->zTarget, zTarget, nTarget+1);
173978        pCsr += nTarget+1;
173979      }
173980      p->zRbu = pCsr;
173981      memcpy(p->zRbu, zRbu, nRbu+1);
173982      pCsr += nRbu+1;
173983      if( zState ){
173984        p->zState = rbuMPrintf(p, "%s", zState);
173985      }
173986
173987      /* If the first attempt to open the database file fails and the bRetry
173988      ** flag it set, this means that the db was not opened because it seemed
173989      ** to be a wal-mode db. But, this may have happened due to an earlier
173990      ** RBU vacuum operation leaving an old wal file in the directory.
173991      ** If this is the case, it will have been checkpointed and deleted
173992      ** when the handle was closed and a second attempt to open the
173993      ** database may succeed.  */
173994      rbuOpenDatabase(p, &bRetry);
173995      if( bRetry ){
173996        rbuOpenDatabase(p, 0);
173997      }
173998    }
173999
174000    if( p->rc==SQLITE_OK ){
174001      pState = rbuLoadState(p);
174002      assert( pState || p->rc!=SQLITE_OK );
174003      if( p->rc==SQLITE_OK ){
174004
174005        if( pState->eStage==0 ){
174006          rbuDeleteOalFile(p);
174007          rbuInitPhaseOneSteps(p);
174008          p->eStage = RBU_STAGE_OAL;
174009        }else{
174010          p->eStage = pState->eStage;
174011          p->nPhaseOneStep = pState->nPhaseOneStep;
174012        }
174013        p->nProgress = pState->nProgress;
174014        p->iOalSz = pState->iOalSz;
174015      }
174016    }
174017    assert( p->rc!=SQLITE_OK || p->eStage!=0 );
174018
174019    if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
174020      if( p->eStage==RBU_STAGE_OAL ){
174021        p->rc = SQLITE_ERROR;
174022        p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
174023      }else if( p->eStage==RBU_STAGE_MOVE ){
174024        p->eStage = RBU_STAGE_CKPT;
174025        p->nStep = 0;
174026      }
174027    }
174028
174029    if( p->rc==SQLITE_OK
174030     && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
174031     && pState->eStage!=0
174032    ){
174033      rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
174034      if( pFd->iCookie!=pState->iCookie ){
174035        /* At this point (pTargetFd->iCookie) contains the value of the
174036        ** change-counter cookie (the thing that gets incremented when a
174037        ** transaction is committed in rollback mode) currently stored on
174038        ** page 1 of the database file. */
174039        p->rc = SQLITE_BUSY;
174040        p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
174041            (rbuIsVacuum(p) ? "vacuum" : "update")
174042        );
174043      }
174044    }
174045
174046    if( p->rc==SQLITE_OK ){
174047      if( p->eStage==RBU_STAGE_OAL ){
174048        sqlite3 *db = p->dbMain;
174049        p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
174050
174051        /* Point the object iterator at the first object */
174052        if( p->rc==SQLITE_OK ){
174053          p->rc = rbuObjIterFirst(p, &p->objiter);
174054        }
174055
174056        /* If the RBU database contains no data_xxx tables, declare the RBU
174057        ** update finished.  */
174058        if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
174059          p->rc = SQLITE_DONE;
174060          p->eStage = RBU_STAGE_DONE;
174061        }else{
174062          if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
174063            rbuCopyPragma(p, "page_size");
174064            rbuCopyPragma(p, "auto_vacuum");
174065          }
174066
174067          /* Open transactions both databases. The *-oal file is opened or
174068          ** created at this point. */
174069          if( p->rc==SQLITE_OK ){
174070            p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
174071          }
174072
174073          /* Check if the main database is a zipvfs db. If it is, set the upper
174074          ** level pager to use "journal_mode=off". This prevents it from
174075          ** generating a large journal using a temp file.  */
174076          if( p->rc==SQLITE_OK ){
174077            int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
174078            if( frc==SQLITE_OK ){
174079              p->rc = sqlite3_exec(
174080                db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
174081            }
174082          }
174083
174084          if( p->rc==SQLITE_OK ){
174085            rbuSetupOal(p, pState);
174086          }
174087        }
174088      }else if( p->eStage==RBU_STAGE_MOVE ){
174089        /* no-op */
174090      }else if( p->eStage==RBU_STAGE_CKPT ){
174091        rbuSetupCheckpoint(p, pState);
174092      }else if( p->eStage==RBU_STAGE_DONE ){
174093        p->rc = SQLITE_DONE;
174094      }else{
174095        p->rc = SQLITE_CORRUPT;
174096      }
174097    }
174098
174099    rbuFreeState(pState);
174100  }
174101
174102  return p;
174103}
174104
174105/*
174106** Allocate and return an RBU handle with all fields zeroed except for the
174107** error code, which is set to SQLITE_MISUSE.
174108*/
174109static sqlite3rbu *rbuMisuseError(void){
174110  sqlite3rbu *pRet;
174111  pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
174112  if( pRet ){
174113    memset(pRet, 0, sizeof(sqlite3rbu));
174114    pRet->rc = SQLITE_MISUSE;
174115  }
174116  return pRet;
174117}
174118
174119/*
174120** Open and return a new RBU handle.
174121*/
174122SQLITE_API sqlite3rbu *sqlite3rbu_open(
174123  const char *zTarget,
174124  const char *zRbu,
174125  const char *zState
174126){
174127  if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
174128  /* TODO: Check that zTarget and zRbu are non-NULL */
174129  return openRbuHandle(zTarget, zRbu, zState);
174130}
174131
174132/*
174133** Open a handle to begin or resume an RBU VACUUM operation.
174134*/
174135SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
174136  const char *zTarget,
174137  const char *zState
174138){
174139  if( zTarget==0 ){ return rbuMisuseError(); }
174140  /* TODO: Check that both arguments are non-NULL */
174141  return openRbuHandle(0, zTarget, zState);
174142}
174143
174144/*
174145** Return the database handle used by pRbu.
174146*/
174147SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
174148  sqlite3 *db = 0;
174149  if( pRbu ){
174150    db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
174151  }
174152  return db;
174153}
174154
174155
174156/*
174157** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
174158** then edit any error message string so as to remove all occurrences of
174159** the pattern "rbu_imp_[0-9]*".
174160*/
174161static void rbuEditErrmsg(sqlite3rbu *p){
174162  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
174163    unsigned int i;
174164    size_t nErrmsg = strlen(p->zErrmsg);
174165    for(i=0; i<(nErrmsg-8); i++){
174166      if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
174167        int nDel = 8;
174168        while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
174169        memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
174170        nErrmsg -= nDel;
174171      }
174172    }
174173  }
174174}
174175
174176/*
174177** Close the RBU handle.
174178*/
174179SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
174180  int rc;
174181  if( p ){
174182
174183    /* Commit the transaction to the *-oal file. */
174184    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
174185      p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
174186    }
174187
174188    /* Sync the db file if currently doing an incremental checkpoint */
174189    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
174190      sqlite3_file *pDb = p->pTargetFd->pReal;
174191      p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
174192    }
174193
174194    rbuSaveState(p, p->eStage);
174195
174196    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
174197      p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
174198    }
174199
174200    /* Close any open statement handles. */
174201    rbuObjIterFinalize(&p->objiter);
174202
174203    /* If this is an RBU vacuum handle and the vacuum has either finished
174204    ** successfully or encountered an error, delete the contents of the
174205    ** state table. This causes the next call to sqlite3rbu_vacuum()
174206    ** specifying the current target and state databases to start a new
174207    ** vacuum from scratch.  */
174208    if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
174209      int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
174210      if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
174211    }
174212
174213    /* Close the open database handle and VFS object. */
174214    sqlite3_close(p->dbRbu);
174215    sqlite3_close(p->dbMain);
174216    rbuDeleteVfs(p);
174217    sqlite3_free(p->aBuf);
174218    sqlite3_free(p->aFrame);
174219
174220    rbuEditErrmsg(p);
174221    rc = p->rc;
174222    if( pzErrmsg ){
174223      *pzErrmsg = p->zErrmsg;
174224    }else{
174225      sqlite3_free(p->zErrmsg);
174226    }
174227    sqlite3_free(p->zState);
174228    sqlite3_free(p);
174229  }else{
174230    rc = SQLITE_NOMEM;
174231    *pzErrmsg = 0;
174232  }
174233  return rc;
174234}
174235
174236/*
174237** Return the total number of key-value operations (inserts, deletes or
174238** updates) that have been performed on the target database since the
174239** current RBU update was started.
174240*/
174241SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
174242  return pRbu->nProgress;
174243}
174244
174245/*
174246** Return permyriadage progress indications for the two main stages of
174247** an RBU update.
174248*/
174249SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
174250  const int MAX_PROGRESS = 10000;
174251  switch( p->eStage ){
174252    case RBU_STAGE_OAL:
174253      if( p->nPhaseOneStep>0 ){
174254        *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
174255      }else{
174256        *pnOne = -1;
174257      }
174258      *pnTwo = 0;
174259      break;
174260
174261    case RBU_STAGE_MOVE:
174262      *pnOne = MAX_PROGRESS;
174263      *pnTwo = 0;
174264      break;
174265
174266    case RBU_STAGE_CKPT:
174267      *pnOne = MAX_PROGRESS;
174268      *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
174269      break;
174270
174271    case RBU_STAGE_DONE:
174272      *pnOne = MAX_PROGRESS;
174273      *pnTwo = MAX_PROGRESS;
174274      break;
174275
174276    default:
174277      assert( 0 );
174278  }
174279}
174280
174281/*
174282** Return the current state of the RBU vacuum or update operation.
174283*/
174284SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
174285  int aRes[] = {
174286    0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
174287    0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
174288  };
174289
174290  assert( RBU_STAGE_OAL==1 );
174291  assert( RBU_STAGE_MOVE==2 );
174292  assert( RBU_STAGE_CKPT==4 );
174293  assert( RBU_STAGE_DONE==5 );
174294  assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
174295  assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
174296  assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
174297  assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
174298
174299  if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
174300    return SQLITE_RBU_STATE_ERROR;
174301  }else{
174302    assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
174303    assert( p->eStage==RBU_STAGE_OAL
174304         || p->eStage==RBU_STAGE_MOVE
174305         || p->eStage==RBU_STAGE_CKPT
174306         || p->eStage==RBU_STAGE_DONE
174307    );
174308    return aRes[p->eStage];
174309  }
174310}
174311
174312SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
174313  int rc = p->rc;
174314  if( rc==SQLITE_DONE ) return SQLITE_OK;
174315
174316  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
174317  if( p->eStage==RBU_STAGE_OAL ){
174318    assert( rc!=SQLITE_DONE );
174319    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
174320  }
174321
174322  /* Sync the db file */
174323  if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
174324    sqlite3_file *pDb = p->pTargetFd->pReal;
174325    rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
174326  }
174327
174328  p->rc = rc;
174329  rbuSaveState(p, p->eStage);
174330  rc = p->rc;
174331
174332  if( p->eStage==RBU_STAGE_OAL ){
174333    assert( rc!=SQLITE_DONE );
174334    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
174335    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
174336    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
174337  }
174338
174339  p->rc = rc;
174340  return rc;
174341}
174342
174343/**************************************************************************
174344** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
174345** of a standard VFS in the following ways:
174346**
174347** 1. Whenever the first page of a main database file is read or
174348**    written, the value of the change-counter cookie is stored in
174349**    rbu_file.iCookie. Similarly, the value of the "write-version"
174350**    database header field is stored in rbu_file.iWriteVer. This ensures
174351**    that the values are always trustworthy within an open transaction.
174352**
174353** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
174354**    member variable of the associated database file descriptor is set
174355**    to point to the new file. A mutex protected linked list of all main
174356**    db fds opened using a particular RBU VFS is maintained at
174357**    rbu_vfs.pMain to facilitate this.
174358**
174359** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
174360**    object can be marked as the target database of an RBU update. This
174361**    turns on the following extra special behaviour:
174362**
174363** 3a. If xAccess() is called to check if there exists a *-wal file
174364**     associated with an RBU target database currently in RBU_STAGE_OAL
174365**     stage (preparing the *-oal file), the following special handling
174366**     applies:
174367**
174368**      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
174369**        target database may not be in wal mode already.
174370**
174371**      * if the *-wal file does not exist, set the output parameter to
174372**        non-zero (to tell SQLite that it does exist) anyway.
174373**
174374**     Then, when xOpen() is called to open the *-wal file associated with
174375**     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
174376**     file, the rbu vfs opens the corresponding *-oal file instead.
174377**
174378** 3b. The *-shm pages returned by xShmMap() for a target db file in
174379**     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
174380**     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
174381**     are no-ops on target database files in RBU_STAGE_OAL mode. This is
174382**     because assert() statements in some VFS implementations fail if
174383**     xShmLock() is called before xShmMap().
174384**
174385** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
174386**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
174387**     fails with an SQLITE_BUSY error. This is to stop RBU connections
174388**     from automatically checkpointing a *-wal (or *-oal) file from within
174389**     sqlite3_close().
174390**
174391** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
174392**     all xWrite() calls on the target database file perform no IO.
174393**     Instead the frame and page numbers that would be read and written
174394**     are recorded. Additionally, successful attempts to obtain exclusive
174395**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
174396**     database file are recorded. xShmLock() calls to unlock the same
174397**     locks are no-ops (so that once obtained, these locks are never
174398**     relinquished). Finally, calls to xSync() on the target database
174399**     file fail with SQLITE_INTERNAL errors.
174400*/
174401
174402static void rbuUnlockShm(rbu_file *p){
174403  if( p->pRbu ){
174404    int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
174405    int i;
174406    for(i=0; i<SQLITE_SHM_NLOCK;i++){
174407      if( (1<<i) & p->pRbu->mLock ){
174408        xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
174409      }
174410    }
174411    p->pRbu->mLock = 0;
174412  }
174413}
174414
174415/*
174416** Close an rbu file.
174417*/
174418static int rbuVfsClose(sqlite3_file *pFile){
174419  rbu_file *p = (rbu_file*)pFile;
174420  int rc;
174421  int i;
174422
174423  /* Free the contents of the apShm[] array. And the array itself. */
174424  for(i=0; i<p->nShm; i++){
174425    sqlite3_free(p->apShm[i]);
174426  }
174427  sqlite3_free(p->apShm);
174428  p->apShm = 0;
174429  sqlite3_free(p->zDel);
174430
174431  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
174432    rbu_file **pp;
174433    sqlite3_mutex_enter(p->pRbuVfs->mutex);
174434    for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
174435    *pp = p->pMainNext;
174436    sqlite3_mutex_leave(p->pRbuVfs->mutex);
174437    rbuUnlockShm(p);
174438    p->pReal->pMethods->xShmUnmap(p->pReal, 0);
174439  }
174440
174441  /* Close the underlying file handle */
174442  rc = p->pReal->pMethods->xClose(p->pReal);
174443  return rc;
174444}
174445
174446
174447/*
174448** Read and return an unsigned 32-bit big-endian integer from the buffer
174449** passed as the only argument.
174450*/
174451static u32 rbuGetU32(u8 *aBuf){
174452  return ((u32)aBuf[0] << 24)
174453       + ((u32)aBuf[1] << 16)
174454       + ((u32)aBuf[2] <<  8)
174455       + ((u32)aBuf[3]);
174456}
174457
174458/*
174459** Write an unsigned 32-bit value in big-endian format to the supplied
174460** buffer.
174461*/
174462static void rbuPutU32(u8 *aBuf, u32 iVal){
174463  aBuf[0] = (iVal >> 24) & 0xFF;
174464  aBuf[1] = (iVal >> 16) & 0xFF;
174465  aBuf[2] = (iVal >>  8) & 0xFF;
174466  aBuf[3] = (iVal >>  0) & 0xFF;
174467}
174468
174469static void rbuPutU16(u8 *aBuf, u16 iVal){
174470  aBuf[0] = (iVal >>  8) & 0xFF;
174471  aBuf[1] = (iVal >>  0) & 0xFF;
174472}
174473
174474/*
174475** Read data from an rbuVfs-file.
174476*/
174477static int rbuVfsRead(
174478  sqlite3_file *pFile,
174479  void *zBuf,
174480  int iAmt,
174481  sqlite_int64 iOfst
174482){
174483  rbu_file *p = (rbu_file*)pFile;
174484  sqlite3rbu *pRbu = p->pRbu;
174485  int rc;
174486
174487  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
174488    assert( p->openFlags & SQLITE_OPEN_WAL );
174489    rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
174490  }else{
174491    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
174492     && (p->openFlags & SQLITE_OPEN_WAL)
174493     && iOfst>=pRbu->iOalSz
174494    ){
174495      rc = SQLITE_OK;
174496      memset(zBuf, 0, iAmt);
174497    }else{
174498      rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
174499#if 1
174500      /* If this is being called to read the first page of the target
174501      ** database as part of an rbu vacuum operation, synthesize the
174502      ** contents of the first page if it does not yet exist. Otherwise,
174503      ** SQLite will not check for a *-wal file.  */
174504      if( pRbu && rbuIsVacuum(pRbu)
174505          && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
174506          && (p->openFlags & SQLITE_OPEN_MAIN_DB)
174507          && pRbu->rc==SQLITE_OK
174508      ){
174509        sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
174510        rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
174511        if( rc==SQLITE_OK ){
174512          u8 *aBuf = (u8*)zBuf;
174513          u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
174514          rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
174515          rbuPutU32(&aBuf[36], 0);          /* number of free pages */
174516          rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
174517          rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
174518          rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
174519
174520          if( iAmt>100 ){
174521            memset(&aBuf[100], 0, iAmt-100);
174522            rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
174523            aBuf[100] = 0x0D;
174524          }
174525        }
174526      }
174527#endif
174528    }
174529    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
174530      /* These look like magic numbers. But they are stable, as they are part
174531       ** of the definition of the SQLite file format, which may not change. */
174532      u8 *pBuf = (u8*)zBuf;
174533      p->iCookie = rbuGetU32(&pBuf[24]);
174534      p->iWriteVer = pBuf[19];
174535    }
174536  }
174537  return rc;
174538}
174539
174540/*
174541** Write data to an rbuVfs-file.
174542*/
174543static int rbuVfsWrite(
174544  sqlite3_file *pFile,
174545  const void *zBuf,
174546  int iAmt,
174547  sqlite_int64 iOfst
174548){
174549  rbu_file *p = (rbu_file*)pFile;
174550  sqlite3rbu *pRbu = p->pRbu;
174551  int rc;
174552
174553  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
174554    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
174555    rc = rbuCaptureDbWrite(p->pRbu, iOfst);
174556  }else{
174557    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
174558     && (p->openFlags & SQLITE_OPEN_WAL)
174559     && iOfst>=pRbu->iOalSz
174560    ){
174561      pRbu->iOalSz = iAmt + iOfst;
174562    }
174563    rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
174564    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
174565      /* These look like magic numbers. But they are stable, as they are part
174566      ** of the definition of the SQLite file format, which may not change. */
174567      u8 *pBuf = (u8*)zBuf;
174568      p->iCookie = rbuGetU32(&pBuf[24]);
174569      p->iWriteVer = pBuf[19];
174570    }
174571  }
174572  return rc;
174573}
174574
174575/*
174576** Truncate an rbuVfs-file.
174577*/
174578static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
174579  rbu_file *p = (rbu_file*)pFile;
174580  return p->pReal->pMethods->xTruncate(p->pReal, size);
174581}
174582
174583/*
174584** Sync an rbuVfs-file.
174585*/
174586static int rbuVfsSync(sqlite3_file *pFile, int flags){
174587  rbu_file *p = (rbu_file *)pFile;
174588  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
174589    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
174590      return SQLITE_INTERNAL;
174591    }
174592    return SQLITE_OK;
174593  }
174594  return p->pReal->pMethods->xSync(p->pReal, flags);
174595}
174596
174597/*
174598** Return the current file-size of an rbuVfs-file.
174599*/
174600static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
174601  rbu_file *p = (rbu_file *)pFile;
174602  int rc;
174603  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
174604
174605  /* If this is an RBU vacuum operation and this is the target database,
174606  ** pretend that it has at least one page. Otherwise, SQLite will not
174607  ** check for the existance of a *-wal file. rbuVfsRead() contains
174608  ** similar logic.  */
174609  if( rc==SQLITE_OK && *pSize==0
174610   && p->pRbu && rbuIsVacuum(p->pRbu)
174611   && (p->openFlags & SQLITE_OPEN_MAIN_DB)
174612  ){
174613    *pSize = 1024;
174614  }
174615  return rc;
174616}
174617
174618/*
174619** Lock an rbuVfs-file.
174620*/
174621static int rbuVfsLock(sqlite3_file *pFile, int eLock){
174622  rbu_file *p = (rbu_file*)pFile;
174623  sqlite3rbu *pRbu = p->pRbu;
174624  int rc = SQLITE_OK;
174625
174626  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
174627  if( eLock==SQLITE_LOCK_EXCLUSIVE
174628   && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
174629  ){
174630    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
174631    ** prevents it from checkpointing the database from sqlite3_close(). */
174632    rc = SQLITE_BUSY;
174633  }else{
174634    rc = p->pReal->pMethods->xLock(p->pReal, eLock);
174635  }
174636
174637  return rc;
174638}
174639
174640/*
174641** Unlock an rbuVfs-file.
174642*/
174643static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
174644  rbu_file *p = (rbu_file *)pFile;
174645  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
174646}
174647
174648/*
174649** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
174650*/
174651static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
174652  rbu_file *p = (rbu_file *)pFile;
174653  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
174654}
174655
174656/*
174657** File control method. For custom operations on an rbuVfs-file.
174658*/
174659static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
174660  rbu_file *p = (rbu_file *)pFile;
174661  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
174662  int rc;
174663
174664  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
174665       || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
174666  );
174667  if( op==SQLITE_FCNTL_RBU ){
174668    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
174669
174670    /* First try to find another RBU vfs lower down in the vfs stack. If
174671    ** one is found, this vfs will operate in pass-through mode. The lower
174672    ** level vfs will do the special RBU handling.  */
174673    rc = xControl(p->pReal, op, pArg);
174674
174675    if( rc==SQLITE_NOTFOUND ){
174676      /* Now search for a zipvfs instance lower down in the VFS stack. If
174677      ** one is found, this is an error.  */
174678      void *dummy = 0;
174679      rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
174680      if( rc==SQLITE_OK ){
174681        rc = SQLITE_ERROR;
174682        pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
174683      }else if( rc==SQLITE_NOTFOUND ){
174684        pRbu->pTargetFd = p;
174685        p->pRbu = pRbu;
174686        if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
174687        rc = SQLITE_OK;
174688      }
174689    }
174690    return rc;
174691  }
174692  else if( op==SQLITE_FCNTL_RBUCNT ){
174693    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
174694    pRbu->nRbu++;
174695    pRbu->pRbuFd = p;
174696    p->bNolock = 1;
174697  }
174698
174699  rc = xControl(p->pReal, op, pArg);
174700  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
174701    rbu_vfs *pRbuVfs = p->pRbuVfs;
174702    char *zIn = *(char**)pArg;
174703    char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
174704    *(char**)pArg = zOut;
174705    if( zOut==0 ) rc = SQLITE_NOMEM;
174706  }
174707
174708  return rc;
174709}
174710
174711/*
174712** Return the sector-size in bytes for an rbuVfs-file.
174713*/
174714static int rbuVfsSectorSize(sqlite3_file *pFile){
174715  rbu_file *p = (rbu_file *)pFile;
174716  return p->pReal->pMethods->xSectorSize(p->pReal);
174717}
174718
174719/*
174720** Return the device characteristic flags supported by an rbuVfs-file.
174721*/
174722static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
174723  rbu_file *p = (rbu_file *)pFile;
174724  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
174725}
174726
174727/*
174728** Take or release a shared-memory lock.
174729*/
174730static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
174731  rbu_file *p = (rbu_file*)pFile;
174732  sqlite3rbu *pRbu = p->pRbu;
174733  int rc = SQLITE_OK;
174734
174735#ifdef SQLITE_AMALGAMATION
174736    assert( WAL_CKPT_LOCK==1 );
174737#endif
174738
174739  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
174740  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
174741    /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
174742    ** taking this lock also prevents any checkpoints from occurring.
174743    ** todo: really, it's not clear why this might occur, as
174744    ** wal_autocheckpoint ought to be turned off.  */
174745    if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
174746  }else{
174747    int bCapture = 0;
174748    if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
174749     && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
174750     && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
174751    ){
174752      bCapture = 1;
174753    }
174754
174755    if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
174756      rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
174757      if( bCapture && rc==SQLITE_OK ){
174758        pRbu->mLock |= (1 << ofst);
174759      }
174760    }
174761  }
174762
174763  return rc;
174764}
174765
174766/*
174767** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
174768*/
174769static int rbuVfsShmMap(
174770  sqlite3_file *pFile,
174771  int iRegion,
174772  int szRegion,
174773  int isWrite,
174774  void volatile **pp
174775){
174776  rbu_file *p = (rbu_file*)pFile;
174777  int rc = SQLITE_OK;
174778  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
174779
174780  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
174781  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
174782  ** instead of a file on disk.  */
174783  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
174784  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
174785    if( iRegion<=p->nShm ){
174786      int nByte = (iRegion+1) * sizeof(char*);
174787      char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
174788      if( apNew==0 ){
174789        rc = SQLITE_NOMEM;
174790      }else{
174791        memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
174792        p->apShm = apNew;
174793        p->nShm = iRegion+1;
174794      }
174795    }
174796
174797    if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
174798      char *pNew = (char*)sqlite3_malloc64(szRegion);
174799      if( pNew==0 ){
174800        rc = SQLITE_NOMEM;
174801      }else{
174802        memset(pNew, 0, szRegion);
174803        p->apShm[iRegion] = pNew;
174804      }
174805    }
174806
174807    if( rc==SQLITE_OK ){
174808      *pp = p->apShm[iRegion];
174809    }else{
174810      *pp = 0;
174811    }
174812  }else{
174813    assert( p->apShm==0 );
174814    rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
174815  }
174816
174817  return rc;
174818}
174819
174820/*
174821** Memory barrier.
174822*/
174823static void rbuVfsShmBarrier(sqlite3_file *pFile){
174824  rbu_file *p = (rbu_file *)pFile;
174825  p->pReal->pMethods->xShmBarrier(p->pReal);
174826}
174827
174828/*
174829** The xShmUnmap method.
174830*/
174831static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
174832  rbu_file *p = (rbu_file*)pFile;
174833  int rc = SQLITE_OK;
174834  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
174835
174836  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
174837  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
174838    /* no-op */
174839  }else{
174840    /* Release the checkpointer and writer locks */
174841    rbuUnlockShm(p);
174842    rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
174843  }
174844  return rc;
174845}
174846
174847/*
174848** Given that zWal points to a buffer containing a wal file name passed to
174849** either the xOpen() or xAccess() VFS method, return a pointer to the
174850** file-handle opened by the same database connection on the corresponding
174851** database file.
174852*/
174853static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
174854  rbu_file *pDb;
174855  sqlite3_mutex_enter(pRbuVfs->mutex);
174856  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
174857  sqlite3_mutex_leave(pRbuVfs->mutex);
174858  return pDb;
174859}
174860
174861/*
174862** A main database named zName has just been opened. The following
174863** function returns a pointer to a buffer owned by SQLite that contains
174864** the name of the *-wal file this db connection will use. SQLite
174865** happens to pass a pointer to this buffer when using xAccess()
174866** or xOpen() to operate on the *-wal file.
174867*/
174868static const char *rbuMainToWal(const char *zName, int flags){
174869  int n = (int)strlen(zName);
174870  const char *z = &zName[n];
174871  if( flags & SQLITE_OPEN_URI ){
174872    int odd = 0;
174873    while( 1 ){
174874      if( z[0]==0 ){
174875        odd = 1 - odd;
174876        if( odd && z[1]==0 ) break;
174877      }
174878      z++;
174879    }
174880    z += 2;
174881  }else{
174882    while( *z==0 ) z++;
174883  }
174884  z += (n + 8 + 1);
174885  return z;
174886}
174887
174888/*
174889** Open an rbu file handle.
174890*/
174891static int rbuVfsOpen(
174892  sqlite3_vfs *pVfs,
174893  const char *zName,
174894  sqlite3_file *pFile,
174895  int flags,
174896  int *pOutFlags
174897){
174898  static sqlite3_io_methods rbuvfs_io_methods = {
174899    2,                            /* iVersion */
174900    rbuVfsClose,                  /* xClose */
174901    rbuVfsRead,                   /* xRead */
174902    rbuVfsWrite,                  /* xWrite */
174903    rbuVfsTruncate,               /* xTruncate */
174904    rbuVfsSync,                   /* xSync */
174905    rbuVfsFileSize,               /* xFileSize */
174906    rbuVfsLock,                   /* xLock */
174907    rbuVfsUnlock,                 /* xUnlock */
174908    rbuVfsCheckReservedLock,      /* xCheckReservedLock */
174909    rbuVfsFileControl,            /* xFileControl */
174910    rbuVfsSectorSize,             /* xSectorSize */
174911    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
174912    rbuVfsShmMap,                 /* xShmMap */
174913    rbuVfsShmLock,                /* xShmLock */
174914    rbuVfsShmBarrier,             /* xShmBarrier */
174915    rbuVfsShmUnmap,               /* xShmUnmap */
174916    0, 0                          /* xFetch, xUnfetch */
174917  };
174918  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
174919  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
174920  rbu_file *pFd = (rbu_file *)pFile;
174921  int rc = SQLITE_OK;
174922  const char *zOpen = zName;
174923  int oflags = flags;
174924
174925  memset(pFd, 0, sizeof(rbu_file));
174926  pFd->pReal = (sqlite3_file*)&pFd[1];
174927  pFd->pRbuVfs = pRbuVfs;
174928  pFd->openFlags = flags;
174929  if( zName ){
174930    if( flags & SQLITE_OPEN_MAIN_DB ){
174931      /* A main database has just been opened. The following block sets
174932      ** (pFd->zWal) to point to a buffer owned by SQLite that contains
174933      ** the name of the *-wal file this db connection will use. SQLite
174934      ** happens to pass a pointer to this buffer when using xAccess()
174935      ** or xOpen() to operate on the *-wal file.  */
174936      pFd->zWal = rbuMainToWal(zName, flags);
174937    }
174938    else if( flags & SQLITE_OPEN_WAL ){
174939      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
174940      if( pDb ){
174941        if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
174942          /* This call is to open a *-wal file. Intead, open the *-oal. This
174943          ** code ensures that the string passed to xOpen() is terminated by a
174944          ** pair of '\0' bytes in case the VFS attempts to extract a URI
174945          ** parameter from it.  */
174946          const char *zBase = zName;
174947          size_t nCopy;
174948          char *zCopy;
174949          if( rbuIsVacuum(pDb->pRbu) ){
174950            zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
174951            zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
174952          }
174953          nCopy = strlen(zBase);
174954          zCopy = sqlite3_malloc64(nCopy+2);
174955          if( zCopy ){
174956            memcpy(zCopy, zBase, nCopy);
174957            zCopy[nCopy-3] = 'o';
174958            zCopy[nCopy] = '\0';
174959            zCopy[nCopy+1] = '\0';
174960            zOpen = (const char*)(pFd->zDel = zCopy);
174961          }else{
174962            rc = SQLITE_NOMEM;
174963          }
174964          pFd->pRbu = pDb->pRbu;
174965        }
174966        pDb->pWalFd = pFd;
174967      }
174968    }
174969  }
174970
174971  if( oflags & SQLITE_OPEN_MAIN_DB
174972   && sqlite3_uri_boolean(zName, "rbu_memory", 0)
174973  ){
174974    assert( oflags & SQLITE_OPEN_MAIN_DB );
174975    oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
174976              SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
174977    zOpen = 0;
174978  }
174979
174980  if( rc==SQLITE_OK ){
174981    rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
174982  }
174983  if( pFd->pReal->pMethods ){
174984    /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
174985    ** pointer and, if the file is a main database file, link it into the
174986    ** mutex protected linked list of all such files.  */
174987    pFile->pMethods = &rbuvfs_io_methods;
174988    if( flags & SQLITE_OPEN_MAIN_DB ){
174989      sqlite3_mutex_enter(pRbuVfs->mutex);
174990      pFd->pMainNext = pRbuVfs->pMain;
174991      pRbuVfs->pMain = pFd;
174992      sqlite3_mutex_leave(pRbuVfs->mutex);
174993    }
174994  }else{
174995    sqlite3_free(pFd->zDel);
174996  }
174997
174998  return rc;
174999}
175000
175001/*
175002** Delete the file located at zPath.
175003*/
175004static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
175005  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175006  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
175007}
175008
175009/*
175010** Test for access permissions. Return true if the requested permission
175011** is available, or false otherwise.
175012*/
175013static int rbuVfsAccess(
175014  sqlite3_vfs *pVfs,
175015  const char *zPath,
175016  int flags,
175017  int *pResOut
175018){
175019  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
175020  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
175021  int rc;
175022
175023  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
175024
175025  /* If this call is to check if a *-wal file associated with an RBU target
175026  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
175027  ** the following special handling is activated:
175028  **
175029  **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
175030  **      ensures that the RBU extension never tries to update a database
175031  **      in wal mode, even if the first page of the database file has
175032  **      been damaged.
175033  **
175034  **   b) if the *-wal file does not exist, claim that it does anyway,
175035  **      causing SQLite to call xOpen() to open it. This call will also
175036  **      be intercepted (see the rbuVfsOpen() function) and the *-oal
175037  **      file opened instead.
175038  */
175039  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
175040    rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
175041    if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
175042      if( *pResOut ){
175043        rc = SQLITE_CANTOPEN;
175044      }else{
175045        *pResOut = 1;
175046      }
175047    }
175048  }
175049
175050  return rc;
175051}
175052
175053/*
175054** Populate buffer zOut with the full canonical pathname corresponding
175055** to the pathname in zPath. zOut is guaranteed to point to a buffer
175056** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
175057*/
175058static int rbuVfsFullPathname(
175059  sqlite3_vfs *pVfs,
175060  const char *zPath,
175061  int nOut,
175062  char *zOut
175063){
175064  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175065  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
175066}
175067
175068#ifndef SQLITE_OMIT_LOAD_EXTENSION
175069/*
175070** Open the dynamic library located at zPath and return a handle.
175071*/
175072static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
175073  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175074  return pRealVfs->xDlOpen(pRealVfs, zPath);
175075}
175076
175077/*
175078** Populate the buffer zErrMsg (size nByte bytes) with a human readable
175079** utf-8 string describing the most recent error encountered associated
175080** with dynamic libraries.
175081*/
175082static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
175083  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175084  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
175085}
175086
175087/*
175088** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
175089*/
175090static void (*rbuVfsDlSym(
175091  sqlite3_vfs *pVfs,
175092  void *pArg,
175093  const char *zSym
175094))(void){
175095  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175096  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
175097}
175098
175099/*
175100** Close the dynamic library handle pHandle.
175101*/
175102static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
175103  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175104  pRealVfs->xDlClose(pRealVfs, pHandle);
175105}
175106#endif /* SQLITE_OMIT_LOAD_EXTENSION */
175107
175108/*
175109** Populate the buffer pointed to by zBufOut with nByte bytes of
175110** random data.
175111*/
175112static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
175113  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175114  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
175115}
175116
175117/*
175118** Sleep for nMicro microseconds. Return the number of microseconds
175119** actually slept.
175120*/
175121static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
175122  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175123  return pRealVfs->xSleep(pRealVfs, nMicro);
175124}
175125
175126/*
175127** Return the current time as a Julian Day number in *pTimeOut.
175128*/
175129static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
175130  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
175131  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
175132}
175133
175134/*
175135** No-op.
175136*/
175137static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
175138  return 0;
175139}
175140
175141/*
175142** Deregister and destroy an RBU vfs created by an earlier call to
175143** sqlite3rbu_create_vfs().
175144*/
175145SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
175146  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
175147  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
175148    sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
175149    sqlite3_vfs_unregister(pVfs);
175150    sqlite3_free(pVfs);
175151  }
175152}
175153
175154/*
175155** Create an RBU VFS named zName that accesses the underlying file-system
175156** via existing VFS zParent. The new object is registered as a non-default
175157** VFS with SQLite before returning.
175158*/
175159SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
175160
175161  /* Template for VFS */
175162  static sqlite3_vfs vfs_template = {
175163    1,                            /* iVersion */
175164    0,                            /* szOsFile */
175165    0,                            /* mxPathname */
175166    0,                            /* pNext */
175167    0,                            /* zName */
175168    0,                            /* pAppData */
175169    rbuVfsOpen,                   /* xOpen */
175170    rbuVfsDelete,                 /* xDelete */
175171    rbuVfsAccess,                 /* xAccess */
175172    rbuVfsFullPathname,           /* xFullPathname */
175173
175174#ifndef SQLITE_OMIT_LOAD_EXTENSION
175175    rbuVfsDlOpen,                 /* xDlOpen */
175176    rbuVfsDlError,                /* xDlError */
175177    rbuVfsDlSym,                  /* xDlSym */
175178    rbuVfsDlClose,                /* xDlClose */
175179#else
175180    0, 0, 0, 0,
175181#endif
175182
175183    rbuVfsRandomness,             /* xRandomness */
175184    rbuVfsSleep,                  /* xSleep */
175185    rbuVfsCurrentTime,            /* xCurrentTime */
175186    rbuVfsGetLastError,           /* xGetLastError */
175187    0,                            /* xCurrentTimeInt64 (version 2) */
175188    0, 0, 0                       /* Unimplemented version 3 methods */
175189  };
175190
175191  rbu_vfs *pNew = 0;              /* Newly allocated VFS */
175192  int rc = SQLITE_OK;
175193  size_t nName;
175194  size_t nByte;
175195
175196  nName = strlen(zName);
175197  nByte = sizeof(rbu_vfs) + nName + 1;
175198  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
175199  if( pNew==0 ){
175200    rc = SQLITE_NOMEM;
175201  }else{
175202    sqlite3_vfs *pParent;           /* Parent VFS */
175203    memset(pNew, 0, nByte);
175204    pParent = sqlite3_vfs_find(zParent);
175205    if( pParent==0 ){
175206      rc = SQLITE_NOTFOUND;
175207    }else{
175208      char *zSpace;
175209      memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
175210      pNew->base.mxPathname = pParent->mxPathname;
175211      pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
175212      pNew->pRealVfs = pParent;
175213      pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
175214      memcpy(zSpace, zName, nName);
175215
175216      /* Allocate the mutex and register the new VFS (not as the default) */
175217      pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
175218      if( pNew->mutex==0 ){
175219        rc = SQLITE_NOMEM;
175220      }else{
175221        rc = sqlite3_vfs_register(&pNew->base, 0);
175222      }
175223    }
175224
175225    if( rc!=SQLITE_OK ){
175226      sqlite3_mutex_free(pNew->mutex);
175227      sqlite3_free(pNew);
175228    }
175229  }
175230
175231  return rc;
175232}
175233
175234
175235/**************************************************************************/
175236
175237#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
175238
175239/************** End of sqlite3rbu.c ******************************************/
175240/************** Begin file dbstat.c ******************************************/
175241/*
175242** 2010 July 12
175243**
175244** The author disclaims copyright to this source code.  In place of
175245** a legal notice, here is a blessing:
175246**
175247**    May you do good and not evil.
175248**    May you find forgiveness for yourself and forgive others.
175249**    May you share freely, never taking more than you give.
175250**
175251******************************************************************************
175252**
175253** This file contains an implementation of the "dbstat" virtual table.
175254**
175255** The dbstat virtual table is used to extract low-level formatting
175256** information from an SQLite database in order to implement the
175257** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
175258** for an example implementation.
175259**
175260** Additional information is available on the "dbstat.html" page of the
175261** official SQLite documentation.
175262*/
175263
175264/* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
175265#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
175266    && !defined(SQLITE_OMIT_VIRTUALTABLE)
175267
175268/*
175269** Page paths:
175270**
175271**   The value of the 'path' column describes the path taken from the
175272**   root-node of the b-tree structure to each page. The value of the
175273**   root-node path is '/'.
175274**
175275**   The value of the path for the left-most child page of the root of
175276**   a b-tree is '/000/'. (Btrees store content ordered from left to right
175277**   so the pages to the left have smaller keys than the pages to the right.)
175278**   The next to left-most child of the root page is
175279**   '/001', and so on, each sibling page identified by a 3-digit hex
175280**   value. The children of the 451st left-most sibling have paths such
175281**   as '/1c2/000/, '/1c2/001/' etc.
175282**
175283**   Overflow pages are specified by appending a '+' character and a
175284**   six-digit hexadecimal value to the path to the cell they are linked
175285**   from. For example, the three overflow pages in a chain linked from
175286**   the left-most cell of the 450th child of the root page are identified
175287**   by the paths:
175288**
175289**      '/1c2/000+000000'         // First page in overflow chain
175290**      '/1c2/000+000001'         // Second page in overflow chain
175291**      '/1c2/000+000002'         // Third page in overflow chain
175292**
175293**   If the paths are sorted using the BINARY collation sequence, then
175294**   the overflow pages associated with a cell will appear earlier in the
175295**   sort-order than its child page:
175296**
175297**      '/1c2/000/'               // Left-most child of 451st child of root
175298*/
175299#define VTAB_SCHEMA                                                         \
175300  "CREATE TABLE xx( "                                                       \
175301  "  name       TEXT,             /* Name of table or index */"             \
175302  "  path       TEXT,             /* Path to page from root */"             \
175303  "  pageno     INTEGER,          /* Page number */"                        \
175304  "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
175305  "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
175306  "  payload    INTEGER,          /* Bytes of payload on this page */"      \
175307  "  unused     INTEGER,          /* Bytes of unused space on this page */" \
175308  "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
175309  "  pgoffset   INTEGER,          /* Offset of page in file */"             \
175310  "  pgsize     INTEGER,          /* Size of the page */"                   \
175311  "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
175312  ");"
175313
175314
175315typedef struct StatTable StatTable;
175316typedef struct StatCursor StatCursor;
175317typedef struct StatPage StatPage;
175318typedef struct StatCell StatCell;
175319
175320struct StatCell {
175321  int nLocal;                     /* Bytes of local payload */
175322  u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
175323  int nOvfl;                      /* Entries in aOvfl[] */
175324  u32 *aOvfl;                     /* Array of overflow page numbers */
175325  int nLastOvfl;                  /* Bytes of payload on final overflow page */
175326  int iOvfl;                      /* Iterates through aOvfl[] */
175327};
175328
175329struct StatPage {
175330  u32 iPgno;
175331  DbPage *pPg;
175332  int iCell;
175333
175334  char *zPath;                    /* Path to this page */
175335
175336  /* Variables populated by statDecodePage(): */
175337  u8 flags;                       /* Copy of flags byte */
175338  int nCell;                      /* Number of cells on page */
175339  int nUnused;                    /* Number of unused bytes on page */
175340  StatCell *aCell;                /* Array of parsed cells */
175341  u32 iRightChildPg;              /* Right-child page number (or 0) */
175342  int nMxPayload;                 /* Largest payload of any cell on this page */
175343};
175344
175345struct StatCursor {
175346  sqlite3_vtab_cursor base;
175347  sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
175348  int isEof;                      /* After pStmt has returned SQLITE_DONE */
175349  int iDb;                        /* Schema used for this query */
175350
175351  StatPage aPage[32];
175352  int iPage;                      /* Current entry in aPage[] */
175353
175354  /* Values to return. */
175355  char *zName;                    /* Value of 'name' column */
175356  char *zPath;                    /* Value of 'path' column */
175357  u32 iPageno;                    /* Value of 'pageno' column */
175358  char *zPagetype;                /* Value of 'pagetype' column */
175359  int nCell;                      /* Value of 'ncell' column */
175360  int nPayload;                   /* Value of 'payload' column */
175361  int nUnused;                    /* Value of 'unused' column */
175362  int nMxPayload;                 /* Value of 'mx_payload' column */
175363  i64 iOffset;                    /* Value of 'pgOffset' column */
175364  int szPage;                     /* Value of 'pgSize' column */
175365};
175366
175367struct StatTable {
175368  sqlite3_vtab base;
175369  sqlite3 *db;
175370  int iDb;                        /* Index of database to analyze */
175371};
175372
175373#ifndef get2byte
175374# define get2byte(x)   ((x)[0]<<8 | (x)[1])
175375#endif
175376
175377/*
175378** Connect to or create a statvfs virtual table.
175379*/
175380static int statConnect(
175381  sqlite3 *db,
175382  void *pAux,
175383  int argc, const char *const*argv,
175384  sqlite3_vtab **ppVtab,
175385  char **pzErr
175386){
175387  StatTable *pTab = 0;
175388  int rc = SQLITE_OK;
175389  int iDb;
175390
175391  if( argc>=4 ){
175392    Token nm;
175393    sqlite3TokenInit(&nm, (char*)argv[3]);
175394    iDb = sqlite3FindDb(db, &nm);
175395    if( iDb<0 ){
175396      *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
175397      return SQLITE_ERROR;
175398    }
175399  }else{
175400    iDb = 0;
175401  }
175402  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
175403  if( rc==SQLITE_OK ){
175404    pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
175405    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
175406  }
175407
175408  assert( rc==SQLITE_OK || pTab==0 );
175409  if( rc==SQLITE_OK ){
175410    memset(pTab, 0, sizeof(StatTable));
175411    pTab->db = db;
175412    pTab->iDb = iDb;
175413  }
175414
175415  *ppVtab = (sqlite3_vtab*)pTab;
175416  return rc;
175417}
175418
175419/*
175420** Disconnect from or destroy a statvfs virtual table.
175421*/
175422static int statDisconnect(sqlite3_vtab *pVtab){
175423  sqlite3_free(pVtab);
175424  return SQLITE_OK;
175425}
175426
175427/*
175428** There is no "best-index". This virtual table always does a linear
175429** scan.  However, a schema=? constraint should cause this table to
175430** operate on a different database schema, so check for it.
175431**
175432** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
175433*/
175434static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
175435  int i;
175436
175437  pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
175438
175439  /* Look for a valid schema=? constraint.  If found, change the idxNum to
175440  ** 1 and request the value of that constraint be sent to xFilter.  And
175441  ** lower the cost estimate to encourage the constrained version to be
175442  ** used.
175443  */
175444  for(i=0; i<pIdxInfo->nConstraint; i++){
175445    if( pIdxInfo->aConstraint[i].usable==0 ) continue;
175446    if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
175447    if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
175448    pIdxInfo->idxNum = 1;
175449    pIdxInfo->estimatedCost = 1.0;
175450    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
175451    pIdxInfo->aConstraintUsage[i].omit = 1;
175452    break;
175453  }
175454
175455
175456  /* Records are always returned in ascending order of (name, path).
175457  ** If this will satisfy the client, set the orderByConsumed flag so that
175458  ** SQLite does not do an external sort.
175459  */
175460  if( ( pIdxInfo->nOrderBy==1
175461     && pIdxInfo->aOrderBy[0].iColumn==0
175462     && pIdxInfo->aOrderBy[0].desc==0
175463     ) ||
175464      ( pIdxInfo->nOrderBy==2
175465     && pIdxInfo->aOrderBy[0].iColumn==0
175466     && pIdxInfo->aOrderBy[0].desc==0
175467     && pIdxInfo->aOrderBy[1].iColumn==1
175468     && pIdxInfo->aOrderBy[1].desc==0
175469     )
175470  ){
175471    pIdxInfo->orderByConsumed = 1;
175472  }
175473
175474  return SQLITE_OK;
175475}
175476
175477/*
175478** Open a new statvfs cursor.
175479*/
175480static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
175481  StatTable *pTab = (StatTable *)pVTab;
175482  StatCursor *pCsr;
175483
175484  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
175485  if( pCsr==0 ){
175486    return SQLITE_NOMEM_BKPT;
175487  }else{
175488    memset(pCsr, 0, sizeof(StatCursor));
175489    pCsr->base.pVtab = pVTab;
175490    pCsr->iDb = pTab->iDb;
175491  }
175492
175493  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
175494  return SQLITE_OK;
175495}
175496
175497static void statClearPage(StatPage *p){
175498  int i;
175499  if( p->aCell ){
175500    for(i=0; i<p->nCell; i++){
175501      sqlite3_free(p->aCell[i].aOvfl);
175502    }
175503    sqlite3_free(p->aCell);
175504  }
175505  sqlite3PagerUnref(p->pPg);
175506  sqlite3_free(p->zPath);
175507  memset(p, 0, sizeof(StatPage));
175508}
175509
175510static void statResetCsr(StatCursor *pCsr){
175511  int i;
175512  sqlite3_reset(pCsr->pStmt);
175513  for(i=0; i<ArraySize(pCsr->aPage); i++){
175514    statClearPage(&pCsr->aPage[i]);
175515  }
175516  pCsr->iPage = 0;
175517  sqlite3_free(pCsr->zPath);
175518  pCsr->zPath = 0;
175519  pCsr->isEof = 0;
175520}
175521
175522/*
175523** Close a statvfs cursor.
175524*/
175525static int statClose(sqlite3_vtab_cursor *pCursor){
175526  StatCursor *pCsr = (StatCursor *)pCursor;
175527  statResetCsr(pCsr);
175528  sqlite3_finalize(pCsr->pStmt);
175529  sqlite3_free(pCsr);
175530  return SQLITE_OK;
175531}
175532
175533static void getLocalPayload(
175534  int nUsable,                    /* Usable bytes per page */
175535  u8 flags,                       /* Page flags */
175536  int nTotal,                     /* Total record (payload) size */
175537  int *pnLocal                    /* OUT: Bytes stored locally */
175538){
175539  int nLocal;
175540  int nMinLocal;
175541  int nMaxLocal;
175542
175543  if( flags==0x0D ){              /* Table leaf node */
175544    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
175545    nMaxLocal = nUsable - 35;
175546  }else{                          /* Index interior and leaf nodes */
175547    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
175548    nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
175549  }
175550
175551  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
175552  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
175553  *pnLocal = nLocal;
175554}
175555
175556static int statDecodePage(Btree *pBt, StatPage *p){
175557  int nUnused;
175558  int iOff;
175559  int nHdr;
175560  int isLeaf;
175561  int szPage;
175562
175563  u8 *aData = sqlite3PagerGetData(p->pPg);
175564  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
175565
175566  p->flags = aHdr[0];
175567  p->nCell = get2byte(&aHdr[3]);
175568  p->nMxPayload = 0;
175569
175570  isLeaf = (p->flags==0x0A || p->flags==0x0D);
175571  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
175572
175573  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
175574  nUnused += (int)aHdr[7];
175575  iOff = get2byte(&aHdr[1]);
175576  while( iOff ){
175577    nUnused += get2byte(&aData[iOff+2]);
175578    iOff = get2byte(&aData[iOff]);
175579  }
175580  p->nUnused = nUnused;
175581  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
175582  szPage = sqlite3BtreeGetPageSize(pBt);
175583
175584  if( p->nCell ){
175585    int i;                        /* Used to iterate through cells */
175586    int nUsable;                  /* Usable bytes per page */
175587
175588    sqlite3BtreeEnter(pBt);
175589    nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
175590    sqlite3BtreeLeave(pBt);
175591    p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
175592    if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
175593    memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
175594
175595    for(i=0; i<p->nCell; i++){
175596      StatCell *pCell = &p->aCell[i];
175597
175598      iOff = get2byte(&aData[nHdr+i*2]);
175599      if( !isLeaf ){
175600        pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
175601        iOff += 4;
175602      }
175603      if( p->flags==0x05 ){
175604        /* A table interior node. nPayload==0. */
175605      }else{
175606        u32 nPayload;             /* Bytes of payload total (local+overflow) */
175607        int nLocal;               /* Bytes of payload stored locally */
175608        iOff += getVarint32(&aData[iOff], nPayload);
175609        if( p->flags==0x0D ){
175610          u64 dummy;
175611          iOff += sqlite3GetVarint(&aData[iOff], &dummy);
175612        }
175613        if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
175614        getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
175615        pCell->nLocal = nLocal;
175616        assert( nLocal>=0 );
175617        assert( nPayload>=(u32)nLocal );
175618        assert( nLocal<=(nUsable-35) );
175619        if( nPayload>(u32)nLocal ){
175620          int j;
175621          int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
175622          pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
175623          pCell->nOvfl = nOvfl;
175624          pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
175625          if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
175626          pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
175627          for(j=1; j<nOvfl; j++){
175628            int rc;
175629            u32 iPrev = pCell->aOvfl[j-1];
175630            DbPage *pPg = 0;
175631            rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
175632            if( rc!=SQLITE_OK ){
175633              assert( pPg==0 );
175634              return rc;
175635            }
175636            pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
175637            sqlite3PagerUnref(pPg);
175638          }
175639        }
175640      }
175641    }
175642  }
175643
175644  return SQLITE_OK;
175645}
175646
175647/*
175648** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
175649** the current value of pCsr->iPageno.
175650*/
175651static void statSizeAndOffset(StatCursor *pCsr){
175652  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
175653  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
175654  Pager *pPager = sqlite3BtreePager(pBt);
175655  sqlite3_file *fd;
175656  sqlite3_int64 x[2];
175657
175658  /* The default page size and offset */
175659  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
175660  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
175661
175662  /* If connected to a ZIPVFS backend, override the page size and
175663  ** offset with actual values obtained from ZIPVFS.
175664  */
175665  fd = sqlite3PagerFile(pPager);
175666  x[0] = pCsr->iPageno;
175667  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
175668    pCsr->iOffset = x[0];
175669    pCsr->szPage = (int)x[1];
175670  }
175671}
175672
175673/*
175674** Move a statvfs cursor to the next entry in the file.
175675*/
175676static int statNext(sqlite3_vtab_cursor *pCursor){
175677  int rc;
175678  int nPayload;
175679  char *z;
175680  StatCursor *pCsr = (StatCursor *)pCursor;
175681  StatTable *pTab = (StatTable *)pCursor->pVtab;
175682  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
175683  Pager *pPager = sqlite3BtreePager(pBt);
175684
175685  sqlite3_free(pCsr->zPath);
175686  pCsr->zPath = 0;
175687
175688statNextRestart:
175689  if( pCsr->aPage[0].pPg==0 ){
175690    rc = sqlite3_step(pCsr->pStmt);
175691    if( rc==SQLITE_ROW ){
175692      int nPage;
175693      u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
175694      sqlite3PagerPagecount(pPager, &nPage);
175695      if( nPage==0 ){
175696        pCsr->isEof = 1;
175697        return sqlite3_reset(pCsr->pStmt);
175698      }
175699      rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
175700      pCsr->aPage[0].iPgno = iRoot;
175701      pCsr->aPage[0].iCell = 0;
175702      pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
175703      pCsr->iPage = 0;
175704      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
175705    }else{
175706      pCsr->isEof = 1;
175707      return sqlite3_reset(pCsr->pStmt);
175708    }
175709  }else{
175710
175711    /* Page p itself has already been visited. */
175712    StatPage *p = &pCsr->aPage[pCsr->iPage];
175713
175714    while( p->iCell<p->nCell ){
175715      StatCell *pCell = &p->aCell[p->iCell];
175716      if( pCell->iOvfl<pCell->nOvfl ){
175717        int nUsable;
175718        sqlite3BtreeEnter(pBt);
175719        nUsable = sqlite3BtreeGetPageSize(pBt) -
175720                        sqlite3BtreeGetReserveNoMutex(pBt);
175721        sqlite3BtreeLeave(pBt);
175722        pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
175723        pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
175724        pCsr->zPagetype = "overflow";
175725        pCsr->nCell = 0;
175726        pCsr->nMxPayload = 0;
175727        pCsr->zPath = z = sqlite3_mprintf(
175728            "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
175729        );
175730        if( pCell->iOvfl<pCell->nOvfl-1 ){
175731          pCsr->nUnused = 0;
175732          pCsr->nPayload = nUsable - 4;
175733        }else{
175734          pCsr->nPayload = pCell->nLastOvfl;
175735          pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
175736        }
175737        pCell->iOvfl++;
175738        statSizeAndOffset(pCsr);
175739        return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
175740      }
175741      if( p->iRightChildPg ) break;
175742      p->iCell++;
175743    }
175744
175745    if( !p->iRightChildPg || p->iCell>p->nCell ){
175746      statClearPage(p);
175747      if( pCsr->iPage==0 ) return statNext(pCursor);
175748      pCsr->iPage--;
175749      goto statNextRestart; /* Tail recursion */
175750    }
175751    pCsr->iPage++;
175752    assert( p==&pCsr->aPage[pCsr->iPage-1] );
175753
175754    if( p->iCell==p->nCell ){
175755      p[1].iPgno = p->iRightChildPg;
175756    }else{
175757      p[1].iPgno = p->aCell[p->iCell].iChildPg;
175758    }
175759    rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
175760    p[1].iCell = 0;
175761    p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
175762    p->iCell++;
175763    if( z==0 ) rc = SQLITE_NOMEM_BKPT;
175764  }
175765
175766
175767  /* Populate the StatCursor fields with the values to be returned
175768  ** by the xColumn() and xRowid() methods.
175769  */
175770  if( rc==SQLITE_OK ){
175771    int i;
175772    StatPage *p = &pCsr->aPage[pCsr->iPage];
175773    pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
175774    pCsr->iPageno = p->iPgno;
175775
175776    rc = statDecodePage(pBt, p);
175777    if( rc==SQLITE_OK ){
175778      statSizeAndOffset(pCsr);
175779
175780      switch( p->flags ){
175781        case 0x05:             /* table internal */
175782        case 0x02:             /* index internal */
175783          pCsr->zPagetype = "internal";
175784          break;
175785        case 0x0D:             /* table leaf */
175786        case 0x0A:             /* index leaf */
175787          pCsr->zPagetype = "leaf";
175788          break;
175789        default:
175790          pCsr->zPagetype = "corrupted";
175791          break;
175792      }
175793      pCsr->nCell = p->nCell;
175794      pCsr->nUnused = p->nUnused;
175795      pCsr->nMxPayload = p->nMxPayload;
175796      pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
175797      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
175798      nPayload = 0;
175799      for(i=0; i<p->nCell; i++){
175800        nPayload += p->aCell[i].nLocal;
175801      }
175802      pCsr->nPayload = nPayload;
175803    }
175804  }
175805
175806  return rc;
175807}
175808
175809static int statEof(sqlite3_vtab_cursor *pCursor){
175810  StatCursor *pCsr = (StatCursor *)pCursor;
175811  return pCsr->isEof;
175812}
175813
175814static int statFilter(
175815  sqlite3_vtab_cursor *pCursor,
175816  int idxNum, const char *idxStr,
175817  int argc, sqlite3_value **argv
175818){
175819  StatCursor *pCsr = (StatCursor *)pCursor;
175820  StatTable *pTab = (StatTable*)(pCursor->pVtab);
175821  char *zSql;
175822  int rc = SQLITE_OK;
175823  char *zMaster;
175824
175825  if( idxNum==1 ){
175826    const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
175827    pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
175828    if( pCsr->iDb<0 ){
175829      sqlite3_free(pCursor->pVtab->zErrMsg);
175830      pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
175831      return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
175832    }
175833  }else{
175834    pCsr->iDb = pTab->iDb;
175835  }
175836  statResetCsr(pCsr);
175837  sqlite3_finalize(pCsr->pStmt);
175838  pCsr->pStmt = 0;
175839  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
175840  zSql = sqlite3_mprintf(
175841      "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
175842      "  UNION ALL  "
175843      "SELECT name, rootpage, type"
175844      "  FROM \"%w\".%s WHERE rootpage!=0"
175845      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
175846  if( zSql==0 ){
175847    return SQLITE_NOMEM_BKPT;
175848  }else{
175849    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
175850    sqlite3_free(zSql);
175851  }
175852
175853  if( rc==SQLITE_OK ){
175854    rc = statNext(pCursor);
175855  }
175856  return rc;
175857}
175858
175859static int statColumn(
175860  sqlite3_vtab_cursor *pCursor,
175861  sqlite3_context *ctx,
175862  int i
175863){
175864  StatCursor *pCsr = (StatCursor *)pCursor;
175865  switch( i ){
175866    case 0:            /* name */
175867      sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
175868      break;
175869    case 1:            /* path */
175870      sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
175871      break;
175872    case 2:            /* pageno */
175873      sqlite3_result_int64(ctx, pCsr->iPageno);
175874      break;
175875    case 3:            /* pagetype */
175876      sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
175877      break;
175878    case 4:            /* ncell */
175879      sqlite3_result_int(ctx, pCsr->nCell);
175880      break;
175881    case 5:            /* payload */
175882      sqlite3_result_int(ctx, pCsr->nPayload);
175883      break;
175884    case 6:            /* unused */
175885      sqlite3_result_int(ctx, pCsr->nUnused);
175886      break;
175887    case 7:            /* mx_payload */
175888      sqlite3_result_int(ctx, pCsr->nMxPayload);
175889      break;
175890    case 8:            /* pgoffset */
175891      sqlite3_result_int64(ctx, pCsr->iOffset);
175892      break;
175893    case 9:            /* pgsize */
175894      sqlite3_result_int(ctx, pCsr->szPage);
175895      break;
175896    default: {          /* schema */
175897      sqlite3 *db = sqlite3_context_db_handle(ctx);
175898      int iDb = pCsr->iDb;
175899      sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
175900      break;
175901    }
175902  }
175903  return SQLITE_OK;
175904}
175905
175906static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
175907  StatCursor *pCsr = (StatCursor *)pCursor;
175908  *pRowid = pCsr->iPageno;
175909  return SQLITE_OK;
175910}
175911
175912/*
175913** Invoke this routine to register the "dbstat" virtual table module
175914*/
175915SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
175916  static sqlite3_module dbstat_module = {
175917    0,                            /* iVersion */
175918    statConnect,                  /* xCreate */
175919    statConnect,                  /* xConnect */
175920    statBestIndex,                /* xBestIndex */
175921    statDisconnect,               /* xDisconnect */
175922    statDisconnect,               /* xDestroy */
175923    statOpen,                     /* xOpen - open a cursor */
175924    statClose,                    /* xClose - close a cursor */
175925    statFilter,                   /* xFilter - configure scan constraints */
175926    statNext,                     /* xNext - advance a cursor */
175927    statEof,                      /* xEof - check for end of scan */
175928    statColumn,                   /* xColumn - read data */
175929    statRowid,                    /* xRowid - read data */
175930    0,                            /* xUpdate */
175931    0,                            /* xBegin */
175932    0,                            /* xSync */
175933    0,                            /* xCommit */
175934    0,                            /* xRollback */
175935    0,                            /* xFindMethod */
175936    0,                            /* xRename */
175937    0,                            /* xSavepoint */
175938    0,                            /* xRelease */
175939    0,                            /* xRollbackTo */
175940  };
175941  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
175942}
175943#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
175944SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
175945#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
175946
175947/************** End of dbstat.c **********************************************/
175948/************** Begin file sqlite3session.c **********************************/
175949
175950#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
175951/* #include "sqlite3session.h" */
175952/* #include <assert.h> */
175953/* #include <string.h> */
175954
175955#ifndef SQLITE_AMALGAMATION
175956/* # include "sqliteInt.h" */
175957/* # include "vdbeInt.h" */
175958#endif
175959
175960typedef struct SessionTable SessionTable;
175961typedef struct SessionChange SessionChange;
175962typedef struct SessionBuffer SessionBuffer;
175963typedef struct SessionInput SessionInput;
175964
175965/*
175966** Minimum chunk size used by streaming versions of functions.
175967*/
175968#ifndef SESSIONS_STRM_CHUNK_SIZE
175969# ifdef SQLITE_TEST
175970#   define SESSIONS_STRM_CHUNK_SIZE 64
175971# else
175972#   define SESSIONS_STRM_CHUNK_SIZE 1024
175973# endif
175974#endif
175975
175976typedef struct SessionHook SessionHook;
175977struct SessionHook {
175978  void *pCtx;
175979  int (*xOld)(void*,int,sqlite3_value**);
175980  int (*xNew)(void*,int,sqlite3_value**);
175981  int (*xCount)(void*);
175982  int (*xDepth)(void*);
175983};
175984
175985/*
175986** Session handle structure.
175987*/
175988struct sqlite3_session {
175989  sqlite3 *db;                    /* Database handle session is attached to */
175990  char *zDb;                      /* Name of database session is attached to */
175991  int bEnable;                    /* True if currently recording */
175992  int bIndirect;                  /* True if all changes are indirect */
175993  int bAutoAttach;                /* True to auto-attach tables */
175994  int rc;                         /* Non-zero if an error has occurred */
175995  void *pFilterCtx;               /* First argument to pass to xTableFilter */
175996  int (*xTableFilter)(void *pCtx, const char *zTab);
175997  sqlite3_session *pNext;         /* Next session object on same db. */
175998  SessionTable *pTable;           /* List of attached tables */
175999  SessionHook hook;               /* APIs to grab new and old data with */
176000};
176001
176002/*
176003** Instances of this structure are used to build strings or binary records.
176004*/
176005struct SessionBuffer {
176006  u8 *aBuf;                       /* Pointer to changeset buffer */
176007  int nBuf;                       /* Size of buffer aBuf */
176008  int nAlloc;                     /* Size of allocation containing aBuf */
176009};
176010
176011/*
176012** An object of this type is used internally as an abstraction for
176013** input data. Input data may be supplied either as a single large buffer
176014** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
176015**  sqlite3changeset_start_strm()).
176016*/
176017struct SessionInput {
176018  int bNoDiscard;                 /* If true, discard no data */
176019  int iCurrent;                   /* Offset in aData[] of current change */
176020  int iNext;                      /* Offset in aData[] of next change */
176021  u8 *aData;                      /* Pointer to buffer containing changeset */
176022  int nData;                      /* Number of bytes in aData */
176023
176024  SessionBuffer buf;              /* Current read buffer */
176025  int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
176026  void *pIn;                                /* First argument to xInput */
176027  int bEof;                       /* Set to true after xInput finished */
176028};
176029
176030/*
176031** Structure for changeset iterators.
176032*/
176033struct sqlite3_changeset_iter {
176034  SessionInput in;                /* Input buffer or stream */
176035  SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
176036  int bPatchset;                  /* True if this is a patchset */
176037  int rc;                         /* Iterator error code */
176038  sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
176039  char *zTab;                     /* Current table */
176040  int nCol;                       /* Number of columns in zTab */
176041  int op;                         /* Current operation */
176042  int bIndirect;                  /* True if current change was indirect */
176043  u8 *abPK;                       /* Primary key array */
176044  sqlite3_value **apValue;        /* old.* and new.* values */
176045};
176046
176047/*
176048** Each session object maintains a set of the following structures, one
176049** for each table the session object is monitoring. The structures are
176050** stored in a linked list starting at sqlite3_session.pTable.
176051**
176052** The keys of the SessionTable.aChange[] hash table are all rows that have
176053** been modified in any way since the session object was attached to the
176054** table.
176055**
176056** The data associated with each hash-table entry is a structure containing
176057** a subset of the initial values that the modified row contained at the
176058** start of the session. Or no initial values if the row was inserted.
176059*/
176060struct SessionTable {
176061  SessionTable *pNext;
176062  char *zName;                    /* Local name of table */
176063  int nCol;                       /* Number of columns in table zName */
176064  const char **azCol;             /* Column names */
176065  u8 *abPK;                       /* Array of primary key flags */
176066  int nEntry;                     /* Total number of entries in hash table */
176067  int nChange;                    /* Size of apChange[] array */
176068  SessionChange **apChange;       /* Hash table buckets */
176069};
176070
176071/*
176072** RECORD FORMAT:
176073**
176074** The following record format is similar to (but not compatible with) that
176075** used in SQLite database files. This format is used as part of the
176076** change-set binary format, and so must be architecture independent.
176077**
176078** Unlike the SQLite database record format, each field is self-contained -
176079** there is no separation of header and data. Each field begins with a
176080** single byte describing its type, as follows:
176081**
176082**       0x00: Undefined value.
176083**       0x01: Integer value.
176084**       0x02: Real value.
176085**       0x03: Text value.
176086**       0x04: Blob value.
176087**       0x05: SQL NULL value.
176088**
176089** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
176090** and so on in sqlite3.h. For undefined and NULL values, the field consists
176091** only of the single type byte. For other types of values, the type byte
176092** is followed by:
176093**
176094**   Text values:
176095**     A varint containing the number of bytes in the value (encoded using
176096**     UTF-8). Followed by a buffer containing the UTF-8 representation
176097**     of the text value. There is no nul terminator.
176098**
176099**   Blob values:
176100**     A varint containing the number of bytes in the value, followed by
176101**     a buffer containing the value itself.
176102**
176103**   Integer values:
176104**     An 8-byte big-endian integer value.
176105**
176106**   Real values:
176107**     An 8-byte big-endian IEEE 754-2008 real value.
176108**
176109** Varint values are encoded in the same way as varints in the SQLite
176110** record format.
176111**
176112** CHANGESET FORMAT:
176113**
176114** A changeset is a collection of DELETE, UPDATE and INSERT operations on
176115** one or more tables. Operations on a single table are grouped together,
176116** but may occur in any order (i.e. deletes, updates and inserts are all
176117** mixed together).
176118**
176119** Each group of changes begins with a table header:
176120**
176121**   1 byte: Constant 0x54 (capital 'T')
176122**   Varint: Number of columns in the table.
176123**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
176124**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
176125**
176126** Followed by one or more changes to the table.
176127**
176128**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
176129**   1 byte: The "indirect-change" flag.
176130**   old.* record: (delete and update only)
176131**   new.* record: (insert and update only)
176132**
176133** The "old.*" and "new.*" records, if present, are N field records in the
176134** format described above under "RECORD FORMAT", where N is the number of
176135** columns in the table. The i'th field of each record is associated with
176136** the i'th column of the table, counting from left to right in the order
176137** in which columns were declared in the CREATE TABLE statement.
176138**
176139** The new.* record that is part of each INSERT change contains the values
176140** that make up the new row. Similarly, the old.* record that is part of each
176141** DELETE change contains the values that made up the row that was deleted
176142** from the database. In the changeset format, the records that are part
176143** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
176144** fields.
176145**
176146** Within the old.* record associated with an UPDATE change, all fields
176147** associated with table columns that are not PRIMARY KEY columns and are
176148** not modified by the UPDATE change are set to "undefined". Other fields
176149** are set to the values that made up the row before the UPDATE that the
176150** change records took place. Within the new.* record, fields associated
176151** with table columns modified by the UPDATE change contain the new
176152** values. Fields associated with table columns that are not modified
176153** are set to "undefined".
176154**
176155** PATCHSET FORMAT:
176156**
176157** A patchset is also a collection of changes. It is similar to a changeset,
176158** but leaves undefined those fields that are not useful if no conflict
176159** resolution is required when applying the changeset.
176160**
176161** Each group of changes begins with a table header:
176162**
176163**   1 byte: Constant 0x50 (capital 'P')
176164**   Varint: Number of columns in the table.
176165**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
176166**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
176167**
176168** Followed by one or more changes to the table.
176169**
176170**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
176171**   1 byte: The "indirect-change" flag.
176172**   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
176173**                   full record for INSERT).
176174**
176175** As in the changeset format, each field of the single record that is part
176176** of a patchset change is associated with the correspondingly positioned
176177** table column, counting from left to right within the CREATE TABLE
176178** statement.
176179**
176180** For a DELETE change, all fields within the record except those associated
176181** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
176182** contain the values identifying the row to delete.
176183**
176184** For an UPDATE change, all fields except those associated with PRIMARY KEY
176185** columns and columns that are modified by the UPDATE are set to "undefined".
176186** PRIMARY KEY fields contain the values identifying the table row to update,
176187** and fields associated with modified columns contain the new column values.
176188**
176189** The records associated with INSERT changes are in the same format as for
176190** changesets. It is not possible for a record associated with an INSERT
176191** change to contain a field set to "undefined".
176192*/
176193
176194/*
176195** For each row modified during a session, there exists a single instance of
176196** this structure stored in a SessionTable.aChange[] hash table.
176197*/
176198struct SessionChange {
176199  int op;                         /* One of UPDATE, DELETE, INSERT */
176200  int bIndirect;                  /* True if this change is "indirect" */
176201  int nRecord;                    /* Number of bytes in buffer aRecord[] */
176202  u8 *aRecord;                    /* Buffer containing old.* record */
176203  SessionChange *pNext;           /* For hash-table collisions */
176204};
176205
176206/*
176207** Write a varint with value iVal into the buffer at aBuf. Return the
176208** number of bytes written.
176209*/
176210static int sessionVarintPut(u8 *aBuf, int iVal){
176211  return putVarint32(aBuf, iVal);
176212}
176213
176214/*
176215** Return the number of bytes required to store value iVal as a varint.
176216*/
176217static int sessionVarintLen(int iVal){
176218  return sqlite3VarintLen(iVal);
176219}
176220
176221/*
176222** Read a varint value from aBuf[] into *piVal. Return the number of
176223** bytes read.
176224*/
176225static int sessionVarintGet(u8 *aBuf, int *piVal){
176226  return getVarint32(aBuf, *piVal);
176227}
176228
176229/* Load an unaligned and unsigned 32-bit integer */
176230#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
176231
176232/*
176233** Read a 64-bit big-endian integer value from buffer aRec[]. Return
176234** the value read.
176235*/
176236static sqlite3_int64 sessionGetI64(u8 *aRec){
176237  u64 x = SESSION_UINT32(aRec);
176238  u32 y = SESSION_UINT32(aRec+4);
176239  x = (x<<32) + y;
176240  return (sqlite3_int64)x;
176241}
176242
176243/*
176244** Write a 64-bit big-endian integer value to the buffer aBuf[].
176245*/
176246static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
176247  aBuf[0] = (i>>56) & 0xFF;
176248  aBuf[1] = (i>>48) & 0xFF;
176249  aBuf[2] = (i>>40) & 0xFF;
176250  aBuf[3] = (i>>32) & 0xFF;
176251  aBuf[4] = (i>>24) & 0xFF;
176252  aBuf[5] = (i>>16) & 0xFF;
176253  aBuf[6] = (i>> 8) & 0xFF;
176254  aBuf[7] = (i>> 0) & 0xFF;
176255}
176256
176257/*
176258** This function is used to serialize the contents of value pValue (see
176259** comment titled "RECORD FORMAT" above).
176260**
176261** If it is non-NULL, the serialized form of the value is written to
176262** buffer aBuf. *pnWrite is set to the number of bytes written before
176263** returning. Or, if aBuf is NULL, the only thing this function does is
176264** set *pnWrite.
176265**
176266** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
176267** within a call to sqlite3_value_text() (may fail if the db is utf-16))
176268** SQLITE_NOMEM is returned.
176269*/
176270static int sessionSerializeValue(
176271  u8 *aBuf,                       /* If non-NULL, write serialized value here */
176272  sqlite3_value *pValue,          /* Value to serialize */
176273  int *pnWrite                    /* IN/OUT: Increment by bytes written */
176274){
176275  int nByte;                      /* Size of serialized value in bytes */
176276
176277  if( pValue ){
176278    int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
176279
176280    eType = sqlite3_value_type(pValue);
176281    if( aBuf ) aBuf[0] = eType;
176282
176283    switch( eType ){
176284      case SQLITE_NULL:
176285        nByte = 1;
176286        break;
176287
176288      case SQLITE_INTEGER:
176289      case SQLITE_FLOAT:
176290        if( aBuf ){
176291          /* TODO: SQLite does something special to deal with mixed-endian
176292          ** floating point values (e.g. ARM7). This code probably should
176293          ** too.  */
176294          u64 i;
176295          if( eType==SQLITE_INTEGER ){
176296            i = (u64)sqlite3_value_int64(pValue);
176297          }else{
176298            double r;
176299            assert( sizeof(double)==8 && sizeof(u64)==8 );
176300            r = sqlite3_value_double(pValue);
176301            memcpy(&i, &r, 8);
176302          }
176303          sessionPutI64(&aBuf[1], i);
176304        }
176305        nByte = 9;
176306        break;
176307
176308      default: {
176309        u8 *z;
176310        int n;
176311        int nVarint;
176312
176313        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
176314        if( eType==SQLITE_TEXT ){
176315          z = (u8 *)sqlite3_value_text(pValue);
176316        }else{
176317          z = (u8 *)sqlite3_value_blob(pValue);
176318        }
176319        n = sqlite3_value_bytes(pValue);
176320        if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
176321        nVarint = sessionVarintLen(n);
176322
176323        if( aBuf ){
176324          sessionVarintPut(&aBuf[1], n);
176325          if( n ) memcpy(&aBuf[nVarint + 1], z, n);
176326        }
176327
176328        nByte = 1 + nVarint + n;
176329        break;
176330      }
176331    }
176332  }else{
176333    nByte = 1;
176334    if( aBuf ) aBuf[0] = '\0';
176335  }
176336
176337  if( pnWrite ) *pnWrite += nByte;
176338  return SQLITE_OK;
176339}
176340
176341
176342/*
176343** This macro is used to calculate hash key values for data structures. In
176344** order to use this macro, the entire data structure must be represented
176345** as a series of unsigned integers. In order to calculate a hash-key value
176346** for a data structure represented as three such integers, the macro may
176347** then be used as follows:
176348**
176349**    int hash_key_value;
176350**    hash_key_value = HASH_APPEND(0, <value 1>);
176351**    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
176352**    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
176353**
176354** In practice, the data structures this macro is used for are the primary
176355** key values of modified rows.
176356*/
176357#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
176358
176359/*
176360** Append the hash of the 64-bit integer passed as the second argument to the
176361** hash-key value passed as the first. Return the new hash-key value.
176362*/
176363static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
176364  h = HASH_APPEND(h, i & 0xFFFFFFFF);
176365  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
176366}
176367
176368/*
176369** Append the hash of the blob passed via the second and third arguments to
176370** the hash-key value passed as the first. Return the new hash-key value.
176371*/
176372static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
176373  int i;
176374  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
176375  return h;
176376}
176377
176378/*
176379** Append the hash of the data type passed as the second argument to the
176380** hash-key value passed as the first. Return the new hash-key value.
176381*/
176382static unsigned int sessionHashAppendType(unsigned int h, int eType){
176383  return HASH_APPEND(h, eType);
176384}
176385
176386/*
176387** This function may only be called from within a pre-update callback.
176388** It calculates a hash based on the primary key values of the old.* or
176389** new.* row currently available and, assuming no error occurs, writes it to
176390** *piHash before returning. If the primary key contains one or more NULL
176391** values, *pbNullPK is set to true before returning.
176392**
176393** If an error occurs, an SQLite error code is returned and the final values
176394** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
176395** and the output variables are set as described above.
176396*/
176397static int sessionPreupdateHash(
176398  sqlite3_session *pSession,      /* Session object that owns pTab */
176399  SessionTable *pTab,             /* Session table handle */
176400  int bNew,                       /* True to hash the new.* PK */
176401  int *piHash,                    /* OUT: Hash value */
176402  int *pbNullPK                   /* OUT: True if there are NULL values in PK */
176403){
176404  unsigned int h = 0;             /* Hash value to return */
176405  int i;                          /* Used to iterate through columns */
176406
176407  assert( *pbNullPK==0 );
176408  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
176409  for(i=0; i<pTab->nCol; i++){
176410    if( pTab->abPK[i] ){
176411      int rc;
176412      int eType;
176413      sqlite3_value *pVal;
176414
176415      if( bNew ){
176416        rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
176417      }else{
176418        rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
176419      }
176420      if( rc!=SQLITE_OK ) return rc;
176421
176422      eType = sqlite3_value_type(pVal);
176423      h = sessionHashAppendType(h, eType);
176424      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
176425        i64 iVal;
176426        if( eType==SQLITE_INTEGER ){
176427          iVal = sqlite3_value_int64(pVal);
176428        }else{
176429          double rVal = sqlite3_value_double(pVal);
176430          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
176431          memcpy(&iVal, &rVal, 8);
176432        }
176433        h = sessionHashAppendI64(h, iVal);
176434      }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
176435        const u8 *z;
176436        int n;
176437        if( eType==SQLITE_TEXT ){
176438          z = (const u8 *)sqlite3_value_text(pVal);
176439        }else{
176440          z = (const u8 *)sqlite3_value_blob(pVal);
176441        }
176442        n = sqlite3_value_bytes(pVal);
176443        if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
176444        h = sessionHashAppendBlob(h, n, z);
176445      }else{
176446        assert( eType==SQLITE_NULL );
176447        *pbNullPK = 1;
176448      }
176449    }
176450  }
176451
176452  *piHash = (h % pTab->nChange);
176453  return SQLITE_OK;
176454}
176455
176456/*
176457** The buffer that the argument points to contains a serialized SQL value.
176458** Return the number of bytes of space occupied by the value (including
176459** the type byte).
176460*/
176461static int sessionSerialLen(u8 *a){
176462  int e = *a;
176463  int n;
176464  if( e==0 ) return 1;
176465  if( e==SQLITE_NULL ) return 1;
176466  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
176467  return sessionVarintGet(&a[1], &n) + 1 + n;
176468}
176469
176470/*
176471** Based on the primary key values stored in change aRecord, calculate a
176472** hash key. Assume the has table has nBucket buckets. The hash keys
176473** calculated by this function are compatible with those calculated by
176474** sessionPreupdateHash().
176475**
176476** The bPkOnly argument is non-zero if the record at aRecord[] is from
176477** a patchset DELETE. In this case the non-PK fields are omitted entirely.
176478*/
176479static unsigned int sessionChangeHash(
176480  SessionTable *pTab,             /* Table handle */
176481  int bPkOnly,                    /* Record consists of PK fields only */
176482  u8 *aRecord,                    /* Change record */
176483  int nBucket                     /* Assume this many buckets in hash table */
176484){
176485  unsigned int h = 0;             /* Value to return */
176486  int i;                          /* Used to iterate through columns */
176487  u8 *a = aRecord;                /* Used to iterate through change record */
176488
176489  for(i=0; i<pTab->nCol; i++){
176490    int eType = *a;
176491    int isPK = pTab->abPK[i];
176492    if( bPkOnly && isPK==0 ) continue;
176493
176494    /* It is not possible for eType to be SQLITE_NULL here. The session
176495    ** module does not record changes for rows with NULL values stored in
176496    ** primary key columns. */
176497    assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
176498         || eType==SQLITE_TEXT || eType==SQLITE_BLOB
176499         || eType==SQLITE_NULL || eType==0
176500    );
176501    assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
176502
176503    if( isPK ){
176504      a++;
176505      h = sessionHashAppendType(h, eType);
176506      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
176507        h = sessionHashAppendI64(h, sessionGetI64(a));
176508        a += 8;
176509      }else{
176510        int n;
176511        a += sessionVarintGet(a, &n);
176512        h = sessionHashAppendBlob(h, n, a);
176513        a += n;
176514      }
176515    }else{
176516      a += sessionSerialLen(a);
176517    }
176518  }
176519  return (h % nBucket);
176520}
176521
176522/*
176523** Arguments aLeft and aRight are pointers to change records for table pTab.
176524** This function returns true if the two records apply to the same row (i.e.
176525** have the same values stored in the primary key columns), or false
176526** otherwise.
176527*/
176528static int sessionChangeEqual(
176529  SessionTable *pTab,             /* Table used for PK definition */
176530  int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
176531  u8 *aLeft,                      /* Change record */
176532  int bRightPkOnly,               /* True if aRight[] contains PK fields only */
176533  u8 *aRight                      /* Change record */
176534){
176535  u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
176536  u8 *a2 = aRight;                /* Cursor to iterate through aRight */
176537  int iCol;                       /* Used to iterate through table columns */
176538
176539  for(iCol=0; iCol<pTab->nCol; iCol++){
176540    if( pTab->abPK[iCol] ){
176541      int n1 = sessionSerialLen(a1);
176542      int n2 = sessionSerialLen(a2);
176543
176544      if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
176545        return 0;
176546      }
176547      a1 += n1;
176548      a2 += n2;
176549    }else{
176550      if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
176551      if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
176552    }
176553  }
176554
176555  return 1;
176556}
176557
176558/*
176559** Arguments aLeft and aRight both point to buffers containing change
176560** records with nCol columns. This function "merges" the two records into
176561** a single records which is written to the buffer at *paOut. *paOut is
176562** then set to point to one byte after the last byte written before
176563** returning.
176564**
176565** The merging of records is done as follows: For each column, if the
176566** aRight record contains a value for the column, copy the value from
176567** their. Otherwise, if aLeft contains a value, copy it. If neither
176568** record contains a value for a given column, then neither does the
176569** output record.
176570*/
176571static void sessionMergeRecord(
176572  u8 **paOut,
176573  int nCol,
176574  u8 *aLeft,
176575  u8 *aRight
176576){
176577  u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
176578  u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
176579  u8 *aOut = *paOut;              /* Output cursor */
176580  int iCol;                       /* Used to iterate from 0 to nCol */
176581
176582  for(iCol=0; iCol<nCol; iCol++){
176583    int n1 = sessionSerialLen(a1);
176584    int n2 = sessionSerialLen(a2);
176585    if( *a2 ){
176586      memcpy(aOut, a2, n2);
176587      aOut += n2;
176588    }else{
176589      memcpy(aOut, a1, n1);
176590      aOut += n1;
176591    }
176592    a1 += n1;
176593    a2 += n2;
176594  }
176595
176596  *paOut = aOut;
176597}
176598
176599/*
176600** This is a helper function used by sessionMergeUpdate().
176601**
176602** When this function is called, both *paOne and *paTwo point to a value
176603** within a change record. Before it returns, both have been advanced so
176604** as to point to the next value in the record.
176605**
176606** If, when this function is called, *paTwo points to a valid value (i.e.
176607** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
176608** pointer is returned and *pnVal is set to the number of bytes in the
176609** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
176610** set to the number of bytes in the value at *paOne. If *paOne points
176611** to the "no value" placeholder, *pnVal is set to 1. In other words:
176612**
176613**   if( *paTwo is valid ) return *paTwo;
176614**   return *paOne;
176615**
176616*/
176617static u8 *sessionMergeValue(
176618  u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
176619  u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
176620  int *pnVal                      /* OUT: Bytes in returned value */
176621){
176622  u8 *a1 = *paOne;
176623  u8 *a2 = *paTwo;
176624  u8 *pRet = 0;
176625  int n1;
176626
176627  assert( a1 );
176628  if( a2 ){
176629    int n2 = sessionSerialLen(a2);
176630    if( *a2 ){
176631      *pnVal = n2;
176632      pRet = a2;
176633    }
176634    *paTwo = &a2[n2];
176635  }
176636
176637  n1 = sessionSerialLen(a1);
176638  if( pRet==0 ){
176639    *pnVal = n1;
176640    pRet = a1;
176641  }
176642  *paOne = &a1[n1];
176643
176644  return pRet;
176645}
176646
176647/*
176648** This function is used by changeset_concat() to merge two UPDATE changes
176649** on the same row.
176650*/
176651static int sessionMergeUpdate(
176652  u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
176653  SessionTable *pTab,             /* Table change pertains to */
176654  int bPatchset,                  /* True if records are patchset records */
176655  u8 *aOldRecord1,                /* old.* record for first change */
176656  u8 *aOldRecord2,                /* old.* record for second change */
176657  u8 *aNewRecord1,                /* new.* record for first change */
176658  u8 *aNewRecord2                 /* new.* record for second change */
176659){
176660  u8 *aOld1 = aOldRecord1;
176661  u8 *aOld2 = aOldRecord2;
176662  u8 *aNew1 = aNewRecord1;
176663  u8 *aNew2 = aNewRecord2;
176664
176665  u8 *aOut = *paOut;
176666  int i;
176667
176668  if( bPatchset==0 ){
176669    int bRequired = 0;
176670
176671    assert( aOldRecord1 && aNewRecord1 );
176672
176673    /* Write the old.* vector first. */
176674    for(i=0; i<pTab->nCol; i++){
176675      int nOld;
176676      u8 *aOld;
176677      int nNew;
176678      u8 *aNew;
176679
176680      aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
176681      aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
176682      if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
176683        if( pTab->abPK[i]==0 ) bRequired = 1;
176684        memcpy(aOut, aOld, nOld);
176685        aOut += nOld;
176686      }else{
176687        *(aOut++) = '\0';
176688      }
176689    }
176690
176691    if( !bRequired ) return 0;
176692  }
176693
176694  /* Write the new.* vector */
176695  aOld1 = aOldRecord1;
176696  aOld2 = aOldRecord2;
176697  aNew1 = aNewRecord1;
176698  aNew2 = aNewRecord2;
176699  for(i=0; i<pTab->nCol; i++){
176700    int nOld;
176701    u8 *aOld;
176702    int nNew;
176703    u8 *aNew;
176704
176705    aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
176706    aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
176707    if( bPatchset==0
176708     && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
176709    ){
176710      *(aOut++) = '\0';
176711    }else{
176712      memcpy(aOut, aNew, nNew);
176713      aOut += nNew;
176714    }
176715  }
176716
176717  *paOut = aOut;
176718  return 1;
176719}
176720
176721/*
176722** This function is only called from within a pre-update-hook callback.
176723** It determines if the current pre-update-hook change affects the same row
176724** as the change stored in argument pChange. If so, it returns true. Otherwise
176725** if the pre-update-hook does not affect the same row as pChange, it returns
176726** false.
176727*/
176728static int sessionPreupdateEqual(
176729  sqlite3_session *pSession,      /* Session object that owns SessionTable */
176730  SessionTable *pTab,             /* Table associated with change */
176731  SessionChange *pChange,         /* Change to compare to */
176732  int op                          /* Current pre-update operation */
176733){
176734  int iCol;                       /* Used to iterate through columns */
176735  u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
176736
176737  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
176738  for(iCol=0; iCol<pTab->nCol; iCol++){
176739    if( !pTab->abPK[iCol] ){
176740      a += sessionSerialLen(a);
176741    }else{
176742      sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
176743      int rc;                     /* Error code from preupdate_new/old */
176744      int eType = *a++;           /* Type of value from change record */
176745
176746      /* The following calls to preupdate_new() and preupdate_old() can not
176747      ** fail. This is because they cache their return values, and by the
176748      ** time control flows to here they have already been called once from
176749      ** within sessionPreupdateHash(). The first two asserts below verify
176750      ** this (that the method has already been called). */
176751      if( op==SQLITE_INSERT ){
176752        /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
176753        rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
176754      }else{
176755        /* assert( db->pPreUpdate->pUnpacked ); */
176756        rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
176757      }
176758      assert( rc==SQLITE_OK );
176759      if( sqlite3_value_type(pVal)!=eType ) return 0;
176760
176761      /* A SessionChange object never has a NULL value in a PK column */
176762      assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
176763           || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
176764      );
176765
176766      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
176767        i64 iVal = sessionGetI64(a);
176768        a += 8;
176769        if( eType==SQLITE_INTEGER ){
176770          if( sqlite3_value_int64(pVal)!=iVal ) return 0;
176771        }else{
176772          double rVal;
176773          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
176774          memcpy(&rVal, &iVal, 8);
176775          if( sqlite3_value_double(pVal)!=rVal ) return 0;
176776        }
176777      }else{
176778        int n;
176779        const u8 *z;
176780        a += sessionVarintGet(a, &n);
176781        if( sqlite3_value_bytes(pVal)!=n ) return 0;
176782        if( eType==SQLITE_TEXT ){
176783          z = sqlite3_value_text(pVal);
176784        }else{
176785          z = sqlite3_value_blob(pVal);
176786        }
176787        if( memcmp(a, z, n) ) return 0;
176788        a += n;
176789        break;
176790      }
176791    }
176792  }
176793
176794  return 1;
176795}
176796
176797/*
176798** If required, grow the hash table used to store changes on table pTab
176799** (part of the session pSession). If a fatal OOM error occurs, set the
176800** session object to failed and return SQLITE_ERROR. Otherwise, return
176801** SQLITE_OK.
176802**
176803** It is possible that a non-fatal OOM error occurs in this function. In
176804** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
176805** Growing the hash table in this case is a performance optimization only,
176806** it is not required for correct operation.
176807*/
176808static int sessionGrowHash(int bPatchset, SessionTable *pTab){
176809  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
176810    int i;
176811    SessionChange **apNew;
176812    int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
176813
176814    apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
176815    if( apNew==0 ){
176816      if( pTab->nChange==0 ){
176817        return SQLITE_ERROR;
176818      }
176819      return SQLITE_OK;
176820    }
176821    memset(apNew, 0, sizeof(SessionChange *) * nNew);
176822
176823    for(i=0; i<pTab->nChange; i++){
176824      SessionChange *p;
176825      SessionChange *pNext;
176826      for(p=pTab->apChange[i]; p; p=pNext){
176827        int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
176828        int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
176829        pNext = p->pNext;
176830        p->pNext = apNew[iHash];
176831        apNew[iHash] = p;
176832      }
176833    }
176834
176835    sqlite3_free(pTab->apChange);
176836    pTab->nChange = nNew;
176837    pTab->apChange = apNew;
176838  }
176839
176840  return SQLITE_OK;
176841}
176842
176843/*
176844** This function queries the database for the names of the columns of table
176845** zThis, in schema zDb. It is expected that the table has nCol columns. If
176846** not, SQLITE_SCHEMA is returned and none of the output variables are
176847** populated.
176848**
176849** Otherwise, if they are not NULL, variable *pnCol is set to the number
176850** of columns in the database table and variable *pzTab is set to point to a
176851** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
176852** point to an array of pointers to column names. And *pabPK (again, if not
176853** NULL) is set to point to an array of booleans - true if the corresponding
176854** column is part of the primary key.
176855**
176856** For example, if the table is declared as:
176857**
176858**     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
176859**
176860** Then the four output variables are populated as follows:
176861**
176862**     *pnCol  = 4
176863**     *pzTab  = "tbl1"
176864**     *pazCol = {"w", "x", "y", "z"}
176865**     *pabPK  = {1, 0, 0, 1}
176866**
176867** All returned buffers are part of the same single allocation, which must
176868** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
176869** pointer *pazCol should be freed to release all memory. Otherwise, pointer
176870** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
176871*/
176872static int sessionTableInfo(
176873  sqlite3 *db,                    /* Database connection */
176874  const char *zDb,                /* Name of attached database (e.g. "main") */
176875  const char *zThis,              /* Table name */
176876  int *pnCol,                     /* OUT: number of columns */
176877  const char **pzTab,             /* OUT: Copy of zThis */
176878  const char ***pazCol,           /* OUT: Array of column names for table */
176879  u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
176880){
176881  char *zPragma;
176882  sqlite3_stmt *pStmt;
176883  int rc;
176884  int nByte;
176885  int nDbCol = 0;
176886  int nThis;
176887  int i;
176888  u8 *pAlloc = 0;
176889  char **azCol = 0;
176890  u8 *abPK = 0;
176891
176892  assert( pazCol && pabPK );
176893
176894  nThis = sqlite3Strlen30(zThis);
176895  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
176896  if( !zPragma ) return SQLITE_NOMEM;
176897
176898  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
176899  sqlite3_free(zPragma);
176900  if( rc!=SQLITE_OK ) return rc;
176901
176902  nByte = nThis + 1;
176903  while( SQLITE_ROW==sqlite3_step(pStmt) ){
176904    nByte += sqlite3_column_bytes(pStmt, 1);
176905    nDbCol++;
176906  }
176907  rc = sqlite3_reset(pStmt);
176908
176909  if( rc==SQLITE_OK ){
176910    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
176911    pAlloc = sqlite3_malloc(nByte);
176912    if( pAlloc==0 ){
176913      rc = SQLITE_NOMEM;
176914    }
176915  }
176916  if( rc==SQLITE_OK ){
176917    azCol = (char **)pAlloc;
176918    pAlloc = (u8 *)&azCol[nDbCol];
176919    abPK = (u8 *)pAlloc;
176920    pAlloc = &abPK[nDbCol];
176921    if( pzTab ){
176922      memcpy(pAlloc, zThis, nThis+1);
176923      *pzTab = (char *)pAlloc;
176924      pAlloc += nThis+1;
176925    }
176926
176927    i = 0;
176928    while( SQLITE_ROW==sqlite3_step(pStmt) ){
176929      int nName = sqlite3_column_bytes(pStmt, 1);
176930      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
176931      if( zName==0 ) break;
176932      memcpy(pAlloc, zName, nName+1);
176933      azCol[i] = (char *)pAlloc;
176934      pAlloc += nName+1;
176935      abPK[i] = sqlite3_column_int(pStmt, 5);
176936      i++;
176937    }
176938    rc = sqlite3_reset(pStmt);
176939
176940  }
176941
176942  /* If successful, populate the output variables. Otherwise, zero them and
176943  ** free any allocation made. An error code will be returned in this case.
176944  */
176945  if( rc==SQLITE_OK ){
176946    *pazCol = (const char **)azCol;
176947    *pabPK = abPK;
176948    *pnCol = nDbCol;
176949  }else{
176950    *pazCol = 0;
176951    *pabPK = 0;
176952    *pnCol = 0;
176953    if( pzTab ) *pzTab = 0;
176954    sqlite3_free(azCol);
176955  }
176956  sqlite3_finalize(pStmt);
176957  return rc;
176958}
176959
176960/*
176961** This function is only called from within a pre-update handler for a
176962** write to table pTab, part of session pSession. If this is the first
176963** write to this table, initalize the SessionTable.nCol, azCol[] and
176964** abPK[] arrays accordingly.
176965**
176966** If an error occurs, an error code is stored in sqlite3_session.rc and
176967** non-zero returned. Or, if no error occurs but the table has no primary
176968** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
176969** indicate that updates on this table should be ignored. SessionTable.abPK
176970** is set to NULL in this case.
176971*/
176972static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
176973  if( pTab->nCol==0 ){
176974    u8 *abPK;
176975    assert( pTab->azCol==0 || pTab->abPK==0 );
176976    pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
176977        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
176978    );
176979    if( pSession->rc==SQLITE_OK ){
176980      int i;
176981      for(i=0; i<pTab->nCol; i++){
176982        if( abPK[i] ){
176983          pTab->abPK = abPK;
176984          break;
176985        }
176986      }
176987    }
176988  }
176989  return (pSession->rc || pTab->abPK==0);
176990}
176991
176992/*
176993** This function is only called from with a pre-update-hook reporting a
176994** change on table pTab (attached to session pSession). The type of change
176995** (UPDATE, INSERT, DELETE) is specified by the first argument.
176996**
176997** Unless one is already present or an error occurs, an entry is added
176998** to the changed-rows hash table associated with table pTab.
176999*/
177000static void sessionPreupdateOneChange(
177001  int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
177002  sqlite3_session *pSession,      /* Session object pTab is attached to */
177003  SessionTable *pTab              /* Table that change applies to */
177004){
177005  int iHash;
177006  int bNull = 0;
177007  int rc = SQLITE_OK;
177008
177009  if( pSession->rc ) return;
177010
177011  /* Load table details if required */
177012  if( sessionInitTable(pSession, pTab) ) return;
177013
177014  /* Check the number of columns in this xPreUpdate call matches the
177015  ** number of columns in the table.  */
177016  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
177017    pSession->rc = SQLITE_SCHEMA;
177018    return;
177019  }
177020
177021  /* Grow the hash table if required */
177022  if( sessionGrowHash(0, pTab) ){
177023    pSession->rc = SQLITE_NOMEM;
177024    return;
177025  }
177026
177027  /* Calculate the hash-key for this change. If the primary key of the row
177028  ** includes a NULL value, exit early. Such changes are ignored by the
177029  ** session module. */
177030  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
177031  if( rc!=SQLITE_OK ) goto error_out;
177032
177033  if( bNull==0 ){
177034    /* Search the hash table for an existing record for this row. */
177035    SessionChange *pC;
177036    for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
177037      if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
177038    }
177039
177040    if( pC==0 ){
177041      /* Create a new change object containing all the old values (if
177042      ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
177043      ** values (if this is an INSERT). */
177044      SessionChange *pChange; /* New change object */
177045      int nByte;              /* Number of bytes to allocate */
177046      int i;                  /* Used to iterate through columns */
177047
177048      assert( rc==SQLITE_OK );
177049      pTab->nEntry++;
177050
177051      /* Figure out how large an allocation is required */
177052      nByte = sizeof(SessionChange);
177053      for(i=0; i<pTab->nCol; i++){
177054        sqlite3_value *p = 0;
177055        if( op!=SQLITE_INSERT ){
177056          TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
177057          assert( trc==SQLITE_OK );
177058        }else if( pTab->abPK[i] ){
177059          TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
177060          assert( trc==SQLITE_OK );
177061        }
177062
177063        /* This may fail if SQLite value p contains a utf-16 string that must
177064        ** be converted to utf-8 and an OOM error occurs while doing so. */
177065        rc = sessionSerializeValue(0, p, &nByte);
177066        if( rc!=SQLITE_OK ) goto error_out;
177067      }
177068
177069      /* Allocate the change object */
177070      pChange = (SessionChange *)sqlite3_malloc(nByte);
177071      if( !pChange ){
177072        rc = SQLITE_NOMEM;
177073        goto error_out;
177074      }else{
177075        memset(pChange, 0, sizeof(SessionChange));
177076        pChange->aRecord = (u8 *)&pChange[1];
177077      }
177078
177079      /* Populate the change object. None of the preupdate_old(),
177080      ** preupdate_new() or SerializeValue() calls below may fail as all
177081      ** required values and encodings have already been cached in memory.
177082      ** It is not possible for an OOM to occur in this block. */
177083      nByte = 0;
177084      for(i=0; i<pTab->nCol; i++){
177085        sqlite3_value *p = 0;
177086        if( op!=SQLITE_INSERT ){
177087          pSession->hook.xOld(pSession->hook.pCtx, i, &p);
177088        }else if( pTab->abPK[i] ){
177089          pSession->hook.xNew(pSession->hook.pCtx, i, &p);
177090        }
177091        sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
177092      }
177093
177094      /* Add the change to the hash-table */
177095      if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
177096        pChange->bIndirect = 1;
177097      }
177098      pChange->nRecord = nByte;
177099      pChange->op = op;
177100      pChange->pNext = pTab->apChange[iHash];
177101      pTab->apChange[iHash] = pChange;
177102
177103    }else if( pC->bIndirect ){
177104      /* If the existing change is considered "indirect", but this current
177105      ** change is "direct", mark the change object as direct. */
177106      if( pSession->hook.xDepth(pSession->hook.pCtx)==0
177107       && pSession->bIndirect==0
177108      ){
177109        pC->bIndirect = 0;
177110      }
177111    }
177112  }
177113
177114  /* If an error has occurred, mark the session object as failed. */
177115 error_out:
177116  if( rc!=SQLITE_OK ){
177117    pSession->rc = rc;
177118  }
177119}
177120
177121static int sessionFindTable(
177122  sqlite3_session *pSession,
177123  const char *zName,
177124  SessionTable **ppTab
177125){
177126  int rc = SQLITE_OK;
177127  int nName = sqlite3Strlen30(zName);
177128  SessionTable *pRet;
177129
177130  /* Search for an existing table */
177131  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
177132    if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
177133  }
177134
177135  if( pRet==0 && pSession->bAutoAttach ){
177136    /* If there is a table-filter configured, invoke it. If it returns 0,
177137    ** do not automatically add the new table. */
177138    if( pSession->xTableFilter==0
177139     || pSession->xTableFilter(pSession->pFilterCtx, zName)
177140    ){
177141      rc = sqlite3session_attach(pSession, zName);
177142      if( rc==SQLITE_OK ){
177143        for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
177144        assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
177145      }
177146    }
177147  }
177148
177149  assert( rc==SQLITE_OK || pRet==0 );
177150  *ppTab = pRet;
177151  return rc;
177152}
177153
177154/*
177155** The 'pre-update' hook registered by this module with SQLite databases.
177156*/
177157static void xPreUpdate(
177158  void *pCtx,                     /* Copy of third arg to preupdate_hook() */
177159  sqlite3 *db,                    /* Database handle */
177160  int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
177161  char const *zDb,                /* Database name */
177162  char const *zName,              /* Table name */
177163  sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
177164  sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
177165){
177166  sqlite3_session *pSession;
177167  int nDb = sqlite3Strlen30(zDb);
177168
177169  assert( sqlite3_mutex_held(db->mutex) );
177170
177171  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
177172    SessionTable *pTab;
177173
177174    /* If this session is attached to a different database ("main", "temp"
177175    ** etc.), or if it is not currently enabled, there is nothing to do. Skip
177176    ** to the next session object attached to this database. */
177177    if( pSession->bEnable==0 ) continue;
177178    if( pSession->rc ) continue;
177179    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
177180
177181    pSession->rc = sessionFindTable(pSession, zName, &pTab);
177182    if( pTab ){
177183      assert( pSession->rc==SQLITE_OK );
177184      sessionPreupdateOneChange(op, pSession, pTab);
177185      if( op==SQLITE_UPDATE ){
177186        sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
177187      }
177188    }
177189  }
177190}
177191
177192/*
177193** The pre-update hook implementations.
177194*/
177195static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
177196  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
177197}
177198static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
177199  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
177200}
177201static int sessionPreupdateCount(void *pCtx){
177202  return sqlite3_preupdate_count((sqlite3*)pCtx);
177203}
177204static int sessionPreupdateDepth(void *pCtx){
177205  return sqlite3_preupdate_depth((sqlite3*)pCtx);
177206}
177207
177208/*
177209** Install the pre-update hooks on the session object passed as the only
177210** argument.
177211*/
177212static void sessionPreupdateHooks(
177213  sqlite3_session *pSession
177214){
177215  pSession->hook.pCtx = (void*)pSession->db;
177216  pSession->hook.xOld = sessionPreupdateOld;
177217  pSession->hook.xNew = sessionPreupdateNew;
177218  pSession->hook.xCount = sessionPreupdateCount;
177219  pSession->hook.xDepth = sessionPreupdateDepth;
177220}
177221
177222typedef struct SessionDiffCtx SessionDiffCtx;
177223struct SessionDiffCtx {
177224  sqlite3_stmt *pStmt;
177225  int nOldOff;
177226};
177227
177228/*
177229** The diff hook implementations.
177230*/
177231static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
177232  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
177233  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
177234  return SQLITE_OK;
177235}
177236static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
177237  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
177238  *ppVal = sqlite3_column_value(p->pStmt, iVal);
177239   return SQLITE_OK;
177240}
177241static int sessionDiffCount(void *pCtx){
177242  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
177243  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
177244}
177245static int sessionDiffDepth(void *pCtx){
177246  return 0;
177247}
177248
177249/*
177250** Install the diff hooks on the session object passed as the only
177251** argument.
177252*/
177253static void sessionDiffHooks(
177254  sqlite3_session *pSession,
177255  SessionDiffCtx *pDiffCtx
177256){
177257  pSession->hook.pCtx = (void*)pDiffCtx;
177258  pSession->hook.xOld = sessionDiffOld;
177259  pSession->hook.xNew = sessionDiffNew;
177260  pSession->hook.xCount = sessionDiffCount;
177261  pSession->hook.xDepth = sessionDiffDepth;
177262}
177263
177264static char *sessionExprComparePK(
177265  int nCol,
177266  const char *zDb1, const char *zDb2,
177267  const char *zTab,
177268  const char **azCol, u8 *abPK
177269){
177270  int i;
177271  const char *zSep = "";
177272  char *zRet = 0;
177273
177274  for(i=0; i<nCol; i++){
177275    if( abPK[i] ){
177276      zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
177277          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
177278      );
177279      zSep = " AND ";
177280      if( zRet==0 ) break;
177281    }
177282  }
177283
177284  return zRet;
177285}
177286
177287static char *sessionExprCompareOther(
177288  int nCol,
177289  const char *zDb1, const char *zDb2,
177290  const char *zTab,
177291  const char **azCol, u8 *abPK
177292){
177293  int i;
177294  const char *zSep = "";
177295  char *zRet = 0;
177296  int bHave = 0;
177297
177298  for(i=0; i<nCol; i++){
177299    if( abPK[i]==0 ){
177300      bHave = 1;
177301      zRet = sqlite3_mprintf(
177302          "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
177303          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
177304      );
177305      zSep = " OR ";
177306      if( zRet==0 ) break;
177307    }
177308  }
177309
177310  if( bHave==0 ){
177311    assert( zRet==0 );
177312    zRet = sqlite3_mprintf("0");
177313  }
177314
177315  return zRet;
177316}
177317
177318static char *sessionSelectFindNew(
177319  int nCol,
177320  const char *zDb1,      /* Pick rows in this db only */
177321  const char *zDb2,      /* But not in this one */
177322  const char *zTbl,      /* Table name */
177323  const char *zExpr
177324){
177325  char *zRet = sqlite3_mprintf(
177326      "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
177327      "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
177328      ")",
177329      zDb1, zTbl, zDb2, zTbl, zExpr
177330  );
177331  return zRet;
177332}
177333
177334static int sessionDiffFindNew(
177335  int op,
177336  sqlite3_session *pSession,
177337  SessionTable *pTab,
177338  const char *zDb1,
177339  const char *zDb2,
177340  char *zExpr
177341){
177342  int rc = SQLITE_OK;
177343  char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
177344
177345  if( zStmt==0 ){
177346    rc = SQLITE_NOMEM;
177347  }else{
177348    sqlite3_stmt *pStmt;
177349    rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
177350    if( rc==SQLITE_OK ){
177351      SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
177352      pDiffCtx->pStmt = pStmt;
177353      pDiffCtx->nOldOff = 0;
177354      while( SQLITE_ROW==sqlite3_step(pStmt) ){
177355        sessionPreupdateOneChange(op, pSession, pTab);
177356      }
177357      rc = sqlite3_finalize(pStmt);
177358    }
177359    sqlite3_free(zStmt);
177360  }
177361
177362  return rc;
177363}
177364
177365static int sessionDiffFindModified(
177366  sqlite3_session *pSession,
177367  SessionTable *pTab,
177368  const char *zFrom,
177369  const char *zExpr
177370){
177371  int rc = SQLITE_OK;
177372
177373  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
177374      pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
177375  );
177376  if( zExpr2==0 ){
177377    rc = SQLITE_NOMEM;
177378  }else{
177379    char *zStmt = sqlite3_mprintf(
177380        "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
177381        pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
177382    );
177383    if( zStmt==0 ){
177384      rc = SQLITE_NOMEM;
177385    }else{
177386      sqlite3_stmt *pStmt;
177387      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
177388
177389      if( rc==SQLITE_OK ){
177390        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
177391        pDiffCtx->pStmt = pStmt;
177392        pDiffCtx->nOldOff = pTab->nCol;
177393        while( SQLITE_ROW==sqlite3_step(pStmt) ){
177394          sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
177395        }
177396        rc = sqlite3_finalize(pStmt);
177397      }
177398      sqlite3_free(zStmt);
177399    }
177400  }
177401
177402  return rc;
177403}
177404
177405SQLITE_API int sqlite3session_diff(
177406  sqlite3_session *pSession,
177407  const char *zFrom,
177408  const char *zTbl,
177409  char **pzErrMsg
177410){
177411  const char *zDb = pSession->zDb;
177412  int rc = pSession->rc;
177413  SessionDiffCtx d;
177414
177415  memset(&d, 0, sizeof(d));
177416  sessionDiffHooks(pSession, &d);
177417
177418  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
177419  if( pzErrMsg ) *pzErrMsg = 0;
177420  if( rc==SQLITE_OK ){
177421    char *zExpr = 0;
177422    sqlite3 *db = pSession->db;
177423    SessionTable *pTo;            /* Table zTbl */
177424
177425    /* Locate and if necessary initialize the target table object */
177426    rc = sessionFindTable(pSession, zTbl, &pTo);
177427    if( pTo==0 ) goto diff_out;
177428    if( sessionInitTable(pSession, pTo) ){
177429      rc = pSession->rc;
177430      goto diff_out;
177431    }
177432
177433    /* Check the table schemas match */
177434    if( rc==SQLITE_OK ){
177435      int bHasPk = 0;
177436      int bMismatch = 0;
177437      int nCol;                   /* Columns in zFrom.zTbl */
177438      u8 *abPK;
177439      const char **azCol = 0;
177440      rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
177441      if( rc==SQLITE_OK ){
177442        if( pTo->nCol!=nCol ){
177443          bMismatch = 1;
177444        }else{
177445          int i;
177446          for(i=0; i<nCol; i++){
177447            if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
177448            if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
177449            if( abPK[i] ) bHasPk = 1;
177450          }
177451        }
177452
177453      }
177454      sqlite3_free((char*)azCol);
177455      if( bMismatch ){
177456        *pzErrMsg = sqlite3_mprintf("table schemas do not match");
177457        rc = SQLITE_SCHEMA;
177458      }
177459      if( bHasPk==0 ){
177460        /* Ignore tables with no primary keys */
177461        goto diff_out;
177462      }
177463    }
177464
177465    if( rc==SQLITE_OK ){
177466      zExpr = sessionExprComparePK(pTo->nCol,
177467          zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
177468      );
177469    }
177470
177471    /* Find new rows */
177472    if( rc==SQLITE_OK ){
177473      rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
177474    }
177475
177476    /* Find old rows */
177477    if( rc==SQLITE_OK ){
177478      rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
177479    }
177480
177481    /* Find modified rows */
177482    if( rc==SQLITE_OK ){
177483      rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
177484    }
177485
177486    sqlite3_free(zExpr);
177487  }
177488
177489 diff_out:
177490  sessionPreupdateHooks(pSession);
177491  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
177492  return rc;
177493}
177494
177495/*
177496** Create a session object. This session object will record changes to
177497** database zDb attached to connection db.
177498*/
177499SQLITE_API int sqlite3session_create(
177500  sqlite3 *db,                    /* Database handle */
177501  const char *zDb,                /* Name of db (e.g. "main") */
177502  sqlite3_session **ppSession     /* OUT: New session object */
177503){
177504  sqlite3_session *pNew;          /* Newly allocated session object */
177505  sqlite3_session *pOld;          /* Session object already attached to db */
177506  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
177507
177508  /* Zero the output value in case an error occurs. */
177509  *ppSession = 0;
177510
177511  /* Allocate and populate the new session object. */
177512  pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
177513  if( !pNew ) return SQLITE_NOMEM;
177514  memset(pNew, 0, sizeof(sqlite3_session));
177515  pNew->db = db;
177516  pNew->zDb = (char *)&pNew[1];
177517  pNew->bEnable = 1;
177518  memcpy(pNew->zDb, zDb, nDb+1);
177519  sessionPreupdateHooks(pNew);
177520
177521  /* Add the new session object to the linked list of session objects
177522  ** attached to database handle $db. Do this under the cover of the db
177523  ** handle mutex.  */
177524  sqlite3_mutex_enter(sqlite3_db_mutex(db));
177525  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
177526  pNew->pNext = pOld;
177527  sqlite3_mutex_leave(sqlite3_db_mutex(db));
177528
177529  *ppSession = pNew;
177530  return SQLITE_OK;
177531}
177532
177533/*
177534** Free the list of table objects passed as the first argument. The contents
177535** of the changed-rows hash tables are also deleted.
177536*/
177537static void sessionDeleteTable(SessionTable *pList){
177538  SessionTable *pNext;
177539  SessionTable *pTab;
177540
177541  for(pTab=pList; pTab; pTab=pNext){
177542    int i;
177543    pNext = pTab->pNext;
177544    for(i=0; i<pTab->nChange; i++){
177545      SessionChange *p;
177546      SessionChange *pNextChange;
177547      for(p=pTab->apChange[i]; p; p=pNextChange){
177548        pNextChange = p->pNext;
177549        sqlite3_free(p);
177550      }
177551    }
177552    sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
177553    sqlite3_free(pTab->apChange);
177554    sqlite3_free(pTab);
177555  }
177556}
177557
177558/*
177559** Delete a session object previously allocated using sqlite3session_create().
177560*/
177561SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
177562  sqlite3 *db = pSession->db;
177563  sqlite3_session *pHead;
177564  sqlite3_session **pp;
177565
177566  /* Unlink the session from the linked list of sessions attached to the
177567  ** database handle. Hold the db mutex while doing so.  */
177568  sqlite3_mutex_enter(sqlite3_db_mutex(db));
177569  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
177570  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
177571    if( (*pp)==pSession ){
177572      *pp = (*pp)->pNext;
177573      if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
177574      break;
177575    }
177576  }
177577  sqlite3_mutex_leave(sqlite3_db_mutex(db));
177578
177579  /* Delete all attached table objects. And the contents of their
177580  ** associated hash-tables. */
177581  sessionDeleteTable(pSession->pTable);
177582
177583  /* Free the session object itself. */
177584  sqlite3_free(pSession);
177585}
177586
177587/*
177588** Set a table filter on a Session Object.
177589*/
177590SQLITE_API void sqlite3session_table_filter(
177591  sqlite3_session *pSession,
177592  int(*xFilter)(void*, const char*),
177593  void *pCtx                      /* First argument passed to xFilter */
177594){
177595  pSession->bAutoAttach = 1;
177596  pSession->pFilterCtx = pCtx;
177597  pSession->xTableFilter = xFilter;
177598}
177599
177600/*
177601** Attach a table to a session. All subsequent changes made to the table
177602** while the session object is enabled will be recorded.
177603**
177604** Only tables that have a PRIMARY KEY defined may be attached. It does
177605** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
177606** or not.
177607*/
177608SQLITE_API int sqlite3session_attach(
177609  sqlite3_session *pSession,      /* Session object */
177610  const char *zName               /* Table name */
177611){
177612  int rc = SQLITE_OK;
177613  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
177614
177615  if( !zName ){
177616    pSession->bAutoAttach = 1;
177617  }else{
177618    SessionTable *pTab;           /* New table object (if required) */
177619    int nName;                    /* Number of bytes in string zName */
177620
177621    /* First search for an existing entry. If one is found, this call is
177622    ** a no-op. Return early. */
177623    nName = sqlite3Strlen30(zName);
177624    for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
177625      if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
177626    }
177627
177628    if( !pTab ){
177629      /* Allocate new SessionTable object. */
177630      pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
177631      if( !pTab ){
177632        rc = SQLITE_NOMEM;
177633      }else{
177634        /* Populate the new SessionTable object and link it into the list.
177635        ** The new object must be linked onto the end of the list, not
177636        ** simply added to the start of it in order to ensure that tables
177637        ** appear in the correct order when a changeset or patchset is
177638        ** eventually generated. */
177639        SessionTable **ppTab;
177640        memset(pTab, 0, sizeof(SessionTable));
177641        pTab->zName = (char *)&pTab[1];
177642        memcpy(pTab->zName, zName, nName+1);
177643        for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
177644        *ppTab = pTab;
177645      }
177646    }
177647  }
177648
177649  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
177650  return rc;
177651}
177652
177653/*
177654** Ensure that there is room in the buffer to append nByte bytes of data.
177655** If not, use sqlite3_realloc() to grow the buffer so that there is.
177656**
177657** If successful, return zero. Otherwise, if an OOM condition is encountered,
177658** set *pRc to SQLITE_NOMEM and return non-zero.
177659*/
177660static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
177661  if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
177662    u8 *aNew;
177663    int nNew = p->nAlloc ? p->nAlloc : 128;
177664    do {
177665      nNew = nNew*2;
177666    }while( nNew<(p->nBuf+nByte) );
177667
177668    aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
177669    if( 0==aNew ){
177670      *pRc = SQLITE_NOMEM;
177671    }else{
177672      p->aBuf = aNew;
177673      p->nAlloc = nNew;
177674    }
177675  }
177676  return (*pRc!=SQLITE_OK);
177677}
177678
177679/*
177680** Append the value passed as the second argument to the buffer passed
177681** as the first.
177682**
177683** This function is a no-op if *pRc is non-zero when it is called.
177684** Otherwise, if an error occurs, *pRc is set to an SQLite error code
177685** before returning.
177686*/
177687static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
177688  int rc = *pRc;
177689  if( rc==SQLITE_OK ){
177690    int nByte = 0;
177691    rc = sessionSerializeValue(0, pVal, &nByte);
177692    sessionBufferGrow(p, nByte, &rc);
177693    if( rc==SQLITE_OK ){
177694      rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
177695      p->nBuf += nByte;
177696    }else{
177697      *pRc = rc;
177698    }
177699  }
177700}
177701
177702/*
177703** This function is a no-op if *pRc is other than SQLITE_OK when it is
177704** called. Otherwise, append a single byte to the buffer.
177705**
177706** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
177707** returning.
177708*/
177709static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
177710  if( 0==sessionBufferGrow(p, 1, pRc) ){
177711    p->aBuf[p->nBuf++] = v;
177712  }
177713}
177714
177715/*
177716** This function is a no-op if *pRc is other than SQLITE_OK when it is
177717** called. Otherwise, append a single varint to the buffer.
177718**
177719** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
177720** returning.
177721*/
177722static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
177723  if( 0==sessionBufferGrow(p, 9, pRc) ){
177724    p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
177725  }
177726}
177727
177728/*
177729** This function is a no-op if *pRc is other than SQLITE_OK when it is
177730** called. Otherwise, append a blob of data to the buffer.
177731**
177732** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
177733** returning.
177734*/
177735static void sessionAppendBlob(
177736  SessionBuffer *p,
177737  const u8 *aBlob,
177738  int nBlob,
177739  int *pRc
177740){
177741  if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
177742    memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
177743    p->nBuf += nBlob;
177744  }
177745}
177746
177747/*
177748** This function is a no-op if *pRc is other than SQLITE_OK when it is
177749** called. Otherwise, append a string to the buffer. All bytes in the string
177750** up to (but not including) the nul-terminator are written to the buffer.
177751**
177752** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
177753** returning.
177754*/
177755static void sessionAppendStr(
177756  SessionBuffer *p,
177757  const char *zStr,
177758  int *pRc
177759){
177760  int nStr = sqlite3Strlen30(zStr);
177761  if( 0==sessionBufferGrow(p, nStr, pRc) ){
177762    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
177763    p->nBuf += nStr;
177764  }
177765}
177766
177767/*
177768** This function is a no-op if *pRc is other than SQLITE_OK when it is
177769** called. Otherwise, append the string representation of integer iVal
177770** to the buffer. No nul-terminator is written.
177771**
177772** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
177773** returning.
177774*/
177775static void sessionAppendInteger(
177776  SessionBuffer *p,               /* Buffer to append to */
177777  int iVal,                       /* Value to write the string rep. of */
177778  int *pRc                        /* IN/OUT: Error code */
177779){
177780  char aBuf[24];
177781  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
177782  sessionAppendStr(p, aBuf, pRc);
177783}
177784
177785/*
177786** This function is a no-op if *pRc is other than SQLITE_OK when it is
177787** called. Otherwise, append the string zStr enclosed in quotes (") and
177788** with any embedded quote characters escaped to the buffer. No
177789** nul-terminator byte is written.
177790**
177791** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
177792** returning.
177793*/
177794static void sessionAppendIdent(
177795  SessionBuffer *p,               /* Buffer to a append to */
177796  const char *zStr,               /* String to quote, escape and append */
177797  int *pRc                        /* IN/OUT: Error code */
177798){
177799  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
177800  if( 0==sessionBufferGrow(p, nStr, pRc) ){
177801    char *zOut = (char *)&p->aBuf[p->nBuf];
177802    const char *zIn = zStr;
177803    *zOut++ = '"';
177804    while( *zIn ){
177805      if( *zIn=='"' ) *zOut++ = '"';
177806      *zOut++ = *(zIn++);
177807    }
177808    *zOut++ = '"';
177809    p->nBuf = (int)((u8 *)zOut - p->aBuf);
177810  }
177811}
177812
177813/*
177814** This function is a no-op if *pRc is other than SQLITE_OK when it is
177815** called. Otherwse, it appends the serialized version of the value stored
177816** in column iCol of the row that SQL statement pStmt currently points
177817** to to the buffer.
177818*/
177819static void sessionAppendCol(
177820  SessionBuffer *p,               /* Buffer to append to */
177821  sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
177822  int iCol,                       /* Column to read value from */
177823  int *pRc                        /* IN/OUT: Error code */
177824){
177825  if( *pRc==SQLITE_OK ){
177826    int eType = sqlite3_column_type(pStmt, iCol);
177827    sessionAppendByte(p, (u8)eType, pRc);
177828    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
177829      sqlite3_int64 i;
177830      u8 aBuf[8];
177831      if( eType==SQLITE_INTEGER ){
177832        i = sqlite3_column_int64(pStmt, iCol);
177833      }else{
177834        double r = sqlite3_column_double(pStmt, iCol);
177835        memcpy(&i, &r, 8);
177836      }
177837      sessionPutI64(aBuf, i);
177838      sessionAppendBlob(p, aBuf, 8, pRc);
177839    }
177840    if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
177841      u8 *z;
177842      int nByte;
177843      if( eType==SQLITE_BLOB ){
177844        z = (u8 *)sqlite3_column_blob(pStmt, iCol);
177845      }else{
177846        z = (u8 *)sqlite3_column_text(pStmt, iCol);
177847      }
177848      nByte = sqlite3_column_bytes(pStmt, iCol);
177849      if( z || (eType==SQLITE_BLOB && nByte==0) ){
177850        sessionAppendVarint(p, nByte, pRc);
177851        sessionAppendBlob(p, z, nByte, pRc);
177852      }else{
177853        *pRc = SQLITE_NOMEM;
177854      }
177855    }
177856  }
177857}
177858
177859/*
177860**
177861** This function appends an update change to the buffer (see the comments
177862** under "CHANGESET FORMAT" at the top of the file). An update change
177863** consists of:
177864**
177865**   1 byte:  SQLITE_UPDATE (0x17)
177866**   n bytes: old.* record (see RECORD FORMAT)
177867**   m bytes: new.* record (see RECORD FORMAT)
177868**
177869** The SessionChange object passed as the third argument contains the
177870** values that were stored in the row when the session began (the old.*
177871** values). The statement handle passed as the second argument points
177872** at the current version of the row (the new.* values).
177873**
177874** If all of the old.* values are equal to their corresponding new.* value
177875** (i.e. nothing has changed), then no data at all is appended to the buffer.
177876**
177877** Otherwise, the old.* record contains all primary key values and the
177878** original values of any fields that have been modified. The new.* record
177879** contains the new values of only those fields that have been modified.
177880*/
177881static int sessionAppendUpdate(
177882  SessionBuffer *pBuf,            /* Buffer to append to */
177883  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
177884  sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
177885  SessionChange *p,               /* Object containing old values */
177886  u8 *abPK                        /* Boolean array - true for PK columns */
177887){
177888  int rc = SQLITE_OK;
177889  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
177890  int bNoop = 1;                /* Set to zero if any values are modified */
177891  int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
177892  int i;                        /* Used to iterate through columns */
177893  u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
177894
177895  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
177896  sessionAppendByte(pBuf, p->bIndirect, &rc);
177897  for(i=0; i<sqlite3_column_count(pStmt); i++){
177898    int bChanged = 0;
177899    int nAdvance;
177900    int eType = *pCsr;
177901    switch( eType ){
177902      case SQLITE_NULL:
177903        nAdvance = 1;
177904        if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
177905          bChanged = 1;
177906        }
177907        break;
177908
177909      case SQLITE_FLOAT:
177910      case SQLITE_INTEGER: {
177911        nAdvance = 9;
177912        if( eType==sqlite3_column_type(pStmt, i) ){
177913          sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
177914          if( eType==SQLITE_INTEGER ){
177915            if( iVal==sqlite3_column_int64(pStmt, i) ) break;
177916          }else{
177917            double dVal;
177918            memcpy(&dVal, &iVal, 8);
177919            if( dVal==sqlite3_column_double(pStmt, i) ) break;
177920          }
177921        }
177922        bChanged = 1;
177923        break;
177924      }
177925
177926      default: {
177927        int n;
177928        int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
177929        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
177930        nAdvance = nHdr + n;
177931        if( eType==sqlite3_column_type(pStmt, i)
177932         && n==sqlite3_column_bytes(pStmt, i)
177933         && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
177934        ){
177935          break;
177936        }
177937        bChanged = 1;
177938      }
177939    }
177940
177941    /* If at least one field has been modified, this is not a no-op. */
177942    if( bChanged ) bNoop = 0;
177943
177944    /* Add a field to the old.* record. This is omitted if this modules is
177945    ** currently generating a patchset. */
177946    if( bPatchset==0 ){
177947      if( bChanged || abPK[i] ){
177948        sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
177949      }else{
177950        sessionAppendByte(pBuf, 0, &rc);
177951      }
177952    }
177953
177954    /* Add a field to the new.* record. Or the only record if currently
177955    ** generating a patchset.  */
177956    if( bChanged || (bPatchset && abPK[i]) ){
177957      sessionAppendCol(&buf2, pStmt, i, &rc);
177958    }else{
177959      sessionAppendByte(&buf2, 0, &rc);
177960    }
177961
177962    pCsr += nAdvance;
177963  }
177964
177965  if( bNoop ){
177966    pBuf->nBuf = nRewind;
177967  }else{
177968    sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
177969  }
177970  sqlite3_free(buf2.aBuf);
177971
177972  return rc;
177973}
177974
177975/*
177976** Append a DELETE change to the buffer passed as the first argument. Use
177977** the changeset format if argument bPatchset is zero, or the patchset
177978** format otherwise.
177979*/
177980static int sessionAppendDelete(
177981  SessionBuffer *pBuf,            /* Buffer to append to */
177982  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
177983  SessionChange *p,               /* Object containing old values */
177984  int nCol,                       /* Number of columns in table */
177985  u8 *abPK                        /* Boolean array - true for PK columns */
177986){
177987  int rc = SQLITE_OK;
177988
177989  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
177990  sessionAppendByte(pBuf, p->bIndirect, &rc);
177991
177992  if( bPatchset==0 ){
177993    sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
177994  }else{
177995    int i;
177996    u8 *a = p->aRecord;
177997    for(i=0; i<nCol; i++){
177998      u8 *pStart = a;
177999      int eType = *a++;
178000
178001      switch( eType ){
178002        case 0:
178003        case SQLITE_NULL:
178004          assert( abPK[i]==0 );
178005          break;
178006
178007        case SQLITE_FLOAT:
178008        case SQLITE_INTEGER:
178009          a += 8;
178010          break;
178011
178012        default: {
178013          int n;
178014          a += sessionVarintGet(a, &n);
178015          a += n;
178016          break;
178017        }
178018      }
178019      if( abPK[i] ){
178020        sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
178021      }
178022    }
178023    assert( (a - p->aRecord)==p->nRecord );
178024  }
178025
178026  return rc;
178027}
178028
178029/*
178030** Formulate and prepare a SELECT statement to retrieve a row from table
178031** zTab in database zDb based on its primary key. i.e.
178032**
178033**   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
178034*/
178035static int sessionSelectStmt(
178036  sqlite3 *db,                    /* Database handle */
178037  const char *zDb,                /* Database name */
178038  const char *zTab,               /* Table name */
178039  int nCol,                       /* Number of columns in table */
178040  const char **azCol,             /* Names of table columns */
178041  u8 *abPK,                       /* PRIMARY KEY  array */
178042  sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
178043){
178044  int rc = SQLITE_OK;
178045  int i;
178046  const char *zSep = "";
178047  SessionBuffer buf = {0, 0, 0};
178048
178049  sessionAppendStr(&buf, "SELECT * FROM ", &rc);
178050  sessionAppendIdent(&buf, zDb, &rc);
178051  sessionAppendStr(&buf, ".", &rc);
178052  sessionAppendIdent(&buf, zTab, &rc);
178053  sessionAppendStr(&buf, " WHERE ", &rc);
178054  for(i=0; i<nCol; i++){
178055    if( abPK[i] ){
178056      sessionAppendStr(&buf, zSep, &rc);
178057      sessionAppendIdent(&buf, azCol[i], &rc);
178058      sessionAppendStr(&buf, " = ?", &rc);
178059      sessionAppendInteger(&buf, i+1, &rc);
178060      zSep = " AND ";
178061    }
178062  }
178063  if( rc==SQLITE_OK ){
178064    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
178065  }
178066  sqlite3_free(buf.aBuf);
178067  return rc;
178068}
178069
178070/*
178071** Bind the PRIMARY KEY values from the change passed in argument pChange
178072** to the SELECT statement passed as the first argument. The SELECT statement
178073** is as prepared by function sessionSelectStmt().
178074**
178075** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
178076** error code (e.g. SQLITE_NOMEM) otherwise.
178077*/
178078static int sessionSelectBind(
178079  sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
178080  int nCol,                       /* Number of columns in table */
178081  u8 *abPK,                       /* PRIMARY KEY array */
178082  SessionChange *pChange          /* Change structure */
178083){
178084  int i;
178085  int rc = SQLITE_OK;
178086  u8 *a = pChange->aRecord;
178087
178088  for(i=0; i<nCol && rc==SQLITE_OK; i++){
178089    int eType = *a++;
178090
178091    switch( eType ){
178092      case 0:
178093      case SQLITE_NULL:
178094        assert( abPK[i]==0 );
178095        break;
178096
178097      case SQLITE_INTEGER: {
178098        if( abPK[i] ){
178099          i64 iVal = sessionGetI64(a);
178100          rc = sqlite3_bind_int64(pSelect, i+1, iVal);
178101        }
178102        a += 8;
178103        break;
178104      }
178105
178106      case SQLITE_FLOAT: {
178107        if( abPK[i] ){
178108          double rVal;
178109          i64 iVal = sessionGetI64(a);
178110          memcpy(&rVal, &iVal, 8);
178111          rc = sqlite3_bind_double(pSelect, i+1, rVal);
178112        }
178113        a += 8;
178114        break;
178115      }
178116
178117      case SQLITE_TEXT: {
178118        int n;
178119        a += sessionVarintGet(a, &n);
178120        if( abPK[i] ){
178121          rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
178122        }
178123        a += n;
178124        break;
178125      }
178126
178127      default: {
178128        int n;
178129        assert( eType==SQLITE_BLOB );
178130        a += sessionVarintGet(a, &n);
178131        if( abPK[i] ){
178132          rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
178133        }
178134        a += n;
178135        break;
178136      }
178137    }
178138  }
178139
178140  return rc;
178141}
178142
178143/*
178144** This function is a no-op if *pRc is set to other than SQLITE_OK when it
178145** is called. Otherwise, append a serialized table header (part of the binary
178146** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
178147** SQLite error code before returning.
178148*/
178149static void sessionAppendTableHdr(
178150  SessionBuffer *pBuf,            /* Append header to this buffer */
178151  int bPatchset,                  /* Use the patchset format if true */
178152  SessionTable *pTab,             /* Table object to append header for */
178153  int *pRc                        /* IN/OUT: Error code */
178154){
178155  /* Write a table header */
178156  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
178157  sessionAppendVarint(pBuf, pTab->nCol, pRc);
178158  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
178159  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
178160}
178161
178162/*
178163** Generate either a changeset (if argument bPatchset is zero) or a patchset
178164** (if it is non-zero) based on the current contents of the session object
178165** passed as the first argument.
178166**
178167** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
178168** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
178169** occurs, an SQLite error code is returned and both output variables set
178170** to 0.
178171*/
178172static int sessionGenerateChangeset(
178173  sqlite3_session *pSession,      /* Session object */
178174  int bPatchset,                  /* True for patchset, false for changeset */
178175  int (*xOutput)(void *pOut, const void *pData, int nData),
178176  void *pOut,                     /* First argument for xOutput */
178177  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
178178  void **ppChangeset              /* OUT: Buffer containing changeset */
178179){
178180  sqlite3 *db = pSession->db;     /* Source database handle */
178181  SessionTable *pTab;             /* Used to iterate through attached tables */
178182  SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
178183  int rc;                         /* Return code */
178184
178185  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
178186
178187  /* Zero the output variables in case an error occurs. If this session
178188  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
178189  ** this call will be a no-op.  */
178190  if( xOutput==0 ){
178191    *pnChangeset = 0;
178192    *ppChangeset = 0;
178193  }
178194
178195  if( pSession->rc ) return pSession->rc;
178196  rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
178197  if( rc!=SQLITE_OK ) return rc;
178198
178199  sqlite3_mutex_enter(sqlite3_db_mutex(db));
178200
178201  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
178202    if( pTab->nEntry ){
178203      const char *zName = pTab->zName;
178204      int nCol;                   /* Number of columns in table */
178205      u8 *abPK;                   /* Primary key array */
178206      const char **azCol = 0;     /* Table columns */
178207      int i;                      /* Used to iterate through hash buckets */
178208      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
178209      int nRewind = buf.nBuf;     /* Initial size of write buffer */
178210      int nNoop;                  /* Size of buffer after writing tbl header */
178211
178212      /* Check the table schema is still Ok. */
178213      rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
178214      if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
178215        rc = SQLITE_SCHEMA;
178216      }
178217
178218      /* Write a table header */
178219      sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
178220
178221      /* Build and compile a statement to execute: */
178222      if( rc==SQLITE_OK ){
178223        rc = sessionSelectStmt(
178224            db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
178225      }
178226
178227      nNoop = buf.nBuf;
178228      for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
178229        SessionChange *p;         /* Used to iterate through changes */
178230
178231        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
178232          rc = sessionSelectBind(pSel, nCol, abPK, p);
178233          if( rc!=SQLITE_OK ) continue;
178234          if( sqlite3_step(pSel)==SQLITE_ROW ){
178235            if( p->op==SQLITE_INSERT ){
178236              int iCol;
178237              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
178238              sessionAppendByte(&buf, p->bIndirect, &rc);
178239              for(iCol=0; iCol<nCol; iCol++){
178240                sessionAppendCol(&buf, pSel, iCol, &rc);
178241              }
178242            }else{
178243              rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
178244            }
178245          }else if( p->op!=SQLITE_INSERT ){
178246            rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
178247          }
178248          if( rc==SQLITE_OK ){
178249            rc = sqlite3_reset(pSel);
178250          }
178251
178252          /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
178253          ** its contents to the xOutput() callback. */
178254          if( xOutput
178255           && rc==SQLITE_OK
178256           && buf.nBuf>nNoop
178257           && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
178258          ){
178259            rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
178260            nNoop = -1;
178261            buf.nBuf = 0;
178262          }
178263
178264        }
178265      }
178266
178267      sqlite3_finalize(pSel);
178268      if( buf.nBuf==nNoop ){
178269        buf.nBuf = nRewind;
178270      }
178271      sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
178272    }
178273  }
178274
178275  if( rc==SQLITE_OK ){
178276    if( xOutput==0 ){
178277      *pnChangeset = buf.nBuf;
178278      *ppChangeset = buf.aBuf;
178279      buf.aBuf = 0;
178280    }else if( buf.nBuf>0 ){
178281      rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
178282    }
178283  }
178284
178285  sqlite3_free(buf.aBuf);
178286  sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
178287  sqlite3_mutex_leave(sqlite3_db_mutex(db));
178288  return rc;
178289}
178290
178291/*
178292** Obtain a changeset object containing all changes recorded by the
178293** session object passed as the first argument.
178294**
178295** It is the responsibility of the caller to eventually free the buffer
178296** using sqlite3_free().
178297*/
178298SQLITE_API int sqlite3session_changeset(
178299  sqlite3_session *pSession,      /* Session object */
178300  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
178301  void **ppChangeset              /* OUT: Buffer containing changeset */
178302){
178303  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
178304}
178305
178306/*
178307** Streaming version of sqlite3session_changeset().
178308*/
178309SQLITE_API int sqlite3session_changeset_strm(
178310  sqlite3_session *pSession,
178311  int (*xOutput)(void *pOut, const void *pData, int nData),
178312  void *pOut
178313){
178314  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
178315}
178316
178317/*
178318** Streaming version of sqlite3session_patchset().
178319*/
178320SQLITE_API int sqlite3session_patchset_strm(
178321  sqlite3_session *pSession,
178322  int (*xOutput)(void *pOut, const void *pData, int nData),
178323  void *pOut
178324){
178325  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
178326}
178327
178328/*
178329** Obtain a patchset object containing all changes recorded by the
178330** session object passed as the first argument.
178331**
178332** It is the responsibility of the caller to eventually free the buffer
178333** using sqlite3_free().
178334*/
178335SQLITE_API int sqlite3session_patchset(
178336  sqlite3_session *pSession,      /* Session object */
178337  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
178338  void **ppPatchset               /* OUT: Buffer containing changeset */
178339){
178340  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
178341}
178342
178343/*
178344** Enable or disable the session object passed as the first argument.
178345*/
178346SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
178347  int ret;
178348  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
178349  if( bEnable>=0 ){
178350    pSession->bEnable = bEnable;
178351  }
178352  ret = pSession->bEnable;
178353  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
178354  return ret;
178355}
178356
178357/*
178358** Enable or disable the session object passed as the first argument.
178359*/
178360SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
178361  int ret;
178362  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
178363  if( bIndirect>=0 ){
178364    pSession->bIndirect = bIndirect;
178365  }
178366  ret = pSession->bIndirect;
178367  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
178368  return ret;
178369}
178370
178371/*
178372** Return true if there have been no changes to monitored tables recorded
178373** by the session object passed as the only argument.
178374*/
178375SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
178376  int ret = 0;
178377  SessionTable *pTab;
178378
178379  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
178380  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
178381    ret = (pTab->nEntry>0);
178382  }
178383  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
178384
178385  return (ret==0);
178386}
178387
178388/*
178389** Do the work for either sqlite3changeset_start() or start_strm().
178390*/
178391static int sessionChangesetStart(
178392  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
178393  int (*xInput)(void *pIn, void *pData, int *pnData),
178394  void *pIn,
178395  int nChangeset,                 /* Size of buffer pChangeset in bytes */
178396  void *pChangeset                /* Pointer to buffer containing changeset */
178397){
178398  sqlite3_changeset_iter *pRet;   /* Iterator to return */
178399  int nByte;                      /* Number of bytes to allocate for iterator */
178400
178401  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
178402
178403  /* Zero the output variable in case an error occurs. */
178404  *pp = 0;
178405
178406  /* Allocate and initialize the iterator structure. */
178407  nByte = sizeof(sqlite3_changeset_iter);
178408  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
178409  if( !pRet ) return SQLITE_NOMEM;
178410  memset(pRet, 0, sizeof(sqlite3_changeset_iter));
178411  pRet->in.aData = (u8 *)pChangeset;
178412  pRet->in.nData = nChangeset;
178413  pRet->in.xInput = xInput;
178414  pRet->in.pIn = pIn;
178415  pRet->in.bEof = (xInput ? 0 : 1);
178416
178417  /* Populate the output variable and return success. */
178418  *pp = pRet;
178419  return SQLITE_OK;
178420}
178421
178422/*
178423** Create an iterator used to iterate through the contents of a changeset.
178424*/
178425SQLITE_API int sqlite3changeset_start(
178426  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
178427  int nChangeset,                 /* Size of buffer pChangeset in bytes */
178428  void *pChangeset                /* Pointer to buffer containing changeset */
178429){
178430  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
178431}
178432
178433/*
178434** Streaming version of sqlite3changeset_start().
178435*/
178436SQLITE_API int sqlite3changeset_start_strm(
178437  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
178438  int (*xInput)(void *pIn, void *pData, int *pnData),
178439  void *pIn
178440){
178441  return sessionChangesetStart(pp, xInput, pIn, 0, 0);
178442}
178443
178444/*
178445** If the SessionInput object passed as the only argument is a streaming
178446** object and the buffer is full, discard some data to free up space.
178447*/
178448static void sessionDiscardData(SessionInput *pIn){
178449  if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
178450    int nMove = pIn->buf.nBuf - pIn->iNext;
178451    assert( nMove>=0 );
178452    if( nMove>0 ){
178453      memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
178454    }
178455    pIn->buf.nBuf -= pIn->iNext;
178456    pIn->iNext = 0;
178457    pIn->nData = pIn->buf.nBuf;
178458  }
178459}
178460
178461/*
178462** Ensure that there are at least nByte bytes available in the buffer. Or,
178463** if there are not nByte bytes remaining in the input, that all available
178464** data is in the buffer.
178465**
178466** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
178467*/
178468static int sessionInputBuffer(SessionInput *pIn, int nByte){
178469  int rc = SQLITE_OK;
178470  if( pIn->xInput ){
178471    while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
178472      int nNew = SESSIONS_STRM_CHUNK_SIZE;
178473
178474      if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
178475      if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
178476        rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
178477        if( nNew==0 ){
178478          pIn->bEof = 1;
178479        }else{
178480          pIn->buf.nBuf += nNew;
178481        }
178482      }
178483
178484      pIn->aData = pIn->buf.aBuf;
178485      pIn->nData = pIn->buf.nBuf;
178486    }
178487  }
178488  return rc;
178489}
178490
178491/*
178492** When this function is called, *ppRec points to the start of a record
178493** that contains nCol values. This function advances the pointer *ppRec
178494** until it points to the byte immediately following that record.
178495*/
178496static void sessionSkipRecord(
178497  u8 **ppRec,                     /* IN/OUT: Record pointer */
178498  int nCol                        /* Number of values in record */
178499){
178500  u8 *aRec = *ppRec;
178501  int i;
178502  for(i=0; i<nCol; i++){
178503    int eType = *aRec++;
178504    if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
178505      int nByte;
178506      aRec += sessionVarintGet((u8*)aRec, &nByte);
178507      aRec += nByte;
178508    }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
178509      aRec += 8;
178510    }
178511  }
178512
178513  *ppRec = aRec;
178514}
178515
178516/*
178517** This function sets the value of the sqlite3_value object passed as the
178518** first argument to a copy of the string or blob held in the aData[]
178519** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
178520** error occurs.
178521*/
178522static int sessionValueSetStr(
178523  sqlite3_value *pVal,            /* Set the value of this object */
178524  u8 *aData,                      /* Buffer containing string or blob data */
178525  int nData,                      /* Size of buffer aData[] in bytes */
178526  u8 enc                          /* String encoding (0 for blobs) */
178527){
178528  /* In theory this code could just pass SQLITE_TRANSIENT as the final
178529  ** argument to sqlite3ValueSetStr() and have the copy created
178530  ** automatically. But doing so makes it difficult to detect any OOM
178531  ** error. Hence the code to create the copy externally. */
178532  u8 *aCopy = sqlite3_malloc(nData+1);
178533  if( aCopy==0 ) return SQLITE_NOMEM;
178534  memcpy(aCopy, aData, nData);
178535  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
178536  return SQLITE_OK;
178537}
178538
178539/*
178540** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
178541** for details.
178542**
178543** When this function is called, *paChange points to the start of the record
178544** to deserialize. Assuming no error occurs, *paChange is set to point to
178545** one byte after the end of the same record before this function returns.
178546** If the argument abPK is NULL, then the record contains nCol values. Or,
178547** if abPK is other than NULL, then the record contains only the PK fields
178548** (in other words, it is a patchset DELETE record).
178549**
178550** If successful, each element of the apOut[] array (allocated by the caller)
178551** is set to point to an sqlite3_value object containing the value read
178552** from the corresponding position in the record. If that value is not
178553** included in the record (i.e. because the record is part of an UPDATE change
178554** and the field was not modified), the corresponding element of apOut[] is
178555** set to NULL.
178556**
178557** It is the responsibility of the caller to free all sqlite_value structures
178558** using sqlite3_free().
178559**
178560** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
178561** The apOut[] array may have been partially populated in this case.
178562*/
178563static int sessionReadRecord(
178564  SessionInput *pIn,              /* Input data */
178565  int nCol,                       /* Number of values in record */
178566  u8 *abPK,                       /* Array of primary key flags, or NULL */
178567  sqlite3_value **apOut           /* Write values to this array */
178568){
178569  int i;                          /* Used to iterate through columns */
178570  int rc = SQLITE_OK;
178571
178572  for(i=0; i<nCol && rc==SQLITE_OK; i++){
178573    int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
178574    if( abPK && abPK[i]==0 ) continue;
178575    rc = sessionInputBuffer(pIn, 9);
178576    if( rc==SQLITE_OK ){
178577      eType = pIn->aData[pIn->iNext++];
178578    }
178579
178580    assert( apOut[i]==0 );
178581    if( eType ){
178582      apOut[i] = sqlite3ValueNew(0);
178583      if( !apOut[i] ) rc = SQLITE_NOMEM;
178584    }
178585
178586    if( rc==SQLITE_OK ){
178587      u8 *aVal = &pIn->aData[pIn->iNext];
178588      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
178589        int nByte;
178590        pIn->iNext += sessionVarintGet(aVal, &nByte);
178591        rc = sessionInputBuffer(pIn, nByte);
178592        if( rc==SQLITE_OK ){
178593          u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
178594          rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
178595        }
178596        pIn->iNext += nByte;
178597      }
178598      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
178599        sqlite3_int64 v = sessionGetI64(aVal);
178600        if( eType==SQLITE_INTEGER ){
178601          sqlite3VdbeMemSetInt64(apOut[i], v);
178602        }else{
178603          double d;
178604          memcpy(&d, &v, 8);
178605          sqlite3VdbeMemSetDouble(apOut[i], d);
178606        }
178607        pIn->iNext += 8;
178608      }
178609    }
178610  }
178611
178612  return rc;
178613}
178614
178615/*
178616** The input pointer currently points to the second byte of a table-header.
178617** Specifically, to the following:
178618**
178619**   + number of columns in table (varint)
178620**   + array of PK flags (1 byte per column),
178621**   + table name (nul terminated).
178622**
178623** This function ensures that all of the above is present in the input
178624** buffer (i.e. that it can be accessed without any calls to xInput()).
178625** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
178626** The input pointer is not moved.
178627*/
178628static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
178629  int rc = SQLITE_OK;
178630  int nCol = 0;
178631  int nRead = 0;
178632
178633  rc = sessionInputBuffer(pIn, 9);
178634  if( rc==SQLITE_OK ){
178635    nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
178636    rc = sessionInputBuffer(pIn, nRead+nCol+100);
178637    nRead += nCol;
178638  }
178639
178640  while( rc==SQLITE_OK ){
178641    while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
178642      nRead++;
178643    }
178644    if( (pIn->iNext + nRead)<pIn->nData ) break;
178645    rc = sessionInputBuffer(pIn, nRead + 100);
178646  }
178647  *pnByte = nRead+1;
178648  return rc;
178649}
178650
178651/*
178652** The input pointer currently points to the first byte of the first field
178653** of a record consisting of nCol columns. This function ensures the entire
178654** record is buffered. It does not move the input pointer.
178655**
178656** If successful, SQLITE_OK is returned and *pnByte is set to the size of
178657** the record in bytes. Otherwise, an SQLite error code is returned. The
178658** final value of *pnByte is undefined in this case.
178659*/
178660static int sessionChangesetBufferRecord(
178661  SessionInput *pIn,              /* Input data */
178662  int nCol,                       /* Number of columns in record */
178663  int *pnByte                     /* OUT: Size of record in bytes */
178664){
178665  int rc = SQLITE_OK;
178666  int nByte = 0;
178667  int i;
178668  for(i=0; rc==SQLITE_OK && i<nCol; i++){
178669    int eType;
178670    rc = sessionInputBuffer(pIn, nByte + 10);
178671    if( rc==SQLITE_OK ){
178672      eType = pIn->aData[pIn->iNext + nByte++];
178673      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
178674        int n;
178675        nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
178676        nByte += n;
178677        rc = sessionInputBuffer(pIn, nByte);
178678      }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
178679        nByte += 8;
178680      }
178681    }
178682  }
178683  *pnByte = nByte;
178684  return rc;
178685}
178686
178687/*
178688** The input pointer currently points to the second byte of a table-header.
178689** Specifically, to the following:
178690**
178691**   + number of columns in table (varint)
178692**   + array of PK flags (1 byte per column),
178693**   + table name (nul terminated).
178694**
178695** This function decodes the table-header and populates the p->nCol,
178696** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
178697** also allocated or resized according to the new value of p->nCol. The
178698** input pointer is left pointing to the byte following the table header.
178699**
178700** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
178701** is returned and the final values of the various fields enumerated above
178702** are undefined.
178703*/
178704static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
178705  int rc;
178706  int nCopy;
178707  assert( p->rc==SQLITE_OK );
178708
178709  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
178710  if( rc==SQLITE_OK ){
178711    int nByte;
178712    int nVarint;
178713    nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
178714    nCopy -= nVarint;
178715    p->in.iNext += nVarint;
178716    nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
178717    p->tblhdr.nBuf = 0;
178718    sessionBufferGrow(&p->tblhdr, nByte, &rc);
178719  }
178720
178721  if( rc==SQLITE_OK ){
178722    int iPK = sizeof(sqlite3_value*)*p->nCol*2;
178723    memset(p->tblhdr.aBuf, 0, iPK);
178724    memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
178725    p->in.iNext += nCopy;
178726  }
178727
178728  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
178729  p->abPK = (u8*)&p->apValue[p->nCol*2];
178730  p->zTab = (char*)&p->abPK[p->nCol];
178731  return (p->rc = rc);
178732}
178733
178734/*
178735** Advance the changeset iterator to the next change.
178736**
178737** If both paRec and pnRec are NULL, then this function works like the public
178738** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
178739** sqlite3changeset_new() and old() APIs may be used to query for values.
178740**
178741** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
178742** record is written to *paRec before returning and the number of bytes in
178743** the record to *pnRec.
178744**
178745** Either way, this function returns SQLITE_ROW if the iterator is
178746** successfully advanced to the next change in the changeset, an SQLite
178747** error code if an error occurs, or SQLITE_DONE if there are no further
178748** changes in the changeset.
178749*/
178750static int sessionChangesetNext(
178751  sqlite3_changeset_iter *p,      /* Changeset iterator */
178752  u8 **paRec,                     /* If non-NULL, store record pointer here */
178753  int *pnRec                      /* If non-NULL, store size of record here */
178754){
178755  int i;
178756  u8 op;
178757
178758  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
178759
178760  /* If the iterator is in the error-state, return immediately. */
178761  if( p->rc!=SQLITE_OK ) return p->rc;
178762
178763  /* Free the current contents of p->apValue[], if any. */
178764  if( p->apValue ){
178765    for(i=0; i<p->nCol*2; i++){
178766      sqlite3ValueFree(p->apValue[i]);
178767    }
178768    memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
178769  }
178770
178771  /* Make sure the buffer contains at least 10 bytes of input data, or all
178772  ** remaining data if there are less than 10 bytes available. This is
178773  ** sufficient either for the 'T' or 'P' byte and the varint that follows
178774  ** it, or for the two single byte values otherwise. */
178775  p->rc = sessionInputBuffer(&p->in, 2);
178776  if( p->rc!=SQLITE_OK ) return p->rc;
178777
178778  /* If the iterator is already at the end of the changeset, return DONE. */
178779  if( p->in.iNext>=p->in.nData ){
178780    return SQLITE_DONE;
178781  }
178782
178783  sessionDiscardData(&p->in);
178784  p->in.iCurrent = p->in.iNext;
178785
178786  op = p->in.aData[p->in.iNext++];
178787  while( op=='T' || op=='P' ){
178788    p->bPatchset = (op=='P');
178789    if( sessionChangesetReadTblhdr(p) ) return p->rc;
178790    if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
178791    p->in.iCurrent = p->in.iNext;
178792    if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
178793    op = p->in.aData[p->in.iNext++];
178794  }
178795
178796  p->op = op;
178797  p->bIndirect = p->in.aData[p->in.iNext++];
178798  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
178799    return (p->rc = SQLITE_CORRUPT_BKPT);
178800  }
178801
178802  if( paRec ){
178803    int nVal;                     /* Number of values to buffer */
178804    if( p->bPatchset==0 && op==SQLITE_UPDATE ){
178805      nVal = p->nCol * 2;
178806    }else if( p->bPatchset && op==SQLITE_DELETE ){
178807      nVal = 0;
178808      for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
178809    }else{
178810      nVal = p->nCol;
178811    }
178812    p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
178813    if( p->rc!=SQLITE_OK ) return p->rc;
178814    *paRec = &p->in.aData[p->in.iNext];
178815    p->in.iNext += *pnRec;
178816  }else{
178817
178818    /* If this is an UPDATE or DELETE, read the old.* record. */
178819    if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
178820      u8 *abPK = p->bPatchset ? p->abPK : 0;
178821      p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
178822      if( p->rc!=SQLITE_OK ) return p->rc;
178823    }
178824
178825    /* If this is an INSERT or UPDATE, read the new.* record. */
178826    if( p->op!=SQLITE_DELETE ){
178827      p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
178828      if( p->rc!=SQLITE_OK ) return p->rc;
178829    }
178830
178831    if( p->bPatchset && p->op==SQLITE_UPDATE ){
178832      /* If this is an UPDATE that is part of a patchset, then all PK and
178833      ** modified fields are present in the new.* record. The old.* record
178834      ** is currently completely empty. This block shifts the PK fields from
178835      ** new.* to old.*, to accommodate the code that reads these arrays.  */
178836      for(i=0; i<p->nCol; i++){
178837        assert( p->apValue[i]==0 );
178838        assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
178839        if( p->abPK[i] ){
178840          p->apValue[i] = p->apValue[i+p->nCol];
178841          p->apValue[i+p->nCol] = 0;
178842        }
178843      }
178844    }
178845  }
178846
178847  return SQLITE_ROW;
178848}
178849
178850/*
178851** Advance an iterator created by sqlite3changeset_start() to the next
178852** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
178853** or SQLITE_CORRUPT.
178854**
178855** This function may not be called on iterators passed to a conflict handler
178856** callback by changeset_apply().
178857*/
178858SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
178859  return sessionChangesetNext(p, 0, 0);
178860}
178861
178862/*
178863** The following function extracts information on the current change
178864** from a changeset iterator. It may only be called after changeset_next()
178865** has returned SQLITE_ROW.
178866*/
178867SQLITE_API int sqlite3changeset_op(
178868  sqlite3_changeset_iter *pIter,  /* Iterator handle */
178869  const char **pzTab,             /* OUT: Pointer to table name */
178870  int *pnCol,                     /* OUT: Number of columns in table */
178871  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
178872  int *pbIndirect                 /* OUT: True if change is indirect */
178873){
178874  *pOp = pIter->op;
178875  *pnCol = pIter->nCol;
178876  *pzTab = pIter->zTab;
178877  if( pbIndirect ) *pbIndirect = pIter->bIndirect;
178878  return SQLITE_OK;
178879}
178880
178881/*
178882** Return information regarding the PRIMARY KEY and number of columns in
178883** the database table affected by the change that pIter currently points
178884** to. This function may only be called after changeset_next() returns
178885** SQLITE_ROW.
178886*/
178887SQLITE_API int sqlite3changeset_pk(
178888  sqlite3_changeset_iter *pIter,  /* Iterator object */
178889  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
178890  int *pnCol                      /* OUT: Number of entries in output array */
178891){
178892  *pabPK = pIter->abPK;
178893  if( pnCol ) *pnCol = pIter->nCol;
178894  return SQLITE_OK;
178895}
178896
178897/*
178898** This function may only be called while the iterator is pointing to an
178899** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
178900** Otherwise, SQLITE_MISUSE is returned.
178901**
178902** It sets *ppValue to point to an sqlite3_value structure containing the
178903** iVal'th value in the old.* record. Or, if that particular value is not
178904** included in the record (because the change is an UPDATE and the field
178905** was not modified and is not a PK column), set *ppValue to NULL.
178906**
178907** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
178908** not modified. Otherwise, SQLITE_OK.
178909*/
178910SQLITE_API int sqlite3changeset_old(
178911  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
178912  int iVal,                       /* Index of old.* value to retrieve */
178913  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
178914){
178915  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
178916    return SQLITE_MISUSE;
178917  }
178918  if( iVal<0 || iVal>=pIter->nCol ){
178919    return SQLITE_RANGE;
178920  }
178921  *ppValue = pIter->apValue[iVal];
178922  return SQLITE_OK;
178923}
178924
178925/*
178926** This function may only be called while the iterator is pointing to an
178927** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
178928** Otherwise, SQLITE_MISUSE is returned.
178929**
178930** It sets *ppValue to point to an sqlite3_value structure containing the
178931** iVal'th value in the new.* record. Or, if that particular value is not
178932** included in the record (because the change is an UPDATE and the field
178933** was not modified), set *ppValue to NULL.
178934**
178935** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
178936** not modified. Otherwise, SQLITE_OK.
178937*/
178938SQLITE_API int sqlite3changeset_new(
178939  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
178940  int iVal,                       /* Index of new.* value to retrieve */
178941  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
178942){
178943  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
178944    return SQLITE_MISUSE;
178945  }
178946  if( iVal<0 || iVal>=pIter->nCol ){
178947    return SQLITE_RANGE;
178948  }
178949  *ppValue = pIter->apValue[pIter->nCol+iVal];
178950  return SQLITE_OK;
178951}
178952
178953/*
178954** The following two macros are used internally. They are similar to the
178955** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
178956** they omit all error checking and return a pointer to the requested value.
178957*/
178958#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
178959#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
178960
178961/*
178962** This function may only be called with a changeset iterator that has been
178963** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
178964** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
178965**
178966** If successful, *ppValue is set to point to an sqlite3_value structure
178967** containing the iVal'th value of the conflicting record.
178968**
178969** If value iVal is out-of-range or some other error occurs, an SQLite error
178970** code is returned. Otherwise, SQLITE_OK.
178971*/
178972SQLITE_API int sqlite3changeset_conflict(
178973  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
178974  int iVal,                       /* Index of conflict record value to fetch */
178975  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
178976){
178977  if( !pIter->pConflict ){
178978    return SQLITE_MISUSE;
178979  }
178980  if( iVal<0 || iVal>=pIter->nCol ){
178981    return SQLITE_RANGE;
178982  }
178983  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
178984  return SQLITE_OK;
178985}
178986
178987/*
178988** This function may only be called with an iterator passed to an
178989** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
178990** it sets the output variable to the total number of known foreign key
178991** violations in the destination database and returns SQLITE_OK.
178992**
178993** In all other cases this function returns SQLITE_MISUSE.
178994*/
178995SQLITE_API int sqlite3changeset_fk_conflicts(
178996  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
178997  int *pnOut                      /* OUT: Number of FK violations */
178998){
178999  if( pIter->pConflict || pIter->apValue ){
179000    return SQLITE_MISUSE;
179001  }
179002  *pnOut = pIter->nCol;
179003  return SQLITE_OK;
179004}
179005
179006
179007/*
179008** Finalize an iterator allocated with sqlite3changeset_start().
179009**
179010** This function may not be called on iterators passed to a conflict handler
179011** callback by changeset_apply().
179012*/
179013SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
179014  int rc = SQLITE_OK;
179015  if( p ){
179016    int i;                        /* Used to iterate through p->apValue[] */
179017    rc = p->rc;
179018    if( p->apValue ){
179019      for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
179020    }
179021    sqlite3_free(p->tblhdr.aBuf);
179022    sqlite3_free(p->in.buf.aBuf);
179023    sqlite3_free(p);
179024  }
179025  return rc;
179026}
179027
179028static int sessionChangesetInvert(
179029  SessionInput *pInput,           /* Input changeset */
179030  int (*xOutput)(void *pOut, const void *pData, int nData),
179031  void *pOut,
179032  int *pnInverted,                /* OUT: Number of bytes in output changeset */
179033  void **ppInverted               /* OUT: Inverse of pChangeset */
179034){
179035  int rc = SQLITE_OK;             /* Return value */
179036  SessionBuffer sOut;             /* Output buffer */
179037  int nCol = 0;                   /* Number of cols in current table */
179038  u8 *abPK = 0;                   /* PK array for current table */
179039  sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
179040  SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
179041
179042  /* Initialize the output buffer */
179043  memset(&sOut, 0, sizeof(SessionBuffer));
179044
179045  /* Zero the output variables in case an error occurs. */
179046  if( ppInverted ){
179047    *ppInverted = 0;
179048    *pnInverted = 0;
179049  }
179050
179051  while( 1 ){
179052    u8 eType;
179053
179054    /* Test for EOF. */
179055    if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
179056    if( pInput->iNext>=pInput->nData ) break;
179057    eType = pInput->aData[pInput->iNext];
179058
179059    switch( eType ){
179060      case 'T': {
179061        /* A 'table' record consists of:
179062        **
179063        **   * A constant 'T' character,
179064        **   * Number of columns in said table (a varint),
179065        **   * An array of nCol bytes (sPK),
179066        **   * A nul-terminated table name.
179067        */
179068        int nByte;
179069        int nVar;
179070        pInput->iNext++;
179071        if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
179072          goto finished_invert;
179073        }
179074        nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
179075        sPK.nBuf = 0;
179076        sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
179077        sessionAppendByte(&sOut, eType, &rc);
179078        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
179079        if( rc ) goto finished_invert;
179080
179081        pInput->iNext += nByte;
179082        sqlite3_free(apVal);
179083        apVal = 0;
179084        abPK = sPK.aBuf;
179085        break;
179086      }
179087
179088      case SQLITE_INSERT:
179089      case SQLITE_DELETE: {
179090        int nByte;
179091        int bIndirect = pInput->aData[pInput->iNext+1];
179092        int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
179093        pInput->iNext += 2;
179094        assert( rc==SQLITE_OK );
179095        rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
179096        sessionAppendByte(&sOut, eType2, &rc);
179097        sessionAppendByte(&sOut, bIndirect, &rc);
179098        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
179099        pInput->iNext += nByte;
179100        if( rc ) goto finished_invert;
179101        break;
179102      }
179103
179104      case SQLITE_UPDATE: {
179105        int iCol;
179106
179107        if( 0==apVal ){
179108          apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
179109          if( 0==apVal ){
179110            rc = SQLITE_NOMEM;
179111            goto finished_invert;
179112          }
179113          memset(apVal, 0, sizeof(apVal[0])*nCol*2);
179114        }
179115
179116        /* Write the header for the new UPDATE change. Same as the original. */
179117        sessionAppendByte(&sOut, eType, &rc);
179118        sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
179119
179120        /* Read the old.* and new.* records for the update change. */
179121        pInput->iNext += 2;
179122        rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
179123        if( rc==SQLITE_OK ){
179124          rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
179125        }
179126
179127        /* Write the new old.* record. Consists of the PK columns from the
179128        ** original old.* record, and the other values from the original
179129        ** new.* record. */
179130        for(iCol=0; iCol<nCol; iCol++){
179131          sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
179132          sessionAppendValue(&sOut, pVal, &rc);
179133        }
179134
179135        /* Write the new new.* record. Consists of a copy of all values
179136        ** from the original old.* record, except for the PK columns, which
179137        ** are set to "undefined". */
179138        for(iCol=0; iCol<nCol; iCol++){
179139          sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
179140          sessionAppendValue(&sOut, pVal, &rc);
179141        }
179142
179143        for(iCol=0; iCol<nCol*2; iCol++){
179144          sqlite3ValueFree(apVal[iCol]);
179145        }
179146        memset(apVal, 0, sizeof(apVal[0])*nCol*2);
179147        if( rc!=SQLITE_OK ){
179148          goto finished_invert;
179149        }
179150
179151        break;
179152      }
179153
179154      default:
179155        rc = SQLITE_CORRUPT_BKPT;
179156        goto finished_invert;
179157    }
179158
179159    assert( rc==SQLITE_OK );
179160    if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
179161      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
179162      sOut.nBuf = 0;
179163      if( rc!=SQLITE_OK ) goto finished_invert;
179164    }
179165  }
179166
179167  assert( rc==SQLITE_OK );
179168  if( pnInverted ){
179169    *pnInverted = sOut.nBuf;
179170    *ppInverted = sOut.aBuf;
179171    sOut.aBuf = 0;
179172  }else if( sOut.nBuf>0 ){
179173    rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
179174  }
179175
179176 finished_invert:
179177  sqlite3_free(sOut.aBuf);
179178  sqlite3_free(apVal);
179179  sqlite3_free(sPK.aBuf);
179180  return rc;
179181}
179182
179183
179184/*
179185** Invert a changeset object.
179186*/
179187SQLITE_API int sqlite3changeset_invert(
179188  int nChangeset,                 /* Number of bytes in input */
179189  const void *pChangeset,         /* Input changeset */
179190  int *pnInverted,                /* OUT: Number of bytes in output changeset */
179191  void **ppInverted               /* OUT: Inverse of pChangeset */
179192){
179193  SessionInput sInput;
179194
179195  /* Set up the input stream */
179196  memset(&sInput, 0, sizeof(SessionInput));
179197  sInput.nData = nChangeset;
179198  sInput.aData = (u8*)pChangeset;
179199
179200  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
179201}
179202
179203/*
179204** Streaming version of sqlite3changeset_invert().
179205*/
179206SQLITE_API int sqlite3changeset_invert_strm(
179207  int (*xInput)(void *pIn, void *pData, int *pnData),
179208  void *pIn,
179209  int (*xOutput)(void *pOut, const void *pData, int nData),
179210  void *pOut
179211){
179212  SessionInput sInput;
179213  int rc;
179214
179215  /* Set up the input stream */
179216  memset(&sInput, 0, sizeof(SessionInput));
179217  sInput.xInput = xInput;
179218  sInput.pIn = pIn;
179219
179220  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
179221  sqlite3_free(sInput.buf.aBuf);
179222  return rc;
179223}
179224
179225typedef struct SessionApplyCtx SessionApplyCtx;
179226struct SessionApplyCtx {
179227  sqlite3 *db;
179228  sqlite3_stmt *pDelete;          /* DELETE statement */
179229  sqlite3_stmt *pUpdate;          /* UPDATE statement */
179230  sqlite3_stmt *pInsert;          /* INSERT statement */
179231  sqlite3_stmt *pSelect;          /* SELECT statement */
179232  int nCol;                       /* Size of azCol[] and abPK[] arrays */
179233  const char **azCol;             /* Array of column names */
179234  u8 *abPK;                       /* Boolean array - true if column is in PK */
179235
179236  int bDeferConstraints;          /* True to defer constraints */
179237  SessionBuffer constraints;      /* Deferred constraints are stored here */
179238};
179239
179240/*
179241** Formulate a statement to DELETE a row from database db. Assuming a table
179242** structure like this:
179243**
179244**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
179245**
179246** The DELETE statement looks like this:
179247**
179248**     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
179249**
179250** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
179251** matching b and d values, or 1 otherwise. The second case comes up if the
179252** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
179253**
179254** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
179255** pointing to the prepared version of the SQL statement.
179256*/
179257static int sessionDeleteRow(
179258  sqlite3 *db,                    /* Database handle */
179259  const char *zTab,               /* Table name */
179260  SessionApplyCtx *p              /* Session changeset-apply context */
179261){
179262  int i;
179263  const char *zSep = "";
179264  int rc = SQLITE_OK;
179265  SessionBuffer buf = {0, 0, 0};
179266  int nPk = 0;
179267
179268  sessionAppendStr(&buf, "DELETE FROM ", &rc);
179269  sessionAppendIdent(&buf, zTab, &rc);
179270  sessionAppendStr(&buf, " WHERE ", &rc);
179271
179272  for(i=0; i<p->nCol; i++){
179273    if( p->abPK[i] ){
179274      nPk++;
179275      sessionAppendStr(&buf, zSep, &rc);
179276      sessionAppendIdent(&buf, p->azCol[i], &rc);
179277      sessionAppendStr(&buf, " = ?", &rc);
179278      sessionAppendInteger(&buf, i+1, &rc);
179279      zSep = " AND ";
179280    }
179281  }
179282
179283  if( nPk<p->nCol ){
179284    sessionAppendStr(&buf, " AND (?", &rc);
179285    sessionAppendInteger(&buf, p->nCol+1, &rc);
179286    sessionAppendStr(&buf, " OR ", &rc);
179287
179288    zSep = "";
179289    for(i=0; i<p->nCol; i++){
179290      if( !p->abPK[i] ){
179291        sessionAppendStr(&buf, zSep, &rc);
179292        sessionAppendIdent(&buf, p->azCol[i], &rc);
179293        sessionAppendStr(&buf, " IS ?", &rc);
179294        sessionAppendInteger(&buf, i+1, &rc);
179295        zSep = "AND ";
179296      }
179297    }
179298    sessionAppendStr(&buf, ")", &rc);
179299  }
179300
179301  if( rc==SQLITE_OK ){
179302    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
179303  }
179304  sqlite3_free(buf.aBuf);
179305
179306  return rc;
179307}
179308
179309/*
179310** Formulate and prepare a statement to UPDATE a row from database db.
179311** Assuming a table structure like this:
179312**
179313**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
179314**
179315** The UPDATE statement looks like this:
179316**
179317**     UPDATE x SET
179318**     a = CASE WHEN ?2  THEN ?3  ELSE a END,
179319**     b = CASE WHEN ?5  THEN ?6  ELSE b END,
179320**     c = CASE WHEN ?8  THEN ?9  ELSE c END,
179321**     d = CASE WHEN ?11 THEN ?12 ELSE d END
179322**     WHERE a = ?1 AND c = ?7 AND (?13 OR
179323**       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
179324**     )
179325**
179326** For each column in the table, there are three variables to bind:
179327**
179328**     ?(i*3+1)    The old.* value of the column, if any.
179329**     ?(i*3+2)    A boolean flag indicating that the value is being modified.
179330**     ?(i*3+3)    The new.* value of the column, if any.
179331**
179332** Also, a boolean flag that, if set to true, causes the statement to update
179333** a row even if the non-PK values do not match. This is required if the
179334** conflict-handler is invoked with CHANGESET_DATA and returns
179335** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
179336**
179337** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
179338** pointing to the prepared version of the SQL statement.
179339*/
179340static int sessionUpdateRow(
179341  sqlite3 *db,                    /* Database handle */
179342  const char *zTab,               /* Table name */
179343  SessionApplyCtx *p              /* Session changeset-apply context */
179344){
179345  int rc = SQLITE_OK;
179346  int i;
179347  const char *zSep = "";
179348  SessionBuffer buf = {0, 0, 0};
179349
179350  /* Append "UPDATE tbl SET " */
179351  sessionAppendStr(&buf, "UPDATE ", &rc);
179352  sessionAppendIdent(&buf, zTab, &rc);
179353  sessionAppendStr(&buf, " SET ", &rc);
179354
179355  /* Append the assignments */
179356  for(i=0; i<p->nCol; i++){
179357    sessionAppendStr(&buf, zSep, &rc);
179358    sessionAppendIdent(&buf, p->azCol[i], &rc);
179359    sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
179360    sessionAppendInteger(&buf, i*3+2, &rc);
179361    sessionAppendStr(&buf, " THEN ?", &rc);
179362    sessionAppendInteger(&buf, i*3+3, &rc);
179363    sessionAppendStr(&buf, " ELSE ", &rc);
179364    sessionAppendIdent(&buf, p->azCol[i], &rc);
179365    sessionAppendStr(&buf, " END", &rc);
179366    zSep = ", ";
179367  }
179368
179369  /* Append the PK part of the WHERE clause */
179370  sessionAppendStr(&buf, " WHERE ", &rc);
179371  for(i=0; i<p->nCol; i++){
179372    if( p->abPK[i] ){
179373      sessionAppendIdent(&buf, p->azCol[i], &rc);
179374      sessionAppendStr(&buf, " = ?", &rc);
179375      sessionAppendInteger(&buf, i*3+1, &rc);
179376      sessionAppendStr(&buf, " AND ", &rc);
179377    }
179378  }
179379
179380  /* Append the non-PK part of the WHERE clause */
179381  sessionAppendStr(&buf, " (?", &rc);
179382  sessionAppendInteger(&buf, p->nCol*3+1, &rc);
179383  sessionAppendStr(&buf, " OR 1", &rc);
179384  for(i=0; i<p->nCol; i++){
179385    if( !p->abPK[i] ){
179386      sessionAppendStr(&buf, " AND (?", &rc);
179387      sessionAppendInteger(&buf, i*3+2, &rc);
179388      sessionAppendStr(&buf, "=0 OR ", &rc);
179389      sessionAppendIdent(&buf, p->azCol[i], &rc);
179390      sessionAppendStr(&buf, " IS ?", &rc);
179391      sessionAppendInteger(&buf, i*3+1, &rc);
179392      sessionAppendStr(&buf, ")", &rc);
179393    }
179394  }
179395  sessionAppendStr(&buf, ")", &rc);
179396
179397  if( rc==SQLITE_OK ){
179398    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
179399  }
179400  sqlite3_free(buf.aBuf);
179401
179402  return rc;
179403}
179404
179405/*
179406** Formulate and prepare an SQL statement to query table zTab by primary
179407** key. Assuming the following table structure:
179408**
179409**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
179410**
179411** The SELECT statement looks like this:
179412**
179413**     SELECT * FROM x WHERE a = ?1 AND c = ?3
179414**
179415** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
179416** pointing to the prepared version of the SQL statement.
179417*/
179418static int sessionSelectRow(
179419  sqlite3 *db,                    /* Database handle */
179420  const char *zTab,               /* Table name */
179421  SessionApplyCtx *p              /* Session changeset-apply context */
179422){
179423  return sessionSelectStmt(
179424      db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
179425}
179426
179427/*
179428** Formulate and prepare an INSERT statement to add a record to table zTab.
179429** For example:
179430**
179431**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
179432**
179433** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
179434** pointing to the prepared version of the SQL statement.
179435*/
179436static int sessionInsertRow(
179437  sqlite3 *db,                    /* Database handle */
179438  const char *zTab,               /* Table name */
179439  SessionApplyCtx *p              /* Session changeset-apply context */
179440){
179441  int rc = SQLITE_OK;
179442  int i;
179443  SessionBuffer buf = {0, 0, 0};
179444
179445  sessionAppendStr(&buf, "INSERT INTO main.", &rc);
179446  sessionAppendIdent(&buf, zTab, &rc);
179447  sessionAppendStr(&buf, "(", &rc);
179448  for(i=0; i<p->nCol; i++){
179449    if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
179450    sessionAppendIdent(&buf, p->azCol[i], &rc);
179451  }
179452
179453  sessionAppendStr(&buf, ") VALUES(?", &rc);
179454  for(i=1; i<p->nCol; i++){
179455    sessionAppendStr(&buf, ", ?", &rc);
179456  }
179457  sessionAppendStr(&buf, ")", &rc);
179458
179459  if( rc==SQLITE_OK ){
179460    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
179461  }
179462  sqlite3_free(buf.aBuf);
179463  return rc;
179464}
179465
179466/*
179467** A wrapper around sqlite3_bind_value() that detects an extra problem.
179468** See comments in the body of this function for details.
179469*/
179470static int sessionBindValue(
179471  sqlite3_stmt *pStmt,            /* Statement to bind value to */
179472  int i,                          /* Parameter number to bind to */
179473  sqlite3_value *pVal             /* Value to bind */
179474){
179475  int eType = sqlite3_value_type(pVal);
179476  /* COVERAGE: The (pVal->z==0) branch is never true using current versions
179477  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
179478  ** the (pVal->z) variable remains as it was or the type of the value is
179479  ** set to SQLITE_NULL.  */
179480  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
179481    /* This condition occurs when an earlier OOM in a call to
179482    ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
179483    ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
179484    return SQLITE_NOMEM;
179485  }
179486  return sqlite3_bind_value(pStmt, i, pVal);
179487}
179488
179489/*
179490** Iterator pIter must point to an SQLITE_INSERT entry. This function
179491** transfers new.* values from the current iterator entry to statement
179492** pStmt. The table being inserted into has nCol columns.
179493**
179494** New.* value $i from the iterator is bound to variable ($i+1) of
179495** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
179496** are transfered to the statement. Otherwise, if abPK is not NULL, it points
179497** to an array nCol elements in size. In this case only those values for
179498** which abPK[$i] is true are read from the iterator and bound to the
179499** statement.
179500**
179501** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
179502*/
179503static int sessionBindRow(
179504  sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
179505  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
179506  int nCol,                       /* Number of columns */
179507  u8 *abPK,                       /* If not NULL, bind only if true */
179508  sqlite3_stmt *pStmt             /* Bind values to this statement */
179509){
179510  int i;
179511  int rc = SQLITE_OK;
179512
179513  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
179514  ** argument iterator points to a suitable entry. Make sure that xValue
179515  ** is one of these to guarantee that it is safe to ignore the return
179516  ** in the code below. */
179517  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
179518
179519  for(i=0; rc==SQLITE_OK && i<nCol; i++){
179520    if( !abPK || abPK[i] ){
179521      sqlite3_value *pVal;
179522      (void)xValue(pIter, i, &pVal);
179523      rc = sessionBindValue(pStmt, i+1, pVal);
179524    }
179525  }
179526  return rc;
179527}
179528
179529/*
179530** SQL statement pSelect is as generated by the sessionSelectRow() function.
179531** This function binds the primary key values from the change that changeset
179532** iterator pIter points to to the SELECT and attempts to seek to the table
179533** entry. If a row is found, the SELECT statement left pointing at the row
179534** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
179535** has occured, the statement is reset and SQLITE_OK is returned. If an
179536** error occurs, the statement is reset and an SQLite error code is returned.
179537**
179538** If this function returns SQLITE_ROW, the caller must eventually reset()
179539** statement pSelect. If any other value is returned, the statement does
179540** not require a reset().
179541**
179542** If the iterator currently points to an INSERT record, bind values from the
179543** new.* record to the SELECT statement. Or, if it points to a DELETE or
179544** UPDATE, bind values from the old.* record.
179545*/
179546static int sessionSeekToRow(
179547  sqlite3 *db,                    /* Database handle */
179548  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
179549  u8 *abPK,                       /* Primary key flags array */
179550  sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
179551){
179552  int rc;                         /* Return code */
179553  int nCol;                       /* Number of columns in table */
179554  int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
179555  const char *zDummy;             /* Unused */
179556
179557  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
179558  rc = sessionBindRow(pIter,
179559      op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
179560      nCol, abPK, pSelect
179561  );
179562
179563  if( rc==SQLITE_OK ){
179564    rc = sqlite3_step(pSelect);
179565    if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
179566  }
179567
179568  return rc;
179569}
179570
179571/*
179572** Invoke the conflict handler for the change that the changeset iterator
179573** currently points to.
179574**
179575** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
179576** If argument pbReplace is NULL, then the type of conflict handler invoked
179577** depends solely on eType, as follows:
179578**
179579**    eType value                 Value passed to xConflict
179580**    -------------------------------------------------
179581**    CHANGESET_DATA              CHANGESET_NOTFOUND
179582**    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
179583**
179584** Or, if pbReplace is not NULL, then an attempt is made to find an existing
179585** record with the same primary key as the record about to be deleted, updated
179586** or inserted. If such a record can be found, it is available to the conflict
179587** handler as the "conflicting" record. In this case the type of conflict
179588** handler invoked is as follows:
179589**
179590**    eType value         PK Record found?   Value passed to xConflict
179591**    ----------------------------------------------------------------
179592**    CHANGESET_DATA      Yes                CHANGESET_DATA
179593**    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
179594**    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
179595**    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
179596**
179597** If pbReplace is not NULL, and a record with a matching PK is found, and
179598** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
179599** is set to non-zero before returning SQLITE_OK.
179600**
179601** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
179602** returned. Or, if the conflict handler returns an invalid value,
179603** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
179604** this function returns SQLITE_OK.
179605*/
179606static int sessionConflictHandler(
179607  int eType,                      /* Either CHANGESET_DATA or CONFLICT */
179608  SessionApplyCtx *p,             /* changeset_apply() context */
179609  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
179610  int(*xConflict)(void *, int, sqlite3_changeset_iter*),
179611  void *pCtx,                     /* First argument for conflict handler */
179612  int *pbReplace                  /* OUT: Set to true if PK row is found */
179613){
179614  int res = 0;                    /* Value returned by conflict handler */
179615  int rc;
179616  int nCol;
179617  int op;
179618  const char *zDummy;
179619
179620  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
179621
179622  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
179623  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
179624  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
179625
179626  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
179627  if( pbReplace ){
179628    rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
179629  }else{
179630    rc = SQLITE_OK;
179631  }
179632
179633  if( rc==SQLITE_ROW ){
179634    /* There exists another row with the new.* primary key. */
179635    pIter->pConflict = p->pSelect;
179636    res = xConflict(pCtx, eType, pIter);
179637    pIter->pConflict = 0;
179638    rc = sqlite3_reset(p->pSelect);
179639  }else if( rc==SQLITE_OK ){
179640    if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
179641      /* Instead of invoking the conflict handler, append the change blob
179642      ** to the SessionApplyCtx.constraints buffer. */
179643      u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
179644      int nBlob = pIter->in.iNext - pIter->in.iCurrent;
179645      sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
179646      res = SQLITE_CHANGESET_OMIT;
179647    }else{
179648      /* No other row with the new.* primary key. */
179649      res = xConflict(pCtx, eType+1, pIter);
179650      if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
179651    }
179652  }
179653
179654  if( rc==SQLITE_OK ){
179655    switch( res ){
179656      case SQLITE_CHANGESET_REPLACE:
179657        assert( pbReplace );
179658        *pbReplace = 1;
179659        break;
179660
179661      case SQLITE_CHANGESET_OMIT:
179662        break;
179663
179664      case SQLITE_CHANGESET_ABORT:
179665        rc = SQLITE_ABORT;
179666        break;
179667
179668      default:
179669        rc = SQLITE_MISUSE;
179670        break;
179671    }
179672  }
179673
179674  return rc;
179675}
179676
179677/*
179678** Attempt to apply the change that the iterator passed as the first argument
179679** currently points to to the database. If a conflict is encountered, invoke
179680** the conflict handler callback.
179681**
179682** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
179683** one is encountered, update or delete the row with the matching primary key
179684** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
179685** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
179686** to true before returning. In this case the caller will invoke this function
179687** again, this time with pbRetry set to NULL.
179688**
179689** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
179690** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
179691** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
179692** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
179693** before retrying. In this case the caller attempts to remove the conflicting
179694** row before invoking this function again, this time with pbReplace set
179695** to NULL.
179696**
179697** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
179698** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
179699** returned.
179700*/
179701static int sessionApplyOneOp(
179702  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
179703  SessionApplyCtx *p,             /* changeset_apply() context */
179704  int(*xConflict)(void *, int, sqlite3_changeset_iter *),
179705  void *pCtx,                     /* First argument for the conflict handler */
179706  int *pbReplace,                 /* OUT: True to remove PK row and retry */
179707  int *pbRetry                    /* OUT: True to retry. */
179708){
179709  const char *zDummy;
179710  int op;
179711  int nCol;
179712  int rc = SQLITE_OK;
179713
179714  assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
179715  assert( p->azCol && p->abPK );
179716  assert( !pbReplace || *pbReplace==0 );
179717
179718  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
179719
179720  if( op==SQLITE_DELETE ){
179721
179722    /* Bind values to the DELETE statement. If conflict handling is required,
179723    ** bind values for all columns and set bound variable (nCol+1) to true.
179724    ** Or, if conflict handling is not required, bind just the PK column
179725    ** values and, if it exists, set (nCol+1) to false. Conflict handling
179726    ** is not required if:
179727    **
179728    **   * this is a patchset, or
179729    **   * (pbRetry==0), or
179730    **   * all columns of the table are PK columns (in this case there is
179731    **     no (nCol+1) variable to bind to).
179732    */
179733    u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
179734    rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
179735    if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
179736      rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
179737    }
179738    if( rc!=SQLITE_OK ) return rc;
179739
179740    sqlite3_step(p->pDelete);
179741    rc = sqlite3_reset(p->pDelete);
179742    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
179743      rc = sessionConflictHandler(
179744          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
179745      );
179746    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
179747      rc = sessionConflictHandler(
179748          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
179749      );
179750    }
179751
179752  }else if( op==SQLITE_UPDATE ){
179753    int i;
179754
179755    /* Bind values to the UPDATE statement. */
179756    for(i=0; rc==SQLITE_OK && i<nCol; i++){
179757      sqlite3_value *pOld = sessionChangesetOld(pIter, i);
179758      sqlite3_value *pNew = sessionChangesetNew(pIter, i);
179759
179760      sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
179761      if( pOld ){
179762        rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
179763      }
179764      if( rc==SQLITE_OK && pNew ){
179765        rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
179766      }
179767    }
179768    if( rc==SQLITE_OK ){
179769      sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
179770    }
179771    if( rc!=SQLITE_OK ) return rc;
179772
179773    /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
179774    ** the result will be SQLITE_OK with 0 rows modified. */
179775    sqlite3_step(p->pUpdate);
179776    rc = sqlite3_reset(p->pUpdate);
179777
179778    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
179779      /* A NOTFOUND or DATA error. Search the table to see if it contains
179780      ** a row with a matching primary key. If so, this is a DATA conflict.
179781      ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
179782
179783      rc = sessionConflictHandler(
179784          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
179785      );
179786
179787    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
179788      /* This is always a CONSTRAINT conflict. */
179789      rc = sessionConflictHandler(
179790          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
179791      );
179792    }
179793
179794  }else{
179795    assert( op==SQLITE_INSERT );
179796    rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
179797    if( rc!=SQLITE_OK ) return rc;
179798
179799    sqlite3_step(p->pInsert);
179800    rc = sqlite3_reset(p->pInsert);
179801    if( (rc&0xff)==SQLITE_CONSTRAINT ){
179802      rc = sessionConflictHandler(
179803          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
179804      );
179805    }
179806  }
179807
179808  return rc;
179809}
179810
179811/*
179812** Attempt to apply the change that the iterator passed as the first argument
179813** currently points to to the database. If a conflict is encountered, invoke
179814** the conflict handler callback.
179815**
179816** The difference between this function and sessionApplyOne() is that this
179817** function handles the case where the conflict-handler is invoked and
179818** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
179819** retried in some manner.
179820*/
179821static int sessionApplyOneWithRetry(
179822  sqlite3 *db,                    /* Apply change to "main" db of this handle */
179823  sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
179824  SessionApplyCtx *pApply,        /* Apply context */
179825  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
179826  void *pCtx                      /* First argument passed to xConflict */
179827){
179828  int bReplace = 0;
179829  int bRetry = 0;
179830  int rc;
179831
179832  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
179833  assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
179834
179835  /* If the bRetry flag is set, the change has not been applied due to an
179836  ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
179837  ** a row with the correct PK is present in the db, but one or more other
179838  ** fields do not contain the expected values) and the conflict handler
179839  ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
179840  ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
179841  ** the SQLITE_CHANGESET_DATA problem.  */
179842  if( bRetry ){
179843    assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
179844    rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
179845  }
179846
179847  /* If the bReplace flag is set, the change is an INSERT that has not
179848  ** been performed because the database already contains a row with the
179849  ** specified primary key and the conflict handler returned
179850  ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
179851  ** before reattempting the INSERT.  */
179852  else if( bReplace ){
179853    assert( pIter->op==SQLITE_INSERT );
179854    rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
179855    if( rc==SQLITE_OK ){
179856      rc = sessionBindRow(pIter,
179857          sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
179858      sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
179859    }
179860    if( rc==SQLITE_OK ){
179861      sqlite3_step(pApply->pDelete);
179862      rc = sqlite3_reset(pApply->pDelete);
179863    }
179864    if( rc==SQLITE_OK ){
179865      rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
179866    }
179867    if( rc==SQLITE_OK ){
179868      rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
179869    }
179870  }
179871
179872  return rc;
179873}
179874
179875/*
179876** Retry the changes accumulated in the pApply->constraints buffer.
179877*/
179878static int sessionRetryConstraints(
179879  sqlite3 *db,
179880  int bPatchset,
179881  const char *zTab,
179882  SessionApplyCtx *pApply,
179883  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
179884  void *pCtx                      /* First argument passed to xConflict */
179885){
179886  int rc = SQLITE_OK;
179887
179888  while( pApply->constraints.nBuf ){
179889    sqlite3_changeset_iter *pIter2 = 0;
179890    SessionBuffer cons = pApply->constraints;
179891    memset(&pApply->constraints, 0, sizeof(SessionBuffer));
179892
179893    rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
179894    if( rc==SQLITE_OK ){
179895      int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
179896      int rc2;
179897      pIter2->bPatchset = bPatchset;
179898      pIter2->zTab = (char*)zTab;
179899      pIter2->nCol = pApply->nCol;
179900      pIter2->abPK = pApply->abPK;
179901      sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
179902      pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
179903      if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
179904
179905      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
179906        rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
179907      }
179908
179909      rc2 = sqlite3changeset_finalize(pIter2);
179910      if( rc==SQLITE_OK ) rc = rc2;
179911    }
179912    assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
179913
179914    sqlite3_free(cons.aBuf);
179915    if( rc!=SQLITE_OK ) break;
179916    if( pApply->constraints.nBuf>=cons.nBuf ){
179917      /* No progress was made on the last round. */
179918      pApply->bDeferConstraints = 0;
179919    }
179920  }
179921
179922  return rc;
179923}
179924
179925/*
179926** Argument pIter is a changeset iterator that has been initialized, but
179927** not yet passed to sqlite3changeset_next(). This function applies the
179928** changeset to the main database attached to handle "db". The supplied
179929** conflict handler callback is invoked to resolve any conflicts encountered
179930** while applying the change.
179931*/
179932static int sessionChangesetApply(
179933  sqlite3 *db,                    /* Apply change to "main" db of this handle */
179934  sqlite3_changeset_iter *pIter,  /* Changeset to apply */
179935  int(*xFilter)(
179936    void *pCtx,                   /* Copy of sixth arg to _apply() */
179937    const char *zTab              /* Table name */
179938  ),
179939  int(*xConflict)(
179940    void *pCtx,                   /* Copy of fifth arg to _apply() */
179941    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
179942    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
179943  ),
179944  void *pCtx                      /* First argument passed to xConflict */
179945){
179946  int schemaMismatch = 0;
179947  int rc;                         /* Return code */
179948  const char *zTab = 0;           /* Name of current table */
179949  int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
179950  SessionApplyCtx sApply;         /* changeset_apply() context object */
179951  int bPatchset;
179952
179953  assert( xConflict!=0 );
179954
179955  pIter->in.bNoDiscard = 1;
179956  memset(&sApply, 0, sizeof(sApply));
179957  sqlite3_mutex_enter(sqlite3_db_mutex(db));
179958  rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
179959  if( rc==SQLITE_OK ){
179960    rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
179961  }
179962  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
179963    int nCol;
179964    int op;
179965    const char *zNew;
179966
179967    sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
179968
179969    if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
179970      u8 *abPK;
179971
179972      rc = sessionRetryConstraints(
179973          db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
179974      );
179975      if( rc!=SQLITE_OK ) break;
179976
179977      sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
179978      sqlite3_finalize(sApply.pDelete);
179979      sqlite3_finalize(sApply.pUpdate);
179980      sqlite3_finalize(sApply.pInsert);
179981      sqlite3_finalize(sApply.pSelect);
179982      memset(&sApply, 0, sizeof(sApply));
179983      sApply.db = db;
179984      sApply.bDeferConstraints = 1;
179985
179986      /* If an xFilter() callback was specified, invoke it now. If the
179987      ** xFilter callback returns zero, skip this table. If it returns
179988      ** non-zero, proceed. */
179989      schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
179990      if( schemaMismatch ){
179991        zTab = sqlite3_mprintf("%s", zNew);
179992        if( zTab==0 ){
179993          rc = SQLITE_NOMEM;
179994          break;
179995        }
179996        nTab = (int)strlen(zTab);
179997        sApply.azCol = (const char **)zTab;
179998      }else{
179999        int nMinCol = 0;
180000        int i;
180001
180002        sqlite3changeset_pk(pIter, &abPK, 0);
180003        rc = sessionTableInfo(
180004            db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
180005        );
180006        if( rc!=SQLITE_OK ) break;
180007        for(i=0; i<sApply.nCol; i++){
180008          if( sApply.abPK[i] ) nMinCol = i+1;
180009        }
180010
180011        if( sApply.nCol==0 ){
180012          schemaMismatch = 1;
180013          sqlite3_log(SQLITE_SCHEMA,
180014              "sqlite3changeset_apply(): no such table: %s", zTab
180015          );
180016        }
180017        else if( sApply.nCol<nCol ){
180018          schemaMismatch = 1;
180019          sqlite3_log(SQLITE_SCHEMA,
180020              "sqlite3changeset_apply(): table %s has %d columns, "
180021              "expected %d or more",
180022              zTab, sApply.nCol, nCol
180023          );
180024        }
180025        else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
180026          schemaMismatch = 1;
180027          sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
180028              "primary key mismatch for table %s", zTab
180029          );
180030        }
180031        else{
180032          sApply.nCol = nCol;
180033          if((rc = sessionSelectRow(db, zTab, &sApply))
180034          || (rc = sessionUpdateRow(db, zTab, &sApply))
180035          || (rc = sessionDeleteRow(db, zTab, &sApply))
180036          || (rc = sessionInsertRow(db, zTab, &sApply))
180037          ){
180038            break;
180039          }
180040        }
180041        nTab = sqlite3Strlen30(zTab);
180042      }
180043    }
180044
180045    /* If there is a schema mismatch on the current table, proceed to the
180046    ** next change. A log message has already been issued. */
180047    if( schemaMismatch ) continue;
180048
180049    rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
180050  }
180051
180052  bPatchset = pIter->bPatchset;
180053  if( rc==SQLITE_OK ){
180054    rc = sqlite3changeset_finalize(pIter);
180055  }else{
180056    sqlite3changeset_finalize(pIter);
180057  }
180058
180059  if( rc==SQLITE_OK ){
180060    rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
180061  }
180062
180063  if( rc==SQLITE_OK ){
180064    int nFk, notUsed;
180065    sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
180066    if( nFk!=0 ){
180067      int res = SQLITE_CHANGESET_ABORT;
180068      sqlite3_changeset_iter sIter;
180069      memset(&sIter, 0, sizeof(sIter));
180070      sIter.nCol = nFk;
180071      res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
180072      if( res!=SQLITE_CHANGESET_OMIT ){
180073        rc = SQLITE_CONSTRAINT;
180074      }
180075    }
180076  }
180077  sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
180078
180079  if( rc==SQLITE_OK ){
180080    rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
180081  }else{
180082    sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
180083    sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
180084  }
180085
180086  sqlite3_finalize(sApply.pInsert);
180087  sqlite3_finalize(sApply.pDelete);
180088  sqlite3_finalize(sApply.pUpdate);
180089  sqlite3_finalize(sApply.pSelect);
180090  sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
180091  sqlite3_free((char*)sApply.constraints.aBuf);
180092  sqlite3_mutex_leave(sqlite3_db_mutex(db));
180093  return rc;
180094}
180095
180096/*
180097** Apply the changeset passed via pChangeset/nChangeset to the main database
180098** attached to handle "db". Invoke the supplied conflict handler callback
180099** to resolve any conflicts encountered while applying the change.
180100*/
180101SQLITE_API int sqlite3changeset_apply(
180102  sqlite3 *db,                    /* Apply change to "main" db of this handle */
180103  int nChangeset,                 /* Size of changeset in bytes */
180104  void *pChangeset,               /* Changeset blob */
180105  int(*xFilter)(
180106    void *pCtx,                   /* Copy of sixth arg to _apply() */
180107    const char *zTab              /* Table name */
180108  ),
180109  int(*xConflict)(
180110    void *pCtx,                   /* Copy of fifth arg to _apply() */
180111    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
180112    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
180113  ),
180114  void *pCtx                      /* First argument passed to xConflict */
180115){
180116  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
180117  int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
180118  if( rc==SQLITE_OK ){
180119    rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
180120  }
180121  return rc;
180122}
180123
180124/*
180125** Apply the changeset passed via xInput/pIn to the main database
180126** attached to handle "db". Invoke the supplied conflict handler callback
180127** to resolve any conflicts encountered while applying the change.
180128*/
180129SQLITE_API int sqlite3changeset_apply_strm(
180130  sqlite3 *db,                    /* Apply change to "main" db of this handle */
180131  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
180132  void *pIn,                                          /* First arg for xInput */
180133  int(*xFilter)(
180134    void *pCtx,                   /* Copy of sixth arg to _apply() */
180135    const char *zTab              /* Table name */
180136  ),
180137  int(*xConflict)(
180138    void *pCtx,                   /* Copy of sixth arg to _apply() */
180139    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
180140    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
180141  ),
180142  void *pCtx                      /* First argument passed to xConflict */
180143){
180144  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
180145  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
180146  if( rc==SQLITE_OK ){
180147    rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
180148  }
180149  return rc;
180150}
180151
180152/*
180153** sqlite3_changegroup handle.
180154*/
180155struct sqlite3_changegroup {
180156  int rc;                         /* Error code */
180157  int bPatch;                     /* True to accumulate patchsets */
180158  SessionTable *pList;            /* List of tables in current patch */
180159};
180160
180161/*
180162** This function is called to merge two changes to the same row together as
180163** part of an sqlite3changeset_concat() operation. A new change object is
180164** allocated and a pointer to it stored in *ppNew.
180165*/
180166static int sessionChangeMerge(
180167  SessionTable *pTab,             /* Table structure */
180168  int bPatchset,                  /* True for patchsets */
180169  SessionChange *pExist,          /* Existing change */
180170  int op2,                        /* Second change operation */
180171  int bIndirect,                  /* True if second change is indirect */
180172  u8 *aRec,                       /* Second change record */
180173  int nRec,                       /* Number of bytes in aRec */
180174  SessionChange **ppNew           /* OUT: Merged change */
180175){
180176  SessionChange *pNew = 0;
180177
180178  if( !pExist ){
180179    pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
180180    if( !pNew ){
180181      return SQLITE_NOMEM;
180182    }
180183    memset(pNew, 0, sizeof(SessionChange));
180184    pNew->op = op2;
180185    pNew->bIndirect = bIndirect;
180186    pNew->nRecord = nRec;
180187    pNew->aRecord = (u8*)&pNew[1];
180188    memcpy(pNew->aRecord, aRec, nRec);
180189  }else{
180190    int op1 = pExist->op;
180191
180192    /*
180193    **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
180194    **   op1=INSERT, op2=UPDATE      ->      INSERT.
180195    **   op1=INSERT, op2=DELETE      ->      (none)
180196    **
180197    **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
180198    **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
180199    **   op1=UPDATE, op2=DELETE      ->      DELETE.
180200    **
180201    **   op1=DELETE, op2=INSERT      ->      UPDATE.
180202    **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
180203    **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
180204    */
180205    if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
180206     || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
180207     || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
180208     || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
180209    ){
180210      pNew = pExist;
180211    }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
180212      sqlite3_free(pExist);
180213      assert( pNew==0 );
180214    }else{
180215      u8 *aExist = pExist->aRecord;
180216      int nByte;
180217      u8 *aCsr;
180218
180219      /* Allocate a new SessionChange object. Ensure that the aRecord[]
180220      ** buffer of the new object is large enough to hold any record that
180221      ** may be generated by combining the input records.  */
180222      nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
180223      pNew = (SessionChange *)sqlite3_malloc(nByte);
180224      if( !pNew ){
180225        sqlite3_free(pExist);
180226        return SQLITE_NOMEM;
180227      }
180228      memset(pNew, 0, sizeof(SessionChange));
180229      pNew->bIndirect = (bIndirect && pExist->bIndirect);
180230      aCsr = pNew->aRecord = (u8 *)&pNew[1];
180231
180232      if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
180233        u8 *a1 = aRec;
180234        assert( op2==SQLITE_UPDATE );
180235        pNew->op = SQLITE_INSERT;
180236        if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
180237        sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
180238      }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
180239        assert( op2==SQLITE_INSERT );
180240        pNew->op = SQLITE_UPDATE;
180241        if( bPatchset ){
180242          memcpy(aCsr, aRec, nRec);
180243          aCsr += nRec;
180244        }else{
180245          if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
180246            sqlite3_free(pNew);
180247            pNew = 0;
180248          }
180249        }
180250      }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
180251        u8 *a1 = aExist;
180252        u8 *a2 = aRec;
180253        assert( op1==SQLITE_UPDATE );
180254        if( bPatchset==0 ){
180255          sessionSkipRecord(&a1, pTab->nCol);
180256          sessionSkipRecord(&a2, pTab->nCol);
180257        }
180258        pNew->op = SQLITE_UPDATE;
180259        if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
180260          sqlite3_free(pNew);
180261          pNew = 0;
180262        }
180263      }else{                                /* UPDATE + DELETE */
180264        assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
180265        pNew->op = SQLITE_DELETE;
180266        if( bPatchset ){
180267          memcpy(aCsr, aRec, nRec);
180268          aCsr += nRec;
180269        }else{
180270          sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
180271        }
180272      }
180273
180274      if( pNew ){
180275        pNew->nRecord = (int)(aCsr - pNew->aRecord);
180276      }
180277      sqlite3_free(pExist);
180278    }
180279  }
180280
180281  *ppNew = pNew;
180282  return SQLITE_OK;
180283}
180284
180285/*
180286** Add all changes in the changeset traversed by the iterator passed as
180287** the first argument to the changegroup hash tables.
180288*/
180289static int sessionChangesetToHash(
180290  sqlite3_changeset_iter *pIter,   /* Iterator to read from */
180291  sqlite3_changegroup *pGrp        /* Changegroup object to add changeset to */
180292){
180293  u8 *aRec;
180294  int nRec;
180295  int rc = SQLITE_OK;
180296  SessionTable *pTab = 0;
180297
180298
180299  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
180300    const char *zNew;
180301    int nCol;
180302    int op;
180303    int iHash;
180304    int bIndirect;
180305    SessionChange *pChange;
180306    SessionChange *pExist = 0;
180307    SessionChange **pp;
180308
180309    if( pGrp->pList==0 ){
180310      pGrp->bPatch = pIter->bPatchset;
180311    }else if( pIter->bPatchset!=pGrp->bPatch ){
180312      rc = SQLITE_ERROR;
180313      break;
180314    }
180315
180316    sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
180317    if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
180318      /* Search the list for a matching table */
180319      int nNew = (int)strlen(zNew);
180320      u8 *abPK;
180321
180322      sqlite3changeset_pk(pIter, &abPK, 0);
180323      for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
180324        if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
180325      }
180326      if( !pTab ){
180327        SessionTable **ppTab;
180328
180329        pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
180330        if( !pTab ){
180331          rc = SQLITE_NOMEM;
180332          break;
180333        }
180334        memset(pTab, 0, sizeof(SessionTable));
180335        pTab->nCol = nCol;
180336        pTab->abPK = (u8*)&pTab[1];
180337        memcpy(pTab->abPK, abPK, nCol);
180338        pTab->zName = (char*)&pTab->abPK[nCol];
180339        memcpy(pTab->zName, zNew, nNew+1);
180340
180341        /* The new object must be linked on to the end of the list, not
180342        ** simply added to the start of it. This is to ensure that the
180343        ** tables within the output of sqlite3changegroup_output() are in
180344        ** the right order.  */
180345        for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
180346        *ppTab = pTab;
180347      }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
180348        rc = SQLITE_SCHEMA;
180349        break;
180350      }
180351    }
180352
180353    if( sessionGrowHash(pIter->bPatchset, pTab) ){
180354      rc = SQLITE_NOMEM;
180355      break;
180356    }
180357    iHash = sessionChangeHash(
180358        pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
180359    );
180360
180361    /* Search for existing entry. If found, remove it from the hash table.
180362    ** Code below may link it back in.
180363    */
180364    for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
180365      int bPkOnly1 = 0;
180366      int bPkOnly2 = 0;
180367      if( pIter->bPatchset ){
180368        bPkOnly1 = (*pp)->op==SQLITE_DELETE;
180369        bPkOnly2 = op==SQLITE_DELETE;
180370      }
180371      if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
180372        pExist = *pp;
180373        *pp = (*pp)->pNext;
180374        pTab->nEntry--;
180375        break;
180376      }
180377    }
180378
180379    rc = sessionChangeMerge(pTab,
180380        pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
180381    );
180382    if( rc ) break;
180383    if( pChange ){
180384      pChange->pNext = pTab->apChange[iHash];
180385      pTab->apChange[iHash] = pChange;
180386      pTab->nEntry++;
180387    }
180388  }
180389
180390  if( rc==SQLITE_OK ) rc = pIter->rc;
180391  return rc;
180392}
180393
180394/*
180395** Serialize a changeset (or patchset) based on all changesets (or patchsets)
180396** added to the changegroup object passed as the first argument.
180397**
180398** If xOutput is not NULL, then the changeset/patchset is returned to the
180399** user via one or more calls to xOutput, as with the other streaming
180400** interfaces.
180401**
180402** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
180403** buffer containing the output changeset before this function returns. In
180404** this case (*pnOut) is set to the size of the output buffer in bytes. It
180405** is the responsibility of the caller to free the output buffer using
180406** sqlite3_free() when it is no longer required.
180407**
180408** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
180409** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
180410** are both set to 0 before returning.
180411*/
180412static int sessionChangegroupOutput(
180413  sqlite3_changegroup *pGrp,
180414  int (*xOutput)(void *pOut, const void *pData, int nData),
180415  void *pOut,
180416  int *pnOut,
180417  void **ppOut
180418){
180419  int rc = SQLITE_OK;
180420  SessionBuffer buf = {0, 0, 0};
180421  SessionTable *pTab;
180422  assert( xOutput==0 || (ppOut==0 && pnOut==0) );
180423
180424  /* Create the serialized output changeset based on the contents of the
180425  ** hash tables attached to the SessionTable objects in list p->pList.
180426  */
180427  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
180428    int i;
180429    if( pTab->nEntry==0 ) continue;
180430
180431    sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
180432    for(i=0; i<pTab->nChange; i++){
180433      SessionChange *p;
180434      for(p=pTab->apChange[i]; p; p=p->pNext){
180435        sessionAppendByte(&buf, p->op, &rc);
180436        sessionAppendByte(&buf, p->bIndirect, &rc);
180437        sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
180438      }
180439    }
180440
180441    if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
180442      rc = xOutput(pOut, buf.aBuf, buf.nBuf);
180443      buf.nBuf = 0;
180444    }
180445  }
180446
180447  if( rc==SQLITE_OK ){
180448    if( xOutput ){
180449      if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
180450    }else{
180451      *ppOut = buf.aBuf;
180452      *pnOut = buf.nBuf;
180453      buf.aBuf = 0;
180454    }
180455  }
180456  sqlite3_free(buf.aBuf);
180457
180458  return rc;
180459}
180460
180461/*
180462** Allocate a new, empty, sqlite3_changegroup.
180463*/
180464SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
180465  int rc = SQLITE_OK;             /* Return code */
180466  sqlite3_changegroup *p;         /* New object */
180467  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
180468  if( p==0 ){
180469    rc = SQLITE_NOMEM;
180470  }else{
180471    memset(p, 0, sizeof(sqlite3_changegroup));
180472  }
180473  *pp = p;
180474  return rc;
180475}
180476
180477/*
180478** Add the changeset currently stored in buffer pData, size nData bytes,
180479** to changeset-group p.
180480*/
180481SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
180482  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
180483  int rc;                         /* Return code */
180484
180485  rc = sqlite3changeset_start(&pIter, nData, pData);
180486  if( rc==SQLITE_OK ){
180487    rc = sessionChangesetToHash(pIter, pGrp);
180488  }
180489  sqlite3changeset_finalize(pIter);
180490  return rc;
180491}
180492
180493/*
180494** Obtain a buffer containing a changeset representing the concatenation
180495** of all changesets added to the group so far.
180496*/
180497SQLITE_API int sqlite3changegroup_output(
180498    sqlite3_changegroup *pGrp,
180499    int *pnData,
180500    void **ppData
180501){
180502  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
180503}
180504
180505/*
180506** Streaming versions of changegroup_add().
180507*/
180508SQLITE_API int sqlite3changegroup_add_strm(
180509  sqlite3_changegroup *pGrp,
180510  int (*xInput)(void *pIn, void *pData, int *pnData),
180511  void *pIn
180512){
180513  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
180514  int rc;                         /* Return code */
180515
180516  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
180517  if( rc==SQLITE_OK ){
180518    rc = sessionChangesetToHash(pIter, pGrp);
180519  }
180520  sqlite3changeset_finalize(pIter);
180521  return rc;
180522}
180523
180524/*
180525** Streaming versions of changegroup_output().
180526*/
180527SQLITE_API int sqlite3changegroup_output_strm(
180528  sqlite3_changegroup *pGrp,
180529  int (*xOutput)(void *pOut, const void *pData, int nData),
180530  void *pOut
180531){
180532  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
180533}
180534
180535/*
180536** Delete a changegroup object.
180537*/
180538SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
180539  if( pGrp ){
180540    sessionDeleteTable(pGrp->pList);
180541    sqlite3_free(pGrp);
180542  }
180543}
180544
180545/*
180546** Combine two changesets together.
180547*/
180548SQLITE_API int sqlite3changeset_concat(
180549  int nLeft,                      /* Number of bytes in lhs input */
180550  void *pLeft,                    /* Lhs input changeset */
180551  int nRight                      /* Number of bytes in rhs input */,
180552  void *pRight,                   /* Rhs input changeset */
180553  int *pnOut,                     /* OUT: Number of bytes in output changeset */
180554  void **ppOut                    /* OUT: changeset (left <concat> right) */
180555){
180556  sqlite3_changegroup *pGrp;
180557  int rc;
180558
180559  rc = sqlite3changegroup_new(&pGrp);
180560  if( rc==SQLITE_OK ){
180561    rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
180562  }
180563  if( rc==SQLITE_OK ){
180564    rc = sqlite3changegroup_add(pGrp, nRight, pRight);
180565  }
180566  if( rc==SQLITE_OK ){
180567    rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
180568  }
180569  sqlite3changegroup_delete(pGrp);
180570
180571  return rc;
180572}
180573
180574/*
180575** Streaming version of sqlite3changeset_concat().
180576*/
180577SQLITE_API int sqlite3changeset_concat_strm(
180578  int (*xInputA)(void *pIn, void *pData, int *pnData),
180579  void *pInA,
180580  int (*xInputB)(void *pIn, void *pData, int *pnData),
180581  void *pInB,
180582  int (*xOutput)(void *pOut, const void *pData, int nData),
180583  void *pOut
180584){
180585  sqlite3_changegroup *pGrp;
180586  int rc;
180587
180588  rc = sqlite3changegroup_new(&pGrp);
180589  if( rc==SQLITE_OK ){
180590    rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
180591  }
180592  if( rc==SQLITE_OK ){
180593    rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
180594  }
180595  if( rc==SQLITE_OK ){
180596    rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
180597  }
180598  sqlite3changegroup_delete(pGrp);
180599
180600  return rc;
180601}
180602
180603#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
180604
180605/************** End of sqlite3session.c **************************************/
180606/************** Begin file json1.c *******************************************/
180607/*
180608** 2015-08-12
180609**
180610** The author disclaims copyright to this source code.  In place of
180611** a legal notice, here is a blessing:
180612**
180613**    May you do good and not evil.
180614**    May you find forgiveness for yourself and forgive others.
180615**    May you share freely, never taking more than you give.
180616**
180617******************************************************************************
180618**
180619** This SQLite extension implements JSON functions.  The interface is
180620** modeled after MySQL JSON functions:
180621**
180622**     https://dev.mysql.com/doc/refman/5.7/en/json.html
180623**
180624** For the time being, all JSON is stored as pure text.  (We might add
180625** a JSONB type in the future which stores a binary encoding of JSON in
180626** a BLOB, but there is no support for JSONB in the current implementation.
180627** This implementation parses JSON text at 250 MB/s, so it is hard to see
180628** how JSONB might improve on that.)
180629*/
180630#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
180631#if !defined(SQLITEINT_H)
180632/* #include "sqlite3ext.h" */
180633#endif
180634SQLITE_EXTENSION_INIT1
180635/* #include <assert.h> */
180636/* #include <string.h> */
180637/* #include <stdlib.h> */
180638/* #include <stdarg.h> */
180639
180640/* Mark a function parameter as unused, to suppress nuisance compiler
180641** warnings. */
180642#ifndef UNUSED_PARAM
180643# define UNUSED_PARAM(X)  (void)(X)
180644#endif
180645
180646#ifndef LARGEST_INT64
180647# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
180648# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
180649#endif
180650
180651/*
180652** Versions of isspace(), isalnum() and isdigit() to which it is safe
180653** to pass signed char values.
180654*/
180655#ifdef sqlite3Isdigit
180656   /* Use the SQLite core versions if this routine is part of the
180657   ** SQLite amalgamation */
180658#  define safe_isdigit(x)  sqlite3Isdigit(x)
180659#  define safe_isalnum(x)  sqlite3Isalnum(x)
180660#  define safe_isxdigit(x) sqlite3Isxdigit(x)
180661#else
180662   /* Use the standard library for separate compilation */
180663#include <ctype.h>  /* amalgamator: keep */
180664#  define safe_isdigit(x)  isdigit((unsigned char)(x))
180665#  define safe_isalnum(x)  isalnum((unsigned char)(x))
180666#  define safe_isxdigit(x) isxdigit((unsigned char)(x))
180667#endif
180668
180669/*
180670** Growing our own isspace() routine this way is twice as fast as
180671** the library isspace() function, resulting in a 7% overall performance
180672** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
180673*/
180674static const char jsonIsSpace[] = {
180675  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
180676  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180677  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180678  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180679  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180680  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180681  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180682  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180683  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180684  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180685  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180686  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180687  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180688  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180689  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180690  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
180691};
180692#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
180693
180694#ifndef SQLITE_AMALGAMATION
180695  /* Unsigned integer types.  These are already defined in the sqliteInt.h,
180696  ** but the definitions need to be repeated for separate compilation. */
180697  typedef sqlite3_uint64 u64;
180698  typedef unsigned int u32;
180699  typedef unsigned short int u16;
180700  typedef unsigned char u8;
180701#endif
180702
180703/* Objects */
180704typedef struct JsonString JsonString;
180705typedef struct JsonNode JsonNode;
180706typedef struct JsonParse JsonParse;
180707
180708/* An instance of this object represents a JSON string
180709** under construction.  Really, this is a generic string accumulator
180710** that can be and is used to create strings other than JSON.
180711*/
180712struct JsonString {
180713  sqlite3_context *pCtx;   /* Function context - put error messages here */
180714  char *zBuf;              /* Append JSON content here */
180715  u64 nAlloc;              /* Bytes of storage available in zBuf[] */
180716  u64 nUsed;               /* Bytes of zBuf[] currently used */
180717  u8 bStatic;              /* True if zBuf is static space */
180718  u8 bErr;                 /* True if an error has been encountered */
180719  char zSpace[100];        /* Initial static space */
180720};
180721
180722/* JSON type values
180723*/
180724#define JSON_NULL     0
180725#define JSON_TRUE     1
180726#define JSON_FALSE    2
180727#define JSON_INT      3
180728#define JSON_REAL     4
180729#define JSON_STRING   5
180730#define JSON_ARRAY    6
180731#define JSON_OBJECT   7
180732
180733/* The "subtype" set for JSON values */
180734#define JSON_SUBTYPE  74    /* Ascii for "J" */
180735
180736/*
180737** Names of the various JSON types:
180738*/
180739static const char * const jsonType[] = {
180740  "null", "true", "false", "integer", "real", "text", "array", "object"
180741};
180742
180743/* Bit values for the JsonNode.jnFlag field
180744*/
180745#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
180746#define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
180747#define JNODE_REMOVE  0x04         /* Do not output */
180748#define JNODE_REPLACE 0x08         /* Replace with JsonNode.u.iReplace */
180749#define JNODE_PATCH   0x10         /* Patch with JsonNode.u.pPatch */
180750#define JNODE_APPEND  0x20         /* More ARRAY/OBJECT entries at u.iAppend */
180751#define JNODE_LABEL   0x40         /* Is a label of an object */
180752
180753
180754/* A single node of parsed JSON
180755*/
180756struct JsonNode {
180757  u8 eType;              /* One of the JSON_ type values */
180758  u8 jnFlags;            /* JNODE flags */
180759  u32 n;                 /* Bytes of content, or number of sub-nodes */
180760  union {
180761    const char *zJContent; /* Content for INT, REAL, and STRING */
180762    u32 iAppend;           /* More terms for ARRAY and OBJECT */
180763    u32 iKey;              /* Key for ARRAY objects in json_tree() */
180764    u32 iReplace;          /* Replacement content for JNODE_REPLACE */
180765    JsonNode *pPatch;      /* Node chain of patch for JNODE_PATCH */
180766  } u;
180767};
180768
180769/* A completely parsed JSON string
180770*/
180771struct JsonParse {
180772  u32 nNode;         /* Number of slots of aNode[] used */
180773  u32 nAlloc;        /* Number of slots of aNode[] allocated */
180774  JsonNode *aNode;   /* Array of nodes containing the parse */
180775  const char *zJson; /* Original JSON string */
180776  u32 *aUp;          /* Index of parent of each node */
180777  u8 oom;            /* Set to true if out of memory */
180778  u8 nErr;           /* Number of errors seen */
180779  u16 iDepth;        /* Nesting depth */
180780  int nJson;         /* Length of the zJson string in bytes */
180781};
180782
180783/*
180784** Maximum nesting depth of JSON for this implementation.
180785**
180786** This limit is needed to avoid a stack overflow in the recursive
180787** descent parser.  A depth of 2000 is far deeper than any sane JSON
180788** should go.
180789*/
180790#define JSON_MAX_DEPTH  2000
180791
180792/**************************************************************************
180793** Utility routines for dealing with JsonString objects
180794**************************************************************************/
180795
180796/* Set the JsonString object to an empty string
180797*/
180798static void jsonZero(JsonString *p){
180799  p->zBuf = p->zSpace;
180800  p->nAlloc = sizeof(p->zSpace);
180801  p->nUsed = 0;
180802  p->bStatic = 1;
180803}
180804
180805/* Initialize the JsonString object
180806*/
180807static void jsonInit(JsonString *p, sqlite3_context *pCtx){
180808  p->pCtx = pCtx;
180809  p->bErr = 0;
180810  jsonZero(p);
180811}
180812
180813
180814/* Free all allocated memory and reset the JsonString object back to its
180815** initial state.
180816*/
180817static void jsonReset(JsonString *p){
180818  if( !p->bStatic ) sqlite3_free(p->zBuf);
180819  jsonZero(p);
180820}
180821
180822
180823/* Report an out-of-memory (OOM) condition
180824*/
180825static void jsonOom(JsonString *p){
180826  p->bErr = 1;
180827  sqlite3_result_error_nomem(p->pCtx);
180828  jsonReset(p);
180829}
180830
180831/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
180832** Return zero on success.  Return non-zero on an OOM error
180833*/
180834static int jsonGrow(JsonString *p, u32 N){
180835  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
180836  char *zNew;
180837  if( p->bStatic ){
180838    if( p->bErr ) return 1;
180839    zNew = sqlite3_malloc64(nTotal);
180840    if( zNew==0 ){
180841      jsonOom(p);
180842      return SQLITE_NOMEM;
180843    }
180844    memcpy(zNew, p->zBuf, (size_t)p->nUsed);
180845    p->zBuf = zNew;
180846    p->bStatic = 0;
180847  }else{
180848    zNew = sqlite3_realloc64(p->zBuf, nTotal);
180849    if( zNew==0 ){
180850      jsonOom(p);
180851      return SQLITE_NOMEM;
180852    }
180853    p->zBuf = zNew;
180854  }
180855  p->nAlloc = nTotal;
180856  return SQLITE_OK;
180857}
180858
180859/* Append N bytes from zIn onto the end of the JsonString string.
180860*/
180861static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
180862  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
180863  memcpy(p->zBuf+p->nUsed, zIn, N);
180864  p->nUsed += N;
180865}
180866
180867/* Append formatted text (not to exceed N bytes) to the JsonString.
180868*/
180869static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
180870  va_list ap;
180871  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
180872  va_start(ap, zFormat);
180873  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
180874  va_end(ap);
180875  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
180876}
180877
180878/* Append a single character
180879*/
180880static void jsonAppendChar(JsonString *p, char c){
180881  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
180882  p->zBuf[p->nUsed++] = c;
180883}
180884
180885/* Append a comma separator to the output buffer, if the previous
180886** character is not '[' or '{'.
180887*/
180888static void jsonAppendSeparator(JsonString *p){
180889  char c;
180890  if( p->nUsed==0 ) return;
180891  c = p->zBuf[p->nUsed-1];
180892  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
180893}
180894
180895/* Append the N-byte string in zIn to the end of the JsonString string
180896** under construction.  Enclose the string in "..." and escape
180897** any double-quotes or backslash characters contained within the
180898** string.
180899*/
180900static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
180901  u32 i;
180902  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
180903  p->zBuf[p->nUsed++] = '"';
180904  for(i=0; i<N; i++){
180905    unsigned char c = ((unsigned const char*)zIn)[i];
180906    if( c=='"' || c=='\\' ){
180907      json_simple_escape:
180908      if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
180909      p->zBuf[p->nUsed++] = '\\';
180910    }else if( c<=0x1f ){
180911      static const char aSpecial[] = {
180912         0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
180913         0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
180914      };
180915      assert( sizeof(aSpecial)==32 );
180916      assert( aSpecial['\b']=='b' );
180917      assert( aSpecial['\f']=='f' );
180918      assert( aSpecial['\n']=='n' );
180919      assert( aSpecial['\r']=='r' );
180920      assert( aSpecial['\t']=='t' );
180921      if( aSpecial[c] ){
180922        c = aSpecial[c];
180923        goto json_simple_escape;
180924      }
180925      if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
180926      p->zBuf[p->nUsed++] = '\\';
180927      p->zBuf[p->nUsed++] = 'u';
180928      p->zBuf[p->nUsed++] = '0';
180929      p->zBuf[p->nUsed++] = '0';
180930      p->zBuf[p->nUsed++] = '0' + (c>>4);
180931      c = "0123456789abcdef"[c&0xf];
180932    }
180933    p->zBuf[p->nUsed++] = c;
180934  }
180935  p->zBuf[p->nUsed++] = '"';
180936  assert( p->nUsed<p->nAlloc );
180937}
180938
180939/*
180940** Append a function parameter value to the JSON string under
180941** construction.
180942*/
180943static void jsonAppendValue(
180944  JsonString *p,                 /* Append to this JSON string */
180945  sqlite3_value *pValue          /* Value to append */
180946){
180947  switch( sqlite3_value_type(pValue) ){
180948    case SQLITE_NULL: {
180949      jsonAppendRaw(p, "null", 4);
180950      break;
180951    }
180952    case SQLITE_INTEGER:
180953    case SQLITE_FLOAT: {
180954      const char *z = (const char*)sqlite3_value_text(pValue);
180955      u32 n = (u32)sqlite3_value_bytes(pValue);
180956      jsonAppendRaw(p, z, n);
180957      break;
180958    }
180959    case SQLITE_TEXT: {
180960      const char *z = (const char*)sqlite3_value_text(pValue);
180961      u32 n = (u32)sqlite3_value_bytes(pValue);
180962      if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
180963        jsonAppendRaw(p, z, n);
180964      }else{
180965        jsonAppendString(p, z, n);
180966      }
180967      break;
180968    }
180969    default: {
180970      if( p->bErr==0 ){
180971        sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
180972        p->bErr = 2;
180973        jsonReset(p);
180974      }
180975      break;
180976    }
180977  }
180978}
180979
180980
180981/* Make the JSON in p the result of the SQL function.
180982*/
180983static void jsonResult(JsonString *p){
180984  if( p->bErr==0 ){
180985    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
180986                          p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
180987                          SQLITE_UTF8);
180988    jsonZero(p);
180989  }
180990  assert( p->bStatic );
180991}
180992
180993/**************************************************************************
180994** Utility routines for dealing with JsonNode and JsonParse objects
180995**************************************************************************/
180996
180997/*
180998** Return the number of consecutive JsonNode slots need to represent
180999** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
181000** OBJECT types, the number might be larger.
181001**
181002** Appended elements are not counted.  The value returned is the number
181003** by which the JsonNode counter should increment in order to go to the
181004** next peer value.
181005*/
181006static u32 jsonNodeSize(JsonNode *pNode){
181007  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
181008}
181009
181010/*
181011** Reclaim all memory allocated by a JsonParse object.  But do not
181012** delete the JsonParse object itself.
181013*/
181014static void jsonParseReset(JsonParse *pParse){
181015  sqlite3_free(pParse->aNode);
181016  pParse->aNode = 0;
181017  pParse->nNode = 0;
181018  pParse->nAlloc = 0;
181019  sqlite3_free(pParse->aUp);
181020  pParse->aUp = 0;
181021}
181022
181023/*
181024** Free a JsonParse object that was obtained from sqlite3_malloc().
181025*/
181026static void jsonParseFree(JsonParse *pParse){
181027  jsonParseReset(pParse);
181028  sqlite3_free(pParse);
181029}
181030
181031/*
181032** Convert the JsonNode pNode into a pure JSON string and
181033** append to pOut.  Subsubstructure is also included.  Return
181034** the number of JsonNode objects that are encoded.
181035*/
181036static void jsonRenderNode(
181037  JsonNode *pNode,               /* The node to render */
181038  JsonString *pOut,              /* Write JSON here */
181039  sqlite3_value **aReplace       /* Replacement values */
181040){
181041  if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
181042    if( pNode->jnFlags & JNODE_REPLACE ){
181043      jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
181044      return;
181045    }
181046    pNode = pNode->u.pPatch;
181047  }
181048  switch( pNode->eType ){
181049    default: {
181050      assert( pNode->eType==JSON_NULL );
181051      jsonAppendRaw(pOut, "null", 4);
181052      break;
181053    }
181054    case JSON_TRUE: {
181055      jsonAppendRaw(pOut, "true", 4);
181056      break;
181057    }
181058    case JSON_FALSE: {
181059      jsonAppendRaw(pOut, "false", 5);
181060      break;
181061    }
181062    case JSON_STRING: {
181063      if( pNode->jnFlags & JNODE_RAW ){
181064        jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
181065        break;
181066      }
181067      /* Fall through into the next case */
181068    }
181069    case JSON_REAL:
181070    case JSON_INT: {
181071      jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
181072      break;
181073    }
181074    case JSON_ARRAY: {
181075      u32 j = 1;
181076      jsonAppendChar(pOut, '[');
181077      for(;;){
181078        while( j<=pNode->n ){
181079          if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
181080            jsonAppendSeparator(pOut);
181081            jsonRenderNode(&pNode[j], pOut, aReplace);
181082          }
181083          j += jsonNodeSize(&pNode[j]);
181084        }
181085        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
181086        pNode = &pNode[pNode->u.iAppend];
181087        j = 1;
181088      }
181089      jsonAppendChar(pOut, ']');
181090      break;
181091    }
181092    case JSON_OBJECT: {
181093      u32 j = 1;
181094      jsonAppendChar(pOut, '{');
181095      for(;;){
181096        while( j<=pNode->n ){
181097          if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
181098            jsonAppendSeparator(pOut);
181099            jsonRenderNode(&pNode[j], pOut, aReplace);
181100            jsonAppendChar(pOut, ':');
181101            jsonRenderNode(&pNode[j+1], pOut, aReplace);
181102          }
181103          j += 1 + jsonNodeSize(&pNode[j+1]);
181104        }
181105        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
181106        pNode = &pNode[pNode->u.iAppend];
181107        j = 1;
181108      }
181109      jsonAppendChar(pOut, '}');
181110      break;
181111    }
181112  }
181113}
181114
181115/*
181116** Return a JsonNode and all its descendents as a JSON string.
181117*/
181118static void jsonReturnJson(
181119  JsonNode *pNode,            /* Node to return */
181120  sqlite3_context *pCtx,      /* Return value for this function */
181121  sqlite3_value **aReplace    /* Array of replacement values */
181122){
181123  JsonString s;
181124  jsonInit(&s, pCtx);
181125  jsonRenderNode(pNode, &s, aReplace);
181126  jsonResult(&s);
181127  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
181128}
181129
181130/*
181131** Make the JsonNode the return value of the function.
181132*/
181133static void jsonReturn(
181134  JsonNode *pNode,            /* Node to return */
181135  sqlite3_context *pCtx,      /* Return value for this function */
181136  sqlite3_value **aReplace    /* Array of replacement values */
181137){
181138  switch( pNode->eType ){
181139    default: {
181140      assert( pNode->eType==JSON_NULL );
181141      sqlite3_result_null(pCtx);
181142      break;
181143    }
181144    case JSON_TRUE: {
181145      sqlite3_result_int(pCtx, 1);
181146      break;
181147    }
181148    case JSON_FALSE: {
181149      sqlite3_result_int(pCtx, 0);
181150      break;
181151    }
181152    case JSON_INT: {
181153      sqlite3_int64 i = 0;
181154      const char *z = pNode->u.zJContent;
181155      if( z[0]=='-' ){ z++; }
181156      while( z[0]>='0' && z[0]<='9' ){
181157        unsigned v = *(z++) - '0';
181158        if( i>=LARGEST_INT64/10 ){
181159          if( i>LARGEST_INT64/10 ) goto int_as_real;
181160          if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
181161          if( v==9 ) goto int_as_real;
181162          if( v==8 ){
181163            if( pNode->u.zJContent[0]=='-' ){
181164              sqlite3_result_int64(pCtx, SMALLEST_INT64);
181165              goto int_done;
181166            }else{
181167              goto int_as_real;
181168            }
181169          }
181170        }
181171        i = i*10 + v;
181172      }
181173      if( pNode->u.zJContent[0]=='-' ){ i = -i; }
181174      sqlite3_result_int64(pCtx, i);
181175      int_done:
181176      break;
181177      int_as_real: /* fall through to real */;
181178    }
181179    case JSON_REAL: {
181180      double r;
181181#ifdef SQLITE_AMALGAMATION
181182      const char *z = pNode->u.zJContent;
181183      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
181184#else
181185      r = strtod(pNode->u.zJContent, 0);
181186#endif
181187      sqlite3_result_double(pCtx, r);
181188      break;
181189    }
181190    case JSON_STRING: {
181191#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
181192      ** json_insert() and json_replace() and those routines do not
181193      ** call jsonReturn() */
181194      if( pNode->jnFlags & JNODE_RAW ){
181195        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
181196                            SQLITE_TRANSIENT);
181197      }else
181198#endif
181199      assert( (pNode->jnFlags & JNODE_RAW)==0 );
181200      if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
181201        /* JSON formatted without any backslash-escapes */
181202        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
181203                            SQLITE_TRANSIENT);
181204      }else{
181205        /* Translate JSON formatted string into raw text */
181206        u32 i;
181207        u32 n = pNode->n;
181208        const char *z = pNode->u.zJContent;
181209        char *zOut;
181210        u32 j;
181211        zOut = sqlite3_malloc( n+1 );
181212        if( zOut==0 ){
181213          sqlite3_result_error_nomem(pCtx);
181214          break;
181215        }
181216        for(i=1, j=0; i<n-1; i++){
181217          char c = z[i];
181218          if( c!='\\' ){
181219            zOut[j++] = c;
181220          }else{
181221            c = z[++i];
181222            if( c=='u' ){
181223              u32 v = 0, k;
181224              for(k=0; k<4; i++, k++){
181225                assert( i<n-2 );
181226                c = z[i+1];
181227                assert( safe_isxdigit(c) );
181228                if( c<='9' ) v = v*16 + c - '0';
181229                else if( c<='F' ) v = v*16 + c - 'A' + 10;
181230                else v = v*16 + c - 'a' + 10;
181231              }
181232              if( v==0 ) break;
181233              if( v<=0x7f ){
181234                zOut[j++] = (char)v;
181235              }else if( v<=0x7ff ){
181236                zOut[j++] = (char)(0xc0 | (v>>6));
181237                zOut[j++] = 0x80 | (v&0x3f);
181238              }else{
181239                zOut[j++] = (char)(0xe0 | (v>>12));
181240                zOut[j++] = 0x80 | ((v>>6)&0x3f);
181241                zOut[j++] = 0x80 | (v&0x3f);
181242              }
181243            }else{
181244              if( c=='b' ){
181245                c = '\b';
181246              }else if( c=='f' ){
181247                c = '\f';
181248              }else if( c=='n' ){
181249                c = '\n';
181250              }else if( c=='r' ){
181251                c = '\r';
181252              }else if( c=='t' ){
181253                c = '\t';
181254              }
181255              zOut[j++] = c;
181256            }
181257          }
181258        }
181259        zOut[j] = 0;
181260        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
181261      }
181262      break;
181263    }
181264    case JSON_ARRAY:
181265    case JSON_OBJECT: {
181266      jsonReturnJson(pNode, pCtx, aReplace);
181267      break;
181268    }
181269  }
181270}
181271
181272/* Forward reference */
181273static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
181274
181275/*
181276** A macro to hint to the compiler that a function should not be
181277** inlined.
181278*/
181279#if defined(__GNUC__)
181280#  define JSON_NOINLINE  __attribute__((noinline))
181281#elif defined(_MSC_VER) && _MSC_VER>=1310
181282#  define JSON_NOINLINE  __declspec(noinline)
181283#else
181284#  define JSON_NOINLINE
181285#endif
181286
181287
181288static JSON_NOINLINE int jsonParseAddNodeExpand(
181289  JsonParse *pParse,        /* Append the node to this object */
181290  u32 eType,                /* Node type */
181291  u32 n,                    /* Content size or sub-node count */
181292  const char *zContent      /* Content */
181293){
181294  u32 nNew;
181295  JsonNode *pNew;
181296  assert( pParse->nNode>=pParse->nAlloc );
181297  if( pParse->oom ) return -1;
181298  nNew = pParse->nAlloc*2 + 10;
181299  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
181300  if( pNew==0 ){
181301    pParse->oom = 1;
181302    return -1;
181303  }
181304  pParse->nAlloc = nNew;
181305  pParse->aNode = pNew;
181306  assert( pParse->nNode<pParse->nAlloc );
181307  return jsonParseAddNode(pParse, eType, n, zContent);
181308}
181309
181310/*
181311** Create a new JsonNode instance based on the arguments and append that
181312** instance to the JsonParse.  Return the index in pParse->aNode[] of the
181313** new node, or -1 if a memory allocation fails.
181314*/
181315static int jsonParseAddNode(
181316  JsonParse *pParse,        /* Append the node to this object */
181317  u32 eType,                /* Node type */
181318  u32 n,                    /* Content size or sub-node count */
181319  const char *zContent      /* Content */
181320){
181321  JsonNode *p;
181322  if( pParse->nNode>=pParse->nAlloc ){
181323    return jsonParseAddNodeExpand(pParse, eType, n, zContent);
181324  }
181325  p = &pParse->aNode[pParse->nNode];
181326  p->eType = (u8)eType;
181327  p->jnFlags = 0;
181328  p->n = n;
181329  p->u.zJContent = zContent;
181330  return pParse->nNode++;
181331}
181332
181333/*
181334** Return true if z[] begins with 4 (or more) hexadecimal digits
181335*/
181336static int jsonIs4Hex(const char *z){
181337  int i;
181338  for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
181339  return 1;
181340}
181341
181342/*
181343** Parse a single JSON value which begins at pParse->zJson[i].  Return the
181344** index of the first character past the end of the value parsed.
181345**
181346** Return negative for a syntax error.  Special cases:  return -2 if the
181347** first non-whitespace character is '}' and return -3 if the first
181348** non-whitespace character is ']'.
181349*/
181350static int jsonParseValue(JsonParse *pParse, u32 i){
181351  char c;
181352  u32 j;
181353  int iThis;
181354  int x;
181355  JsonNode *pNode;
181356  const char *z = pParse->zJson;
181357  while( safe_isspace(z[i]) ){ i++; }
181358  if( (c = z[i])=='{' ){
181359    /* Parse object */
181360    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
181361    if( iThis<0 ) return -1;
181362    for(j=i+1;;j++){
181363      while( safe_isspace(z[j]) ){ j++; }
181364      if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
181365      x = jsonParseValue(pParse, j);
181366      if( x<0 ){
181367        pParse->iDepth--;
181368        if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
181369        return -1;
181370      }
181371      if( pParse->oom ) return -1;
181372      pNode = &pParse->aNode[pParse->nNode-1];
181373      if( pNode->eType!=JSON_STRING ) return -1;
181374      pNode->jnFlags |= JNODE_LABEL;
181375      j = x;
181376      while( safe_isspace(z[j]) ){ j++; }
181377      if( z[j]!=':' ) return -1;
181378      j++;
181379      x = jsonParseValue(pParse, j);
181380      pParse->iDepth--;
181381      if( x<0 ) return -1;
181382      j = x;
181383      while( safe_isspace(z[j]) ){ j++; }
181384      c = z[j];
181385      if( c==',' ) continue;
181386      if( c!='}' ) return -1;
181387      break;
181388    }
181389    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
181390    return j+1;
181391  }else if( c=='[' ){
181392    /* Parse array */
181393    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
181394    if( iThis<0 ) return -1;
181395    for(j=i+1;;j++){
181396      while( safe_isspace(z[j]) ){ j++; }
181397      if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
181398      x = jsonParseValue(pParse, j);
181399      pParse->iDepth--;
181400      if( x<0 ){
181401        if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
181402        return -1;
181403      }
181404      j = x;
181405      while( safe_isspace(z[j]) ){ j++; }
181406      c = z[j];
181407      if( c==',' ) continue;
181408      if( c!=']' ) return -1;
181409      break;
181410    }
181411    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
181412    return j+1;
181413  }else if( c=='"' ){
181414    /* Parse string */
181415    u8 jnFlags = 0;
181416    j = i+1;
181417    for(;;){
181418      c = z[j];
181419      if( (c & ~0x1f)==0 ){
181420        /* Control characters are not allowed in strings */
181421        return -1;
181422      }
181423      if( c=='\\' ){
181424        c = z[++j];
181425        if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
181426           || c=='n' || c=='r' || c=='t'
181427           || (c=='u' && jsonIs4Hex(z+j+1)) ){
181428          jnFlags = JNODE_ESCAPE;
181429        }else{
181430          return -1;
181431        }
181432      }else if( c=='"' ){
181433        break;
181434      }
181435      j++;
181436    }
181437    jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
181438    if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
181439    return j+1;
181440  }else if( c=='n'
181441         && strncmp(z+i,"null",4)==0
181442         && !safe_isalnum(z[i+4]) ){
181443    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
181444    return i+4;
181445  }else if( c=='t'
181446         && strncmp(z+i,"true",4)==0
181447         && !safe_isalnum(z[i+4]) ){
181448    jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
181449    return i+4;
181450  }else if( c=='f'
181451         && strncmp(z+i,"false",5)==0
181452         && !safe_isalnum(z[i+5]) ){
181453    jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
181454    return i+5;
181455  }else if( c=='-' || (c>='0' && c<='9') ){
181456    /* Parse number */
181457    u8 seenDP = 0;
181458    u8 seenE = 0;
181459    assert( '-' < '0' );
181460    if( c<='0' ){
181461      j = c=='-' ? i+1 : i;
181462      if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
181463    }
181464    j = i+1;
181465    for(;; j++){
181466      c = z[j];
181467      if( c>='0' && c<='9' ) continue;
181468      if( c=='.' ){
181469        if( z[j-1]=='-' ) return -1;
181470        if( seenDP ) return -1;
181471        seenDP = 1;
181472        continue;
181473      }
181474      if( c=='e' || c=='E' ){
181475        if( z[j-1]<'0' ) return -1;
181476        if( seenE ) return -1;
181477        seenDP = seenE = 1;
181478        c = z[j+1];
181479        if( c=='+' || c=='-' ){
181480          j++;
181481          c = z[j+1];
181482        }
181483        if( c<'0' || c>'9' ) return -1;
181484        continue;
181485      }
181486      break;
181487    }
181488    if( z[j-1]<'0' ) return -1;
181489    jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
181490                        j - i, &z[i]);
181491    return j;
181492  }else if( c=='}' ){
181493    return -2;  /* End of {...} */
181494  }else if( c==']' ){
181495    return -3;  /* End of [...] */
181496  }else if( c==0 ){
181497    return 0;   /* End of file */
181498  }else{
181499    return -1;  /* Syntax error */
181500  }
181501}
181502
181503/*
181504** Parse a complete JSON string.  Return 0 on success or non-zero if there
181505** are any errors.  If an error occurs, free all memory associated with
181506** pParse.
181507**
181508** pParse is uninitialized when this routine is called.
181509*/
181510static int jsonParse(
181511  JsonParse *pParse,           /* Initialize and fill this JsonParse object */
181512  sqlite3_context *pCtx,       /* Report errors here */
181513  const char *zJson            /* Input JSON text to be parsed */
181514){
181515  int i;
181516  memset(pParse, 0, sizeof(*pParse));
181517  if( zJson==0 ) return 1;
181518  pParse->zJson = zJson;
181519  i = jsonParseValue(pParse, 0);
181520  if( pParse->oom ) i = -1;
181521  if( i>0 ){
181522    assert( pParse->iDepth==0 );
181523    while( safe_isspace(zJson[i]) ) i++;
181524    if( zJson[i] ) i = -1;
181525  }
181526  if( i<=0 ){
181527    if( pCtx!=0 ){
181528      if( pParse->oom ){
181529        sqlite3_result_error_nomem(pCtx);
181530      }else{
181531        sqlite3_result_error(pCtx, "malformed JSON", -1);
181532      }
181533    }
181534    jsonParseReset(pParse);
181535    return 1;
181536  }
181537  return 0;
181538}
181539
181540/* Mark node i of pParse as being a child of iParent.  Call recursively
181541** to fill in all the descendants of node i.
181542*/
181543static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
181544  JsonNode *pNode = &pParse->aNode[i];
181545  u32 j;
181546  pParse->aUp[i] = iParent;
181547  switch( pNode->eType ){
181548    case JSON_ARRAY: {
181549      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
181550        jsonParseFillInParentage(pParse, i+j, i);
181551      }
181552      break;
181553    }
181554    case JSON_OBJECT: {
181555      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
181556        pParse->aUp[i+j] = i;
181557        jsonParseFillInParentage(pParse, i+j+1, i);
181558      }
181559      break;
181560    }
181561    default: {
181562      break;
181563    }
181564  }
181565}
181566
181567/*
181568** Compute the parentage of all nodes in a completed parse.
181569*/
181570static int jsonParseFindParents(JsonParse *pParse){
181571  u32 *aUp;
181572  assert( pParse->aUp==0 );
181573  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
181574  if( aUp==0 ){
181575    pParse->oom = 1;
181576    return SQLITE_NOMEM;
181577  }
181578  jsonParseFillInParentage(pParse, 0, 0);
181579  return SQLITE_OK;
181580}
181581
181582/*
181583** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
181584*/
181585#define JSON_CACHE_ID  (-429938)
181586
181587/*
181588** Obtain a complete parse of the JSON found in the first argument
181589** of the argv array.  Use the sqlite3_get_auxdata() cache for this
181590** parse if it is available.  If the cache is not available or if it
181591** is no longer valid, parse the JSON again and return the new parse,
181592** and also register the new parse so that it will be available for
181593** future sqlite3_get_auxdata() calls.
181594*/
181595static JsonParse *jsonParseCached(
181596  sqlite3_context *pCtx,
181597  sqlite3_value **argv
181598){
181599  const char *zJson = (const char*)sqlite3_value_text(argv[0]);
181600  int nJson = sqlite3_value_bytes(argv[0]);
181601  JsonParse *p;
181602  if( zJson==0 ) return 0;
181603  p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
181604  if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
181605    p->nErr = 0;
181606    return p; /* The cached entry matches, so return it */
181607  }
181608  p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
181609  if( p==0 ){
181610    sqlite3_result_error_nomem(pCtx);
181611    return 0;
181612  }
181613  memset(p, 0, sizeof(*p));
181614  p->zJson = (char*)&p[1];
181615  memcpy((char*)p->zJson, zJson, nJson+1);
181616  if( jsonParse(p, pCtx, p->zJson) ){
181617    sqlite3_free(p);
181618    return 0;
181619  }
181620  p->nJson = nJson;
181621  sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
181622  return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
181623}
181624
181625/*
181626** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
181627** a match.
181628*/
181629static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
181630  if( pNode->jnFlags & JNODE_RAW ){
181631    if( pNode->n!=nKey ) return 0;
181632    return strncmp(pNode->u.zJContent, zKey, nKey)==0;
181633  }else{
181634    if( pNode->n!=nKey+2 ) return 0;
181635    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
181636  }
181637}
181638
181639/* forward declaration */
181640static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
181641
181642/*
181643** Search along zPath to find the node specified.  Return a pointer
181644** to that node, or NULL if zPath is malformed or if there is no such
181645** node.
181646**
181647** If pApnd!=0, then try to append new nodes to complete zPath if it is
181648** possible to do so and if no existing node corresponds to zPath.  If
181649** new nodes are appended *pApnd is set to 1.
181650*/
181651static JsonNode *jsonLookupStep(
181652  JsonParse *pParse,      /* The JSON to search */
181653  u32 iRoot,              /* Begin the search at this node */
181654  const char *zPath,      /* The path to search */
181655  int *pApnd,             /* Append nodes to complete path if not NULL */
181656  const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
181657){
181658  u32 i, j, nKey;
181659  const char *zKey;
181660  JsonNode *pRoot = &pParse->aNode[iRoot];
181661  if( zPath[0]==0 ) return pRoot;
181662  if( zPath[0]=='.' ){
181663    if( pRoot->eType!=JSON_OBJECT ) return 0;
181664    zPath++;
181665    if( zPath[0]=='"' ){
181666      zKey = zPath + 1;
181667      for(i=1; zPath[i] && zPath[i]!='"'; i++){}
181668      nKey = i-1;
181669      if( zPath[i] ){
181670        i++;
181671      }else{
181672        *pzErr = zPath;
181673        return 0;
181674      }
181675    }else{
181676      zKey = zPath;
181677      for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
181678      nKey = i;
181679    }
181680    if( nKey==0 ){
181681      *pzErr = zPath;
181682      return 0;
181683    }
181684    j = 1;
181685    for(;;){
181686      while( j<=pRoot->n ){
181687        if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
181688          return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
181689        }
181690        j++;
181691        j += jsonNodeSize(&pRoot[j]);
181692      }
181693      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
181694      iRoot += pRoot->u.iAppend;
181695      pRoot = &pParse->aNode[iRoot];
181696      j = 1;
181697    }
181698    if( pApnd ){
181699      u32 iStart, iLabel;
181700      JsonNode *pNode;
181701      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
181702      iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
181703      zPath += i;
181704      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
181705      if( pParse->oom ) return 0;
181706      if( pNode ){
181707        pRoot = &pParse->aNode[iRoot];
181708        pRoot->u.iAppend = iStart - iRoot;
181709        pRoot->jnFlags |= JNODE_APPEND;
181710        pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
181711      }
181712      return pNode;
181713    }
181714  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
181715    if( pRoot->eType!=JSON_ARRAY ) return 0;
181716    i = 0;
181717    j = 1;
181718    while( safe_isdigit(zPath[j]) ){
181719      i = i*10 + zPath[j] - '0';
181720      j++;
181721    }
181722    if( zPath[j]!=']' ){
181723      *pzErr = zPath;
181724      return 0;
181725    }
181726    zPath += j + 1;
181727    j = 1;
181728    for(;;){
181729      while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
181730        if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
181731        j += jsonNodeSize(&pRoot[j]);
181732      }
181733      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
181734      iRoot += pRoot->u.iAppend;
181735      pRoot = &pParse->aNode[iRoot];
181736      j = 1;
181737    }
181738    if( j<=pRoot->n ){
181739      return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
181740    }
181741    if( i==0 && pApnd ){
181742      u32 iStart;
181743      JsonNode *pNode;
181744      iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
181745      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
181746      if( pParse->oom ) return 0;
181747      if( pNode ){
181748        pRoot = &pParse->aNode[iRoot];
181749        pRoot->u.iAppend = iStart - iRoot;
181750        pRoot->jnFlags |= JNODE_APPEND;
181751      }
181752      return pNode;
181753    }
181754  }else{
181755    *pzErr = zPath;
181756  }
181757  return 0;
181758}
181759
181760/*
181761** Append content to pParse that will complete zPath.  Return a pointer
181762** to the inserted node, or return NULL if the append fails.
181763*/
181764static JsonNode *jsonLookupAppend(
181765  JsonParse *pParse,     /* Append content to the JSON parse */
181766  const char *zPath,     /* Description of content to append */
181767  int *pApnd,            /* Set this flag to 1 */
181768  const char **pzErr     /* Make this point to any syntax error */
181769){
181770  *pApnd = 1;
181771  if( zPath[0]==0 ){
181772    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
181773    return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
181774  }
181775  if( zPath[0]=='.' ){
181776    jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
181777  }else if( strncmp(zPath,"[0]",3)==0 ){
181778    jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
181779  }else{
181780    return 0;
181781  }
181782  if( pParse->oom ) return 0;
181783  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
181784}
181785
181786/*
181787** Return the text of a syntax error message on a JSON path.  Space is
181788** obtained from sqlite3_malloc().
181789*/
181790static char *jsonPathSyntaxError(const char *zErr){
181791  return sqlite3_mprintf("JSON path error near '%q'", zErr);
181792}
181793
181794/*
181795** Do a node lookup using zPath.  Return a pointer to the node on success.
181796** Return NULL if not found or if there is an error.
181797**
181798** On an error, write an error message into pCtx and increment the
181799** pParse->nErr counter.
181800**
181801** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
181802** nodes are appended.
181803*/
181804static JsonNode *jsonLookup(
181805  JsonParse *pParse,      /* The JSON to search */
181806  const char *zPath,      /* The path to search */
181807  int *pApnd,             /* Append nodes to complete path if not NULL */
181808  sqlite3_context *pCtx   /* Report errors here, if not NULL */
181809){
181810  const char *zErr = 0;
181811  JsonNode *pNode = 0;
181812  char *zMsg;
181813
181814  if( zPath==0 ) return 0;
181815  if( zPath[0]!='$' ){
181816    zErr = zPath;
181817    goto lookup_err;
181818  }
181819  zPath++;
181820  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
181821  if( zErr==0 ) return pNode;
181822
181823lookup_err:
181824  pParse->nErr++;
181825  assert( zErr!=0 && pCtx!=0 );
181826  zMsg = jsonPathSyntaxError(zErr);
181827  if( zMsg ){
181828    sqlite3_result_error(pCtx, zMsg, -1);
181829    sqlite3_free(zMsg);
181830  }else{
181831    sqlite3_result_error_nomem(pCtx);
181832  }
181833  return 0;
181834}
181835
181836
181837/*
181838** Report the wrong number of arguments for json_insert(), json_replace()
181839** or json_set().
181840*/
181841static void jsonWrongNumArgs(
181842  sqlite3_context *pCtx,
181843  const char *zFuncName
181844){
181845  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
181846                               zFuncName);
181847  sqlite3_result_error(pCtx, zMsg, -1);
181848  sqlite3_free(zMsg);
181849}
181850
181851/*
181852** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
181853*/
181854static void jsonRemoveAllNulls(JsonNode *pNode){
181855  int i, n;
181856  assert( pNode->eType==JSON_OBJECT );
181857  n = pNode->n;
181858  for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
181859    switch( pNode[i].eType ){
181860      case JSON_NULL:
181861        pNode[i].jnFlags |= JNODE_REMOVE;
181862        break;
181863      case JSON_OBJECT:
181864        jsonRemoveAllNulls(&pNode[i]);
181865        break;
181866    }
181867  }
181868}
181869
181870
181871/****************************************************************************
181872** SQL functions used for testing and debugging
181873****************************************************************************/
181874
181875#ifdef SQLITE_DEBUG
181876/*
181877** The json_parse(JSON) function returns a string which describes
181878** a parse of the JSON provided.  Or it returns NULL if JSON is not
181879** well-formed.
181880*/
181881static void jsonParseFunc(
181882  sqlite3_context *ctx,
181883  int argc,
181884  sqlite3_value **argv
181885){
181886  JsonString s;       /* Output string - not real JSON */
181887  JsonParse x;        /* The parse */
181888  u32 i;
181889
181890  assert( argc==1 );
181891  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
181892  jsonParseFindParents(&x);
181893  jsonInit(&s, ctx);
181894  for(i=0; i<x.nNode; i++){
181895    const char *zType;
181896    if( x.aNode[i].jnFlags & JNODE_LABEL ){
181897      assert( x.aNode[i].eType==JSON_STRING );
181898      zType = "label";
181899    }else{
181900      zType = jsonType[x.aNode[i].eType];
181901    }
181902    jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
181903               i, zType, x.aNode[i].n, x.aUp[i]);
181904    if( x.aNode[i].u.zJContent!=0 ){
181905      jsonAppendRaw(&s, " ", 1);
181906      jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
181907    }
181908    jsonAppendRaw(&s, "\n", 1);
181909  }
181910  jsonParseReset(&x);
181911  jsonResult(&s);
181912}
181913
181914/*
181915** The json_test1(JSON) function return true (1) if the input is JSON
181916** text generated by another json function.  It returns (0) if the input
181917** is not known to be JSON.
181918*/
181919static void jsonTest1Func(
181920  sqlite3_context *ctx,
181921  int argc,
181922  sqlite3_value **argv
181923){
181924  UNUSED_PARAM(argc);
181925  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
181926}
181927#endif /* SQLITE_DEBUG */
181928
181929/****************************************************************************
181930** Scalar SQL function implementations
181931****************************************************************************/
181932
181933/*
181934** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
181935** corresponding to the SQL value input.  Mostly this means putting
181936** double-quotes around strings and returning the unquoted string "null"
181937** when given a NULL input.
181938*/
181939static void jsonQuoteFunc(
181940  sqlite3_context *ctx,
181941  int argc,
181942  sqlite3_value **argv
181943){
181944  JsonString jx;
181945  UNUSED_PARAM(argc);
181946
181947  jsonInit(&jx, ctx);
181948  jsonAppendValue(&jx, argv[0]);
181949  jsonResult(&jx);
181950  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
181951}
181952
181953/*
181954** Implementation of the json_array(VALUE,...) function.  Return a JSON
181955** array that contains all values given in arguments.  Or if any argument
181956** is a BLOB, throw an error.
181957*/
181958static void jsonArrayFunc(
181959  sqlite3_context *ctx,
181960  int argc,
181961  sqlite3_value **argv
181962){
181963  int i;
181964  JsonString jx;
181965
181966  jsonInit(&jx, ctx);
181967  jsonAppendChar(&jx, '[');
181968  for(i=0; i<argc; i++){
181969    jsonAppendSeparator(&jx);
181970    jsonAppendValue(&jx, argv[i]);
181971  }
181972  jsonAppendChar(&jx, ']');
181973  jsonResult(&jx);
181974  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
181975}
181976
181977
181978/*
181979** json_array_length(JSON)
181980** json_array_length(JSON, PATH)
181981**
181982** Return the number of elements in the top-level JSON array.
181983** Return 0 if the input is not a well-formed JSON array.
181984*/
181985static void jsonArrayLengthFunc(
181986  sqlite3_context *ctx,
181987  int argc,
181988  sqlite3_value **argv
181989){
181990  JsonParse *p;          /* The parse */
181991  sqlite3_int64 n = 0;
181992  u32 i;
181993  JsonNode *pNode;
181994
181995  p = jsonParseCached(ctx, argv);
181996  if( p==0 ) return;
181997  assert( p->nNode );
181998  if( argc==2 ){
181999    const char *zPath = (const char*)sqlite3_value_text(argv[1]);
182000    pNode = jsonLookup(p, zPath, 0, ctx);
182001  }else{
182002    pNode = p->aNode;
182003  }
182004  if( pNode==0 ){
182005    return;
182006  }
182007  if( pNode->eType==JSON_ARRAY ){
182008    assert( (pNode->jnFlags & JNODE_APPEND)==0 );
182009    for(i=1; i<=pNode->n; n++){
182010      i += jsonNodeSize(&pNode[i]);
182011    }
182012  }
182013  sqlite3_result_int64(ctx, n);
182014}
182015
182016/*
182017** json_extract(JSON, PATH, ...)
182018**
182019** Return the element described by PATH.  Return NULL if there is no
182020** PATH element.  If there are multiple PATHs, then return a JSON array
182021** with the result from each path.  Throw an error if the JSON or any PATH
182022** is malformed.
182023*/
182024static void jsonExtractFunc(
182025  sqlite3_context *ctx,
182026  int argc,
182027  sqlite3_value **argv
182028){
182029  JsonParse *p;          /* The parse */
182030  JsonNode *pNode;
182031  const char *zPath;
182032  JsonString jx;
182033  int i;
182034
182035  if( argc<2 ) return;
182036  p = jsonParseCached(ctx, argv);
182037  if( p==0 ) return;
182038  jsonInit(&jx, ctx);
182039  jsonAppendChar(&jx, '[');
182040  for(i=1; i<argc; i++){
182041    zPath = (const char*)sqlite3_value_text(argv[i]);
182042    pNode = jsonLookup(p, zPath, 0, ctx);
182043    if( p->nErr ) break;
182044    if( argc>2 ){
182045      jsonAppendSeparator(&jx);
182046      if( pNode ){
182047        jsonRenderNode(pNode, &jx, 0);
182048      }else{
182049        jsonAppendRaw(&jx, "null", 4);
182050      }
182051    }else if( pNode ){
182052      jsonReturn(pNode, ctx, 0);
182053    }
182054  }
182055  if( argc>2 && i==argc ){
182056    jsonAppendChar(&jx, ']');
182057    jsonResult(&jx);
182058    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182059  }
182060  jsonReset(&jx);
182061}
182062
182063/* This is the RFC 7396 MergePatch algorithm.
182064*/
182065static JsonNode *jsonMergePatch(
182066  JsonParse *pParse,   /* The JSON parser that contains the TARGET */
182067  u32 iTarget,         /* Node of the TARGET in pParse */
182068  JsonNode *pPatch     /* The PATCH */
182069){
182070  u32 i, j;
182071  u32 iRoot;
182072  JsonNode *pTarget;
182073  if( pPatch->eType!=JSON_OBJECT ){
182074    return pPatch;
182075  }
182076  assert( iTarget>=0 && iTarget<pParse->nNode );
182077  pTarget = &pParse->aNode[iTarget];
182078  assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
182079  if( pTarget->eType!=JSON_OBJECT ){
182080    jsonRemoveAllNulls(pPatch);
182081    return pPatch;
182082  }
182083  iRoot = iTarget;
182084  for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
182085    u32 nKey;
182086    const char *zKey;
182087    assert( pPatch[i].eType==JSON_STRING );
182088    assert( pPatch[i].jnFlags & JNODE_LABEL );
182089    nKey = pPatch[i].n;
182090    zKey = pPatch[i].u.zJContent;
182091    assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
182092    for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
182093      assert( pTarget[j].eType==JSON_STRING );
182094      assert( pTarget[j].jnFlags & JNODE_LABEL );
182095      assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
182096      if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
182097        if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
182098        if( pPatch[i+1].eType==JSON_NULL ){
182099          pTarget[j+1].jnFlags |= JNODE_REMOVE;
182100        }else{
182101          JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
182102          if( pNew==0 ) return 0;
182103          pTarget = &pParse->aNode[iTarget];
182104          if( pNew!=&pTarget[j+1] ){
182105            pTarget[j+1].u.pPatch = pNew;
182106            pTarget[j+1].jnFlags |= JNODE_PATCH;
182107          }
182108        }
182109        break;
182110      }
182111    }
182112    if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
182113      int iStart, iPatch;
182114      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
182115      jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
182116      iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
182117      if( pParse->oom ) return 0;
182118      jsonRemoveAllNulls(pPatch);
182119      pTarget = &pParse->aNode[iTarget];
182120      pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
182121      pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
182122      iRoot = iStart;
182123      pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
182124      pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
182125    }
182126  }
182127  return pTarget;
182128}
182129
182130/*
182131** Implementation of the json_mergepatch(JSON1,JSON2) function.  Return a JSON
182132** object that is the result of running the RFC 7396 MergePatch() algorithm
182133** on the two arguments.
182134*/
182135static void jsonPatchFunc(
182136  sqlite3_context *ctx,
182137  int argc,
182138  sqlite3_value **argv
182139){
182140  JsonParse x;     /* The JSON that is being patched */
182141  JsonParse y;     /* The patch */
182142  JsonNode *pResult;   /* The result of the merge */
182143
182144  UNUSED_PARAM(argc);
182145  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182146  if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
182147    jsonParseReset(&x);
182148    return;
182149  }
182150  pResult = jsonMergePatch(&x, 0, y.aNode);
182151  assert( pResult!=0 || x.oom );
182152  if( pResult ){
182153    jsonReturnJson(pResult, ctx, 0);
182154  }else{
182155    sqlite3_result_error_nomem(ctx);
182156  }
182157  jsonParseReset(&x);
182158  jsonParseReset(&y);
182159}
182160
182161
182162/*
182163** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
182164** object that contains all name/value given in arguments.  Or if any name
182165** is not a string or if any value is a BLOB, throw an error.
182166*/
182167static void jsonObjectFunc(
182168  sqlite3_context *ctx,
182169  int argc,
182170  sqlite3_value **argv
182171){
182172  int i;
182173  JsonString jx;
182174  const char *z;
182175  u32 n;
182176
182177  if( argc&1 ){
182178    sqlite3_result_error(ctx, "json_object() requires an even number "
182179                                  "of arguments", -1);
182180    return;
182181  }
182182  jsonInit(&jx, ctx);
182183  jsonAppendChar(&jx, '{');
182184  for(i=0; i<argc; i+=2){
182185    if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
182186      sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
182187      jsonReset(&jx);
182188      return;
182189    }
182190    jsonAppendSeparator(&jx);
182191    z = (const char*)sqlite3_value_text(argv[i]);
182192    n = (u32)sqlite3_value_bytes(argv[i]);
182193    jsonAppendString(&jx, z, n);
182194    jsonAppendChar(&jx, ':');
182195    jsonAppendValue(&jx, argv[i+1]);
182196  }
182197  jsonAppendChar(&jx, '}');
182198  jsonResult(&jx);
182199  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182200}
182201
182202
182203/*
182204** json_remove(JSON, PATH, ...)
182205**
182206** Remove the named elements from JSON and return the result.  malformed
182207** JSON or PATH arguments result in an error.
182208*/
182209static void jsonRemoveFunc(
182210  sqlite3_context *ctx,
182211  int argc,
182212  sqlite3_value **argv
182213){
182214  JsonParse x;          /* The parse */
182215  JsonNode *pNode;
182216  const char *zPath;
182217  u32 i;
182218
182219  if( argc<1 ) return;
182220  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182221  assert( x.nNode );
182222  for(i=1; i<(u32)argc; i++){
182223    zPath = (const char*)sqlite3_value_text(argv[i]);
182224    if( zPath==0 ) goto remove_done;
182225    pNode = jsonLookup(&x, zPath, 0, ctx);
182226    if( x.nErr ) goto remove_done;
182227    if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
182228  }
182229  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
182230    jsonReturnJson(x.aNode, ctx, 0);
182231  }
182232remove_done:
182233  jsonParseReset(&x);
182234}
182235
182236/*
182237** json_replace(JSON, PATH, VALUE, ...)
182238**
182239** Replace the value at PATH with VALUE.  If PATH does not already exist,
182240** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
182241*/
182242static void jsonReplaceFunc(
182243  sqlite3_context *ctx,
182244  int argc,
182245  sqlite3_value **argv
182246){
182247  JsonParse x;          /* The parse */
182248  JsonNode *pNode;
182249  const char *zPath;
182250  u32 i;
182251
182252  if( argc<1 ) return;
182253  if( (argc&1)==0 ) {
182254    jsonWrongNumArgs(ctx, "replace");
182255    return;
182256  }
182257  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182258  assert( x.nNode );
182259  for(i=1; i<(u32)argc; i+=2){
182260    zPath = (const char*)sqlite3_value_text(argv[i]);
182261    pNode = jsonLookup(&x, zPath, 0, ctx);
182262    if( x.nErr ) goto replace_err;
182263    if( pNode ){
182264      pNode->jnFlags |= (u8)JNODE_REPLACE;
182265      pNode->u.iReplace = i + 1;
182266    }
182267  }
182268  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
182269    sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
182270  }else{
182271    jsonReturnJson(x.aNode, ctx, argv);
182272  }
182273replace_err:
182274  jsonParseReset(&x);
182275}
182276
182277/*
182278** json_set(JSON, PATH, VALUE, ...)
182279**
182280** Set the value at PATH to VALUE.  Create the PATH if it does not already
182281** exist.  Overwrite existing values that do exist.
182282** If JSON or PATH is malformed, throw an error.
182283**
182284** json_insert(JSON, PATH, VALUE, ...)
182285**
182286** Create PATH and initialize it to VALUE.  If PATH already exists, this
182287** routine is a no-op.  If JSON or PATH is malformed, throw an error.
182288*/
182289static void jsonSetFunc(
182290  sqlite3_context *ctx,
182291  int argc,
182292  sqlite3_value **argv
182293){
182294  JsonParse x;          /* The parse */
182295  JsonNode *pNode;
182296  const char *zPath;
182297  u32 i;
182298  int bApnd;
182299  int bIsSet = *(int*)sqlite3_user_data(ctx);
182300
182301  if( argc<1 ) return;
182302  if( (argc&1)==0 ) {
182303    jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
182304    return;
182305  }
182306  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182307  assert( x.nNode );
182308  for(i=1; i<(u32)argc; i+=2){
182309    zPath = (const char*)sqlite3_value_text(argv[i]);
182310    bApnd = 0;
182311    pNode = jsonLookup(&x, zPath, &bApnd, ctx);
182312    if( x.oom ){
182313      sqlite3_result_error_nomem(ctx);
182314      goto jsonSetDone;
182315    }else if( x.nErr ){
182316      goto jsonSetDone;
182317    }else if( pNode && (bApnd || bIsSet) ){
182318      pNode->jnFlags |= (u8)JNODE_REPLACE;
182319      pNode->u.iReplace = i + 1;
182320    }
182321  }
182322  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
182323    sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
182324  }else{
182325    jsonReturnJson(x.aNode, ctx, argv);
182326  }
182327jsonSetDone:
182328  jsonParseReset(&x);
182329}
182330
182331/*
182332** json_type(JSON)
182333** json_type(JSON, PATH)
182334**
182335** Return the top-level "type" of a JSON string.  Throw an error if
182336** either the JSON or PATH inputs are not well-formed.
182337*/
182338static void jsonTypeFunc(
182339  sqlite3_context *ctx,
182340  int argc,
182341  sqlite3_value **argv
182342){
182343  JsonParse x;          /* The parse */
182344  const char *zPath;
182345  JsonNode *pNode;
182346
182347  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
182348  assert( x.nNode );
182349  if( argc==2 ){
182350    zPath = (const char*)sqlite3_value_text(argv[1]);
182351    pNode = jsonLookup(&x, zPath, 0, ctx);
182352  }else{
182353    pNode = x.aNode;
182354  }
182355  if( pNode ){
182356    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
182357  }
182358  jsonParseReset(&x);
182359}
182360
182361/*
182362** json_valid(JSON)
182363**
182364** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
182365** Return 0 otherwise.
182366*/
182367static void jsonValidFunc(
182368  sqlite3_context *ctx,
182369  int argc,
182370  sqlite3_value **argv
182371){
182372  JsonParse x;          /* The parse */
182373  int rc = 0;
182374
182375  UNUSED_PARAM(argc);
182376  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
182377    rc = 1;
182378  }
182379  jsonParseReset(&x);
182380  sqlite3_result_int(ctx, rc);
182381}
182382
182383
182384/****************************************************************************
182385** Aggregate SQL function implementations
182386****************************************************************************/
182387/*
182388** json_group_array(VALUE)
182389**
182390** Return a JSON array composed of all values in the aggregate.
182391*/
182392static void jsonArrayStep(
182393  sqlite3_context *ctx,
182394  int argc,
182395  sqlite3_value **argv
182396){
182397  JsonString *pStr;
182398  UNUSED_PARAM(argc);
182399  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
182400  if( pStr ){
182401    if( pStr->zBuf==0 ){
182402      jsonInit(pStr, ctx);
182403      jsonAppendChar(pStr, '[');
182404    }else{
182405      jsonAppendChar(pStr, ',');
182406      pStr->pCtx = ctx;
182407    }
182408    jsonAppendValue(pStr, argv[0]);
182409  }
182410}
182411static void jsonArrayFinal(sqlite3_context *ctx){
182412  JsonString *pStr;
182413  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
182414  if( pStr ){
182415    pStr->pCtx = ctx;
182416    jsonAppendChar(pStr, ']');
182417    if( pStr->bErr ){
182418      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
182419      assert( pStr->bStatic );
182420    }else{
182421      sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
182422                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
182423      pStr->bStatic = 1;
182424    }
182425  }else{
182426    sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
182427  }
182428  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182429}
182430
182431/*
182432** json_group_obj(NAME,VALUE)
182433**
182434** Return a JSON object composed of all names and values in the aggregate.
182435*/
182436static void jsonObjectStep(
182437  sqlite3_context *ctx,
182438  int argc,
182439  sqlite3_value **argv
182440){
182441  JsonString *pStr;
182442  const char *z;
182443  u32 n;
182444  UNUSED_PARAM(argc);
182445  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
182446  if( pStr ){
182447    if( pStr->zBuf==0 ){
182448      jsonInit(pStr, ctx);
182449      jsonAppendChar(pStr, '{');
182450    }else{
182451      jsonAppendChar(pStr, ',');
182452      pStr->pCtx = ctx;
182453    }
182454    z = (const char*)sqlite3_value_text(argv[0]);
182455    n = (u32)sqlite3_value_bytes(argv[0]);
182456    jsonAppendString(pStr, z, n);
182457    jsonAppendChar(pStr, ':');
182458    jsonAppendValue(pStr, argv[1]);
182459  }
182460}
182461static void jsonObjectFinal(sqlite3_context *ctx){
182462  JsonString *pStr;
182463  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
182464  if( pStr ){
182465    jsonAppendChar(pStr, '}');
182466    if( pStr->bErr ){
182467      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
182468      assert( pStr->bStatic );
182469    }else{
182470      sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
182471                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
182472      pStr->bStatic = 1;
182473    }
182474  }else{
182475    sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
182476  }
182477  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
182478}
182479
182480
182481#ifndef SQLITE_OMIT_VIRTUALTABLE
182482/****************************************************************************
182483** The json_each virtual table
182484****************************************************************************/
182485typedef struct JsonEachCursor JsonEachCursor;
182486struct JsonEachCursor {
182487  sqlite3_vtab_cursor base;  /* Base class - must be first */
182488  u32 iRowid;                /* The rowid */
182489  u32 iBegin;                /* The first node of the scan */
182490  u32 i;                     /* Index in sParse.aNode[] of current row */
182491  u32 iEnd;                  /* EOF when i equals or exceeds this value */
182492  u8 eType;                  /* Type of top-level element */
182493  u8 bRecursive;             /* True for json_tree().  False for json_each() */
182494  char *zJson;               /* Input JSON */
182495  char *zRoot;               /* Path by which to filter zJson */
182496  JsonParse sParse;          /* Parse of the input JSON */
182497};
182498
182499/* Constructor for the json_each virtual table */
182500static int jsonEachConnect(
182501  sqlite3 *db,
182502  void *pAux,
182503  int argc, const char *const*argv,
182504  sqlite3_vtab **ppVtab,
182505  char **pzErr
182506){
182507  sqlite3_vtab *pNew;
182508  int rc;
182509
182510/* Column numbers */
182511#define JEACH_KEY     0
182512#define JEACH_VALUE   1
182513#define JEACH_TYPE    2
182514#define JEACH_ATOM    3
182515#define JEACH_ID      4
182516#define JEACH_PARENT  5
182517#define JEACH_FULLKEY 6
182518#define JEACH_PATH    7
182519#define JEACH_JSON    8
182520#define JEACH_ROOT    9
182521
182522  UNUSED_PARAM(pzErr);
182523  UNUSED_PARAM(argv);
182524  UNUSED_PARAM(argc);
182525  UNUSED_PARAM(pAux);
182526  rc = sqlite3_declare_vtab(db,
182527     "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
182528                    "json HIDDEN,root HIDDEN)");
182529  if( rc==SQLITE_OK ){
182530    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
182531    if( pNew==0 ) return SQLITE_NOMEM;
182532    memset(pNew, 0, sizeof(*pNew));
182533  }
182534  return rc;
182535}
182536
182537/* destructor for json_each virtual table */
182538static int jsonEachDisconnect(sqlite3_vtab *pVtab){
182539  sqlite3_free(pVtab);
182540  return SQLITE_OK;
182541}
182542
182543/* constructor for a JsonEachCursor object for json_each(). */
182544static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
182545  JsonEachCursor *pCur;
182546
182547  UNUSED_PARAM(p);
182548  pCur = sqlite3_malloc( sizeof(*pCur) );
182549  if( pCur==0 ) return SQLITE_NOMEM;
182550  memset(pCur, 0, sizeof(*pCur));
182551  *ppCursor = &pCur->base;
182552  return SQLITE_OK;
182553}
182554
182555/* constructor for a JsonEachCursor object for json_tree(). */
182556static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
182557  int rc = jsonEachOpenEach(p, ppCursor);
182558  if( rc==SQLITE_OK ){
182559    JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
182560    pCur->bRecursive = 1;
182561  }
182562  return rc;
182563}
182564
182565/* Reset a JsonEachCursor back to its original state.  Free any memory
182566** held. */
182567static void jsonEachCursorReset(JsonEachCursor *p){
182568  sqlite3_free(p->zJson);
182569  sqlite3_free(p->zRoot);
182570  jsonParseReset(&p->sParse);
182571  p->iRowid = 0;
182572  p->i = 0;
182573  p->iEnd = 0;
182574  p->eType = 0;
182575  p->zJson = 0;
182576  p->zRoot = 0;
182577}
182578
182579/* Destructor for a jsonEachCursor object */
182580static int jsonEachClose(sqlite3_vtab_cursor *cur){
182581  JsonEachCursor *p = (JsonEachCursor*)cur;
182582  jsonEachCursorReset(p);
182583  sqlite3_free(cur);
182584  return SQLITE_OK;
182585}
182586
182587/* Return TRUE if the jsonEachCursor object has been advanced off the end
182588** of the JSON object */
182589static int jsonEachEof(sqlite3_vtab_cursor *cur){
182590  JsonEachCursor *p = (JsonEachCursor*)cur;
182591  return p->i >= p->iEnd;
182592}
182593
182594/* Advance the cursor to the next element for json_tree() */
182595static int jsonEachNext(sqlite3_vtab_cursor *cur){
182596  JsonEachCursor *p = (JsonEachCursor*)cur;
182597  if( p->bRecursive ){
182598    if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
182599    p->i++;
182600    p->iRowid++;
182601    if( p->i<p->iEnd ){
182602      u32 iUp = p->sParse.aUp[p->i];
182603      JsonNode *pUp = &p->sParse.aNode[iUp];
182604      p->eType = pUp->eType;
182605      if( pUp->eType==JSON_ARRAY ){
182606        if( iUp==p->i-1 ){
182607          pUp->u.iKey = 0;
182608        }else{
182609          pUp->u.iKey++;
182610        }
182611      }
182612    }
182613  }else{
182614    switch( p->eType ){
182615      case JSON_ARRAY: {
182616        p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
182617        p->iRowid++;
182618        break;
182619      }
182620      case JSON_OBJECT: {
182621        p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
182622        p->iRowid++;
182623        break;
182624      }
182625      default: {
182626        p->i = p->iEnd;
182627        break;
182628      }
182629    }
182630  }
182631  return SQLITE_OK;
182632}
182633
182634/* Append the name of the path for element i to pStr
182635*/
182636static void jsonEachComputePath(
182637  JsonEachCursor *p,       /* The cursor */
182638  JsonString *pStr,        /* Write the path here */
182639  u32 i                    /* Path to this element */
182640){
182641  JsonNode *pNode, *pUp;
182642  u32 iUp;
182643  if( i==0 ){
182644    jsonAppendChar(pStr, '$');
182645    return;
182646  }
182647  iUp = p->sParse.aUp[i];
182648  jsonEachComputePath(p, pStr, iUp);
182649  pNode = &p->sParse.aNode[i];
182650  pUp = &p->sParse.aNode[iUp];
182651  if( pUp->eType==JSON_ARRAY ){
182652    jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
182653  }else{
182654    assert( pUp->eType==JSON_OBJECT );
182655    if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
182656    assert( pNode->eType==JSON_STRING );
182657    assert( pNode->jnFlags & JNODE_LABEL );
182658    jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
182659  }
182660}
182661
182662/* Return the value of a column */
182663static int jsonEachColumn(
182664  sqlite3_vtab_cursor *cur,   /* The cursor */
182665  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
182666  int i                       /* Which column to return */
182667){
182668  JsonEachCursor *p = (JsonEachCursor*)cur;
182669  JsonNode *pThis = &p->sParse.aNode[p->i];
182670  switch( i ){
182671    case JEACH_KEY: {
182672      if( p->i==0 ) break;
182673      if( p->eType==JSON_OBJECT ){
182674        jsonReturn(pThis, ctx, 0);
182675      }else if( p->eType==JSON_ARRAY ){
182676        u32 iKey;
182677        if( p->bRecursive ){
182678          if( p->iRowid==0 ) break;
182679          iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
182680        }else{
182681          iKey = p->iRowid;
182682        }
182683        sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
182684      }
182685      break;
182686    }
182687    case JEACH_VALUE: {
182688      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
182689      jsonReturn(pThis, ctx, 0);
182690      break;
182691    }
182692    case JEACH_TYPE: {
182693      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
182694      sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
182695      break;
182696    }
182697    case JEACH_ATOM: {
182698      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
182699      if( pThis->eType>=JSON_ARRAY ) break;
182700      jsonReturn(pThis, ctx, 0);
182701      break;
182702    }
182703    case JEACH_ID: {
182704      sqlite3_result_int64(ctx,
182705         (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
182706      break;
182707    }
182708    case JEACH_PARENT: {
182709      if( p->i>p->iBegin && p->bRecursive ){
182710        sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
182711      }
182712      break;
182713    }
182714    case JEACH_FULLKEY: {
182715      JsonString x;
182716      jsonInit(&x, ctx);
182717      if( p->bRecursive ){
182718        jsonEachComputePath(p, &x, p->i);
182719      }else{
182720        if( p->zRoot ){
182721          jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
182722        }else{
182723          jsonAppendChar(&x, '$');
182724        }
182725        if( p->eType==JSON_ARRAY ){
182726          jsonPrintf(30, &x, "[%d]", p->iRowid);
182727        }else{
182728          jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
182729        }
182730      }
182731      jsonResult(&x);
182732      break;
182733    }
182734    case JEACH_PATH: {
182735      if( p->bRecursive ){
182736        JsonString x;
182737        jsonInit(&x, ctx);
182738        jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
182739        jsonResult(&x);
182740        break;
182741      }
182742      /* For json_each() path and root are the same so fall through
182743      ** into the root case */
182744    }
182745    default: {
182746      const char *zRoot = p->zRoot;
182747      if( zRoot==0 ) zRoot = "$";
182748      sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
182749      break;
182750    }
182751    case JEACH_JSON: {
182752      assert( i==JEACH_JSON );
182753      sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
182754      break;
182755    }
182756  }
182757  return SQLITE_OK;
182758}
182759
182760/* Return the current rowid value */
182761static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
182762  JsonEachCursor *p = (JsonEachCursor*)cur;
182763  *pRowid = p->iRowid;
182764  return SQLITE_OK;
182765}
182766
182767/* The query strategy is to look for an equality constraint on the json
182768** column.  Without such a constraint, the table cannot operate.  idxNum is
182769** 1 if the constraint is found, 3 if the constraint and zRoot are found,
182770** and 0 otherwise.
182771*/
182772static int jsonEachBestIndex(
182773  sqlite3_vtab *tab,
182774  sqlite3_index_info *pIdxInfo
182775){
182776  int i;
182777  int jsonIdx = -1;
182778  int rootIdx = -1;
182779  const struct sqlite3_index_constraint *pConstraint;
182780
182781  UNUSED_PARAM(tab);
182782  pConstraint = pIdxInfo->aConstraint;
182783  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
182784    if( pConstraint->usable==0 ) continue;
182785    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
182786    switch( pConstraint->iColumn ){
182787      case JEACH_JSON:   jsonIdx = i;    break;
182788      case JEACH_ROOT:   rootIdx = i;    break;
182789      default:           /* no-op */     break;
182790    }
182791  }
182792  if( jsonIdx<0 ){
182793    pIdxInfo->idxNum = 0;
182794    pIdxInfo->estimatedCost = 1e99;
182795  }else{
182796    pIdxInfo->estimatedCost = 1.0;
182797    pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
182798    pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
182799    if( rootIdx<0 ){
182800      pIdxInfo->idxNum = 1;
182801    }else{
182802      pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
182803      pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
182804      pIdxInfo->idxNum = 3;
182805    }
182806  }
182807  return SQLITE_OK;
182808}
182809
182810/* Start a search on a new JSON string */
182811static int jsonEachFilter(
182812  sqlite3_vtab_cursor *cur,
182813  int idxNum, const char *idxStr,
182814  int argc, sqlite3_value **argv
182815){
182816  JsonEachCursor *p = (JsonEachCursor*)cur;
182817  const char *z;
182818  const char *zRoot = 0;
182819  sqlite3_int64 n;
182820
182821  UNUSED_PARAM(idxStr);
182822  UNUSED_PARAM(argc);
182823  jsonEachCursorReset(p);
182824  if( idxNum==0 ) return SQLITE_OK;
182825  z = (const char*)sqlite3_value_text(argv[0]);
182826  if( z==0 ) return SQLITE_OK;
182827  n = sqlite3_value_bytes(argv[0]);
182828  p->zJson = sqlite3_malloc64( n+1 );
182829  if( p->zJson==0 ) return SQLITE_NOMEM;
182830  memcpy(p->zJson, z, (size_t)n+1);
182831  if( jsonParse(&p->sParse, 0, p->zJson) ){
182832    int rc = SQLITE_NOMEM;
182833    if( p->sParse.oom==0 ){
182834      sqlite3_free(cur->pVtab->zErrMsg);
182835      cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
182836      if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
182837    }
182838    jsonEachCursorReset(p);
182839    return rc;
182840  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
182841    jsonEachCursorReset(p);
182842    return SQLITE_NOMEM;
182843  }else{
182844    JsonNode *pNode = 0;
182845    if( idxNum==3 ){
182846      const char *zErr = 0;
182847      zRoot = (const char*)sqlite3_value_text(argv[1]);
182848      if( zRoot==0 ) return SQLITE_OK;
182849      n = sqlite3_value_bytes(argv[1]);
182850      p->zRoot = sqlite3_malloc64( n+1 );
182851      if( p->zRoot==0 ) return SQLITE_NOMEM;
182852      memcpy(p->zRoot, zRoot, (size_t)n+1);
182853      if( zRoot[0]!='$' ){
182854        zErr = zRoot;
182855      }else{
182856        pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
182857      }
182858      if( zErr ){
182859        sqlite3_free(cur->pVtab->zErrMsg);
182860        cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
182861        jsonEachCursorReset(p);
182862        return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
182863      }else if( pNode==0 ){
182864        return SQLITE_OK;
182865      }
182866    }else{
182867      pNode = p->sParse.aNode;
182868    }
182869    p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
182870    p->eType = pNode->eType;
182871    if( p->eType>=JSON_ARRAY ){
182872      pNode->u.iKey = 0;
182873      p->iEnd = p->i + pNode->n + 1;
182874      if( p->bRecursive ){
182875        p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
182876        if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
182877          p->i--;
182878        }
182879      }else{
182880        p->i++;
182881      }
182882    }else{
182883      p->iEnd = p->i+1;
182884    }
182885  }
182886  return SQLITE_OK;
182887}
182888
182889/* The methods of the json_each virtual table */
182890static sqlite3_module jsonEachModule = {
182891  0,                         /* iVersion */
182892  0,                         /* xCreate */
182893  jsonEachConnect,           /* xConnect */
182894  jsonEachBestIndex,         /* xBestIndex */
182895  jsonEachDisconnect,        /* xDisconnect */
182896  0,                         /* xDestroy */
182897  jsonEachOpenEach,          /* xOpen - open a cursor */
182898  jsonEachClose,             /* xClose - close a cursor */
182899  jsonEachFilter,            /* xFilter - configure scan constraints */
182900  jsonEachNext,              /* xNext - advance a cursor */
182901  jsonEachEof,               /* xEof - check for end of scan */
182902  jsonEachColumn,            /* xColumn - read data */
182903  jsonEachRowid,             /* xRowid - read data */
182904  0,                         /* xUpdate */
182905  0,                         /* xBegin */
182906  0,                         /* xSync */
182907  0,                         /* xCommit */
182908  0,                         /* xRollback */
182909  0,                         /* xFindMethod */
182910  0,                         /* xRename */
182911  0,                         /* xSavepoint */
182912  0,                         /* xRelease */
182913  0                          /* xRollbackTo */
182914};
182915
182916/* The methods of the json_tree virtual table. */
182917static sqlite3_module jsonTreeModule = {
182918  0,                         /* iVersion */
182919  0,                         /* xCreate */
182920  jsonEachConnect,           /* xConnect */
182921  jsonEachBestIndex,         /* xBestIndex */
182922  jsonEachDisconnect,        /* xDisconnect */
182923  0,                         /* xDestroy */
182924  jsonEachOpenTree,          /* xOpen - open a cursor */
182925  jsonEachClose,             /* xClose - close a cursor */
182926  jsonEachFilter,            /* xFilter - configure scan constraints */
182927  jsonEachNext,              /* xNext - advance a cursor */
182928  jsonEachEof,               /* xEof - check for end of scan */
182929  jsonEachColumn,            /* xColumn - read data */
182930  jsonEachRowid,             /* xRowid - read data */
182931  0,                         /* xUpdate */
182932  0,                         /* xBegin */
182933  0,                         /* xSync */
182934  0,                         /* xCommit */
182935  0,                         /* xRollback */
182936  0,                         /* xFindMethod */
182937  0,                         /* xRename */
182938  0,                         /* xSavepoint */
182939  0,                         /* xRelease */
182940  0                          /* xRollbackTo */
182941};
182942#endif /* SQLITE_OMIT_VIRTUALTABLE */
182943
182944/****************************************************************************
182945** The following routines are the only publically visible identifiers in this
182946** file.  Call the following routines in order to register the various SQL
182947** functions and the virtual table implemented by this file.
182948****************************************************************************/
182949
182950SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
182951  int rc = SQLITE_OK;
182952  unsigned int i;
182953  static const struct {
182954     const char *zName;
182955     int nArg;
182956     int flag;
182957     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
182958  } aFunc[] = {
182959    { "json",                 1, 0,   jsonRemoveFunc        },
182960    { "json_array",          -1, 0,   jsonArrayFunc         },
182961    { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
182962    { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
182963    { "json_extract",        -1, 0,   jsonExtractFunc       },
182964    { "json_insert",         -1, 0,   jsonSetFunc           },
182965    { "json_object",         -1, 0,   jsonObjectFunc        },
182966    { "json_patch",           2, 0,   jsonPatchFunc         },
182967    { "json_quote",           1, 0,   jsonQuoteFunc         },
182968    { "json_remove",         -1, 0,   jsonRemoveFunc        },
182969    { "json_replace",        -1, 0,   jsonReplaceFunc       },
182970    { "json_set",            -1, 1,   jsonSetFunc           },
182971    { "json_type",            1, 0,   jsonTypeFunc          },
182972    { "json_type",            2, 0,   jsonTypeFunc          },
182973    { "json_valid",           1, 0,   jsonValidFunc         },
182974
182975#if SQLITE_DEBUG
182976    /* DEBUG and TESTING functions */
182977    { "json_parse",           1, 0,   jsonParseFunc         },
182978    { "json_test1",           1, 0,   jsonTest1Func         },
182979#endif
182980  };
182981  static const struct {
182982     const char *zName;
182983     int nArg;
182984     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
182985     void (*xFinal)(sqlite3_context*);
182986  } aAgg[] = {
182987    { "json_group_array",     1,   jsonArrayStep,   jsonArrayFinal  },
182988    { "json_group_object",    2,   jsonObjectStep,  jsonObjectFinal },
182989  };
182990#ifndef SQLITE_OMIT_VIRTUALTABLE
182991  static const struct {
182992     const char *zName;
182993     sqlite3_module *pModule;
182994  } aMod[] = {
182995    { "json_each",            &jsonEachModule               },
182996    { "json_tree",            &jsonTreeModule               },
182997  };
182998#endif
182999  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
183000    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
183001                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
183002                                 (void*)&aFunc[i].flag,
183003                                 aFunc[i].xFunc, 0, 0);
183004  }
183005  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
183006    rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
183007                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
183008                                 0, aAgg[i].xStep, aAgg[i].xFinal);
183009  }
183010#ifndef SQLITE_OMIT_VIRTUALTABLE
183011  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
183012    rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
183013  }
183014#endif
183015  return rc;
183016}
183017
183018
183019#ifndef SQLITE_CORE
183020#ifdef _WIN32
183021__declspec(dllexport)
183022#endif
183023SQLITE_API int sqlite3_json_init(
183024  sqlite3 *db,
183025  char **pzErrMsg,
183026  const sqlite3_api_routines *pApi
183027){
183028  SQLITE_EXTENSION_INIT2(pApi);
183029  (void)pzErrMsg;  /* Unused parameter */
183030  return sqlite3Json1Init(db);
183031}
183032#endif
183033#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
183034
183035/************** End of json1.c ***********************************************/
183036/************** Begin file fts5.c ********************************************/
183037
183038
183039#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
183040
183041#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
183042# define NDEBUG 1
183043#endif
183044#if defined(NDEBUG) && defined(SQLITE_DEBUG)
183045# undef NDEBUG
183046#endif
183047
183048/*
183049** 2014 May 31
183050**
183051** The author disclaims copyright to this source code.  In place of
183052** a legal notice, here is a blessing:
183053**
183054**    May you do good and not evil.
183055**    May you find forgiveness for yourself and forgive others.
183056**    May you share freely, never taking more than you give.
183057**
183058******************************************************************************
183059**
183060** Interfaces to extend FTS5. Using the interfaces defined in this file,
183061** FTS5 may be extended with:
183062**
183063**     * custom tokenizers, and
183064**     * custom auxiliary functions.
183065*/
183066
183067
183068#ifndef _FTS5_H
183069#define _FTS5_H
183070
183071/* #include "sqlite3.h" */
183072
183073#if 0
183074extern "C" {
183075#endif
183076
183077/*************************************************************************
183078** CUSTOM AUXILIARY FUNCTIONS
183079**
183080** Virtual table implementations may overload SQL functions by implementing
183081** the sqlite3_module.xFindFunction() method.
183082*/
183083
183084typedef struct Fts5ExtensionApi Fts5ExtensionApi;
183085typedef struct Fts5Context Fts5Context;
183086typedef struct Fts5PhraseIter Fts5PhraseIter;
183087
183088typedef void (*fts5_extension_function)(
183089  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
183090  Fts5Context *pFts,              /* First arg to pass to pApi functions */
183091  sqlite3_context *pCtx,          /* Context for returning result/error */
183092  int nVal,                       /* Number of values in apVal[] array */
183093  sqlite3_value **apVal           /* Array of trailing arguments */
183094);
183095
183096struct Fts5PhraseIter {
183097  const unsigned char *a;
183098  const unsigned char *b;
183099};
183100
183101/*
183102** EXTENSION API FUNCTIONS
183103**
183104** xUserData(pFts):
183105**   Return a copy of the context pointer the extension function was
183106**   registered with.
183107**
183108** xColumnTotalSize(pFts, iCol, pnToken):
183109**   If parameter iCol is less than zero, set output variable *pnToken
183110**   to the total number of tokens in the FTS5 table. Or, if iCol is
183111**   non-negative but less than the number of columns in the table, return
183112**   the total number of tokens in column iCol, considering all rows in
183113**   the FTS5 table.
183114**
183115**   If parameter iCol is greater than or equal to the number of columns
183116**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
183117**   an OOM condition or IO error), an appropriate SQLite error code is
183118**   returned.
183119**
183120** xColumnCount(pFts):
183121**   Return the number of columns in the table.
183122**
183123** xColumnSize(pFts, iCol, pnToken):
183124**   If parameter iCol is less than zero, set output variable *pnToken
183125**   to the total number of tokens in the current row. Or, if iCol is
183126**   non-negative but less than the number of columns in the table, set
183127**   *pnToken to the number of tokens in column iCol of the current row.
183128**
183129**   If parameter iCol is greater than or equal to the number of columns
183130**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
183131**   an OOM condition or IO error), an appropriate SQLite error code is
183132**   returned.
183133**
183134**   This function may be quite inefficient if used with an FTS5 table
183135**   created with the "columnsize=0" option.
183136**
183137** xColumnText:
183138**   This function attempts to retrieve the text of column iCol of the
183139**   current document. If successful, (*pz) is set to point to a buffer
183140**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
183141**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
183142**   if an error occurs, an SQLite error code is returned and the final values
183143**   of (*pz) and (*pn) are undefined.
183144**
183145** xPhraseCount:
183146**   Returns the number of phrases in the current query expression.
183147**
183148** xPhraseSize:
183149**   Returns the number of tokens in phrase iPhrase of the query. Phrases
183150**   are numbered starting from zero.
183151**
183152** xInstCount:
183153**   Set *pnInst to the total number of occurrences of all phrases within
183154**   the query within the current row. Return SQLITE_OK if successful, or
183155**   an error code (i.e. SQLITE_NOMEM) if an error occurs.
183156**
183157**   This API can be quite slow if used with an FTS5 table created with the
183158**   "detail=none" or "detail=column" option. If the FTS5 table is created
183159**   with either "detail=none" or "detail=column" and "content=" option
183160**   (i.e. if it is a contentless table), then this API always returns 0.
183161**
183162** xInst:
183163**   Query for the details of phrase match iIdx within the current row.
183164**   Phrase matches are numbered starting from zero, so the iIdx argument
183165**   should be greater than or equal to zero and smaller than the value
183166**   output by xInstCount().
183167**
183168**   Usually, output parameter *piPhrase is set to the phrase number, *piCol
183169**   to the column in which it occurs and *piOff the token offset of the
183170**   first token of the phrase. The exception is if the table was created
183171**   with the offsets=0 option specified. In this case *piOff is always
183172**   set to -1.
183173**
183174**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
183175**   if an error occurs.
183176**
183177**   This API can be quite slow if used with an FTS5 table created with the
183178**   "detail=none" or "detail=column" option.
183179**
183180** xRowid:
183181**   Returns the rowid of the current row.
183182**
183183** xTokenize:
183184**   Tokenize text using the tokenizer belonging to the FTS5 table.
183185**
183186** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
183187**   This API function is used to query the FTS table for phrase iPhrase
183188**   of the current query. Specifically, a query equivalent to:
183189**
183190**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
183191**
183192**   with $p set to a phrase equivalent to the phrase iPhrase of the
183193**   current query is executed. Any column filter that applies to
183194**   phrase iPhrase of the current query is included in $p. For each
183195**   row visited, the callback function passed as the fourth argument
183196**   is invoked. The context and API objects passed to the callback
183197**   function may be used to access the properties of each matched row.
183198**   Invoking Api.xUserData() returns a copy of the pointer passed as
183199**   the third argument to pUserData.
183200**
183201**   If the callback function returns any value other than SQLITE_OK, the
183202**   query is abandoned and the xQueryPhrase function returns immediately.
183203**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
183204**   Otherwise, the error code is propagated upwards.
183205**
183206**   If the query runs to completion without incident, SQLITE_OK is returned.
183207**   Or, if some error occurs before the query completes or is aborted by
183208**   the callback, an SQLite error code is returned.
183209**
183210**
183211** xSetAuxdata(pFts5, pAux, xDelete)
183212**
183213**   Save the pointer passed as the second argument as the extension functions
183214**   "auxiliary data". The pointer may then be retrieved by the current or any
183215**   future invocation of the same fts5 extension function made as part of
183216**   of the same MATCH query using the xGetAuxdata() API.
183217**
183218**   Each extension function is allocated a single auxiliary data slot for
183219**   each FTS query (MATCH expression). If the extension function is invoked
183220**   more than once for a single FTS query, then all invocations share a
183221**   single auxiliary data context.
183222**
183223**   If there is already an auxiliary data pointer when this function is
183224**   invoked, then it is replaced by the new pointer. If an xDelete callback
183225**   was specified along with the original pointer, it is invoked at this
183226**   point.
183227**
183228**   The xDelete callback, if one is specified, is also invoked on the
183229**   auxiliary data pointer after the FTS5 query has finished.
183230**
183231**   If an error (e.g. an OOM condition) occurs within this function, an
183232**   the auxiliary data is set to NULL and an error code returned. If the
183233**   xDelete parameter was not NULL, it is invoked on the auxiliary data
183234**   pointer before returning.
183235**
183236**
183237** xGetAuxdata(pFts5, bClear)
183238**
183239**   Returns the current auxiliary data pointer for the fts5 extension
183240**   function. See the xSetAuxdata() method for details.
183241**
183242**   If the bClear argument is non-zero, then the auxiliary data is cleared
183243**   (set to NULL) before this function returns. In this case the xDelete,
183244**   if any, is not invoked.
183245**
183246**
183247** xRowCount(pFts5, pnRow)
183248**
183249**   This function is used to retrieve the total number of rows in the table.
183250**   In other words, the same value that would be returned by:
183251**
183252**        SELECT count(*) FROM ftstable;
183253**
183254** xPhraseFirst()
183255**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
183256**   method, to iterate through all instances of a single query phrase within
183257**   the current row. This is the same information as is accessible via the
183258**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
183259**   to use, this API may be faster under some circumstances. To iterate
183260**   through instances of phrase iPhrase, use the following code:
183261**
183262**       Fts5PhraseIter iter;
183263**       int iCol, iOff;
183264**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
183265**           iCol>=0;
183266**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
183267**       ){
183268**         // An instance of phrase iPhrase at offset iOff of column iCol
183269**       }
183270**
183271**   The Fts5PhraseIter structure is defined above. Applications should not
183272**   modify this structure directly - it should only be used as shown above
183273**   with the xPhraseFirst() and xPhraseNext() API methods (and by
183274**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
183275**
183276**   This API can be quite slow if used with an FTS5 table created with the
183277**   "detail=none" or "detail=column" option. If the FTS5 table is created
183278**   with either "detail=none" or "detail=column" and "content=" option
183279**   (i.e. if it is a contentless table), then this API always iterates
183280**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
183281**
183282** xPhraseNext()
183283**   See xPhraseFirst above.
183284**
183285** xPhraseFirstColumn()
183286**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
183287**   and xPhraseNext() APIs described above. The difference is that instead
183288**   of iterating through all instances of a phrase in the current row, these
183289**   APIs are used to iterate through the set of columns in the current row
183290**   that contain one or more instances of a specified phrase. For example:
183291**
183292**       Fts5PhraseIter iter;
183293**       int iCol;
183294**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
183295**           iCol>=0;
183296**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
183297**       ){
183298**         // Column iCol contains at least one instance of phrase iPhrase
183299**       }
183300**
183301**   This API can be quite slow if used with an FTS5 table created with the
183302**   "detail=none" option. If the FTS5 table is created with either
183303**   "detail=none" "content=" option (i.e. if it is a contentless table),
183304**   then this API always iterates through an empty set (all calls to
183305**   xPhraseFirstColumn() set iCol to -1).
183306**
183307**   The information accessed using this API and its companion
183308**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
183309**   (or xInst/xInstCount). The chief advantage of this API is that it is
183310**   significantly more efficient than those alternatives when used with
183311**   "detail=column" tables.
183312**
183313** xPhraseNextColumn()
183314**   See xPhraseFirstColumn above.
183315*/
183316struct Fts5ExtensionApi {
183317  int iVersion;                   /* Currently always set to 3 */
183318
183319  void *(*xUserData)(Fts5Context*);
183320
183321  int (*xColumnCount)(Fts5Context*);
183322  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
183323  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
183324
183325  int (*xTokenize)(Fts5Context*,
183326    const char *pText, int nText, /* Text to tokenize */
183327    void *pCtx,                   /* Context passed to xToken() */
183328    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
183329  );
183330
183331  int (*xPhraseCount)(Fts5Context*);
183332  int (*xPhraseSize)(Fts5Context*, int iPhrase);
183333
183334  int (*xInstCount)(Fts5Context*, int *pnInst);
183335  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
183336
183337  sqlite3_int64 (*xRowid)(Fts5Context*);
183338  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
183339  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
183340
183341  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
183342    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
183343  );
183344  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
183345  void *(*xGetAuxdata)(Fts5Context*, int bClear);
183346
183347  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
183348  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
183349
183350  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
183351  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
183352};
183353
183354/*
183355** CUSTOM AUXILIARY FUNCTIONS
183356*************************************************************************/
183357
183358/*************************************************************************
183359** CUSTOM TOKENIZERS
183360**
183361** Applications may also register custom tokenizer types. A tokenizer
183362** is registered by providing fts5 with a populated instance of the
183363** following structure. All structure methods must be defined, setting
183364** any member of the fts5_tokenizer struct to NULL leads to undefined
183365** behaviour. The structure methods are expected to function as follows:
183366**
183367** xCreate:
183368**   This function is used to allocate and initialize a tokenizer instance.
183369**   A tokenizer instance is required to actually tokenize text.
183370**
183371**   The first argument passed to this function is a copy of the (void*)
183372**   pointer provided by the application when the fts5_tokenizer object
183373**   was registered with FTS5 (the third argument to xCreateTokenizer()).
183374**   The second and third arguments are an array of nul-terminated strings
183375**   containing the tokenizer arguments, if any, specified following the
183376**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
183377**   to create the FTS5 table.
183378**
183379**   The final argument is an output variable. If successful, (*ppOut)
183380**   should be set to point to the new tokenizer handle and SQLITE_OK
183381**   returned. If an error occurs, some value other than SQLITE_OK should
183382**   be returned. In this case, fts5 assumes that the final value of *ppOut
183383**   is undefined.
183384**
183385** xDelete:
183386**   This function is invoked to delete a tokenizer handle previously
183387**   allocated using xCreate(). Fts5 guarantees that this function will
183388**   be invoked exactly once for each successful call to xCreate().
183389**
183390** xTokenize:
183391**   This function is expected to tokenize the nText byte string indicated
183392**   by argument pText. pText may or may not be nul-terminated. The first
183393**   argument passed to this function is a pointer to an Fts5Tokenizer object
183394**   returned by an earlier call to xCreate().
183395**
183396**   The second argument indicates the reason that FTS5 is requesting
183397**   tokenization of the supplied text. This is always one of the following
183398**   four values:
183399**
183400**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
183401**            or removed from the FTS table. The tokenizer is being invoked to
183402**            determine the set of tokens to add to (or delete from) the
183403**            FTS index.
183404**
183405**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
183406**            against the FTS index. The tokenizer is being called to tokenize
183407**            a bareword or quoted string specified as part of the query.
183408**
183409**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
183410**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
183411**            followed by a "*" character, indicating that the last token
183412**            returned by the tokenizer will be treated as a token prefix.
183413**
183414**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
183415**            satisfy an fts5_api.xTokenize() request made by an auxiliary
183416**            function. Or an fts5_api.xColumnSize() request made by the same
183417**            on a columnsize=0 database.
183418**   </ul>
183419**
183420**   For each token in the input string, the supplied callback xToken() must
183421**   be invoked. The first argument to it should be a copy of the pointer
183422**   passed as the second argument to xTokenize(). The third and fourth
183423**   arguments are a pointer to a buffer containing the token text, and the
183424**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
183425**   of the first byte of and first byte immediately following the text from
183426**   which the token is derived within the input.
183427**
183428**   The second argument passed to the xToken() callback ("tflags") should
183429**   normally be set to 0. The exception is if the tokenizer supports
183430**   synonyms. In this case see the discussion below for details.
183431**
183432**   FTS5 assumes the xToken() callback is invoked for each token in the
183433**   order that they occur within the input text.
183434**
183435**   If an xToken() callback returns any value other than SQLITE_OK, then
183436**   the tokenization should be abandoned and the xTokenize() method should
183437**   immediately return a copy of the xToken() return value. Or, if the
183438**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
183439**   if an error occurs with the xTokenize() implementation itself, it
183440**   may abandon the tokenization and return any error code other than
183441**   SQLITE_OK or SQLITE_DONE.
183442**
183443** SYNONYM SUPPORT
183444**
183445**   Custom tokenizers may also support synonyms. Consider a case in which a
183446**   user wishes to query for a phrase such as "first place". Using the
183447**   built-in tokenizers, the FTS5 query 'first + place' will match instances
183448**   of "first place" within the document set, but not alternative forms
183449**   such as "1st place". In some applications, it would be better to match
183450**   all instances of "first place" or "1st place" regardless of which form
183451**   the user specified in the MATCH query text.
183452**
183453**   There are several ways to approach this in FTS5:
183454**
183455**   <ol><li> By mapping all synonyms to a single token. In this case, the
183456**            In the above example, this means that the tokenizer returns the
183457**            same token for inputs "first" and "1st". Say that token is in
183458**            fact "first", so that when the user inserts the document "I won
183459**            1st place" entries are added to the index for tokens "i", "won",
183460**            "first" and "place". If the user then queries for '1st + place',
183461**            the tokenizer substitutes "first" for "1st" and the query works
183462**            as expected.
183463**
183464**       <li> By adding multiple synonyms for a single term to the FTS index.
183465**            In this case, when tokenizing query text, the tokenizer may
183466**            provide multiple synonyms for a single term within the document.
183467**            FTS5 then queries the index for each synonym individually. For
183468**            example, faced with the query:
183469**
183470**   <codeblock>
183471**     ... MATCH 'first place'</codeblock>
183472**
183473**            the tokenizer offers both "1st" and "first" as synonyms for the
183474**            first token in the MATCH query and FTS5 effectively runs a query
183475**            similar to:
183476**
183477**   <codeblock>
183478**     ... MATCH '(first OR 1st) place'</codeblock>
183479**
183480**            except that, for the purposes of auxiliary functions, the query
183481**            still appears to contain just two phrases - "(first OR 1st)"
183482**            being treated as a single phrase.
183483**
183484**       <li> By adding multiple synonyms for a single term to the FTS index.
183485**            Using this method, when tokenizing document text, the tokenizer
183486**            provides multiple synonyms for each token. So that when a
183487**            document such as "I won first place" is tokenized, entries are
183488**            added to the FTS index for "i", "won", "first", "1st" and
183489**            "place".
183490**
183491**            This way, even if the tokenizer does not provide synonyms
183492**            when tokenizing query text (it should not - to do would be
183493**            inefficient), it doesn't matter if the user queries for
183494**            'first + place' or '1st + place', as there are entires in the
183495**            FTS index corresponding to both forms of the first token.
183496**   </ol>
183497**
183498**   Whether it is parsing document or query text, any call to xToken that
183499**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
183500**   is considered to supply a synonym for the previous token. For example,
183501**   when parsing the document "I won first place", a tokenizer that supports
183502**   synonyms would call xToken() 5 times, as follows:
183503**
183504**   <codeblock>
183505**       xToken(pCtx, 0, "i",                      1,  0,  1);
183506**       xToken(pCtx, 0, "won",                    3,  2,  5);
183507**       xToken(pCtx, 0, "first",                  5,  6, 11);
183508**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
183509**       xToken(pCtx, 0, "place",                  5, 12, 17);
183510**</codeblock>
183511**
183512**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
183513**   xToken() is called. Multiple synonyms may be specified for a single token
183514**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
183515**   There is no limit to the number of synonyms that may be provided for a
183516**   single token.
183517**
183518**   In many cases, method (1) above is the best approach. It does not add
183519**   extra data to the FTS index or require FTS5 to query for multiple terms,
183520**   so it is efficient in terms of disk space and query speed. However, it
183521**   does not support prefix queries very well. If, as suggested above, the
183522**   token "first" is subsituted for "1st" by the tokenizer, then the query:
183523**
183524**   <codeblock>
183525**     ... MATCH '1s*'</codeblock>
183526**
183527**   will not match documents that contain the token "1st" (as the tokenizer
183528**   will probably not map "1s" to any prefix of "first").
183529**
183530**   For full prefix support, method (3) may be preferred. In this case,
183531**   because the index contains entries for both "first" and "1st", prefix
183532**   queries such as 'fi*' or '1s*' will match correctly. However, because
183533**   extra entries are added to the FTS index, this method uses more space
183534**   within the database.
183535**
183536**   Method (2) offers a midpoint between (1) and (3). Using this method,
183537**   a query such as '1s*' will match documents that contain the literal
183538**   token "1st", but not "first" (assuming the tokenizer is not able to
183539**   provide synonyms for prefixes). However, a non-prefix query like '1st'
183540**   will match against "1st" and "first". This method does not require
183541**   extra disk space, as no extra entries are added to the FTS index.
183542**   On the other hand, it may require more CPU cycles to run MATCH queries,
183543**   as separate queries of the FTS index are required for each synonym.
183544**
183545**   When using methods (2) or (3), it is important that the tokenizer only
183546**   provide synonyms when tokenizing document text (method (2)) or query
183547**   text (method (3)), not both. Doing so will not cause any errors, but is
183548**   inefficient.
183549*/
183550typedef struct Fts5Tokenizer Fts5Tokenizer;
183551typedef struct fts5_tokenizer fts5_tokenizer;
183552struct fts5_tokenizer {
183553  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
183554  void (*xDelete)(Fts5Tokenizer*);
183555  int (*xTokenize)(Fts5Tokenizer*,
183556      void *pCtx,
183557      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
183558      const char *pText, int nText,
183559      int (*xToken)(
183560        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
183561        int tflags,         /* Mask of FTS5_TOKEN_* flags */
183562        const char *pToken, /* Pointer to buffer containing token */
183563        int nToken,         /* Size of token in bytes */
183564        int iStart,         /* Byte offset of token within input text */
183565        int iEnd            /* Byte offset of end of token within input text */
183566      )
183567  );
183568};
183569
183570/* Flags that may be passed as the third argument to xTokenize() */
183571#define FTS5_TOKENIZE_QUERY     0x0001
183572#define FTS5_TOKENIZE_PREFIX    0x0002
183573#define FTS5_TOKENIZE_DOCUMENT  0x0004
183574#define FTS5_TOKENIZE_AUX       0x0008
183575
183576/* Flags that may be passed by the tokenizer implementation back to FTS5
183577** as the third argument to the supplied xToken callback. */
183578#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
183579
183580/*
183581** END OF CUSTOM TOKENIZERS
183582*************************************************************************/
183583
183584/*************************************************************************
183585** FTS5 EXTENSION REGISTRATION API
183586*/
183587typedef struct fts5_api fts5_api;
183588struct fts5_api {
183589  int iVersion;                   /* Currently always set to 2 */
183590
183591  /* Create a new tokenizer */
183592  int (*xCreateTokenizer)(
183593    fts5_api *pApi,
183594    const char *zName,
183595    void *pContext,
183596    fts5_tokenizer *pTokenizer,
183597    void (*xDestroy)(void*)
183598  );
183599
183600  /* Find an existing tokenizer */
183601  int (*xFindTokenizer)(
183602    fts5_api *pApi,
183603    const char *zName,
183604    void **ppContext,
183605    fts5_tokenizer *pTokenizer
183606  );
183607
183608  /* Create a new auxiliary function */
183609  int (*xCreateFunction)(
183610    fts5_api *pApi,
183611    const char *zName,
183612    void *pContext,
183613    fts5_extension_function xFunction,
183614    void (*xDestroy)(void*)
183615  );
183616};
183617
183618/*
183619** END OF REGISTRATION API
183620*************************************************************************/
183621
183622#if 0
183623}  /* end of the 'extern "C"' block */
183624#endif
183625
183626#endif /* _FTS5_H */
183627
183628/*
183629** 2014 May 31
183630**
183631** The author disclaims copyright to this source code.  In place of
183632** a legal notice, here is a blessing:
183633**
183634**    May you do good and not evil.
183635**    May you find forgiveness for yourself and forgive others.
183636**    May you share freely, never taking more than you give.
183637**
183638******************************************************************************
183639**
183640*/
183641#ifndef _FTS5INT_H
183642#define _FTS5INT_H
183643
183644/* #include "fts5.h" */
183645/* #include "sqlite3ext.h" */
183646SQLITE_EXTENSION_INIT1
183647
183648/* #include <string.h> */
183649/* #include <assert.h> */
183650
183651#ifndef SQLITE_AMALGAMATION
183652
183653typedef unsigned char  u8;
183654typedef unsigned int   u32;
183655typedef unsigned short u16;
183656typedef short i16;
183657typedef sqlite3_int64 i64;
183658typedef sqlite3_uint64 u64;
183659
183660#ifndef ArraySize
183661# define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
183662#endif
183663
183664#define testcase(x)
183665#define ALWAYS(x) 1
183666#define NEVER(x) 0
183667
183668#define MIN(x,y) (((x) < (y)) ? (x) : (y))
183669#define MAX(x,y) (((x) > (y)) ? (x) : (y))
183670
183671/*
183672** Constants for the largest and smallest possible 64-bit signed integers.
183673*/
183674# define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
183675# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
183676
183677#endif
183678
183679/* Truncate very long tokens to this many bytes. Hard limit is
183680** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
183681** field that occurs at the start of each leaf page (see fts5_index.c). */
183682#define FTS5_MAX_TOKEN_SIZE 32768
183683
183684/*
183685** Maximum number of prefix indexes on single FTS5 table. This must be
183686** less than 32. If it is set to anything large than that, an #error
183687** directive in fts5_index.c will cause the build to fail.
183688*/
183689#define FTS5_MAX_PREFIX_INDEXES 31
183690
183691#define FTS5_DEFAULT_NEARDIST 10
183692#define FTS5_DEFAULT_RANK     "bm25"
183693
183694/* Name of rank and rowid columns */
183695#define FTS5_RANK_NAME "rank"
183696#define FTS5_ROWID_NAME "rowid"
183697
183698#ifdef SQLITE_DEBUG
183699# define FTS5_CORRUPT sqlite3Fts5Corrupt()
183700static int sqlite3Fts5Corrupt(void);
183701#else
183702# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
183703#endif
183704
183705/*
183706** The assert_nc() macro is similar to the assert() macro, except that it
183707** is used for assert() conditions that are true only if it can be
183708** guranteed that the database is not corrupt.
183709*/
183710#ifdef SQLITE_DEBUG
183711SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
183712# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
183713#else
183714# define assert_nc(x) assert(x)
183715#endif
183716
183717/* Mark a function parameter as unused, to suppress nuisance compiler
183718** warnings. */
183719#ifndef UNUSED_PARAM
183720# define UNUSED_PARAM(X)  (void)(X)
183721#endif
183722
183723#ifndef UNUSED_PARAM2
183724# define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
183725#endif
183726
183727typedef struct Fts5Global Fts5Global;
183728typedef struct Fts5Colset Fts5Colset;
183729
183730/* If a NEAR() clump or phrase may only match a specific set of columns,
183731** then an object of the following type is used to record the set of columns.
183732** Each entry in the aiCol[] array is a column that may be matched.
183733**
183734** This object is used by fts5_expr.c and fts5_index.c.
183735*/
183736struct Fts5Colset {
183737  int nCol;
183738  int aiCol[1];
183739};
183740
183741
183742
183743/**************************************************************************
183744** Interface to code in fts5_config.c. fts5_config.c contains contains code
183745** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
183746*/
183747
183748typedef struct Fts5Config Fts5Config;
183749
183750/*
183751** An instance of the following structure encodes all information that can
183752** be gleaned from the CREATE VIRTUAL TABLE statement.
183753**
183754** And all information loaded from the %_config table.
183755**
183756** nAutomerge:
183757**   The minimum number of segments that an auto-merge operation should
183758**   attempt to merge together. A value of 1 sets the object to use the
183759**   compile time default. Zero disables auto-merge altogether.
183760**
183761** zContent:
183762**
183763** zContentRowid:
183764**   The value of the content_rowid= option, if one was specified. Or
183765**   the string "rowid" otherwise. This text is not quoted - if it is
183766**   used as part of an SQL statement it needs to be quoted appropriately.
183767**
183768** zContentExprlist:
183769**
183770** pzErrmsg:
183771**   This exists in order to allow the fts5_index.c module to return a
183772**   decent error message if it encounters a file-format version it does
183773**   not understand.
183774**
183775** bColumnsize:
183776**   True if the %_docsize table is created.
183777**
183778** bPrefixIndex:
183779**   This is only used for debugging. If set to false, any prefix indexes
183780**   are ignored. This value is configured using:
183781**
183782**       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
183783**
183784*/
183785struct Fts5Config {
183786  sqlite3 *db;                    /* Database handle */
183787  char *zDb;                      /* Database holding FTS index (e.g. "main") */
183788  char *zName;                    /* Name of FTS index */
183789  int nCol;                       /* Number of columns */
183790  char **azCol;                   /* Column names */
183791  u8 *abUnindexed;                /* True for unindexed columns */
183792  int nPrefix;                    /* Number of prefix indexes */
183793  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
183794  int eContent;                   /* An FTS5_CONTENT value */
183795  char *zContent;                 /* content table */
183796  char *zContentRowid;            /* "content_rowid=" option value */
183797  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
183798  int eDetail;                    /* FTS5_DETAIL_XXX value */
183799  char *zContentExprlist;
183800  Fts5Tokenizer *pTok;
183801  fts5_tokenizer *pTokApi;
183802
183803  /* Values loaded from the %_config table */
183804  int iCookie;                    /* Incremented when %_config is modified */
183805  int pgsz;                       /* Approximate page size used in %_data */
183806  int nAutomerge;                 /* 'automerge' setting */
183807  int nCrisisMerge;               /* Maximum allowed segments per level */
183808  int nUsermerge;                 /* 'usermerge' setting */
183809  int nHashSize;                  /* Bytes of memory for in-memory hash */
183810  char *zRank;                    /* Name of rank function */
183811  char *zRankArgs;                /* Arguments to rank function */
183812
183813  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
183814  char **pzErrmsg;
183815
183816#ifdef SQLITE_DEBUG
183817  int bPrefixIndex;               /* True to use prefix-indexes */
183818#endif
183819};
183820
183821/* Current expected value of %_config table 'version' field */
183822#define FTS5_CURRENT_VERSION 4
183823
183824#define FTS5_CONTENT_NORMAL   0
183825#define FTS5_CONTENT_NONE     1
183826#define FTS5_CONTENT_EXTERNAL 2
183827
183828#define FTS5_DETAIL_FULL    0
183829#define FTS5_DETAIL_NONE    1
183830#define FTS5_DETAIL_COLUMNS 2
183831
183832
183833
183834static int sqlite3Fts5ConfigParse(
183835    Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
183836);
183837static void sqlite3Fts5ConfigFree(Fts5Config*);
183838
183839static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
183840
183841static int sqlite3Fts5Tokenize(
183842  Fts5Config *pConfig,            /* FTS5 Configuration object */
183843  int flags,                      /* FTS5_TOKENIZE_* flags */
183844  const char *pText, int nText,   /* Text to tokenize */
183845  void *pCtx,                     /* Context passed to xToken() */
183846  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
183847);
183848
183849static void sqlite3Fts5Dequote(char *z);
183850
183851/* Load the contents of the %_config table */
183852static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
183853
183854/* Set the value of a single config attribute */
183855static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
183856
183857static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
183858
183859/*
183860** End of interface to code in fts5_config.c.
183861**************************************************************************/
183862
183863/**************************************************************************
183864** Interface to code in fts5_buffer.c.
183865*/
183866
183867/*
183868** Buffer object for the incremental building of string data.
183869*/
183870typedef struct Fts5Buffer Fts5Buffer;
183871struct Fts5Buffer {
183872  u8 *p;
183873  int n;
183874  int nSpace;
183875};
183876
183877static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
183878static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
183879static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
183880static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
183881static void sqlite3Fts5BufferFree(Fts5Buffer*);
183882static void sqlite3Fts5BufferZero(Fts5Buffer*);
183883static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
183884static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
183885
183886static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
183887
183888#define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
183889#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
183890#define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
183891#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
183892#define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
183893
183894#define fts5BufferGrow(pRc,pBuf,nn) ( \
183895  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
183896    sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
183897)
183898
183899/* Write and decode big-endian 32-bit integer values */
183900static void sqlite3Fts5Put32(u8*, int);
183901static int sqlite3Fts5Get32(const u8*);
183902
183903#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
183904#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
183905
183906typedef struct Fts5PoslistReader Fts5PoslistReader;
183907struct Fts5PoslistReader {
183908  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
183909  const u8 *a;                    /* Position list to iterate through */
183910  int n;                          /* Size of buffer at a[] in bytes */
183911  int i;                          /* Current offset in a[] */
183912
183913  u8 bFlag;                       /* For client use (any custom purpose) */
183914
183915  /* Output variables */
183916  u8 bEof;                        /* Set to true at EOF */
183917  i64 iPos;                       /* (iCol<<32) + iPos */
183918};
183919static int sqlite3Fts5PoslistReaderInit(
183920  const u8 *a, int n,             /* Poslist buffer to iterate through */
183921  Fts5PoslistReader *pIter        /* Iterator object to initialize */
183922);
183923static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
183924
183925typedef struct Fts5PoslistWriter Fts5PoslistWriter;
183926struct Fts5PoslistWriter {
183927  i64 iPrev;
183928};
183929static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
183930static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
183931
183932static int sqlite3Fts5PoslistNext64(
183933  const u8 *a, int n,             /* Buffer containing poslist */
183934  int *pi,                        /* IN/OUT: Offset within a[] */
183935  i64 *piOff                      /* IN/OUT: Current offset */
183936);
183937
183938/* Malloc utility */
183939static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
183940static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
183941
183942/* Character set tests (like isspace(), isalpha() etc.) */
183943static int sqlite3Fts5IsBareword(char t);
183944
183945
183946/* Bucket of terms object used by the integrity-check in offsets=0 mode. */
183947typedef struct Fts5Termset Fts5Termset;
183948static int sqlite3Fts5TermsetNew(Fts5Termset**);
183949static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
183950static void sqlite3Fts5TermsetFree(Fts5Termset*);
183951
183952/*
183953** End of interface to code in fts5_buffer.c.
183954**************************************************************************/
183955
183956/**************************************************************************
183957** Interface to code in fts5_index.c. fts5_index.c contains contains code
183958** to access the data stored in the %_data table.
183959*/
183960
183961typedef struct Fts5Index Fts5Index;
183962typedef struct Fts5IndexIter Fts5IndexIter;
183963
183964struct Fts5IndexIter {
183965  i64 iRowid;
183966  const u8 *pData;
183967  int nData;
183968  u8 bEof;
183969};
183970
183971#define sqlite3Fts5IterEof(x) ((x)->bEof)
183972
183973/*
183974** Values used as part of the flags argument passed to IndexQuery().
183975*/
183976#define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
183977#define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
183978#define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
183979#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
183980
183981/* The following are used internally by the fts5_index.c module. They are
183982** defined here only to make it easier to avoid clashes with the flags
183983** above. */
183984#define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
183985#define FTS5INDEX_QUERY_NOOUTPUT   0x0020
183986
183987/*
183988** Create/destroy an Fts5Index object.
183989*/
183990static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
183991static int sqlite3Fts5IndexClose(Fts5Index *p);
183992
183993/*
183994** Return a simple checksum value based on the arguments.
183995*/
183996static u64 sqlite3Fts5IndexEntryCksum(
183997  i64 iRowid,
183998  int iCol,
183999  int iPos,
184000  int iIdx,
184001  const char *pTerm,
184002  int nTerm
184003);
184004
184005/*
184006** Argument p points to a buffer containing utf-8 text that is n bytes in
184007** size. Return the number of bytes in the nChar character prefix of the
184008** buffer, or 0 if there are less than nChar characters in total.
184009*/
184010static int sqlite3Fts5IndexCharlenToBytelen(
184011  const char *p,
184012  int nByte,
184013  int nChar
184014);
184015
184016/*
184017** Open a new iterator to iterate though all rowids that match the
184018** specified token or token prefix.
184019*/
184020static int sqlite3Fts5IndexQuery(
184021  Fts5Index *p,                   /* FTS index to query */
184022  const char *pToken, int nToken, /* Token (or prefix) to query for */
184023  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
184024  Fts5Colset *pColset,            /* Match these columns only */
184025  Fts5IndexIter **ppIter          /* OUT: New iterator object */
184026);
184027
184028/*
184029** The various operations on open token or token prefix iterators opened
184030** using sqlite3Fts5IndexQuery().
184031*/
184032static int sqlite3Fts5IterNext(Fts5IndexIter*);
184033static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
184034
184035/*
184036** Close an iterator opened by sqlite3Fts5IndexQuery().
184037*/
184038static void sqlite3Fts5IterClose(Fts5IndexIter*);
184039
184040/*
184041** This interface is used by the fts5vocab module.
184042*/
184043static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
184044static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
184045
184046
184047/*
184048** Insert or remove data to or from the index. Each time a document is
184049** added to or removed from the index, this function is called one or more
184050** times.
184051**
184052** For an insert, it must be called once for each token in the new document.
184053** If the operation is a delete, it must be called (at least) once for each
184054** unique token in the document with an iCol value less than zero. The iPos
184055** argument is ignored for a delete.
184056*/
184057static int sqlite3Fts5IndexWrite(
184058  Fts5Index *p,                   /* Index to write to */
184059  int iCol,                       /* Column token appears in (-ve -> delete) */
184060  int iPos,                       /* Position of token within column */
184061  const char *pToken, int nToken  /* Token to add or remove to or from index */
184062);
184063
184064/*
184065** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
184066** document iDocid.
184067*/
184068static int sqlite3Fts5IndexBeginWrite(
184069  Fts5Index *p,                   /* Index to write to */
184070  int bDelete,                    /* True if current operation is a delete */
184071  i64 iDocid                      /* Docid to add or remove data from */
184072);
184073
184074/*
184075** Flush any data stored in the in-memory hash tables to the database.
184076** Also close any open blob handles.
184077*/
184078static int sqlite3Fts5IndexSync(Fts5Index *p);
184079
184080/*
184081** Discard any data stored in the in-memory hash tables. Do not write it
184082** to the database. Additionally, assume that the contents of the %_data
184083** table may have changed on disk. So any in-memory caches of %_data
184084** records must be invalidated.
184085*/
184086static int sqlite3Fts5IndexRollback(Fts5Index *p);
184087
184088/*
184089** Get or set the "averages" values.
184090*/
184091static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
184092static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
184093
184094/*
184095** Functions called by the storage module as part of integrity-check.
184096*/
184097static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
184098
184099/*
184100** Called during virtual module initialization to register UDF
184101** fts5_decode() with SQLite
184102*/
184103static int sqlite3Fts5IndexInit(sqlite3*);
184104
184105static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
184106
184107/*
184108** Return the total number of entries read from the %_data table by
184109** this connection since it was created.
184110*/
184111static int sqlite3Fts5IndexReads(Fts5Index *p);
184112
184113static int sqlite3Fts5IndexReinit(Fts5Index *p);
184114static int sqlite3Fts5IndexOptimize(Fts5Index *p);
184115static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
184116static int sqlite3Fts5IndexReset(Fts5Index *p);
184117
184118static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
184119
184120/*
184121** End of interface to code in fts5_index.c.
184122**************************************************************************/
184123
184124/**************************************************************************
184125** Interface to code in fts5_varint.c.
184126*/
184127static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
184128static int sqlite3Fts5GetVarintLen(u32 iVal);
184129static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
184130static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
184131
184132#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
184133#define fts5GetVarint    sqlite3Fts5GetVarint
184134
184135#define fts5FastGetVarint32(a, iOff, nVal) {      \
184136  nVal = (a)[iOff++];                             \
184137  if( nVal & 0x80 ){                              \
184138    iOff--;                                       \
184139    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
184140  }                                               \
184141}
184142
184143
184144/*
184145** End of interface to code in fts5_varint.c.
184146**************************************************************************/
184147
184148
184149/**************************************************************************
184150** Interface to code in fts5.c.
184151*/
184152
184153static int sqlite3Fts5GetTokenizer(
184154  Fts5Global*,
184155  const char **azArg,
184156  int nArg,
184157  Fts5Tokenizer**,
184158  fts5_tokenizer**,
184159  char **pzErr
184160);
184161
184162static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
184163
184164/*
184165** End of interface to code in fts5.c.
184166**************************************************************************/
184167
184168/**************************************************************************
184169** Interface to code in fts5_hash.c.
184170*/
184171typedef struct Fts5Hash Fts5Hash;
184172
184173/*
184174** Create a hash table, free a hash table.
184175*/
184176static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
184177static void sqlite3Fts5HashFree(Fts5Hash*);
184178
184179static int sqlite3Fts5HashWrite(
184180  Fts5Hash*,
184181  i64 iRowid,                     /* Rowid for this entry */
184182  int iCol,                       /* Column token appears in (-ve -> delete) */
184183  int iPos,                       /* Position of token within column */
184184  char bByte,
184185  const char *pToken, int nToken  /* Token to add or remove to or from index */
184186);
184187
184188/*
184189** Empty (but do not delete) a hash table.
184190*/
184191static void sqlite3Fts5HashClear(Fts5Hash*);
184192
184193static int sqlite3Fts5HashQuery(
184194  Fts5Hash*,                      /* Hash table to query */
184195  const char *pTerm, int nTerm,   /* Query term */
184196  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
184197  int *pnDoclist                  /* OUT: Size of doclist in bytes */
184198);
184199
184200static int sqlite3Fts5HashScanInit(
184201  Fts5Hash*,                      /* Hash table to query */
184202  const char *pTerm, int nTerm    /* Query prefix */
184203);
184204static void sqlite3Fts5HashScanNext(Fts5Hash*);
184205static int sqlite3Fts5HashScanEof(Fts5Hash*);
184206static void sqlite3Fts5HashScanEntry(Fts5Hash *,
184207  const char **pzTerm,            /* OUT: term (nul-terminated) */
184208  const u8 **ppDoclist,           /* OUT: pointer to doclist */
184209  int *pnDoclist                  /* OUT: size of doclist in bytes */
184210);
184211
184212
184213/*
184214** End of interface to code in fts5_hash.c.
184215**************************************************************************/
184216
184217/**************************************************************************
184218** Interface to code in fts5_storage.c. fts5_storage.c contains contains
184219** code to access the data stored in the %_content and %_docsize tables.
184220*/
184221
184222#define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
184223#define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
184224#define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
184225
184226typedef struct Fts5Storage Fts5Storage;
184227
184228static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
184229static int sqlite3Fts5StorageClose(Fts5Storage *p);
184230static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
184231
184232static int sqlite3Fts5DropAll(Fts5Config*);
184233static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
184234
184235static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
184236static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
184237static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
184238
184239static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
184240
184241static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
184242static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
184243
184244static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
184245static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
184246static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
184247
184248static int sqlite3Fts5StorageSync(Fts5Storage *p);
184249static int sqlite3Fts5StorageRollback(Fts5Storage *p);
184250
184251static int sqlite3Fts5StorageConfigValue(
184252    Fts5Storage *p, const char*, sqlite3_value*, int
184253);
184254
184255static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
184256static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
184257static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
184258static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
184259static int sqlite3Fts5StorageReset(Fts5Storage *p);
184260
184261/*
184262** End of interface to code in fts5_storage.c.
184263**************************************************************************/
184264
184265
184266/**************************************************************************
184267** Interface to code in fts5_expr.c.
184268*/
184269typedef struct Fts5Expr Fts5Expr;
184270typedef struct Fts5ExprNode Fts5ExprNode;
184271typedef struct Fts5Parse Fts5Parse;
184272typedef struct Fts5Token Fts5Token;
184273typedef struct Fts5ExprPhrase Fts5ExprPhrase;
184274typedef struct Fts5ExprNearset Fts5ExprNearset;
184275
184276struct Fts5Token {
184277  const char *p;                  /* Token text (not NULL terminated) */
184278  int n;                          /* Size of buffer p in bytes */
184279};
184280
184281/* Parse a MATCH expression. */
184282static int sqlite3Fts5ExprNew(
184283  Fts5Config *pConfig,
184284  int iCol,                       /* Column on LHS of MATCH operator */
184285  const char *zExpr,
184286  Fts5Expr **ppNew,
184287  char **pzErr
184288);
184289
184290/*
184291** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
184292**     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
184293**     rc = sqlite3Fts5ExprNext(pExpr)
184294** ){
184295**   // The document with rowid iRowid matches the expression!
184296**   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
184297** }
184298*/
184299static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
184300static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
184301static int sqlite3Fts5ExprEof(Fts5Expr*);
184302static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
184303
184304static void sqlite3Fts5ExprFree(Fts5Expr*);
184305
184306/* Called during startup to register a UDF with SQLite */
184307static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
184308
184309static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
184310static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
184311static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
184312
184313typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
184314static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
184315static int sqlite3Fts5ExprPopulatePoslists(
184316    Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
184317);
184318static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
184319
184320static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
184321
184322static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
184323
184324/*******************************************
184325** The fts5_expr.c API above this point is used by the other hand-written
184326** C code in this module. The interfaces below this point are called by
184327** the parser code in fts5parse.y.  */
184328
184329static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
184330
184331static Fts5ExprNode *sqlite3Fts5ParseNode(
184332  Fts5Parse *pParse,
184333  int eType,
184334  Fts5ExprNode *pLeft,
184335  Fts5ExprNode *pRight,
184336  Fts5ExprNearset *pNear
184337);
184338
184339static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
184340  Fts5Parse *pParse,
184341  Fts5ExprNode *pLeft,
184342  Fts5ExprNode *pRight
184343);
184344
184345static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
184346  Fts5Parse *pParse,
184347  Fts5ExprPhrase *pPhrase,
184348  Fts5Token *pToken,
184349  int bPrefix
184350);
184351
184352static Fts5ExprNearset *sqlite3Fts5ParseNearset(
184353  Fts5Parse*,
184354  Fts5ExprNearset*,
184355  Fts5ExprPhrase*
184356);
184357
184358static Fts5Colset *sqlite3Fts5ParseColset(
184359  Fts5Parse*,
184360  Fts5Colset*,
184361  Fts5Token *
184362);
184363
184364static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
184365static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
184366static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
184367
184368static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
184369static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
184370static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
184371static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
184372static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
184373
184374/*
184375** End of interface to code in fts5_expr.c.
184376**************************************************************************/
184377
184378
184379
184380/**************************************************************************
184381** Interface to code in fts5_aux.c.
184382*/
184383
184384static int sqlite3Fts5AuxInit(fts5_api*);
184385/*
184386** End of interface to code in fts5_aux.c.
184387**************************************************************************/
184388
184389/**************************************************************************
184390** Interface to code in fts5_tokenizer.c.
184391*/
184392
184393static int sqlite3Fts5TokenizerInit(fts5_api*);
184394/*
184395** End of interface to code in fts5_tokenizer.c.
184396**************************************************************************/
184397
184398/**************************************************************************
184399** Interface to code in fts5_vocab.c.
184400*/
184401
184402static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
184403
184404/*
184405** End of interface to code in fts5_vocab.c.
184406**************************************************************************/
184407
184408
184409/**************************************************************************
184410** Interface to automatically generated code in fts5_unicode2.c.
184411*/
184412static int sqlite3Fts5UnicodeIsalnum(int c);
184413static int sqlite3Fts5UnicodeIsdiacritic(int c);
184414static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
184415/*
184416** End of interface to code in fts5_unicode2.c.
184417**************************************************************************/
184418
184419#endif
184420
184421#define FTS5_OR                               1
184422#define FTS5_AND                              2
184423#define FTS5_NOT                              3
184424#define FTS5_TERM                             4
184425#define FTS5_COLON                            5
184426#define FTS5_MINUS                            6
184427#define FTS5_LCP                              7
184428#define FTS5_RCP                              8
184429#define FTS5_STRING                           9
184430#define FTS5_LP                              10
184431#define FTS5_RP                              11
184432#define FTS5_COMMA                           12
184433#define FTS5_PLUS                            13
184434#define FTS5_STAR                            14
184435
184436/*
184437** 2000-05-29
184438**
184439** The author disclaims copyright to this source code.  In place of
184440** a legal notice, here is a blessing:
184441**
184442**    May you do good and not evil.
184443**    May you find forgiveness for yourself and forgive others.
184444**    May you share freely, never taking more than you give.
184445**
184446*************************************************************************
184447** Driver template for the LEMON parser generator.
184448**
184449** The "lemon" program processes an LALR(1) input grammar file, then uses
184450** this template to construct a parser.  The "lemon" program inserts text
184451** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
184452** interstitial "-" characters) contained in this template is changed into
184453** the value of the %name directive from the grammar.  Otherwise, the content
184454** of this template is copied straight through into the generate parser
184455** source file.
184456**
184457** The following is the concatenation of all %include directives from the
184458** input grammar file:
184459*/
184460/* #include <stdio.h> */
184461/************ Begin %include sections from the grammar ************************/
184462
184463/* #include "fts5Int.h" */
184464/* #include "fts5parse.h" */
184465
184466/*
184467** Disable all error recovery processing in the parser push-down
184468** automaton.
184469*/
184470#define fts5YYNOERRORRECOVERY 1
184471
184472/*
184473** Make fts5yytestcase() the same as testcase()
184474*/
184475#define fts5yytestcase(X) testcase(X)
184476
184477/*
184478** Indicate that sqlite3ParserFree() will never be called with a null
184479** pointer.
184480*/
184481#define fts5YYPARSEFREENOTNULL 1
184482
184483/*
184484** Alternative datatype for the argument to the malloc() routine passed
184485** into sqlite3ParserAlloc().  The default is size_t.
184486*/
184487#define fts5YYMALLOCARGTYPE  u64
184488
184489/**************** End of %include directives **********************************/
184490/* These constants specify the various numeric values for terminal symbols
184491** in a format understandable to "makeheaders".  This section is blank unless
184492** "lemon" is run with the "-m" command-line option.
184493***************** Begin makeheaders token definitions *************************/
184494/**************** End makeheaders token definitions ***************************/
184495
184496/* The next sections is a series of control #defines.
184497** various aspects of the generated parser.
184498**    fts5YYCODETYPE         is the data type used to store the integer codes
184499**                       that represent terminal and non-terminal symbols.
184500**                       "unsigned char" is used if there are fewer than
184501**                       256 symbols.  Larger types otherwise.
184502**    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
184503**                       any terminal or nonterminal symbol.
184504**    fts5YYFALLBACK         If defined, this indicates that one or more tokens
184505**                       (also known as: "terminal symbols") have fall-back
184506**                       values which should be used if the original symbol
184507**                       would not parse.  This permits keywords to sometimes
184508**                       be used as identifiers, for example.
184509**    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
184510**                       that indicate what to do in response to the next
184511**                       token.
184512**    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
184513**                       symbols.  Background: A "minor type" is a semantic
184514**                       value associated with a terminal or non-terminal
184515**                       symbols.  For example, for an "ID" terminal symbol,
184516**                       the minor type might be the name of the identifier.
184517**                       Each non-terminal can have a different minor type.
184518**                       Terminal symbols all have the same minor type, though.
184519**                       This macros defines the minor type for terminal
184520**                       symbols.
184521**    fts5YYMINORTYPE        is the data type used for all minor types.
184522**                       This is typically a union of many types, one of
184523**                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
184524**                       for terminal symbols is called "fts5yy0".
184525**    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
184526**                       zero the stack is dynamically sized using realloc()
184527**    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
184528**    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
184529**    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
184530**    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
184531**    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
184532**                       defined, then do no error processing.
184533**    fts5YYNSTATE           the combined number of states.
184534**    fts5YYNRULE            the number of rules in the grammar
184535**    fts5YY_MAX_SHIFT       Maximum value for shift actions
184536**    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
184537**    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
184538**    fts5YY_MIN_REDUCE      Maximum value for reduce actions
184539**    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
184540**    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
184541**    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
184542*/
184543#ifndef INTERFACE
184544# define INTERFACE 1
184545#endif
184546/************* Begin control #defines *****************************************/
184547#define fts5YYCODETYPE unsigned char
184548#define fts5YYNOCODE 28
184549#define fts5YYACTIONTYPE unsigned char
184550#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
184551typedef union {
184552  int fts5yyinit;
184553  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
184554  int fts5yy4;
184555  Fts5Colset* fts5yy11;
184556  Fts5ExprNode* fts5yy24;
184557  Fts5ExprNearset* fts5yy46;
184558  Fts5ExprPhrase* fts5yy53;
184559} fts5YYMINORTYPE;
184560#ifndef fts5YYSTACKDEPTH
184561#define fts5YYSTACKDEPTH 100
184562#endif
184563#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
184564#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
184565#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
184566#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
184567#define fts5YYNSTATE             33
184568#define fts5YYNRULE              27
184569#define fts5YY_MAX_SHIFT         32
184570#define fts5YY_MIN_SHIFTREDUCE   50
184571#define fts5YY_MAX_SHIFTREDUCE   76
184572#define fts5YY_MIN_REDUCE        77
184573#define fts5YY_MAX_REDUCE        103
184574#define fts5YY_ERROR_ACTION      104
184575#define fts5YY_ACCEPT_ACTION     105
184576#define fts5YY_NO_ACTION         106
184577/************* End control #defines *******************************************/
184578
184579/* Define the fts5yytestcase() macro to be a no-op if is not already defined
184580** otherwise.
184581**
184582** Applications can choose to define fts5yytestcase() in the %include section
184583** to a macro that can assist in verifying code coverage.  For production
184584** code the fts5yytestcase() macro should be turned off.  But it is useful
184585** for testing.
184586*/
184587#ifndef fts5yytestcase
184588# define fts5yytestcase(X)
184589#endif
184590
184591
184592/* Next are the tables used to determine what action to take based on the
184593** current state and lookahead token.  These tables are used to implement
184594** functions that take a state number and lookahead value and return an
184595** action integer.
184596**
184597** Suppose the action integer is N.  Then the action is determined as
184598** follows
184599**
184600**   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
184601**                                      token onto the stack and goto state N.
184602**
184603**   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
184604**     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
184605**
184606**   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
184607**     and fts5YY_MAX_REDUCE
184608**
184609**   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
184610**
184611**   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
184612**
184613**   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
184614**                                      slots in the fts5yy_action[] table.
184615**
184616** The action table is constructed as a single large table named fts5yy_action[].
184617** Given state S and lookahead X, the action is computed as either:
184618**
184619**    (A)   N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
184620**    (B)   N = fts5yy_default[S]
184621**
184622** The (A) formula is preferred.  The B formula is used instead if:
184623**    (1)  The fts5yy_shift_ofst[S]+X value is out of range, or
184624**    (2)  fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
184625**    (3)  fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
184626** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
184627** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
184628** Hence only tests (1) and (2) need to be evaluated.)
184629**
184630** The formulas above are for computing the action when the lookahead is
184631** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
184632** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
184633** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
184634** fts5YY_SHIFT_USE_DFLT.
184635**
184636** The following are the tables generated in this section:
184637**
184638**  fts5yy_action[]        A single table containing all actions.
184639**  fts5yy_lookahead[]     A table containing the lookahead for each entry in
184640**                     fts5yy_action.  Used to detect hash collisions.
184641**  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
184642**                     shifting terminals.
184643**  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
184644**                     shifting non-terminals after a reduce.
184645**  fts5yy_default[]       Default action for each state.
184646**
184647*********** Begin parsing tables **********************************************/
184648#define fts5YY_ACTTAB_COUNT (98)
184649static const fts5YYACTIONTYPE fts5yy_action[] = {
184650 /*     0 */   105,   19,   90,    6,   26,   93,   92,   24,   24,   17,
184651 /*    10 */    90,    6,   26,   16,   92,   54,   24,   18,   90,    6,
184652 /*    20 */    26,   10,   92,   12,   24,   75,   86,   90,    6,   26,
184653 /*    30 */    13,   92,   75,   24,   20,   90,    6,   26,  101,   92,
184654 /*    40 */    56,   24,   27,   90,    6,   26,  100,   92,   21,   24,
184655 /*    50 */    23,   15,   30,   11,    1,   91,   22,   25,    9,   92,
184656 /*    60 */     7,   24,    3,    4,    5,    3,    4,    5,    3,   77,
184657 /*    70 */     4,    5,    3,   61,   23,   15,   60,   11,   80,   12,
184658 /*    80 */     2,   13,   68,   10,   29,   52,   55,   75,   31,   32,
184659 /*    90 */     8,   28,    5,    3,   51,   55,   72,   14,
184660};
184661static const fts5YYCODETYPE fts5yy_lookahead[] = {
184662 /*     0 */    16,   17,   18,   19,   20,   22,   22,   24,   24,   17,
184663 /*    10 */    18,   19,   20,    7,   22,    9,   24,   17,   18,   19,
184664 /*    20 */    20,   10,   22,    9,   24,   14,   17,   18,   19,   20,
184665 /*    30 */     9,   22,   14,   24,   17,   18,   19,   20,   26,   22,
184666 /*    40 */     9,   24,   17,   18,   19,   20,   26,   22,   21,   24,
184667 /*    50 */     6,    7,   13,    9,   10,   18,   21,   20,    5,   22,
184668 /*    60 */     5,   24,    3,    1,    2,    3,    1,    2,    3,    0,
184669 /*    70 */     1,    2,    3,   11,    6,    7,   11,    9,    5,    9,
184670 /*    80 */    10,    9,   11,   10,   12,    8,    9,   14,   24,   25,
184671 /*    90 */    23,   24,    2,    3,    8,    9,    9,    9,
184672};
184673#define fts5YY_SHIFT_USE_DFLT (98)
184674#define fts5YY_SHIFT_COUNT    (32)
184675#define fts5YY_SHIFT_MIN      (0)
184676#define fts5YY_SHIFT_MAX      (90)
184677static const unsigned char fts5yy_shift_ofst[] = {
184678 /*     0 */    44,   44,   44,   44,   44,   44,   68,   70,   72,   14,
184679 /*    10 */    21,   73,   11,   18,   18,   31,   31,   62,   65,   69,
184680 /*    20 */    90,   77,   86,    6,   39,   53,   55,   59,   39,   87,
184681 /*    30 */    88,   39,   71,
184682};
184683#define fts5YY_REDUCE_USE_DFLT (-18)
184684#define fts5YY_REDUCE_COUNT (16)
184685#define fts5YY_REDUCE_MIN   (-17)
184686#define fts5YY_REDUCE_MAX   (67)
184687static const signed char fts5yy_reduce_ofst[] = {
184688 /*     0 */   -16,   -8,    0,    9,   17,   25,   37,  -17,   64,  -17,
184689 /*    10 */    67,   12,   12,   12,   20,   27,   35,
184690};
184691static const fts5YYACTIONTYPE fts5yy_default[] = {
184692 /*     0 */   104,  104,  104,  104,  104,  104,   89,  104,   98,  104,
184693 /*    10 */   104,  103,  103,  103,  103,  104,  104,  104,  104,  104,
184694 /*    20 */    85,  104,  104,  104,   94,  104,  104,   84,   96,  104,
184695 /*    30 */   104,   97,  104,
184696};
184697/********** End of lemon-generated parsing tables *****************************/
184698
184699/* The next table maps tokens (terminal symbols) into fallback tokens.
184700** If a construct like the following:
184701**
184702**      %fallback ID X Y Z.
184703**
184704** appears in the grammar, then ID becomes a fallback token for X, Y,
184705** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
184706** but it does not parse, the type of the token is changed to ID and
184707** the parse is retried before an error is thrown.
184708**
184709** This feature can be used, for example, to cause some keywords in a language
184710** to revert to identifiers if they keyword does not apply in the context where
184711** it appears.
184712*/
184713#ifdef fts5YYFALLBACK
184714static const fts5YYCODETYPE fts5yyFallback[] = {
184715};
184716#endif /* fts5YYFALLBACK */
184717
184718/* The following structure represents a single element of the
184719** parser's stack.  Information stored includes:
184720**
184721**   +  The state number for the parser at this level of the stack.
184722**
184723**   +  The value of the token stored at this level of the stack.
184724**      (In other words, the "major" token.)
184725**
184726**   +  The semantic value stored at this level of the stack.  This is
184727**      the information used by the action routines in the grammar.
184728**      It is sometimes called the "minor" token.
184729**
184730** After the "shift" half of a SHIFTREDUCE action, the stateno field
184731** actually contains the reduce action for the second half of the
184732** SHIFTREDUCE.
184733*/
184734struct fts5yyStackEntry {
184735  fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
184736  fts5YYCODETYPE major;      /* The major token value.  This is the code
184737                         ** number for the token at this stack level */
184738  fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
184739                         ** is the value of the token  */
184740};
184741typedef struct fts5yyStackEntry fts5yyStackEntry;
184742
184743/* The state of the parser is completely contained in an instance of
184744** the following structure */
184745struct fts5yyParser {
184746  fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
184747#ifdef fts5YYTRACKMAXSTACKDEPTH
184748  int fts5yyhwm;                    /* High-water mark of the stack */
184749#endif
184750#ifndef fts5YYNOERRORRECOVERY
184751  int fts5yyerrcnt;                 /* Shifts left before out of the error */
184752#endif
184753  sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
184754#if fts5YYSTACKDEPTH<=0
184755  int fts5yystksz;                  /* Current side of the stack */
184756  fts5yyStackEntry *fts5yystack;        /* The parser's stack */
184757  fts5yyStackEntry fts5yystk0;          /* First stack entry */
184758#else
184759  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
184760  fts5yyStackEntry *fts5yystackEnd;            /* Last entry in the stack */
184761#endif
184762};
184763typedef struct fts5yyParser fts5yyParser;
184764
184765#ifndef NDEBUG
184766/* #include <stdio.h> */
184767static FILE *fts5yyTraceFILE = 0;
184768static char *fts5yyTracePrompt = 0;
184769#endif /* NDEBUG */
184770
184771#ifndef NDEBUG
184772/*
184773** Turn parser tracing on by giving a stream to which to write the trace
184774** and a prompt to preface each trace message.  Tracing is turned off
184775** by making either argument NULL
184776**
184777** Inputs:
184778** <ul>
184779** <li> A FILE* to which trace output should be written.
184780**      If NULL, then tracing is turned off.
184781** <li> A prefix string written at the beginning of every
184782**      line of trace output.  If NULL, then tracing is
184783**      turned off.
184784** </ul>
184785**
184786** Outputs:
184787** None.
184788*/
184789static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
184790  fts5yyTraceFILE = TraceFILE;
184791  fts5yyTracePrompt = zTracePrompt;
184792  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
184793  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
184794}
184795#endif /* NDEBUG */
184796
184797#ifndef NDEBUG
184798/* For tracing shifts, the names of all terminals and nonterminals
184799** are required.  The following table supplies these names */
184800static const char *const fts5yyTokenName[] = {
184801  "$",             "OR",            "AND",           "NOT",
184802  "TERM",          "COLON",         "MINUS",         "LCP",
184803  "RCP",           "STRING",        "LP",            "RP",
184804  "COMMA",         "PLUS",          "STAR",          "error",
184805  "input",         "expr",          "cnearset",      "exprlist",
184806  "colset",        "colsetlist",    "nearset",       "nearphrases",
184807  "phrase",        "neardist_opt",  "star_opt",
184808};
184809#endif /* NDEBUG */
184810
184811#ifndef NDEBUG
184812/* For tracing reduce actions, the names of all rules are required.
184813*/
184814static const char *const fts5yyRuleName[] = {
184815 /*   0 */ "input ::= expr",
184816 /*   1 */ "colset ::= MINUS LCP colsetlist RCP",
184817 /*   2 */ "colset ::= LCP colsetlist RCP",
184818 /*   3 */ "colset ::= STRING",
184819 /*   4 */ "colset ::= MINUS STRING",
184820 /*   5 */ "colsetlist ::= colsetlist STRING",
184821 /*   6 */ "colsetlist ::= STRING",
184822 /*   7 */ "expr ::= expr AND expr",
184823 /*   8 */ "expr ::= expr OR expr",
184824 /*   9 */ "expr ::= expr NOT expr",
184825 /*  10 */ "expr ::= colset COLON LP expr RP",
184826 /*  11 */ "expr ::= LP expr RP",
184827 /*  12 */ "expr ::= exprlist",
184828 /*  13 */ "exprlist ::= cnearset",
184829 /*  14 */ "exprlist ::= exprlist cnearset",
184830 /*  15 */ "cnearset ::= nearset",
184831 /*  16 */ "cnearset ::= colset COLON nearset",
184832 /*  17 */ "nearset ::= phrase",
184833 /*  18 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
184834 /*  19 */ "nearphrases ::= phrase",
184835 /*  20 */ "nearphrases ::= nearphrases phrase",
184836 /*  21 */ "neardist_opt ::=",
184837 /*  22 */ "neardist_opt ::= COMMA STRING",
184838 /*  23 */ "phrase ::= phrase PLUS STRING star_opt",
184839 /*  24 */ "phrase ::= STRING star_opt",
184840 /*  25 */ "star_opt ::= STAR",
184841 /*  26 */ "star_opt ::=",
184842};
184843#endif /* NDEBUG */
184844
184845
184846#if fts5YYSTACKDEPTH<=0
184847/*
184848** Try to increase the size of the parser stack.  Return the number
184849** of errors.  Return 0 on success.
184850*/
184851static int fts5yyGrowStack(fts5yyParser *p){
184852  int newSize;
184853  int idx;
184854  fts5yyStackEntry *pNew;
184855
184856  newSize = p->fts5yystksz*2 + 100;
184857  idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
184858  if( p->fts5yystack==&p->fts5yystk0 ){
184859    pNew = malloc(newSize*sizeof(pNew[0]));
184860    if( pNew ) pNew[0] = p->fts5yystk0;
184861  }else{
184862    pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
184863  }
184864  if( pNew ){
184865    p->fts5yystack = pNew;
184866    p->fts5yytos = &p->fts5yystack[idx];
184867#ifndef NDEBUG
184868    if( fts5yyTraceFILE ){
184869      fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
184870              fts5yyTracePrompt, p->fts5yystksz, newSize);
184871    }
184872#endif
184873    p->fts5yystksz = newSize;
184874  }
184875  return pNew==0;
184876}
184877#endif
184878
184879/* Datatype of the argument to the memory allocated passed as the
184880** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
184881** putting an appropriate #define in the %include section of the input
184882** grammar.
184883*/
184884#ifndef fts5YYMALLOCARGTYPE
184885# define fts5YYMALLOCARGTYPE size_t
184886#endif
184887
184888/* Initialize a new parser that has already been allocated.
184889*/
184890static void sqlite3Fts5ParserInit(void *fts5yypParser){
184891  fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
184892#ifdef fts5YYTRACKMAXSTACKDEPTH
184893  pParser->fts5yyhwm = 0;
184894#endif
184895#if fts5YYSTACKDEPTH<=0
184896  pParser->fts5yytos = NULL;
184897  pParser->fts5yystack = NULL;
184898  pParser->fts5yystksz = 0;
184899  if( fts5yyGrowStack(pParser) ){
184900    pParser->fts5yystack = &pParser->fts5yystk0;
184901    pParser->fts5yystksz = 1;
184902  }
184903#endif
184904#ifndef fts5YYNOERRORRECOVERY
184905  pParser->fts5yyerrcnt = -1;
184906#endif
184907  pParser->fts5yytos = pParser->fts5yystack;
184908  pParser->fts5yystack[0].stateno = 0;
184909  pParser->fts5yystack[0].major = 0;
184910#if fts5YYSTACKDEPTH>0
184911  pParser->fts5yystackEnd = &pParser->fts5yystack[fts5YYSTACKDEPTH-1];
184912#endif
184913}
184914
184915#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
184916/*
184917** This function allocates a new parser.
184918** The only argument is a pointer to a function which works like
184919** malloc.
184920**
184921** Inputs:
184922** A pointer to the function used to allocate memory.
184923**
184924** Outputs:
184925** A pointer to a parser.  This pointer is used in subsequent calls
184926** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
184927*/
184928static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
184929  fts5yyParser *pParser;
184930  pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
184931  if( pParser ) sqlite3Fts5ParserInit(pParser);
184932  return pParser;
184933}
184934#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
184935
184936
184937/* The following function deletes the "minor type" or semantic value
184938** associated with a symbol.  The symbol can be either a terminal
184939** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
184940** a pointer to the value to be deleted.  The code used to do the
184941** deletions is derived from the %destructor and/or %token_destructor
184942** directives of the input grammar.
184943*/
184944static void fts5yy_destructor(
184945  fts5yyParser *fts5yypParser,    /* The parser */
184946  fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
184947  fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
184948){
184949  sqlite3Fts5ParserARG_FETCH;
184950  switch( fts5yymajor ){
184951    /* Here is inserted the actions which take place when a
184952    ** terminal or non-terminal is destroyed.  This can happen
184953    ** when the symbol is popped from the stack during a
184954    ** reduce or during error processing or when a parser is
184955    ** being destroyed before it is finished parsing.
184956    **
184957    ** Note: during a reduce, the only symbols destroyed are those
184958    ** which appear on the RHS of the rule, but which are *not* used
184959    ** inside the C code.
184960    */
184961/********* Begin destructor definitions ***************************************/
184962    case 16: /* input */
184963{
184964 (void)pParse;
184965}
184966      break;
184967    case 17: /* expr */
184968    case 18: /* cnearset */
184969    case 19: /* exprlist */
184970{
184971 sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
184972}
184973      break;
184974    case 20: /* colset */
184975    case 21: /* colsetlist */
184976{
184977 sqlite3_free((fts5yypminor->fts5yy11));
184978}
184979      break;
184980    case 22: /* nearset */
184981    case 23: /* nearphrases */
184982{
184983 sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
184984}
184985      break;
184986    case 24: /* phrase */
184987{
184988 sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
184989}
184990      break;
184991/********* End destructor definitions *****************************************/
184992    default:  break;   /* If no destructor action specified: do nothing */
184993  }
184994}
184995
184996/*
184997** Pop the parser's stack once.
184998**
184999** If there is a destructor routine associated with the token which
185000** is popped from the stack, then call it.
185001*/
185002static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
185003  fts5yyStackEntry *fts5yytos;
185004  assert( pParser->fts5yytos!=0 );
185005  assert( pParser->fts5yytos > pParser->fts5yystack );
185006  fts5yytos = pParser->fts5yytos--;
185007#ifndef NDEBUG
185008  if( fts5yyTraceFILE ){
185009    fprintf(fts5yyTraceFILE,"%sPopping %s\n",
185010      fts5yyTracePrompt,
185011      fts5yyTokenName[fts5yytos->major]);
185012  }
185013#endif
185014  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
185015}
185016
185017/*
185018** Clear all secondary memory allocations from the parser
185019*/
185020static void sqlite3Fts5ParserFinalize(void *p){
185021  fts5yyParser *pParser = (fts5yyParser*)p;
185022  while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
185023#if fts5YYSTACKDEPTH<=0
185024  if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
185025#endif
185026}
185027
185028#ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
185029/*
185030** Deallocate and destroy a parser.  Destructors are called for
185031** all stack elements before shutting the parser down.
185032**
185033** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
185034** is defined in a %include section of the input grammar) then it is
185035** assumed that the input pointer is never NULL.
185036*/
185037static void sqlite3Fts5ParserFree(
185038  void *p,                    /* The parser to be deleted */
185039  void (*freeProc)(void*)     /* Function used to reclaim memory */
185040){
185041#ifndef fts5YYPARSEFREENEVERNULL
185042  if( p==0 ) return;
185043#endif
185044  sqlite3Fts5ParserFinalize(p);
185045  (*freeProc)(p);
185046}
185047#endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
185048
185049/*
185050** Return the peak depth of the stack for a parser.
185051*/
185052#ifdef fts5YYTRACKMAXSTACKDEPTH
185053static int sqlite3Fts5ParserStackPeak(void *p){
185054  fts5yyParser *pParser = (fts5yyParser*)p;
185055  return pParser->fts5yyhwm;
185056}
185057#endif
185058
185059/*
185060** Find the appropriate action for a parser given the terminal
185061** look-ahead token iLookAhead.
185062*/
185063static unsigned int fts5yy_find_shift_action(
185064  fts5yyParser *pParser,        /* The parser */
185065  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
185066){
185067  int i;
185068  int stateno = pParser->fts5yytos->stateno;
185069
185070  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
185071  assert( stateno <= fts5YY_SHIFT_COUNT );
185072  do{
185073    i = fts5yy_shift_ofst[stateno];
185074    assert( iLookAhead!=fts5YYNOCODE );
185075    i += iLookAhead;
185076    if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
185077#ifdef fts5YYFALLBACK
185078      fts5YYCODETYPE iFallback;            /* Fallback token */
185079      if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
185080             && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
185081#ifndef NDEBUG
185082        if( fts5yyTraceFILE ){
185083          fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
185084             fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
185085        }
185086#endif
185087        assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
185088        iLookAhead = iFallback;
185089        continue;
185090      }
185091#endif
185092#ifdef fts5YYWILDCARD
185093      {
185094        int j = i - iLookAhead + fts5YYWILDCARD;
185095        if(
185096#if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
185097          j>=0 &&
185098#endif
185099#if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
185100          j<fts5YY_ACTTAB_COUNT &&
185101#endif
185102          fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
185103        ){
185104#ifndef NDEBUG
185105          if( fts5yyTraceFILE ){
185106            fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
185107               fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
185108               fts5yyTokenName[fts5YYWILDCARD]);
185109          }
185110#endif /* NDEBUG */
185111          return fts5yy_action[j];
185112        }
185113      }
185114#endif /* fts5YYWILDCARD */
185115      return fts5yy_default[stateno];
185116    }else{
185117      return fts5yy_action[i];
185118    }
185119  }while(1);
185120}
185121
185122/*
185123** Find the appropriate action for a parser given the non-terminal
185124** look-ahead token iLookAhead.
185125*/
185126static int fts5yy_find_reduce_action(
185127  int stateno,              /* Current state number */
185128  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
185129){
185130  int i;
185131#ifdef fts5YYERRORSYMBOL
185132  if( stateno>fts5YY_REDUCE_COUNT ){
185133    return fts5yy_default[stateno];
185134  }
185135#else
185136  assert( stateno<=fts5YY_REDUCE_COUNT );
185137#endif
185138  i = fts5yy_reduce_ofst[stateno];
185139  assert( i!=fts5YY_REDUCE_USE_DFLT );
185140  assert( iLookAhead!=fts5YYNOCODE );
185141  i += iLookAhead;
185142#ifdef fts5YYERRORSYMBOL
185143  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
185144    return fts5yy_default[stateno];
185145  }
185146#else
185147  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
185148  assert( fts5yy_lookahead[i]==iLookAhead );
185149#endif
185150  return fts5yy_action[i];
185151}
185152
185153/*
185154** The following routine is called if the stack overflows.
185155*/
185156static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
185157   sqlite3Fts5ParserARG_FETCH;
185158#ifndef NDEBUG
185159   if( fts5yyTraceFILE ){
185160     fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
185161   }
185162#endif
185163   while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
185164   /* Here code is inserted which will execute if the parser
185165   ** stack every overflows */
185166/******** Begin %stack_overflow code ******************************************/
185167
185168  sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
185169/******** End %stack_overflow code ********************************************/
185170   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
185171}
185172
185173/*
185174** Print tracing information for a SHIFT action
185175*/
185176#ifndef NDEBUG
185177static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
185178  if( fts5yyTraceFILE ){
185179    if( fts5yyNewState<fts5YYNSTATE ){
185180      fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
185181         fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
185182         fts5yyNewState);
185183    }else{
185184      fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
185185         fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
185186    }
185187  }
185188}
185189#else
185190# define fts5yyTraceShift(X,Y)
185191#endif
185192
185193/*
185194** Perform a shift action.
185195*/
185196static void fts5yy_shift(
185197  fts5yyParser *fts5yypParser,          /* The parser to be shifted */
185198  int fts5yyNewState,               /* The new state to shift in */
185199  int fts5yyMajor,                  /* The major token to shift in */
185200  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
185201){
185202  fts5yyStackEntry *fts5yytos;
185203  fts5yypParser->fts5yytos++;
185204#ifdef fts5YYTRACKMAXSTACKDEPTH
185205  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
185206    fts5yypParser->fts5yyhwm++;
185207    assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
185208  }
185209#endif
185210#if fts5YYSTACKDEPTH>0
185211  if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
185212    fts5yypParser->fts5yytos--;
185213    fts5yyStackOverflow(fts5yypParser);
185214    return;
185215  }
185216#else
185217  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
185218    if( fts5yyGrowStack(fts5yypParser) ){
185219      fts5yypParser->fts5yytos--;
185220      fts5yyStackOverflow(fts5yypParser);
185221      return;
185222    }
185223  }
185224#endif
185225  if( fts5yyNewState > fts5YY_MAX_SHIFT ){
185226    fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
185227  }
185228  fts5yytos = fts5yypParser->fts5yytos;
185229  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
185230  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
185231  fts5yytos->minor.fts5yy0 = fts5yyMinor;
185232  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
185233}
185234
185235/* The following table contains information about every rule that
185236** is used during the reduce.
185237*/
185238static const struct {
185239  fts5YYCODETYPE lhs;       /* Symbol on the left-hand side of the rule */
185240  signed char nrhs;     /* Negative of the number of RHS symbols in the rule */
185241} fts5yyRuleInfo[] = {
185242  { 16, -1 },
185243  { 20, -4 },
185244  { 20, -3 },
185245  { 20, -1 },
185246  { 20, -2 },
185247  { 21, -2 },
185248  { 21, -1 },
185249  { 17, -3 },
185250  { 17, -3 },
185251  { 17, -3 },
185252  { 17, -5 },
185253  { 17, -3 },
185254  { 17, -1 },
185255  { 19, -1 },
185256  { 19, -2 },
185257  { 18, -1 },
185258  { 18, -3 },
185259  { 22, -1 },
185260  { 22, -5 },
185261  { 23, -1 },
185262  { 23, -2 },
185263  { 25, 0 },
185264  { 25, -2 },
185265  { 24, -4 },
185266  { 24, -2 },
185267  { 26, -1 },
185268  { 26, 0 },
185269};
185270
185271static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
185272
185273/*
185274** Perform a reduce action and the shift that must immediately
185275** follow the reduce.
185276*/
185277static void fts5yy_reduce(
185278  fts5yyParser *fts5yypParser,         /* The parser */
185279  unsigned int fts5yyruleno        /* Number of the rule by which to reduce */
185280){
185281  int fts5yygoto;                     /* The next state */
185282  int fts5yyact;                      /* The next action */
185283  fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
185284  int fts5yysize;                     /* Amount to pop the stack */
185285  sqlite3Fts5ParserARG_FETCH;
185286  fts5yymsp = fts5yypParser->fts5yytos;
185287#ifndef NDEBUG
185288  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
185289    fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
185290    fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
185291      fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
185292  }
185293#endif /* NDEBUG */
185294
185295  /* Check that the stack is large enough to grow by a single entry
185296  ** if the RHS of the rule is empty.  This ensures that there is room
185297  ** enough on the stack to push the LHS value */
185298  if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
185299#ifdef fts5YYTRACKMAXSTACKDEPTH
185300    if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
185301      fts5yypParser->fts5yyhwm++;
185302      assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
185303    }
185304#endif
185305#if fts5YYSTACKDEPTH>0
185306    if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
185307      fts5yyStackOverflow(fts5yypParser);
185308      return;
185309    }
185310#else
185311    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
185312      if( fts5yyGrowStack(fts5yypParser) ){
185313        fts5yyStackOverflow(fts5yypParser);
185314        return;
185315      }
185316      fts5yymsp = fts5yypParser->fts5yytos;
185317    }
185318#endif
185319  }
185320
185321  switch( fts5yyruleno ){
185322  /* Beginning here are the reduction cases.  A typical example
185323  ** follows:
185324  **   case 0:
185325  **  #line <lineno> <grammarfile>
185326  **     { ... }           // User supplied code
185327  **  #line <lineno> <thisfile>
185328  **     break;
185329  */
185330/********** Begin reduce actions **********************************************/
185331        fts5YYMINORTYPE fts5yylhsminor;
185332      case 0: /* input ::= expr */
185333{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
185334        break;
185335      case 1: /* colset ::= MINUS LCP colsetlist RCP */
185336{
185337    fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
185338}
185339        break;
185340      case 2: /* colset ::= LCP colsetlist RCP */
185341{ fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
185342        break;
185343      case 3: /* colset ::= STRING */
185344{
185345  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
185346}
185347  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
185348        break;
185349      case 4: /* colset ::= MINUS STRING */
185350{
185351  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
185352  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
185353}
185354        break;
185355      case 5: /* colsetlist ::= colsetlist STRING */
185356{
185357  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
185358  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
185359        break;
185360      case 6: /* colsetlist ::= STRING */
185361{
185362  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
185363}
185364  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
185365        break;
185366      case 7: /* expr ::= expr AND expr */
185367{
185368  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
185369}
185370  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
185371        break;
185372      case 8: /* expr ::= expr OR expr */
185373{
185374  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
185375}
185376  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
185377        break;
185378      case 9: /* expr ::= expr NOT expr */
185379{
185380  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
185381}
185382  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
185383        break;
185384      case 10: /* expr ::= colset COLON LP expr RP */
185385{
185386  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
185387  fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
185388}
185389  fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
185390        break;
185391      case 11: /* expr ::= LP expr RP */
185392{fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
185393        break;
185394      case 12: /* expr ::= exprlist */
185395      case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
185396{fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
185397  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
185398        break;
185399      case 14: /* exprlist ::= exprlist cnearset */
185400{
185401  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
185402}
185403  fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
185404        break;
185405      case 15: /* cnearset ::= nearset */
185406{
185407  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
185408}
185409  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
185410        break;
185411      case 16: /* cnearset ::= colset COLON nearset */
185412{
185413  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
185414  sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
185415}
185416  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
185417        break;
185418      case 17: /* nearset ::= phrase */
185419{ fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
185420  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
185421        break;
185422      case 18: /* nearset ::= STRING LP nearphrases neardist_opt RP */
185423{
185424  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
185425  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
185426  fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
185427}
185428  fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
185429        break;
185430      case 19: /* nearphrases ::= phrase */
185431{
185432  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
185433}
185434  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
185435        break;
185436      case 20: /* nearphrases ::= nearphrases phrase */
185437{
185438  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
185439}
185440  fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
185441        break;
185442      case 21: /* neardist_opt ::= */
185443{ fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
185444        break;
185445      case 22: /* neardist_opt ::= COMMA STRING */
185446{ fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
185447        break;
185448      case 23: /* phrase ::= phrase PLUS STRING star_opt */
185449{
185450  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
185451}
185452  fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
185453        break;
185454      case 24: /* phrase ::= STRING star_opt */
185455{
185456  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
185457}
185458  fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
185459        break;
185460      case 25: /* star_opt ::= STAR */
185461{ fts5yymsp[0].minor.fts5yy4 = 1; }
185462        break;
185463      case 26: /* star_opt ::= */
185464{ fts5yymsp[1].minor.fts5yy4 = 0; }
185465        break;
185466      default:
185467        break;
185468/********** End reduce actions ************************************************/
185469  };
185470  assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
185471  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
185472  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
185473  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
185474
185475  /* There are no SHIFTREDUCE actions on nonterminals because the table
185476  ** generator has simplified them to pure REDUCE actions. */
185477  assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
185478
185479  /* It is not possible for a REDUCE to be followed by an error */
185480  assert( fts5yyact!=fts5YY_ERROR_ACTION );
185481
185482  if( fts5yyact==fts5YY_ACCEPT_ACTION ){
185483    fts5yypParser->fts5yytos += fts5yysize;
185484    fts5yy_accept(fts5yypParser);
185485  }else{
185486    fts5yymsp += fts5yysize+1;
185487    fts5yypParser->fts5yytos = fts5yymsp;
185488    fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
185489    fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
185490    fts5yyTraceShift(fts5yypParser, fts5yyact);
185491  }
185492}
185493
185494/*
185495** The following code executes when the parse fails
185496*/
185497#ifndef fts5YYNOERRORRECOVERY
185498static void fts5yy_parse_failed(
185499  fts5yyParser *fts5yypParser           /* The parser */
185500){
185501  sqlite3Fts5ParserARG_FETCH;
185502#ifndef NDEBUG
185503  if( fts5yyTraceFILE ){
185504    fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
185505  }
185506#endif
185507  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
185508  /* Here code is inserted which will be executed whenever the
185509  ** parser fails */
185510/************ Begin %parse_failure code ***************************************/
185511/************ End %parse_failure code *****************************************/
185512  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
185513}
185514#endif /* fts5YYNOERRORRECOVERY */
185515
185516/*
185517** The following code executes when a syntax error first occurs.
185518*/
185519static void fts5yy_syntax_error(
185520  fts5yyParser *fts5yypParser,           /* The parser */
185521  int fts5yymajor,                   /* The major type of the error token */
185522  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
185523){
185524  sqlite3Fts5ParserARG_FETCH;
185525#define FTS5TOKEN fts5yyminor
185526/************ Begin %syntax_error code ****************************************/
185527
185528  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
185529  sqlite3Fts5ParseError(
185530    pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
185531  );
185532/************ End %syntax_error code ******************************************/
185533  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
185534}
185535
185536/*
185537** The following is executed when the parser accepts
185538*/
185539static void fts5yy_accept(
185540  fts5yyParser *fts5yypParser           /* The parser */
185541){
185542  sqlite3Fts5ParserARG_FETCH;
185543#ifndef NDEBUG
185544  if( fts5yyTraceFILE ){
185545    fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
185546  }
185547#endif
185548#ifndef fts5YYNOERRORRECOVERY
185549  fts5yypParser->fts5yyerrcnt = -1;
185550#endif
185551  assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
185552  /* Here code is inserted which will be executed whenever the
185553  ** parser accepts */
185554/*********** Begin %parse_accept code *****************************************/
185555/*********** End %parse_accept code *******************************************/
185556  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
185557}
185558
185559/* The main parser program.
185560** The first argument is a pointer to a structure obtained from
185561** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
185562** The second argument is the major token number.  The third is
185563** the minor token.  The fourth optional argument is whatever the
185564** user wants (and specified in the grammar) and is available for
185565** use by the action routines.
185566**
185567** Inputs:
185568** <ul>
185569** <li> A pointer to the parser (an opaque structure.)
185570** <li> The major token number.
185571** <li> The minor token number.
185572** <li> An option argument of a grammar-specified type.
185573** </ul>
185574**
185575** Outputs:
185576** None.
185577*/
185578static void sqlite3Fts5Parser(
185579  void *fts5yyp,                   /* The parser */
185580  int fts5yymajor,                 /* The major token code number */
185581  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
185582  sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
185583){
185584  fts5YYMINORTYPE fts5yyminorunion;
185585  unsigned int fts5yyact;   /* The parser action. */
185586#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
185587  int fts5yyendofinput;     /* True if we are at the end of input */
185588#endif
185589#ifdef fts5YYERRORSYMBOL
185590  int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
185591#endif
185592  fts5yyParser *fts5yypParser;  /* The parser */
185593
185594  fts5yypParser = (fts5yyParser*)fts5yyp;
185595  assert( fts5yypParser->fts5yytos!=0 );
185596#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
185597  fts5yyendofinput = (fts5yymajor==0);
185598#endif
185599  sqlite3Fts5ParserARG_STORE;
185600
185601#ifndef NDEBUG
185602  if( fts5yyTraceFILE ){
185603    fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
185604  }
185605#endif
185606
185607  do{
185608    fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
185609    if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
185610      fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
185611#ifndef fts5YYNOERRORRECOVERY
185612      fts5yypParser->fts5yyerrcnt--;
185613#endif
185614      fts5yymajor = fts5YYNOCODE;
185615    }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
185616      fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
185617    }else{
185618      assert( fts5yyact == fts5YY_ERROR_ACTION );
185619      fts5yyminorunion.fts5yy0 = fts5yyminor;
185620#ifdef fts5YYERRORSYMBOL
185621      int fts5yymx;
185622#endif
185623#ifndef NDEBUG
185624      if( fts5yyTraceFILE ){
185625        fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
185626      }
185627#endif
185628#ifdef fts5YYERRORSYMBOL
185629      /* A syntax error has occurred.
185630      ** The response to an error depends upon whether or not the
185631      ** grammar defines an error token "ERROR".
185632      **
185633      ** This is what we do if the grammar does define ERROR:
185634      **
185635      **  * Call the %syntax_error function.
185636      **
185637      **  * Begin popping the stack until we enter a state where
185638      **    it is legal to shift the error symbol, then shift
185639      **    the error symbol.
185640      **
185641      **  * Set the error count to three.
185642      **
185643      **  * Begin accepting and shifting new tokens.  No new error
185644      **    processing will occur until three tokens have been
185645      **    shifted successfully.
185646      **
185647      */
185648      if( fts5yypParser->fts5yyerrcnt<0 ){
185649        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
185650      }
185651      fts5yymx = fts5yypParser->fts5yytos->major;
185652      if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
185653#ifndef NDEBUG
185654        if( fts5yyTraceFILE ){
185655          fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
185656             fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
185657        }
185658#endif
185659        fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
185660        fts5yymajor = fts5YYNOCODE;
185661      }else{
185662        while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
185663            && fts5yymx != fts5YYERRORSYMBOL
185664            && (fts5yyact = fts5yy_find_reduce_action(
185665                        fts5yypParser->fts5yytos->stateno,
185666                        fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
185667        ){
185668          fts5yy_pop_parser_stack(fts5yypParser);
185669        }
185670        if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
185671          fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
185672          fts5yy_parse_failed(fts5yypParser);
185673#ifndef fts5YYNOERRORRECOVERY
185674          fts5yypParser->fts5yyerrcnt = -1;
185675#endif
185676          fts5yymajor = fts5YYNOCODE;
185677        }else if( fts5yymx!=fts5YYERRORSYMBOL ){
185678          fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
185679        }
185680      }
185681      fts5yypParser->fts5yyerrcnt = 3;
185682      fts5yyerrorhit = 1;
185683#elif defined(fts5YYNOERRORRECOVERY)
185684      /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
185685      ** do any kind of error recovery.  Instead, simply invoke the syntax
185686      ** error routine and continue going as if nothing had happened.
185687      **
185688      ** Applications can set this macro (for example inside %include) if
185689      ** they intend to abandon the parse upon the first syntax error seen.
185690      */
185691      fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
185692      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
185693      fts5yymajor = fts5YYNOCODE;
185694
185695#else  /* fts5YYERRORSYMBOL is not defined */
185696      /* This is what we do if the grammar does not define ERROR:
185697      **
185698      **  * Report an error message, and throw away the input token.
185699      **
185700      **  * If the input token is $, then fail the parse.
185701      **
185702      ** As before, subsequent error messages are suppressed until
185703      ** three input tokens have been successfully shifted.
185704      */
185705      if( fts5yypParser->fts5yyerrcnt<=0 ){
185706        fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
185707      }
185708      fts5yypParser->fts5yyerrcnt = 3;
185709      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
185710      if( fts5yyendofinput ){
185711        fts5yy_parse_failed(fts5yypParser);
185712#ifndef fts5YYNOERRORRECOVERY
185713        fts5yypParser->fts5yyerrcnt = -1;
185714#endif
185715      }
185716      fts5yymajor = fts5YYNOCODE;
185717#endif
185718    }
185719  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
185720#ifndef NDEBUG
185721  if( fts5yyTraceFILE ){
185722    fts5yyStackEntry *i;
185723    char cDiv = '[';
185724    fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
185725    for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
185726      fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
185727      cDiv = ' ';
185728    }
185729    fprintf(fts5yyTraceFILE,"]\n");
185730  }
185731#endif
185732  return;
185733}
185734
185735/*
185736** 2014 May 31
185737**
185738** The author disclaims copyright to this source code.  In place of
185739** a legal notice, here is a blessing:
185740**
185741**    May you do good and not evil.
185742**    May you find forgiveness for yourself and forgive others.
185743**    May you share freely, never taking more than you give.
185744**
185745******************************************************************************
185746*/
185747
185748
185749/* #include "fts5Int.h" */
185750#include <math.h>                 /* amalgamator: keep */
185751
185752/*
185753** Object used to iterate through all "coalesced phrase instances" in
185754** a single column of the current row. If the phrase instances in the
185755** column being considered do not overlap, this object simply iterates
185756** through them. Or, if they do overlap (share one or more tokens in
185757** common), each set of overlapping instances is treated as a single
185758** match. See documentation for the highlight() auxiliary function for
185759** details.
185760**
185761** Usage is:
185762**
185763**   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
185764**      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
185765**      rc = fts5CInstIterNext(&iter)
185766**   ){
185767**     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
185768**   }
185769**
185770*/
185771typedef struct CInstIter CInstIter;
185772struct CInstIter {
185773  const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
185774  Fts5Context *pFts;              /* First arg to pass to pApi functions */
185775  int iCol;                       /* Column to search */
185776  int iInst;                      /* Next phrase instance index */
185777  int nInst;                      /* Total number of phrase instances */
185778
185779  /* Output variables */
185780  int iStart;                     /* First token in coalesced phrase instance */
185781  int iEnd;                       /* Last token in coalesced phrase instance */
185782};
185783
185784/*
185785** Advance the iterator to the next coalesced phrase instance. Return
185786** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
185787*/
185788static int fts5CInstIterNext(CInstIter *pIter){
185789  int rc = SQLITE_OK;
185790  pIter->iStart = -1;
185791  pIter->iEnd = -1;
185792
185793  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
185794    int ip; int ic; int io;
185795    rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
185796    if( rc==SQLITE_OK ){
185797      if( ic==pIter->iCol ){
185798        int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
185799        if( pIter->iStart<0 ){
185800          pIter->iStart = io;
185801          pIter->iEnd = iEnd;
185802        }else if( io<=pIter->iEnd ){
185803          if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
185804        }else{
185805          break;
185806        }
185807      }
185808      pIter->iInst++;
185809    }
185810  }
185811
185812  return rc;
185813}
185814
185815/*
185816** Initialize the iterator object indicated by the final parameter to
185817** iterate through coalesced phrase instances in column iCol.
185818*/
185819static int fts5CInstIterInit(
185820  const Fts5ExtensionApi *pApi,
185821  Fts5Context *pFts,
185822  int iCol,
185823  CInstIter *pIter
185824){
185825  int rc;
185826
185827  memset(pIter, 0, sizeof(CInstIter));
185828  pIter->pApi = pApi;
185829  pIter->pFts = pFts;
185830  pIter->iCol = iCol;
185831  rc = pApi->xInstCount(pFts, &pIter->nInst);
185832
185833  if( rc==SQLITE_OK ){
185834    rc = fts5CInstIterNext(pIter);
185835  }
185836
185837  return rc;
185838}
185839
185840
185841
185842/*************************************************************************
185843** Start of highlight() implementation.
185844*/
185845typedef struct HighlightContext HighlightContext;
185846struct HighlightContext {
185847  CInstIter iter;                 /* Coalesced Instance Iterator */
185848  int iPos;                       /* Current token offset in zIn[] */
185849  int iRangeStart;                /* First token to include */
185850  int iRangeEnd;                  /* If non-zero, last token to include */
185851  const char *zOpen;              /* Opening highlight */
185852  const char *zClose;             /* Closing highlight */
185853  const char *zIn;                /* Input text */
185854  int nIn;                        /* Size of input text in bytes */
185855  int iOff;                       /* Current offset within zIn[] */
185856  char *zOut;                     /* Output value */
185857};
185858
185859/*
185860** Append text to the HighlightContext output string - p->zOut. Argument
185861** z points to a buffer containing n bytes of text to append. If n is
185862** negative, everything up until the first '\0' is appended to the output.
185863**
185864** If *pRc is set to any value other than SQLITE_OK when this function is
185865** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
185866** *pRc is set to an error code before returning.
185867*/
185868static void fts5HighlightAppend(
185869  int *pRc,
185870  HighlightContext *p,
185871  const char *z, int n
185872){
185873  if( *pRc==SQLITE_OK ){
185874    if( n<0 ) n = (int)strlen(z);
185875    p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
185876    if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
185877  }
185878}
185879
185880/*
185881** Tokenizer callback used by implementation of highlight() function.
185882*/
185883static int fts5HighlightCb(
185884  void *pContext,                 /* Pointer to HighlightContext object */
185885  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
185886  const char *pToken,             /* Buffer containing token */
185887  int nToken,                     /* Size of token in bytes */
185888  int iStartOff,                  /* Start offset of token */
185889  int iEndOff                     /* End offset of token */
185890){
185891  HighlightContext *p = (HighlightContext*)pContext;
185892  int rc = SQLITE_OK;
185893  int iPos;
185894
185895  UNUSED_PARAM2(pToken, nToken);
185896
185897  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
185898  iPos = p->iPos++;
185899
185900  if( p->iRangeEnd>0 ){
185901    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
185902    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
185903  }
185904
185905  if( iPos==p->iter.iStart ){
185906    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
185907    fts5HighlightAppend(&rc, p, p->zOpen, -1);
185908    p->iOff = iStartOff;
185909  }
185910
185911  if( iPos==p->iter.iEnd ){
185912    if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
185913      fts5HighlightAppend(&rc, p, p->zOpen, -1);
185914    }
185915    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
185916    fts5HighlightAppend(&rc, p, p->zClose, -1);
185917    p->iOff = iEndOff;
185918    if( rc==SQLITE_OK ){
185919      rc = fts5CInstIterNext(&p->iter);
185920    }
185921  }
185922
185923  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
185924    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
185925    p->iOff = iEndOff;
185926    if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
185927      fts5HighlightAppend(&rc, p, p->zClose, -1);
185928    }
185929  }
185930
185931  return rc;
185932}
185933
185934/*
185935** Implementation of highlight() function.
185936*/
185937static void fts5HighlightFunction(
185938  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
185939  Fts5Context *pFts,              /* First arg to pass to pApi functions */
185940  sqlite3_context *pCtx,          /* Context for returning result/error */
185941  int nVal,                       /* Number of values in apVal[] array */
185942  sqlite3_value **apVal           /* Array of trailing arguments */
185943){
185944  HighlightContext ctx;
185945  int rc;
185946  int iCol;
185947
185948  if( nVal!=3 ){
185949    const char *zErr = "wrong number of arguments to function highlight()";
185950    sqlite3_result_error(pCtx, zErr, -1);
185951    return;
185952  }
185953
185954  iCol = sqlite3_value_int(apVal[0]);
185955  memset(&ctx, 0, sizeof(HighlightContext));
185956  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
185957  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
185958  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
185959
185960  if( ctx.zIn ){
185961    if( rc==SQLITE_OK ){
185962      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
185963    }
185964
185965    if( rc==SQLITE_OK ){
185966      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
185967    }
185968    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
185969
185970    if( rc==SQLITE_OK ){
185971      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
185972    }
185973    sqlite3_free(ctx.zOut);
185974  }
185975  if( rc!=SQLITE_OK ){
185976    sqlite3_result_error_code(pCtx, rc);
185977  }
185978}
185979/*
185980** End of highlight() implementation.
185981**************************************************************************/
185982
185983/*
185984** Context object passed to the fts5SentenceFinderCb() function.
185985*/
185986typedef struct Fts5SFinder Fts5SFinder;
185987struct Fts5SFinder {
185988  int iPos;                       /* Current token position */
185989  int nFirstAlloc;                /* Allocated size of aFirst[] */
185990  int nFirst;                     /* Number of entries in aFirst[] */
185991  int *aFirst;                    /* Array of first token in each sentence */
185992  const char *zDoc;               /* Document being tokenized */
185993};
185994
185995/*
185996** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
185997** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
185998** error occurs.
185999*/
186000static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
186001  if( p->nFirstAlloc==p->nFirst ){
186002    int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
186003    int *aNew;
186004
186005    aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
186006    if( aNew==0 ) return SQLITE_NOMEM;
186007    p->aFirst = aNew;
186008    p->nFirstAlloc = nNew;
186009  }
186010  p->aFirst[p->nFirst++] = iAdd;
186011  return SQLITE_OK;
186012}
186013
186014/*
186015** This function is an xTokenize() callback used by the auxiliary snippet()
186016** function. Its job is to identify tokens that are the first in a sentence.
186017** For each such token, an entry is added to the SFinder.aFirst[] array.
186018*/
186019static int fts5SentenceFinderCb(
186020  void *pContext,                 /* Pointer to HighlightContext object */
186021  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
186022  const char *pToken,             /* Buffer containing token */
186023  int nToken,                     /* Size of token in bytes */
186024  int iStartOff,                  /* Start offset of token */
186025  int iEndOff                     /* End offset of token */
186026){
186027  int rc = SQLITE_OK;
186028
186029  UNUSED_PARAM2(pToken, nToken);
186030  UNUSED_PARAM(iEndOff);
186031
186032  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
186033    Fts5SFinder *p = (Fts5SFinder*)pContext;
186034    if( p->iPos>0 ){
186035      int i;
186036      char c = 0;
186037      for(i=iStartOff-1; i>=0; i--){
186038        c = p->zDoc[i];
186039        if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
186040      }
186041      if( i!=iStartOff-1 && (c=='.' || c==':') ){
186042        rc = fts5SentenceFinderAdd(p, p->iPos);
186043      }
186044    }else{
186045      rc = fts5SentenceFinderAdd(p, 0);
186046    }
186047    p->iPos++;
186048  }
186049  return rc;
186050}
186051
186052static int fts5SnippetScore(
186053  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
186054  Fts5Context *pFts,              /* First arg to pass to pApi functions */
186055  int nDocsize,                   /* Size of column in tokens */
186056  unsigned char *aSeen,           /* Array with one element per query phrase */
186057  int iCol,                       /* Column to score */
186058  int iPos,                       /* Starting offset to score */
186059  int nToken,                     /* Max tokens per snippet */
186060  int *pnScore,                   /* OUT: Score */
186061  int *piPos                      /* OUT: Adjusted offset */
186062){
186063  int rc;
186064  int i;
186065  int ip = 0;
186066  int ic = 0;
186067  int iOff = 0;
186068  int iFirst = -1;
186069  int nInst;
186070  int nScore = 0;
186071  int iLast = 0;
186072
186073  rc = pApi->xInstCount(pFts, &nInst);
186074  for(i=0; i<nInst && rc==SQLITE_OK; i++){
186075    rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
186076    if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
186077      nScore += (aSeen[ip] ? 1 : 1000);
186078      aSeen[ip] = 1;
186079      if( iFirst<0 ) iFirst = iOff;
186080      iLast = iOff + pApi->xPhraseSize(pFts, ip);
186081    }
186082  }
186083
186084  *pnScore = nScore;
186085  if( piPos ){
186086    int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
186087    if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
186088    if( iAdj<0 ) iAdj = 0;
186089    *piPos = iAdj;
186090  }
186091
186092  return rc;
186093}
186094
186095/*
186096** Implementation of snippet() function.
186097*/
186098static void fts5SnippetFunction(
186099  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
186100  Fts5Context *pFts,              /* First arg to pass to pApi functions */
186101  sqlite3_context *pCtx,          /* Context for returning result/error */
186102  int nVal,                       /* Number of values in apVal[] array */
186103  sqlite3_value **apVal           /* Array of trailing arguments */
186104){
186105  HighlightContext ctx;
186106  int rc = SQLITE_OK;             /* Return code */
186107  int iCol;                       /* 1st argument to snippet() */
186108  const char *zEllips;            /* 4th argument to snippet() */
186109  int nToken;                     /* 5th argument to snippet() */
186110  int nInst = 0;                  /* Number of instance matches this row */
186111  int i;                          /* Used to iterate through instances */
186112  int nPhrase;                    /* Number of phrases in query */
186113  unsigned char *aSeen;           /* Array of "seen instance" flags */
186114  int iBestCol;                   /* Column containing best snippet */
186115  int iBestStart = 0;             /* First token of best snippet */
186116  int nBestScore = 0;             /* Score of best snippet */
186117  int nColSize = 0;               /* Total size of iBestCol in tokens */
186118  Fts5SFinder sFinder;            /* Used to find the beginnings of sentences */
186119  int nCol;
186120
186121  if( nVal!=5 ){
186122    const char *zErr = "wrong number of arguments to function snippet()";
186123    sqlite3_result_error(pCtx, zErr, -1);
186124    return;
186125  }
186126
186127  nCol = pApi->xColumnCount(pFts);
186128  memset(&ctx, 0, sizeof(HighlightContext));
186129  iCol = sqlite3_value_int(apVal[0]);
186130  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
186131  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
186132  zEllips = (const char*)sqlite3_value_text(apVal[3]);
186133  nToken = sqlite3_value_int(apVal[4]);
186134
186135  iBestCol = (iCol>=0 ? iCol : 0);
186136  nPhrase = pApi->xPhraseCount(pFts);
186137  aSeen = sqlite3_malloc(nPhrase);
186138  if( aSeen==0 ){
186139    rc = SQLITE_NOMEM;
186140  }
186141  if( rc==SQLITE_OK ){
186142    rc = pApi->xInstCount(pFts, &nInst);
186143  }
186144
186145  memset(&sFinder, 0, sizeof(Fts5SFinder));
186146  for(i=0; i<nCol; i++){
186147    if( iCol<0 || iCol==i ){
186148      int nDoc;
186149      int nDocsize;
186150      int ii;
186151      sFinder.iPos = 0;
186152      sFinder.nFirst = 0;
186153      rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
186154      if( rc!=SQLITE_OK ) break;
186155      rc = pApi->xTokenize(pFts,
186156          sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
186157      );
186158      if( rc!=SQLITE_OK ) break;
186159      rc = pApi->xColumnSize(pFts, i, &nDocsize);
186160      if( rc!=SQLITE_OK ) break;
186161
186162      for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
186163        int ip, ic, io;
186164        int iAdj;
186165        int nScore;
186166        int jj;
186167
186168        rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
186169        if( ic!=i || rc!=SQLITE_OK ) continue;
186170        memset(aSeen, 0, nPhrase);
186171        rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
186172            io, nToken, &nScore, &iAdj
186173        );
186174        if( rc==SQLITE_OK && nScore>nBestScore ){
186175          nBestScore = nScore;
186176          iBestCol = i;
186177          iBestStart = iAdj;
186178          nColSize = nDocsize;
186179        }
186180
186181        if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
186182          for(jj=0; jj<(sFinder.nFirst-1); jj++){
186183            if( sFinder.aFirst[jj+1]>io ) break;
186184          }
186185
186186          if( sFinder.aFirst[jj]<io ){
186187            memset(aSeen, 0, nPhrase);
186188            rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
186189              sFinder.aFirst[jj], nToken, &nScore, 0
186190            );
186191
186192            nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
186193            if( rc==SQLITE_OK && nScore>nBestScore ){
186194              nBestScore = nScore;
186195              iBestCol = i;
186196              iBestStart = sFinder.aFirst[jj];
186197              nColSize = nDocsize;
186198            }
186199          }
186200        }
186201      }
186202    }
186203  }
186204
186205  if( rc==SQLITE_OK ){
186206    rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
186207  }
186208  if( rc==SQLITE_OK && nColSize==0 ){
186209    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
186210  }
186211  if( ctx.zIn ){
186212    if( rc==SQLITE_OK ){
186213      rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
186214    }
186215
186216    ctx.iRangeStart = iBestStart;
186217    ctx.iRangeEnd = iBestStart + nToken - 1;
186218
186219    if( iBestStart>0 ){
186220      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
186221    }
186222
186223    /* Advance iterator ctx.iter so that it points to the first coalesced
186224    ** phrase instance at or following position iBestStart. */
186225    while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
186226      rc = fts5CInstIterNext(&ctx.iter);
186227    }
186228
186229    if( rc==SQLITE_OK ){
186230      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
186231    }
186232    if( ctx.iRangeEnd>=(nColSize-1) ){
186233      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
186234    }else{
186235      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
186236    }
186237  }
186238  if( rc==SQLITE_OK ){
186239    sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
186240  }else{
186241    sqlite3_result_error_code(pCtx, rc);
186242  }
186243  sqlite3_free(ctx.zOut);
186244  sqlite3_free(aSeen);
186245  sqlite3_free(sFinder.aFirst);
186246}
186247
186248/************************************************************************/
186249
186250/*
186251** The first time the bm25() function is called for a query, an instance
186252** of the following structure is allocated and populated.
186253*/
186254typedef struct Fts5Bm25Data Fts5Bm25Data;
186255struct Fts5Bm25Data {
186256  int nPhrase;                    /* Number of phrases in query */
186257  double avgdl;                   /* Average number of tokens in each row */
186258  double *aIDF;                   /* IDF for each phrase */
186259  double *aFreq;                  /* Array used to calculate phrase freq. */
186260};
186261
186262/*
186263** Callback used by fts5Bm25GetData() to count the number of rows in the
186264** table matched by each individual phrase within the query.
186265*/
186266static int fts5CountCb(
186267  const Fts5ExtensionApi *pApi,
186268  Fts5Context *pFts,
186269  void *pUserData                 /* Pointer to sqlite3_int64 variable */
186270){
186271  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
186272  UNUSED_PARAM2(pApi, pFts);
186273  (*pn)++;
186274  return SQLITE_OK;
186275}
186276
186277/*
186278** Set *ppData to point to the Fts5Bm25Data object for the current query.
186279** If the object has not already been allocated, allocate and populate it
186280** now.
186281*/
186282static int fts5Bm25GetData(
186283  const Fts5ExtensionApi *pApi,
186284  Fts5Context *pFts,
186285  Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
186286){
186287  int rc = SQLITE_OK;             /* Return code */
186288  Fts5Bm25Data *p;                /* Object to return */
186289
186290  p = pApi->xGetAuxdata(pFts, 0);
186291  if( p==0 ){
186292    int nPhrase;                  /* Number of phrases in query */
186293    sqlite3_int64 nRow = 0;       /* Number of rows in table */
186294    sqlite3_int64 nToken = 0;     /* Number of tokens in table */
186295    int nByte;                    /* Bytes of space to allocate */
186296    int i;
186297
186298    /* Allocate the Fts5Bm25Data object */
186299    nPhrase = pApi->xPhraseCount(pFts);
186300    nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
186301    p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
186302    if( p==0 ){
186303      rc = SQLITE_NOMEM;
186304    }else{
186305      memset(p, 0, nByte);
186306      p->nPhrase = nPhrase;
186307      p->aIDF = (double*)&p[1];
186308      p->aFreq = &p->aIDF[nPhrase];
186309    }
186310
186311    /* Calculate the average document length for this FTS5 table */
186312    if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
186313    if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
186314    if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
186315
186316    /* Calculate an IDF for each phrase in the query */
186317    for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
186318      sqlite3_int64 nHit = 0;
186319      rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
186320      if( rc==SQLITE_OK ){
186321        /* Calculate the IDF (Inverse Document Frequency) for phrase i.
186322        ** This is done using the standard BM25 formula as found on wikipedia:
186323        **
186324        **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
186325        **
186326        ** where "N" is the total number of documents in the set and nHit
186327        ** is the number that contain at least one instance of the phrase
186328        ** under consideration.
186329        **
186330        ** The problem with this is that if (N < 2*nHit), the IDF is
186331        ** negative. Which is undesirable. So the mimimum allowable IDF is
186332        ** (1e-6) - roughly the same as a term that appears in just over
186333        ** half of set of 5,000,000 documents.  */
186334        double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
186335        if( idf<=0.0 ) idf = 1e-6;
186336        p->aIDF[i] = idf;
186337      }
186338    }
186339
186340    if( rc!=SQLITE_OK ){
186341      sqlite3_free(p);
186342    }else{
186343      rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
186344    }
186345    if( rc!=SQLITE_OK ) p = 0;
186346  }
186347  *ppData = p;
186348  return rc;
186349}
186350
186351/*
186352** Implementation of bm25() function.
186353*/
186354static void fts5Bm25Function(
186355  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
186356  Fts5Context *pFts,              /* First arg to pass to pApi functions */
186357  sqlite3_context *pCtx,          /* Context for returning result/error */
186358  int nVal,                       /* Number of values in apVal[] array */
186359  sqlite3_value **apVal           /* Array of trailing arguments */
186360){
186361  const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
186362  const double b = 0.75;          /* Constant "b" from BM25 formula */
186363  int rc = SQLITE_OK;             /* Error code */
186364  double score = 0.0;             /* SQL function return value */
186365  Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
186366  int i;                          /* Iterator variable */
186367  int nInst = 0;                  /* Value returned by xInstCount() */
186368  double D = 0.0;                 /* Total number of tokens in row */
186369  double *aFreq = 0;              /* Array of phrase freq. for current row */
186370
186371  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
186372  ** for each phrase in the query for the current row. */
186373  rc = fts5Bm25GetData(pApi, pFts, &pData);
186374  if( rc==SQLITE_OK ){
186375    aFreq = pData->aFreq;
186376    memset(aFreq, 0, sizeof(double) * pData->nPhrase);
186377    rc = pApi->xInstCount(pFts, &nInst);
186378  }
186379  for(i=0; rc==SQLITE_OK && i<nInst; i++){
186380    int ip; int ic; int io;
186381    rc = pApi->xInst(pFts, i, &ip, &ic, &io);
186382    if( rc==SQLITE_OK ){
186383      double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
186384      aFreq[ip] += w;
186385    }
186386  }
186387
186388  /* Figure out the total size of the current row in tokens. */
186389  if( rc==SQLITE_OK ){
186390    int nTok;
186391    rc = pApi->xColumnSize(pFts, -1, &nTok);
186392    D = (double)nTok;
186393  }
186394
186395  /* Determine the BM25 score for the current row. */
186396  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
186397    score += pData->aIDF[i] * (
186398      ( aFreq[i] * (k1 + 1.0) ) /
186399      ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
186400    );
186401  }
186402
186403  /* If no error has occurred, return the calculated score. Otherwise,
186404  ** throw an SQL exception.  */
186405  if( rc==SQLITE_OK ){
186406    sqlite3_result_double(pCtx, -1.0 * score);
186407  }else{
186408    sqlite3_result_error_code(pCtx, rc);
186409  }
186410}
186411
186412static int sqlite3Fts5AuxInit(fts5_api *pApi){
186413  struct Builtin {
186414    const char *zFunc;            /* Function name (nul-terminated) */
186415    void *pUserData;              /* User-data pointer */
186416    fts5_extension_function xFunc;/* Callback function */
186417    void (*xDestroy)(void*);      /* Destructor function */
186418  } aBuiltin [] = {
186419    { "snippet",   0, fts5SnippetFunction, 0 },
186420    { "highlight", 0, fts5HighlightFunction, 0 },
186421    { "bm25",      0, fts5Bm25Function,    0 },
186422  };
186423  int rc = SQLITE_OK;             /* Return code */
186424  int i;                          /* To iterate through builtin functions */
186425
186426  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
186427    rc = pApi->xCreateFunction(pApi,
186428        aBuiltin[i].zFunc,
186429        aBuiltin[i].pUserData,
186430        aBuiltin[i].xFunc,
186431        aBuiltin[i].xDestroy
186432    );
186433  }
186434
186435  return rc;
186436}
186437
186438
186439
186440/*
186441** 2014 May 31
186442**
186443** The author disclaims copyright to this source code.  In place of
186444** a legal notice, here is a blessing:
186445**
186446**    May you do good and not evil.
186447**    May you find forgiveness for yourself and forgive others.
186448**    May you share freely, never taking more than you give.
186449**
186450******************************************************************************
186451*/
186452
186453
186454
186455/* #include "fts5Int.h" */
186456
186457static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
186458  if( (u32)pBuf->nSpace<nByte ){
186459    u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
186460    u8 *pNew;
186461    while( nNew<nByte ){
186462      nNew = nNew * 2;
186463    }
186464    pNew = sqlite3_realloc(pBuf->p, nNew);
186465    if( pNew==0 ){
186466      *pRc = SQLITE_NOMEM;
186467      return 1;
186468    }else{
186469      pBuf->nSpace = nNew;
186470      pBuf->p = pNew;
186471    }
186472  }
186473  return 0;
186474}
186475
186476
186477/*
186478** Encode value iVal as an SQLite varint and append it to the buffer object
186479** pBuf. If an OOM error occurs, set the error code in p.
186480*/
186481static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
186482  if( fts5BufferGrow(pRc, pBuf, 9) ) return;
186483  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
186484}
186485
186486static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
186487  aBuf[0] = (iVal>>24) & 0x00FF;
186488  aBuf[1] = (iVal>>16) & 0x00FF;
186489  aBuf[2] = (iVal>> 8) & 0x00FF;
186490  aBuf[3] = (iVal>> 0) & 0x00FF;
186491}
186492
186493static int sqlite3Fts5Get32(const u8 *aBuf){
186494  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
186495}
186496
186497/*
186498** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
186499** the error code in p. If an error has already occurred when this function
186500** is called, it is a no-op.
186501*/
186502static void sqlite3Fts5BufferAppendBlob(
186503  int *pRc,
186504  Fts5Buffer *pBuf,
186505  u32 nData,
186506  const u8 *pData
186507){
186508  assert_nc( *pRc || nData>=0 );
186509  if( nData ){
186510    if( fts5BufferGrow(pRc, pBuf, nData) ) return;
186511    memcpy(&pBuf->p[pBuf->n], pData, nData);
186512    pBuf->n += nData;
186513  }
186514}
186515
186516/*
186517** Append the nul-terminated string zStr to the buffer pBuf. This function
186518** ensures that the byte following the buffer data is set to 0x00, even
186519** though this byte is not included in the pBuf->n count.
186520*/
186521static void sqlite3Fts5BufferAppendString(
186522  int *pRc,
186523  Fts5Buffer *pBuf,
186524  const char *zStr
186525){
186526  int nStr = (int)strlen(zStr);
186527  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
186528  pBuf->n--;
186529}
186530
186531/*
186532** Argument zFmt is a printf() style format string. This function performs
186533** the printf() style processing, then appends the results to buffer pBuf.
186534**
186535** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
186536** following the buffer data is set to 0x00, even though this byte is not
186537** included in the pBuf->n count.
186538*/
186539static void sqlite3Fts5BufferAppendPrintf(
186540  int *pRc,
186541  Fts5Buffer *pBuf,
186542  char *zFmt, ...
186543){
186544  if( *pRc==SQLITE_OK ){
186545    char *zTmp;
186546    va_list ap;
186547    va_start(ap, zFmt);
186548    zTmp = sqlite3_vmprintf(zFmt, ap);
186549    va_end(ap);
186550
186551    if( zTmp==0 ){
186552      *pRc = SQLITE_NOMEM;
186553    }else{
186554      sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
186555      sqlite3_free(zTmp);
186556    }
186557  }
186558}
186559
186560static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
186561  char *zRet = 0;
186562  if( *pRc==SQLITE_OK ){
186563    va_list ap;
186564    va_start(ap, zFmt);
186565    zRet = sqlite3_vmprintf(zFmt, ap);
186566    va_end(ap);
186567    if( zRet==0 ){
186568      *pRc = SQLITE_NOMEM;
186569    }
186570  }
186571  return zRet;
186572}
186573
186574
186575/*
186576** Free any buffer allocated by pBuf. Zero the structure before returning.
186577*/
186578static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
186579  sqlite3_free(pBuf->p);
186580  memset(pBuf, 0, sizeof(Fts5Buffer));
186581}
186582
186583/*
186584** Zero the contents of the buffer object. But do not free the associated
186585** memory allocation.
186586*/
186587static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
186588  pBuf->n = 0;
186589}
186590
186591/*
186592** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
186593** the error code in p. If an error has already occurred when this function
186594** is called, it is a no-op.
186595*/
186596static void sqlite3Fts5BufferSet(
186597  int *pRc,
186598  Fts5Buffer *pBuf,
186599  int nData,
186600  const u8 *pData
186601){
186602  pBuf->n = 0;
186603  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
186604}
186605
186606static int sqlite3Fts5PoslistNext64(
186607  const u8 *a, int n,             /* Buffer containing poslist */
186608  int *pi,                        /* IN/OUT: Offset within a[] */
186609  i64 *piOff                      /* IN/OUT: Current offset */
186610){
186611  int i = *pi;
186612  if( i>=n ){
186613    /* EOF */
186614    *piOff = -1;
186615    return 1;
186616  }else{
186617    i64 iOff = *piOff;
186618    int iVal;
186619    fts5FastGetVarint32(a, i, iVal);
186620    if( iVal==1 ){
186621      fts5FastGetVarint32(a, i, iVal);
186622      iOff = ((i64)iVal) << 32;
186623      fts5FastGetVarint32(a, i, iVal);
186624    }
186625    *piOff = iOff + (iVal-2);
186626    *pi = i;
186627    return 0;
186628  }
186629}
186630
186631
186632/*
186633** Advance the iterator object passed as the only argument. Return true
186634** if the iterator reaches EOF, or false otherwise.
186635*/
186636static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
186637  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
186638    pIter->bEof = 1;
186639  }
186640  return pIter->bEof;
186641}
186642
186643static int sqlite3Fts5PoslistReaderInit(
186644  const u8 *a, int n,             /* Poslist buffer to iterate through */
186645  Fts5PoslistReader *pIter        /* Iterator object to initialize */
186646){
186647  memset(pIter, 0, sizeof(*pIter));
186648  pIter->a = a;
186649  pIter->n = n;
186650  sqlite3Fts5PoslistReaderNext(pIter);
186651  return pIter->bEof;
186652}
186653
186654/*
186655** Append position iPos to the position list being accumulated in buffer
186656** pBuf, which must be already be large enough to hold the new data.
186657** The previous position written to this list is *piPrev. *piPrev is set
186658** to iPos before returning.
186659*/
186660static void sqlite3Fts5PoslistSafeAppend(
186661  Fts5Buffer *pBuf,
186662  i64 *piPrev,
186663  i64 iPos
186664){
186665  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
186666  if( (iPos & colmask) != (*piPrev & colmask) ){
186667    pBuf->p[pBuf->n++] = 1;
186668    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
186669    *piPrev = (iPos & colmask);
186670  }
186671  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
186672  *piPrev = iPos;
186673}
186674
186675static int sqlite3Fts5PoslistWriterAppend(
186676  Fts5Buffer *pBuf,
186677  Fts5PoslistWriter *pWriter,
186678  i64 iPos
186679){
186680  int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
186681  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
186682  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
186683  return SQLITE_OK;
186684}
186685
186686static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
186687  void *pRet = 0;
186688  if( *pRc==SQLITE_OK ){
186689    pRet = sqlite3_malloc(nByte);
186690    if( pRet==0 ){
186691      if( nByte>0 ) *pRc = SQLITE_NOMEM;
186692    }else{
186693      memset(pRet, 0, nByte);
186694    }
186695  }
186696  return pRet;
186697}
186698
186699/*
186700** Return a nul-terminated copy of the string indicated by pIn. If nIn
186701** is non-negative, then it is the length of the string in bytes. Otherwise,
186702** the length of the string is determined using strlen().
186703**
186704** It is the responsibility of the caller to eventually free the returned
186705** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
186706*/
186707static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
186708  char *zRet = 0;
186709  if( *pRc==SQLITE_OK ){
186710    if( nIn<0 ){
186711      nIn = (int)strlen(pIn);
186712    }
186713    zRet = (char*)sqlite3_malloc(nIn+1);
186714    if( zRet ){
186715      memcpy(zRet, pIn, nIn);
186716      zRet[nIn] = '\0';
186717    }else{
186718      *pRc = SQLITE_NOMEM;
186719    }
186720  }
186721  return zRet;
186722}
186723
186724
186725/*
186726** Return true if character 't' may be part of an FTS5 bareword, or false
186727** otherwise. Characters that may be part of barewords:
186728**
186729**   * All non-ASCII characters,
186730**   * The 52 upper and lower case ASCII characters, and
186731**   * The 10 integer ASCII characters.
186732**   * The underscore character "_" (0x5F).
186733**   * The unicode "subsitute" character (0x1A).
186734*/
186735static int sqlite3Fts5IsBareword(char t){
186736  u8 aBareword[128] = {
186737    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
186738    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
186739    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
186740    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
186741    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
186742    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
186743    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
186744    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
186745  };
186746
186747  return (t & 0x80) || aBareword[(int)t];
186748}
186749
186750
186751/*************************************************************************
186752*/
186753typedef struct Fts5TermsetEntry Fts5TermsetEntry;
186754struct Fts5TermsetEntry {
186755  char *pTerm;
186756  int nTerm;
186757  int iIdx;                       /* Index (main or aPrefix[] entry) */
186758  Fts5TermsetEntry *pNext;
186759};
186760
186761struct Fts5Termset {
186762  Fts5TermsetEntry *apHash[512];
186763};
186764
186765static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
186766  int rc = SQLITE_OK;
186767  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
186768  return rc;
186769}
186770
186771static int sqlite3Fts5TermsetAdd(
186772  Fts5Termset *p,
186773  int iIdx,
186774  const char *pTerm, int nTerm,
186775  int *pbPresent
186776){
186777  int rc = SQLITE_OK;
186778  *pbPresent = 0;
186779  if( p ){
186780    int i;
186781    u32 hash = 13;
186782    Fts5TermsetEntry *pEntry;
186783
186784    /* Calculate a hash value for this term. This is the same hash checksum
186785    ** used by the fts5_hash.c module. This is not important for correct
186786    ** operation of the module, but is necessary to ensure that some tests
186787    ** designed to produce hash table collisions really do work.  */
186788    for(i=nTerm-1; i>=0; i--){
186789      hash = (hash << 3) ^ hash ^ pTerm[i];
186790    }
186791    hash = (hash << 3) ^ hash ^ iIdx;
186792    hash = hash % ArraySize(p->apHash);
186793
186794    for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
186795      if( pEntry->iIdx==iIdx
186796          && pEntry->nTerm==nTerm
186797          && memcmp(pEntry->pTerm, pTerm, nTerm)==0
186798      ){
186799        *pbPresent = 1;
186800        break;
186801      }
186802    }
186803
186804    if( pEntry==0 ){
186805      pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
186806      if( pEntry ){
186807        pEntry->pTerm = (char*)&pEntry[1];
186808        pEntry->nTerm = nTerm;
186809        pEntry->iIdx = iIdx;
186810        memcpy(pEntry->pTerm, pTerm, nTerm);
186811        pEntry->pNext = p->apHash[hash];
186812        p->apHash[hash] = pEntry;
186813      }
186814    }
186815  }
186816
186817  return rc;
186818}
186819
186820static void sqlite3Fts5TermsetFree(Fts5Termset *p){
186821  if( p ){
186822    u32 i;
186823    for(i=0; i<ArraySize(p->apHash); i++){
186824      Fts5TermsetEntry *pEntry = p->apHash[i];
186825      while( pEntry ){
186826        Fts5TermsetEntry *pDel = pEntry;
186827        pEntry = pEntry->pNext;
186828        sqlite3_free(pDel);
186829      }
186830    }
186831    sqlite3_free(p);
186832  }
186833}
186834
186835/*
186836** 2014 Jun 09
186837**
186838** The author disclaims copyright to this source code.  In place of
186839** a legal notice, here is a blessing:
186840**
186841**    May you do good and not evil.
186842**    May you find forgiveness for yourself and forgive others.
186843**    May you share freely, never taking more than you give.
186844**
186845******************************************************************************
186846**
186847** This is an SQLite module implementing full-text search.
186848*/
186849
186850
186851/* #include "fts5Int.h" */
186852
186853#define FTS5_DEFAULT_PAGE_SIZE   4050
186854#define FTS5_DEFAULT_AUTOMERGE      4
186855#define FTS5_DEFAULT_USERMERGE      4
186856#define FTS5_DEFAULT_CRISISMERGE   16
186857#define FTS5_DEFAULT_HASHSIZE    (1024*1024)
186858
186859/* Maximum allowed page size */
186860#define FTS5_MAX_PAGE_SIZE (128*1024)
186861
186862static int fts5_iswhitespace(char x){
186863  return (x==' ');
186864}
186865
186866static int fts5_isopenquote(char x){
186867  return (x=='"' || x=='\'' || x=='[' || x=='`');
186868}
186869
186870/*
186871** Argument pIn points to a character that is part of a nul-terminated
186872** string. Return a pointer to the first character following *pIn in
186873** the string that is not a white-space character.
186874*/
186875static const char *fts5ConfigSkipWhitespace(const char *pIn){
186876  const char *p = pIn;
186877  if( p ){
186878    while( fts5_iswhitespace(*p) ){ p++; }
186879  }
186880  return p;
186881}
186882
186883/*
186884** Argument pIn points to a character that is part of a nul-terminated
186885** string. Return a pointer to the first character following *pIn in
186886** the string that is not a "bareword" character.
186887*/
186888static const char *fts5ConfigSkipBareword(const char *pIn){
186889  const char *p = pIn;
186890  while ( sqlite3Fts5IsBareword(*p) ) p++;
186891  if( p==pIn ) p = 0;
186892  return p;
186893}
186894
186895static int fts5_isdigit(char a){
186896  return (a>='0' && a<='9');
186897}
186898
186899
186900
186901static const char *fts5ConfigSkipLiteral(const char *pIn){
186902  const char *p = pIn;
186903  switch( *p ){
186904    case 'n': case 'N':
186905      if( sqlite3_strnicmp("null", p, 4)==0 ){
186906        p = &p[4];
186907      }else{
186908        p = 0;
186909      }
186910      break;
186911
186912    case 'x': case 'X':
186913      p++;
186914      if( *p=='\'' ){
186915        p++;
186916        while( (*p>='a' && *p<='f')
186917            || (*p>='A' && *p<='F')
186918            || (*p>='0' && *p<='9')
186919            ){
186920          p++;
186921        }
186922        if( *p=='\'' && 0==((p-pIn)%2) ){
186923          p++;
186924        }else{
186925          p = 0;
186926        }
186927      }else{
186928        p = 0;
186929      }
186930      break;
186931
186932    case '\'':
186933      p++;
186934      while( p ){
186935        if( *p=='\'' ){
186936          p++;
186937          if( *p!='\'' ) break;
186938        }
186939        p++;
186940        if( *p==0 ) p = 0;
186941      }
186942      break;
186943
186944    default:
186945      /* maybe a number */
186946      if( *p=='+' || *p=='-' ) p++;
186947      while( fts5_isdigit(*p) ) p++;
186948
186949      /* At this point, if the literal was an integer, the parse is
186950      ** finished. Or, if it is a floating point value, it may continue
186951      ** with either a decimal point or an 'E' character. */
186952      if( *p=='.' && fts5_isdigit(p[1]) ){
186953        p += 2;
186954        while( fts5_isdigit(*p) ) p++;
186955      }
186956      if( p==pIn ) p = 0;
186957
186958      break;
186959  }
186960
186961  return p;
186962}
186963
186964/*
186965** The first character of the string pointed to by argument z is guaranteed
186966** to be an open-quote character (see function fts5_isopenquote()).
186967**
186968** This function searches for the corresponding close-quote character within
186969** the string and, if found, dequotes the string in place and adds a new
186970** nul-terminator byte.
186971**
186972** If the close-quote is found, the value returned is the byte offset of
186973** the character immediately following it. Or, if the close-quote is not
186974** found, -1 is returned. If -1 is returned, the buffer is left in an
186975** undefined state.
186976*/
186977static int fts5Dequote(char *z){
186978  char q;
186979  int iIn = 1;
186980  int iOut = 0;
186981  q = z[0];
186982
186983  /* Set stack variable q to the close-quote character */
186984  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
186985  if( q=='[' ) q = ']';
186986
186987  while( ALWAYS(z[iIn]) ){
186988    if( z[iIn]==q ){
186989      if( z[iIn+1]!=q ){
186990        /* Character iIn was the close quote. */
186991        iIn++;
186992        break;
186993      }else{
186994        /* Character iIn and iIn+1 form an escaped quote character. Skip
186995        ** the input cursor past both and copy a single quote character
186996        ** to the output buffer. */
186997        iIn += 2;
186998        z[iOut++] = q;
186999      }
187000    }else{
187001      z[iOut++] = z[iIn++];
187002    }
187003  }
187004
187005  z[iOut] = '\0';
187006  return iIn;
187007}
187008
187009/*
187010** Convert an SQL-style quoted string into a normal string by removing
187011** the quote characters.  The conversion is done in-place.  If the
187012** input does not begin with a quote character, then this routine
187013** is a no-op.
187014**
187015** Examples:
187016**
187017**     "abc"   becomes   abc
187018**     'xyz'   becomes   xyz
187019**     [pqr]   becomes   pqr
187020**     `mno`   becomes   mno
187021*/
187022static void sqlite3Fts5Dequote(char *z){
187023  char quote;                     /* Quote character (if any ) */
187024
187025  assert( 0==fts5_iswhitespace(z[0]) );
187026  quote = z[0];
187027  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
187028    fts5Dequote(z);
187029  }
187030}
187031
187032
187033struct Fts5Enum {
187034  const char *zName;
187035  int eVal;
187036};
187037typedef struct Fts5Enum Fts5Enum;
187038
187039static int fts5ConfigSetEnum(
187040  const Fts5Enum *aEnum,
187041  const char *zEnum,
187042  int *peVal
187043){
187044  int nEnum = (int)strlen(zEnum);
187045  int i;
187046  int iVal = -1;
187047
187048  for(i=0; aEnum[i].zName; i++){
187049    if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
187050      if( iVal>=0 ) return SQLITE_ERROR;
187051      iVal = aEnum[i].eVal;
187052    }
187053  }
187054
187055  *peVal = iVal;
187056  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
187057}
187058
187059/*
187060** Parse a "special" CREATE VIRTUAL TABLE directive and update
187061** configuration object pConfig as appropriate.
187062**
187063** If successful, object pConfig is updated and SQLITE_OK returned. If
187064** an error occurs, an SQLite error code is returned and an error message
187065** may be left in *pzErr. It is the responsibility of the caller to
187066** eventually free any such error message using sqlite3_free().
187067*/
187068static int fts5ConfigParseSpecial(
187069  Fts5Global *pGlobal,
187070  Fts5Config *pConfig,            /* Configuration object to update */
187071  const char *zCmd,               /* Special command to parse */
187072  const char *zArg,               /* Argument to parse */
187073  char **pzErr                    /* OUT: Error message */
187074){
187075  int rc = SQLITE_OK;
187076  int nCmd = (int)strlen(zCmd);
187077  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
187078    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
187079    const char *p;
187080    int bFirst = 1;
187081    if( pConfig->aPrefix==0 ){
187082      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
187083      if( rc ) return rc;
187084    }
187085
187086    p = zArg;
187087    while( 1 ){
187088      int nPre = 0;
187089
187090      while( p[0]==' ' ) p++;
187091      if( bFirst==0 && p[0]==',' ){
187092        p++;
187093        while( p[0]==' ' ) p++;
187094      }else if( p[0]=='\0' ){
187095        break;
187096      }
187097      if( p[0]<'0' || p[0]>'9' ){
187098        *pzErr = sqlite3_mprintf("malformed prefix=... directive");
187099        rc = SQLITE_ERROR;
187100        break;
187101      }
187102
187103      if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
187104        *pzErr = sqlite3_mprintf(
187105            "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
187106        );
187107        rc = SQLITE_ERROR;
187108        break;
187109      }
187110
187111      while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
187112        nPre = nPre*10 + (p[0] - '0');
187113        p++;
187114      }
187115
187116      if( nPre<=0 || nPre>=1000 ){
187117        *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
187118        rc = SQLITE_ERROR;
187119        break;
187120      }
187121
187122      pConfig->aPrefix[pConfig->nPrefix] = nPre;
187123      pConfig->nPrefix++;
187124      bFirst = 0;
187125    }
187126    assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
187127    return rc;
187128  }
187129
187130  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
187131    const char *p = (const char*)zArg;
187132    int nArg = (int)strlen(zArg) + 1;
187133    char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
187134    char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
187135    char *pSpace = pDel;
187136
187137    if( azArg && pSpace ){
187138      if( pConfig->pTok ){
187139        *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
187140        rc = SQLITE_ERROR;
187141      }else{
187142        for(nArg=0; p && *p; nArg++){
187143          const char *p2 = fts5ConfigSkipWhitespace(p);
187144          if( *p2=='\'' ){
187145            p = fts5ConfigSkipLiteral(p2);
187146          }else{
187147            p = fts5ConfigSkipBareword(p2);
187148          }
187149          if( p ){
187150            memcpy(pSpace, p2, p-p2);
187151            azArg[nArg] = pSpace;
187152            sqlite3Fts5Dequote(pSpace);
187153            pSpace += (p - p2) + 1;
187154            p = fts5ConfigSkipWhitespace(p);
187155          }
187156        }
187157        if( p==0 ){
187158          *pzErr = sqlite3_mprintf("parse error in tokenize directive");
187159          rc = SQLITE_ERROR;
187160        }else{
187161          rc = sqlite3Fts5GetTokenizer(pGlobal,
187162              (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
187163              pzErr
187164          );
187165        }
187166      }
187167    }
187168
187169    sqlite3_free(azArg);
187170    sqlite3_free(pDel);
187171    return rc;
187172  }
187173
187174  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
187175    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
187176      *pzErr = sqlite3_mprintf("multiple content=... directives");
187177      rc = SQLITE_ERROR;
187178    }else{
187179      if( zArg[0] ){
187180        pConfig->eContent = FTS5_CONTENT_EXTERNAL;
187181        pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
187182      }else{
187183        pConfig->eContent = FTS5_CONTENT_NONE;
187184      }
187185    }
187186    return rc;
187187  }
187188
187189  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
187190    if( pConfig->zContentRowid ){
187191      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
187192      rc = SQLITE_ERROR;
187193    }else{
187194      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
187195    }
187196    return rc;
187197  }
187198
187199  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
187200    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
187201      *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
187202      rc = SQLITE_ERROR;
187203    }else{
187204      pConfig->bColumnsize = (zArg[0]=='1');
187205    }
187206    return rc;
187207  }
187208
187209  if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
187210    const Fts5Enum aDetail[] = {
187211      { "none", FTS5_DETAIL_NONE },
187212      { "full", FTS5_DETAIL_FULL },
187213      { "columns", FTS5_DETAIL_COLUMNS },
187214      { 0, 0 }
187215    };
187216
187217    if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
187218      *pzErr = sqlite3_mprintf("malformed detail=... directive");
187219    }
187220    return rc;
187221  }
187222
187223  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
187224  return SQLITE_ERROR;
187225}
187226
187227/*
187228** Allocate an instance of the default tokenizer ("simple") at
187229** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
187230** code if an error occurs.
187231*/
187232static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
187233  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
187234  return sqlite3Fts5GetTokenizer(
187235      pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
187236  );
187237}
187238
187239/*
187240** Gobble up the first bareword or quoted word from the input buffer zIn.
187241** Return a pointer to the character immediately following the last in
187242** the gobbled word if successful, or a NULL pointer otherwise (failed
187243** to find close-quote character).
187244**
187245** Before returning, set pzOut to point to a new buffer containing a
187246** nul-terminated, dequoted copy of the gobbled word. If the word was
187247** quoted, *pbQuoted is also set to 1 before returning.
187248**
187249** If *pRc is other than SQLITE_OK when this function is called, it is
187250** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
187251** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
187252** set if a parse error (failed to find close quote) occurs.
187253*/
187254static const char *fts5ConfigGobbleWord(
187255  int *pRc,                       /* IN/OUT: Error code */
187256  const char *zIn,                /* Buffer to gobble string/bareword from */
187257  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
187258  int *pbQuoted                   /* OUT: Set to true if dequoting required */
187259){
187260  const char *zRet = 0;
187261
187262  int nIn = (int)strlen(zIn);
187263  char *zOut = sqlite3_malloc(nIn+1);
187264
187265  assert( *pRc==SQLITE_OK );
187266  *pbQuoted = 0;
187267  *pzOut = 0;
187268
187269  if( zOut==0 ){
187270    *pRc = SQLITE_NOMEM;
187271  }else{
187272    memcpy(zOut, zIn, nIn+1);
187273    if( fts5_isopenquote(zOut[0]) ){
187274      int ii = fts5Dequote(zOut);
187275      zRet = &zIn[ii];
187276      *pbQuoted = 1;
187277    }else{
187278      zRet = fts5ConfigSkipBareword(zIn);
187279      if( zRet ){
187280        zOut[zRet-zIn] = '\0';
187281      }
187282    }
187283  }
187284
187285  if( zRet==0 ){
187286    sqlite3_free(zOut);
187287  }else{
187288    *pzOut = zOut;
187289  }
187290
187291  return zRet;
187292}
187293
187294static int fts5ConfigParseColumn(
187295  Fts5Config *p,
187296  char *zCol,
187297  char *zArg,
187298  char **pzErr
187299){
187300  int rc = SQLITE_OK;
187301  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
187302   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
187303  ){
187304    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
187305    rc = SQLITE_ERROR;
187306  }else if( zArg ){
187307    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
187308      p->abUnindexed[p->nCol] = 1;
187309    }else{
187310      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
187311      rc = SQLITE_ERROR;
187312    }
187313  }
187314
187315  p->azCol[p->nCol++] = zCol;
187316  return rc;
187317}
187318
187319/*
187320** Populate the Fts5Config.zContentExprlist string.
187321*/
187322static int fts5ConfigMakeExprlist(Fts5Config *p){
187323  int i;
187324  int rc = SQLITE_OK;
187325  Fts5Buffer buf = {0, 0, 0};
187326
187327  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
187328  if( p->eContent!=FTS5_CONTENT_NONE ){
187329    for(i=0; i<p->nCol; i++){
187330      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
187331        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
187332      }else{
187333        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
187334      }
187335    }
187336  }
187337
187338  assert( p->zContentExprlist==0 );
187339  p->zContentExprlist = (char*)buf.p;
187340  return rc;
187341}
187342
187343/*
187344** Arguments nArg/azArg contain the string arguments passed to the xCreate
187345** or xConnect method of the virtual table. This function attempts to
187346** allocate an instance of Fts5Config containing the results of parsing
187347** those arguments.
187348**
187349** If successful, SQLITE_OK is returned and *ppOut is set to point to the
187350** new Fts5Config object. If an error occurs, an SQLite error code is
187351** returned, *ppOut is set to NULL and an error message may be left in
187352** *pzErr. It is the responsibility of the caller to eventually free any
187353** such error message using sqlite3_free().
187354*/
187355static int sqlite3Fts5ConfigParse(
187356  Fts5Global *pGlobal,
187357  sqlite3 *db,
187358  int nArg,                       /* Number of arguments */
187359  const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
187360  Fts5Config **ppOut,             /* OUT: Results of parse */
187361  char **pzErr                    /* OUT: Error message */
187362){
187363  int rc = SQLITE_OK;             /* Return code */
187364  Fts5Config *pRet;               /* New object to return */
187365  int i;
187366  int nByte;
187367
187368  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
187369  if( pRet==0 ) return SQLITE_NOMEM;
187370  memset(pRet, 0, sizeof(Fts5Config));
187371  pRet->db = db;
187372  pRet->iCookie = -1;
187373
187374  nByte = nArg * (sizeof(char*) + sizeof(u8));
187375  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
187376  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
187377  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
187378  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
187379  pRet->bColumnsize = 1;
187380  pRet->eDetail = FTS5_DETAIL_FULL;
187381#ifdef SQLITE_DEBUG
187382  pRet->bPrefixIndex = 1;
187383#endif
187384  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
187385    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
187386    rc = SQLITE_ERROR;
187387  }
187388
187389  for(i=3; rc==SQLITE_OK && i<nArg; i++){
187390    const char *zOrig = azArg[i];
187391    const char *z;
187392    char *zOne = 0;
187393    char *zTwo = 0;
187394    int bOption = 0;
187395    int bMustBeCol = 0;
187396
187397    z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
187398    z = fts5ConfigSkipWhitespace(z);
187399    if( z && *z=='=' ){
187400      bOption = 1;
187401      z++;
187402      if( bMustBeCol ) z = 0;
187403    }
187404    z = fts5ConfigSkipWhitespace(z);
187405    if( z && z[0] ){
187406      int bDummy;
187407      z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
187408      if( z && z[0] ) z = 0;
187409    }
187410
187411    if( rc==SQLITE_OK ){
187412      if( z==0 ){
187413        *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
187414        rc = SQLITE_ERROR;
187415      }else{
187416        if( bOption ){
187417          rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
187418        }else{
187419          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
187420          zOne = 0;
187421        }
187422      }
187423    }
187424
187425    sqlite3_free(zOne);
187426    sqlite3_free(zTwo);
187427  }
187428
187429  /* If a tokenizer= option was successfully parsed, the tokenizer has
187430  ** already been allocated. Otherwise, allocate an instance of the default
187431  ** tokenizer (unicode61) now.  */
187432  if( rc==SQLITE_OK && pRet->pTok==0 ){
187433    rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
187434  }
187435
187436  /* If no zContent option was specified, fill in the default values. */
187437  if( rc==SQLITE_OK && pRet->zContent==0 ){
187438    const char *zTail = 0;
187439    assert( pRet->eContent==FTS5_CONTENT_NORMAL
187440         || pRet->eContent==FTS5_CONTENT_NONE
187441    );
187442    if( pRet->eContent==FTS5_CONTENT_NORMAL ){
187443      zTail = "content";
187444    }else if( pRet->bColumnsize ){
187445      zTail = "docsize";
187446    }
187447
187448    if( zTail ){
187449      pRet->zContent = sqlite3Fts5Mprintf(
187450          &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
187451      );
187452    }
187453  }
187454
187455  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
187456    pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
187457  }
187458
187459  /* Formulate the zContentExprlist text */
187460  if( rc==SQLITE_OK ){
187461    rc = fts5ConfigMakeExprlist(pRet);
187462  }
187463
187464  if( rc!=SQLITE_OK ){
187465    sqlite3Fts5ConfigFree(pRet);
187466    *ppOut = 0;
187467  }
187468  return rc;
187469}
187470
187471/*
187472** Free the configuration object passed as the only argument.
187473*/
187474static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
187475  if( pConfig ){
187476    int i;
187477    if( pConfig->pTok ){
187478      pConfig->pTokApi->xDelete(pConfig->pTok);
187479    }
187480    sqlite3_free(pConfig->zDb);
187481    sqlite3_free(pConfig->zName);
187482    for(i=0; i<pConfig->nCol; i++){
187483      sqlite3_free(pConfig->azCol[i]);
187484    }
187485    sqlite3_free(pConfig->azCol);
187486    sqlite3_free(pConfig->aPrefix);
187487    sqlite3_free(pConfig->zRank);
187488    sqlite3_free(pConfig->zRankArgs);
187489    sqlite3_free(pConfig->zContent);
187490    sqlite3_free(pConfig->zContentRowid);
187491    sqlite3_free(pConfig->zContentExprlist);
187492    sqlite3_free(pConfig);
187493  }
187494}
187495
187496/*
187497** Call sqlite3_declare_vtab() based on the contents of the configuration
187498** object passed as the only argument. Return SQLITE_OK if successful, or
187499** an SQLite error code if an error occurs.
187500*/
187501static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
187502  int i;
187503  int rc = SQLITE_OK;
187504  char *zSql;
187505
187506  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
187507  for(i=0; zSql && i<pConfig->nCol; i++){
187508    const char *zSep = (i==0?"":", ");
187509    zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
187510  }
187511  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
187512      zSql, pConfig->zName, FTS5_RANK_NAME
187513  );
187514
187515  assert( zSql || rc==SQLITE_NOMEM );
187516  if( zSql ){
187517    rc = sqlite3_declare_vtab(pConfig->db, zSql);
187518    sqlite3_free(zSql);
187519  }
187520
187521  return rc;
187522}
187523
187524/*
187525** Tokenize the text passed via the second and third arguments.
187526**
187527** The callback is invoked once for each token in the input text. The
187528** arguments passed to it are, in order:
187529**
187530**     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
187531**     const char *pToken  // Pointer to buffer containing token
187532**     int nToken          // Size of token in bytes
187533**     int iStart          // Byte offset of start of token within input text
187534**     int iEnd            // Byte offset of end of token within input text
187535**     int iPos            // Position of token in input (first token is 0)
187536**
187537** If the callback returns a non-zero value the tokenization is abandoned
187538** and no further callbacks are issued.
187539**
187540** This function returns SQLITE_OK if successful or an SQLite error code
187541** if an error occurs. If the tokenization was abandoned early because
187542** the callback returned SQLITE_DONE, this is not an error and this function
187543** still returns SQLITE_OK. Or, if the tokenization was abandoned early
187544** because the callback returned another non-zero value, it is assumed
187545** to be an SQLite error code and returned to the caller.
187546*/
187547static int sqlite3Fts5Tokenize(
187548  Fts5Config *pConfig,            /* FTS5 Configuration object */
187549  int flags,                      /* FTS5_TOKENIZE_* flags */
187550  const char *pText, int nText,   /* Text to tokenize */
187551  void *pCtx,                     /* Context passed to xToken() */
187552  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
187553){
187554  if( pText==0 ) return SQLITE_OK;
187555  return pConfig->pTokApi->xTokenize(
187556      pConfig->pTok, pCtx, flags, pText, nText, xToken
187557  );
187558}
187559
187560/*
187561** Argument pIn points to the first character in what is expected to be
187562** a comma-separated list of SQL literals followed by a ')' character.
187563** If it actually is this, return a pointer to the ')'. Otherwise, return
187564** NULL to indicate a parse error.
187565*/
187566static const char *fts5ConfigSkipArgs(const char *pIn){
187567  const char *p = pIn;
187568
187569  while( 1 ){
187570    p = fts5ConfigSkipWhitespace(p);
187571    p = fts5ConfigSkipLiteral(p);
187572    p = fts5ConfigSkipWhitespace(p);
187573    if( p==0 || *p==')' ) break;
187574    if( *p!=',' ){
187575      p = 0;
187576      break;
187577    }
187578    p++;
187579  }
187580
187581  return p;
187582}
187583
187584/*
187585** Parameter zIn contains a rank() function specification. The format of
187586** this is:
187587**
187588**   + Bareword (function name)
187589**   + Open parenthesis - "("
187590**   + Zero or more SQL literals in a comma separated list
187591**   + Close parenthesis - ")"
187592*/
187593static int sqlite3Fts5ConfigParseRank(
187594  const char *zIn,                /* Input string */
187595  char **pzRank,                  /* OUT: Rank function name */
187596  char **pzRankArgs               /* OUT: Rank function arguments */
187597){
187598  const char *p = zIn;
187599  const char *pRank;
187600  char *zRank = 0;
187601  char *zRankArgs = 0;
187602  int rc = SQLITE_OK;
187603
187604  *pzRank = 0;
187605  *pzRankArgs = 0;
187606
187607  if( p==0 ){
187608    rc = SQLITE_ERROR;
187609  }else{
187610    p = fts5ConfigSkipWhitespace(p);
187611    pRank = p;
187612    p = fts5ConfigSkipBareword(p);
187613
187614    if( p ){
187615      zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
187616      if( zRank ) memcpy(zRank, pRank, p-pRank);
187617    }else{
187618      rc = SQLITE_ERROR;
187619    }
187620
187621    if( rc==SQLITE_OK ){
187622      p = fts5ConfigSkipWhitespace(p);
187623      if( *p!='(' ) rc = SQLITE_ERROR;
187624      p++;
187625    }
187626    if( rc==SQLITE_OK ){
187627      const char *pArgs;
187628      p = fts5ConfigSkipWhitespace(p);
187629      pArgs = p;
187630      if( *p!=')' ){
187631        p = fts5ConfigSkipArgs(p);
187632        if( p==0 ){
187633          rc = SQLITE_ERROR;
187634        }else{
187635          zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
187636          if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
187637        }
187638      }
187639    }
187640  }
187641
187642  if( rc!=SQLITE_OK ){
187643    sqlite3_free(zRank);
187644    assert( zRankArgs==0 );
187645  }else{
187646    *pzRank = zRank;
187647    *pzRankArgs = zRankArgs;
187648  }
187649  return rc;
187650}
187651
187652static int sqlite3Fts5ConfigSetValue(
187653  Fts5Config *pConfig,
187654  const char *zKey,
187655  sqlite3_value *pVal,
187656  int *pbBadkey
187657){
187658  int rc = SQLITE_OK;
187659
187660  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
187661    int pgsz = 0;
187662    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
187663      pgsz = sqlite3_value_int(pVal);
187664    }
187665    if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
187666      *pbBadkey = 1;
187667    }else{
187668      pConfig->pgsz = pgsz;
187669    }
187670  }
187671
187672  else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
187673    int nHashSize = -1;
187674    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
187675      nHashSize = sqlite3_value_int(pVal);
187676    }
187677    if( nHashSize<=0 ){
187678      *pbBadkey = 1;
187679    }else{
187680      pConfig->nHashSize = nHashSize;
187681    }
187682  }
187683
187684  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
187685    int nAutomerge = -1;
187686    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
187687      nAutomerge = sqlite3_value_int(pVal);
187688    }
187689    if( nAutomerge<0 || nAutomerge>64 ){
187690      *pbBadkey = 1;
187691    }else{
187692      if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
187693      pConfig->nAutomerge = nAutomerge;
187694    }
187695  }
187696
187697  else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
187698    int nUsermerge = -1;
187699    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
187700      nUsermerge = sqlite3_value_int(pVal);
187701    }
187702    if( nUsermerge<2 || nUsermerge>16 ){
187703      *pbBadkey = 1;
187704    }else{
187705      pConfig->nUsermerge = nUsermerge;
187706    }
187707  }
187708
187709  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
187710    int nCrisisMerge = -1;
187711    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
187712      nCrisisMerge = sqlite3_value_int(pVal);
187713    }
187714    if( nCrisisMerge<0 ){
187715      *pbBadkey = 1;
187716    }else{
187717      if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
187718      pConfig->nCrisisMerge = nCrisisMerge;
187719    }
187720  }
187721
187722  else if( 0==sqlite3_stricmp(zKey, "rank") ){
187723    const char *zIn = (const char*)sqlite3_value_text(pVal);
187724    char *zRank;
187725    char *zRankArgs;
187726    rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
187727    if( rc==SQLITE_OK ){
187728      sqlite3_free(pConfig->zRank);
187729      sqlite3_free(pConfig->zRankArgs);
187730      pConfig->zRank = zRank;
187731      pConfig->zRankArgs = zRankArgs;
187732    }else if( rc==SQLITE_ERROR ){
187733      rc = SQLITE_OK;
187734      *pbBadkey = 1;
187735    }
187736  }else{
187737    *pbBadkey = 1;
187738  }
187739  return rc;
187740}
187741
187742/*
187743** Load the contents of the %_config table into memory.
187744*/
187745static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
187746  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
187747  char *zSql;
187748  sqlite3_stmt *p = 0;
187749  int rc = SQLITE_OK;
187750  int iVersion = 0;
187751
187752  /* Set default values */
187753  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
187754  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
187755  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
187756  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
187757  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
187758
187759  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
187760  if( zSql ){
187761    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
187762    sqlite3_free(zSql);
187763  }
187764
187765  assert( rc==SQLITE_OK || p==0 );
187766  if( rc==SQLITE_OK ){
187767    while( SQLITE_ROW==sqlite3_step(p) ){
187768      const char *zK = (const char*)sqlite3_column_text(p, 0);
187769      sqlite3_value *pVal = sqlite3_column_value(p, 1);
187770      if( 0==sqlite3_stricmp(zK, "version") ){
187771        iVersion = sqlite3_value_int(pVal);
187772      }else{
187773        int bDummy = 0;
187774        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
187775      }
187776    }
187777    rc = sqlite3_finalize(p);
187778  }
187779
187780  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
187781    rc = SQLITE_ERROR;
187782    if( pConfig->pzErrmsg ){
187783      assert( 0==*pConfig->pzErrmsg );
187784      *pConfig->pzErrmsg = sqlite3_mprintf(
187785          "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
187786          iVersion, FTS5_CURRENT_VERSION
187787      );
187788    }
187789  }
187790
187791  if( rc==SQLITE_OK ){
187792    pConfig->iCookie = iCookie;
187793  }
187794  return rc;
187795}
187796
187797/*
187798** 2014 May 31
187799**
187800** The author disclaims copyright to this source code.  In place of
187801** a legal notice, here is a blessing:
187802**
187803**    May you do good and not evil.
187804**    May you find forgiveness for yourself and forgive others.
187805**    May you share freely, never taking more than you give.
187806**
187807******************************************************************************
187808**
187809*/
187810
187811
187812
187813/* #include "fts5Int.h" */
187814/* #include "fts5parse.h" */
187815
187816/*
187817** All token types in the generated fts5parse.h file are greater than 0.
187818*/
187819#define FTS5_EOF 0
187820
187821#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
187822
187823typedef struct Fts5ExprTerm Fts5ExprTerm;
187824
187825/*
187826** Functions generated by lemon from fts5parse.y.
187827*/
187828static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
187829static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
187830static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
187831#ifndef NDEBUG
187832/* #include <stdio.h> */
187833static void sqlite3Fts5ParserTrace(FILE*, char*);
187834#endif
187835
187836
187837struct Fts5Expr {
187838  Fts5Index *pIndex;
187839  Fts5Config *pConfig;
187840  Fts5ExprNode *pRoot;
187841  int bDesc;                      /* Iterate in descending rowid order */
187842  int nPhrase;                    /* Number of phrases in expression */
187843  Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
187844};
187845
187846/*
187847** eType:
187848**   Expression node type. Always one of:
187849**
187850**       FTS5_AND                 (nChild, apChild valid)
187851**       FTS5_OR                  (nChild, apChild valid)
187852**       FTS5_NOT                 (nChild, apChild valid)
187853**       FTS5_STRING              (pNear valid)
187854**       FTS5_TERM                (pNear valid)
187855*/
187856struct Fts5ExprNode {
187857  int eType;                      /* Node type */
187858  int bEof;                       /* True at EOF */
187859  int bNomatch;                   /* True if entry is not a match */
187860
187861  /* Next method for this node. */
187862  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
187863
187864  i64 iRowid;                     /* Current rowid */
187865  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
187866
187867  /* Child nodes. For a NOT node, this array always contains 2 entries. For
187868  ** AND or OR nodes, it contains 2 or more entries.  */
187869  int nChild;                     /* Number of child nodes */
187870  Fts5ExprNode *apChild[1];       /* Array of child nodes */
187871};
187872
187873#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
187874
187875/*
187876** Invoke the xNext method of an Fts5ExprNode object. This macro should be
187877** used as if it has the same signature as the xNext() methods themselves.
187878*/
187879#define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
187880
187881/*
187882** An instance of the following structure represents a single search term
187883** or term prefix.
187884*/
187885struct Fts5ExprTerm {
187886  int bPrefix;                    /* True for a prefix term */
187887  char *zTerm;                    /* nul-terminated term */
187888  Fts5IndexIter *pIter;           /* Iterator for this term */
187889  Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
187890};
187891
187892/*
187893** A phrase. One or more terms that must appear in a contiguous sequence
187894** within a document for it to match.
187895*/
187896struct Fts5ExprPhrase {
187897  Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
187898  Fts5Buffer poslist;             /* Current position list */
187899  int nTerm;                      /* Number of entries in aTerm[] */
187900  Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
187901};
187902
187903/*
187904** One or more phrases that must appear within a certain token distance of
187905** each other within each matching document.
187906*/
187907struct Fts5ExprNearset {
187908  int nNear;                      /* NEAR parameter */
187909  Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
187910  int nPhrase;                    /* Number of entries in aPhrase[] array */
187911  Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
187912};
187913
187914
187915/*
187916** Parse context.
187917*/
187918struct Fts5Parse {
187919  Fts5Config *pConfig;
187920  char *zErr;
187921  int rc;
187922  int nPhrase;                    /* Size of apPhrase array */
187923  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
187924  Fts5ExprNode *pExpr;            /* Result of a successful parse */
187925};
187926
187927static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
187928  va_list ap;
187929  va_start(ap, zFmt);
187930  if( pParse->rc==SQLITE_OK ){
187931    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
187932    pParse->rc = SQLITE_ERROR;
187933  }
187934  va_end(ap);
187935}
187936
187937static int fts5ExprIsspace(char t){
187938  return t==' ' || t=='\t' || t=='\n' || t=='\r';
187939}
187940
187941/*
187942** Read the first token from the nul-terminated string at *pz.
187943*/
187944static int fts5ExprGetToken(
187945  Fts5Parse *pParse,
187946  const char **pz,                /* IN/OUT: Pointer into buffer */
187947  Fts5Token *pToken
187948){
187949  const char *z = *pz;
187950  int tok;
187951
187952  /* Skip past any whitespace */
187953  while( fts5ExprIsspace(*z) ) z++;
187954
187955  pToken->p = z;
187956  pToken->n = 1;
187957  switch( *z ){
187958    case '(':  tok = FTS5_LP;    break;
187959    case ')':  tok = FTS5_RP;    break;
187960    case '{':  tok = FTS5_LCP;   break;
187961    case '}':  tok = FTS5_RCP;   break;
187962    case ':':  tok = FTS5_COLON; break;
187963    case ',':  tok = FTS5_COMMA; break;
187964    case '+':  tok = FTS5_PLUS;  break;
187965    case '*':  tok = FTS5_STAR;  break;
187966    case '-':  tok = FTS5_MINUS; break;
187967    case '\0': tok = FTS5_EOF;   break;
187968
187969    case '"': {
187970      const char *z2;
187971      tok = FTS5_STRING;
187972
187973      for(z2=&z[1]; 1; z2++){
187974        if( z2[0]=='"' ){
187975          z2++;
187976          if( z2[0]!='"' ) break;
187977        }
187978        if( z2[0]=='\0' ){
187979          sqlite3Fts5ParseError(pParse, "unterminated string");
187980          return FTS5_EOF;
187981        }
187982      }
187983      pToken->n = (z2 - z);
187984      break;
187985    }
187986
187987    default: {
187988      const char *z2;
187989      if( sqlite3Fts5IsBareword(z[0])==0 ){
187990        sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
187991        return FTS5_EOF;
187992      }
187993      tok = FTS5_STRING;
187994      for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
187995      pToken->n = (z2 - z);
187996      if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
187997      if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
187998      if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
187999      break;
188000    }
188001  }
188002
188003  *pz = &pToken->p[pToken->n];
188004  return tok;
188005}
188006
188007static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
188008static void fts5ParseFree(void *p){ sqlite3_free(p); }
188009
188010static int sqlite3Fts5ExprNew(
188011  Fts5Config *pConfig,            /* FTS5 Configuration */
188012  int iCol,
188013  const char *zExpr,              /* Expression text */
188014  Fts5Expr **ppNew,
188015  char **pzErr
188016){
188017  Fts5Parse sParse;
188018  Fts5Token token;
188019  const char *z = zExpr;
188020  int t;                          /* Next token type */
188021  void *pEngine;
188022  Fts5Expr *pNew;
188023
188024  *ppNew = 0;
188025  *pzErr = 0;
188026  memset(&sParse, 0, sizeof(sParse));
188027  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
188028  if( pEngine==0 ){ return SQLITE_NOMEM; }
188029  sParse.pConfig = pConfig;
188030
188031  do {
188032    t = fts5ExprGetToken(&sParse, &z, &token);
188033    sqlite3Fts5Parser(pEngine, t, token, &sParse);
188034  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
188035  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
188036
188037  /* If the LHS of the MATCH expression was a user column, apply the
188038  ** implicit column-filter.  */
188039  if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
188040    int n = sizeof(Fts5Colset);
188041    Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
188042    if( pColset ){
188043      pColset->nCol = 1;
188044      pColset->aiCol[0] = iCol;
188045      sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
188046    }
188047  }
188048
188049  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
188050  if( sParse.rc==SQLITE_OK ){
188051    *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
188052    if( pNew==0 ){
188053      sParse.rc = SQLITE_NOMEM;
188054      sqlite3Fts5ParseNodeFree(sParse.pExpr);
188055    }else{
188056      if( !sParse.pExpr ){
188057        const int nByte = sizeof(Fts5ExprNode);
188058        pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
188059        if( pNew->pRoot ){
188060          pNew->pRoot->bEof = 1;
188061        }
188062      }else{
188063        pNew->pRoot = sParse.pExpr;
188064      }
188065      pNew->pIndex = 0;
188066      pNew->pConfig = pConfig;
188067      pNew->apExprPhrase = sParse.apPhrase;
188068      pNew->nPhrase = sParse.nPhrase;
188069      sParse.apPhrase = 0;
188070    }
188071  }else{
188072    sqlite3Fts5ParseNodeFree(sParse.pExpr);
188073  }
188074
188075  sqlite3_free(sParse.apPhrase);
188076  *pzErr = sParse.zErr;
188077  return sParse.rc;
188078}
188079
188080/*
188081** Free the expression node object passed as the only argument.
188082*/
188083static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
188084  if( p ){
188085    int i;
188086    for(i=0; i<p->nChild; i++){
188087      sqlite3Fts5ParseNodeFree(p->apChild[i]);
188088    }
188089    sqlite3Fts5ParseNearsetFree(p->pNear);
188090    sqlite3_free(p);
188091  }
188092}
188093
188094/*
188095** Free the expression object passed as the only argument.
188096*/
188097static void sqlite3Fts5ExprFree(Fts5Expr *p){
188098  if( p ){
188099    sqlite3Fts5ParseNodeFree(p->pRoot);
188100    sqlite3_free(p->apExprPhrase);
188101    sqlite3_free(p);
188102  }
188103}
188104
188105/*
188106** Argument pTerm must be a synonym iterator. Return the current rowid
188107** that it points to.
188108*/
188109static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
188110  i64 iRet = 0;
188111  int bRetValid = 0;
188112  Fts5ExprTerm *p;
188113
188114  assert( pTerm->pSynonym );
188115  assert( bDesc==0 || bDesc==1 );
188116  for(p=pTerm; p; p=p->pSynonym){
188117    if( 0==sqlite3Fts5IterEof(p->pIter) ){
188118      i64 iRowid = p->pIter->iRowid;
188119      if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
188120        iRet = iRowid;
188121        bRetValid = 1;
188122      }
188123    }
188124  }
188125
188126  if( pbEof && bRetValid==0 ) *pbEof = 1;
188127  return iRet;
188128}
188129
188130/*
188131** Argument pTerm must be a synonym iterator.
188132*/
188133static int fts5ExprSynonymList(
188134  Fts5ExprTerm *pTerm,
188135  i64 iRowid,
188136  Fts5Buffer *pBuf,               /* Use this buffer for space if required */
188137  u8 **pa, int *pn
188138){
188139  Fts5PoslistReader aStatic[4];
188140  Fts5PoslistReader *aIter = aStatic;
188141  int nIter = 0;
188142  int nAlloc = 4;
188143  int rc = SQLITE_OK;
188144  Fts5ExprTerm *p;
188145
188146  assert( pTerm->pSynonym );
188147  for(p=pTerm; p; p=p->pSynonym){
188148    Fts5IndexIter *pIter = p->pIter;
188149    if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
188150      if( pIter->nData==0 ) continue;
188151      if( nIter==nAlloc ){
188152        int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
188153        Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
188154        if( aNew==0 ){
188155          rc = SQLITE_NOMEM;
188156          goto synonym_poslist_out;
188157        }
188158        memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
188159        nAlloc = nAlloc*2;
188160        if( aIter!=aStatic ) sqlite3_free(aIter);
188161        aIter = aNew;
188162      }
188163      sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
188164      assert( aIter[nIter].bEof==0 );
188165      nIter++;
188166    }
188167  }
188168
188169  if( nIter==1 ){
188170    *pa = (u8*)aIter[0].a;
188171    *pn = aIter[0].n;
188172  }else{
188173    Fts5PoslistWriter writer = {0};
188174    i64 iPrev = -1;
188175    fts5BufferZero(pBuf);
188176    while( 1 ){
188177      int i;
188178      i64 iMin = FTS5_LARGEST_INT64;
188179      for(i=0; i<nIter; i++){
188180        if( aIter[i].bEof==0 ){
188181          if( aIter[i].iPos==iPrev ){
188182            if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
188183          }
188184          if( aIter[i].iPos<iMin ){
188185            iMin = aIter[i].iPos;
188186          }
188187        }
188188      }
188189      if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
188190      rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
188191      iPrev = iMin;
188192    }
188193    if( rc==SQLITE_OK ){
188194      *pa = pBuf->p;
188195      *pn = pBuf->n;
188196    }
188197  }
188198
188199 synonym_poslist_out:
188200  if( aIter!=aStatic ) sqlite3_free(aIter);
188201  return rc;
188202}
188203
188204
188205/*
188206** All individual term iterators in pPhrase are guaranteed to be valid and
188207** pointing to the same rowid when this function is called. This function
188208** checks if the current rowid really is a match, and if so populates
188209** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
188210** is set to true if this is really a match, or false otherwise.
188211**
188212** SQLITE_OK is returned if an error occurs, or an SQLite error code
188213** otherwise. It is not considered an error code if the current rowid is
188214** not a match.
188215*/
188216static int fts5ExprPhraseIsMatch(
188217  Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
188218  Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
188219  int *pbMatch                    /* OUT: Set to true if really a match */
188220){
188221  Fts5PoslistWriter writer = {0};
188222  Fts5PoslistReader aStatic[4];
188223  Fts5PoslistReader *aIter = aStatic;
188224  int i;
188225  int rc = SQLITE_OK;
188226
188227  fts5BufferZero(&pPhrase->poslist);
188228
188229  /* If the aStatic[] array is not large enough, allocate a large array
188230  ** using sqlite3_malloc(). This approach could be improved upon. */
188231  if( pPhrase->nTerm>ArraySize(aStatic) ){
188232    int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
188233    aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
188234    if( !aIter ) return SQLITE_NOMEM;
188235  }
188236  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
188237
188238  /* Initialize a term iterator for each term in the phrase */
188239  for(i=0; i<pPhrase->nTerm; i++){
188240    Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
188241    int n = 0;
188242    int bFlag = 0;
188243    u8 *a = 0;
188244    if( pTerm->pSynonym ){
188245      Fts5Buffer buf = {0, 0, 0};
188246      rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
188247      if( rc ){
188248        sqlite3_free(a);
188249        goto ismatch_out;
188250      }
188251      if( a==buf.p ) bFlag = 1;
188252    }else{
188253      a = (u8*)pTerm->pIter->pData;
188254      n = pTerm->pIter->nData;
188255    }
188256    sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
188257    aIter[i].bFlag = (u8)bFlag;
188258    if( aIter[i].bEof ) goto ismatch_out;
188259  }
188260
188261  while( 1 ){
188262    int bMatch;
188263    i64 iPos = aIter[0].iPos;
188264    do {
188265      bMatch = 1;
188266      for(i=0; i<pPhrase->nTerm; i++){
188267        Fts5PoslistReader *pPos = &aIter[i];
188268        i64 iAdj = iPos + i;
188269        if( pPos->iPos!=iAdj ){
188270          bMatch = 0;
188271          while( pPos->iPos<iAdj ){
188272            if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
188273          }
188274          if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
188275        }
188276      }
188277    }while( bMatch==0 );
188278
188279    /* Append position iPos to the output */
188280    rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
188281    if( rc!=SQLITE_OK ) goto ismatch_out;
188282
188283    for(i=0; i<pPhrase->nTerm; i++){
188284      if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
188285    }
188286  }
188287
188288 ismatch_out:
188289  *pbMatch = (pPhrase->poslist.n>0);
188290  for(i=0; i<pPhrase->nTerm; i++){
188291    if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
188292  }
188293  if( aIter!=aStatic ) sqlite3_free(aIter);
188294  return rc;
188295}
188296
188297typedef struct Fts5LookaheadReader Fts5LookaheadReader;
188298struct Fts5LookaheadReader {
188299  const u8 *a;                    /* Buffer containing position list */
188300  int n;                          /* Size of buffer a[] in bytes */
188301  int i;                          /* Current offset in position list */
188302  i64 iPos;                       /* Current position */
188303  i64 iLookahead;                 /* Next position */
188304};
188305
188306#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
188307
188308static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
188309  p->iPos = p->iLookahead;
188310  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
188311    p->iLookahead = FTS5_LOOKAHEAD_EOF;
188312  }
188313  return (p->iPos==FTS5_LOOKAHEAD_EOF);
188314}
188315
188316static int fts5LookaheadReaderInit(
188317  const u8 *a, int n,             /* Buffer to read position list from */
188318  Fts5LookaheadReader *p          /* Iterator object to initialize */
188319){
188320  memset(p, 0, sizeof(Fts5LookaheadReader));
188321  p->a = a;
188322  p->n = n;
188323  fts5LookaheadReaderNext(p);
188324  return fts5LookaheadReaderNext(p);
188325}
188326
188327typedef struct Fts5NearTrimmer Fts5NearTrimmer;
188328struct Fts5NearTrimmer {
188329  Fts5LookaheadReader reader;     /* Input iterator */
188330  Fts5PoslistWriter writer;       /* Writer context */
188331  Fts5Buffer *pOut;               /* Output poslist */
188332};
188333
188334/*
188335** The near-set object passed as the first argument contains more than
188336** one phrase. All phrases currently point to the same row. The
188337** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
188338** tests if the current row contains instances of each phrase sufficiently
188339** close together to meet the NEAR constraint. Non-zero is returned if it
188340** does, or zero otherwise.
188341**
188342** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
188343** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
188344** occurs within this function (*pRc) is set accordingly before returning.
188345** The return value is undefined in both these cases.
188346**
188347** If no error occurs and non-zero (a match) is returned, the position-list
188348** of each phrase object is edited to contain only those entries that
188349** meet the constraint before returning.
188350*/
188351static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
188352  Fts5NearTrimmer aStatic[4];
188353  Fts5NearTrimmer *a = aStatic;
188354  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
188355
188356  int i;
188357  int rc = *pRc;
188358  int bMatch;
188359
188360  assert( pNear->nPhrase>1 );
188361
188362  /* If the aStatic[] array is not large enough, allocate a large array
188363  ** using sqlite3_malloc(). This approach could be improved upon. */
188364  if( pNear->nPhrase>ArraySize(aStatic) ){
188365    int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
188366    a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
188367  }else{
188368    memset(aStatic, 0, sizeof(aStatic));
188369  }
188370  if( rc!=SQLITE_OK ){
188371    *pRc = rc;
188372    return 0;
188373  }
188374
188375  /* Initialize a lookahead iterator for each phrase. After passing the
188376  ** buffer and buffer size to the lookaside-reader init function, zero
188377  ** the phrase poslist buffer. The new poslist for the phrase (containing
188378  ** the same entries as the original with some entries removed on account
188379  ** of the NEAR constraint) is written over the original even as it is
188380  ** being read. This is safe as the entries for the new poslist are a
188381  ** subset of the old, so it is not possible for data yet to be read to
188382  ** be overwritten.  */
188383  for(i=0; i<pNear->nPhrase; i++){
188384    Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
188385    fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
188386    pPoslist->n = 0;
188387    a[i].pOut = pPoslist;
188388  }
188389
188390  while( 1 ){
188391    int iAdv;
188392    i64 iMin;
188393    i64 iMax;
188394
188395    /* This block advances the phrase iterators until they point to a set of
188396    ** entries that together comprise a match.  */
188397    iMax = a[0].reader.iPos;
188398    do {
188399      bMatch = 1;
188400      for(i=0; i<pNear->nPhrase; i++){
188401        Fts5LookaheadReader *pPos = &a[i].reader;
188402        iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
188403        if( pPos->iPos<iMin || pPos->iPos>iMax ){
188404          bMatch = 0;
188405          while( pPos->iPos<iMin ){
188406            if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
188407          }
188408          if( pPos->iPos>iMax ) iMax = pPos->iPos;
188409        }
188410      }
188411    }while( bMatch==0 );
188412
188413    /* Add an entry to each output position list */
188414    for(i=0; i<pNear->nPhrase; i++){
188415      i64 iPos = a[i].reader.iPos;
188416      Fts5PoslistWriter *pWriter = &a[i].writer;
188417      if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
188418        sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
188419      }
188420    }
188421
188422    iAdv = 0;
188423    iMin = a[0].reader.iLookahead;
188424    for(i=0; i<pNear->nPhrase; i++){
188425      if( a[i].reader.iLookahead < iMin ){
188426        iMin = a[i].reader.iLookahead;
188427        iAdv = i;
188428      }
188429    }
188430    if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
188431  }
188432
188433  ismatch_out: {
188434    int bRet = a[0].pOut->n>0;
188435    *pRc = rc;
188436    if( a!=aStatic ) sqlite3_free(a);
188437    return bRet;
188438  }
188439}
188440
188441/*
188442** Advance iterator pIter until it points to a value equal to or laster
188443** than the initial value of *piLast. If this means the iterator points
188444** to a value laster than *piLast, update *piLast to the new lastest value.
188445**
188446** If the iterator reaches EOF, set *pbEof to true before returning. If
188447** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
188448** are set, return a non-zero value. Otherwise, return zero.
188449*/
188450static int fts5ExprAdvanceto(
188451  Fts5IndexIter *pIter,           /* Iterator to advance */
188452  int bDesc,                      /* True if iterator is "rowid DESC" */
188453  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
188454  int *pRc,                       /* OUT: Error code */
188455  int *pbEof                      /* OUT: Set to true if EOF */
188456){
188457  i64 iLast = *piLast;
188458  i64 iRowid;
188459
188460  iRowid = pIter->iRowid;
188461  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
188462    int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
188463    if( rc || sqlite3Fts5IterEof(pIter) ){
188464      *pRc = rc;
188465      *pbEof = 1;
188466      return 1;
188467    }
188468    iRowid = pIter->iRowid;
188469    assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
188470  }
188471  *piLast = iRowid;
188472
188473  return 0;
188474}
188475
188476static int fts5ExprSynonymAdvanceto(
188477  Fts5ExprTerm *pTerm,            /* Term iterator to advance */
188478  int bDesc,                      /* True if iterator is "rowid DESC" */
188479  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
188480  int *pRc                        /* OUT: Error code */
188481){
188482  int rc = SQLITE_OK;
188483  i64 iLast = *piLast;
188484  Fts5ExprTerm *p;
188485  int bEof = 0;
188486
188487  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
188488    if( sqlite3Fts5IterEof(p->pIter)==0 ){
188489      i64 iRowid = p->pIter->iRowid;
188490      if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
188491        rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
188492      }
188493    }
188494  }
188495
188496  if( rc!=SQLITE_OK ){
188497    *pRc = rc;
188498    bEof = 1;
188499  }else{
188500    *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
188501  }
188502  return bEof;
188503}
188504
188505
188506static int fts5ExprNearTest(
188507  int *pRc,
188508  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
188509  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
188510){
188511  Fts5ExprNearset *pNear = pNode->pNear;
188512  int rc = *pRc;
188513
188514  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
188515    Fts5ExprTerm *pTerm;
188516    Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
188517    pPhrase->poslist.n = 0;
188518    for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
188519      Fts5IndexIter *pIter = pTerm->pIter;
188520      if( sqlite3Fts5IterEof(pIter)==0 ){
188521        if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
188522          pPhrase->poslist.n = 1;
188523        }
188524      }
188525    }
188526    return pPhrase->poslist.n;
188527  }else{
188528    int i;
188529
188530    /* Check that each phrase in the nearset matches the current row.
188531    ** Populate the pPhrase->poslist buffers at the same time. If any
188532    ** phrase is not a match, break out of the loop early.  */
188533    for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
188534      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
188535      if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
188536        int bMatch = 0;
188537        rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
188538        if( bMatch==0 ) break;
188539      }else{
188540        Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
188541        fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
188542      }
188543    }
188544
188545    *pRc = rc;
188546    if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
188547      return 1;
188548    }
188549    return 0;
188550  }
188551}
188552
188553
188554/*
188555** Initialize all term iterators in the pNear object. If any term is found
188556** to match no documents at all, return immediately without initializing any
188557** further iterators.
188558**
188559** If an error occurs, return an SQLite error code. Otherwise, return
188560** SQLITE_OK. It is not considered an error if some term matches zero
188561** documents.
188562*/
188563static int fts5ExprNearInitAll(
188564  Fts5Expr *pExpr,
188565  Fts5ExprNode *pNode
188566){
188567  Fts5ExprNearset *pNear = pNode->pNear;
188568  int i;
188569
188570  assert( pNode->bNomatch==0 );
188571  for(i=0; i<pNear->nPhrase; i++){
188572    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
188573    if( pPhrase->nTerm==0 ){
188574      pNode->bEof = 1;
188575      return SQLITE_OK;
188576    }else{
188577      int j;
188578      for(j=0; j<pPhrase->nTerm; j++){
188579        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
188580        Fts5ExprTerm *p;
188581        int bHit = 0;
188582
188583        for(p=pTerm; p; p=p->pSynonym){
188584          int rc;
188585          if( p->pIter ){
188586            sqlite3Fts5IterClose(p->pIter);
188587            p->pIter = 0;
188588          }
188589          rc = sqlite3Fts5IndexQuery(
188590              pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
188591              (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
188592              (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
188593              pNear->pColset,
188594              &p->pIter
188595          );
188596          assert( (rc==SQLITE_OK)==(p->pIter!=0) );
188597          if( rc!=SQLITE_OK ) return rc;
188598          if( 0==sqlite3Fts5IterEof(p->pIter) ){
188599            bHit = 1;
188600          }
188601        }
188602
188603        if( bHit==0 ){
188604          pNode->bEof = 1;
188605          return SQLITE_OK;
188606        }
188607      }
188608    }
188609  }
188610
188611  pNode->bEof = 0;
188612  return SQLITE_OK;
188613}
188614
188615/*
188616** If pExpr is an ASC iterator, this function returns a value with the
188617** same sign as:
188618**
188619**   (iLhs - iRhs)
188620**
188621** Otherwise, if this is a DESC iterator, the opposite is returned:
188622**
188623**   (iRhs - iLhs)
188624*/
188625static int fts5RowidCmp(
188626  Fts5Expr *pExpr,
188627  i64 iLhs,
188628  i64 iRhs
188629){
188630  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
188631  if( pExpr->bDesc==0 ){
188632    if( iLhs<iRhs ) return -1;
188633    return (iLhs > iRhs);
188634  }else{
188635    if( iLhs>iRhs ) return -1;
188636    return (iLhs < iRhs);
188637  }
188638}
188639
188640static void fts5ExprSetEof(Fts5ExprNode *pNode){
188641  int i;
188642  pNode->bEof = 1;
188643  pNode->bNomatch = 0;
188644  for(i=0; i<pNode->nChild; i++){
188645    fts5ExprSetEof(pNode->apChild[i]);
188646  }
188647}
188648
188649static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
188650  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
188651    Fts5ExprNearset *pNear = pNode->pNear;
188652    int i;
188653    for(i=0; i<pNear->nPhrase; i++){
188654      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
188655      pPhrase->poslist.n = 0;
188656    }
188657  }else{
188658    int i;
188659    for(i=0; i<pNode->nChild; i++){
188660      fts5ExprNodeZeroPoslist(pNode->apChild[i]);
188661    }
188662  }
188663}
188664
188665
188666
188667/*
188668** Compare the values currently indicated by the two nodes as follows:
188669**
188670**    res = (*p1) - (*p2)
188671**
188672** Nodes that point to values that come later in the iteration order are
188673** considered to be larger. Nodes at EOF are the largest of all.
188674**
188675** This means that if the iteration order is ASC, then numerically larger
188676** rowids are considered larger. Or if it is the default DESC, numerically
188677** smaller rowids are larger.
188678*/
188679static int fts5NodeCompare(
188680  Fts5Expr *pExpr,
188681  Fts5ExprNode *p1,
188682  Fts5ExprNode *p2
188683){
188684  if( p2->bEof ) return -1;
188685  if( p1->bEof ) return +1;
188686  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
188687}
188688
188689/*
188690** All individual term iterators in pNear are guaranteed to be valid when
188691** this function is called. This function checks if all term iterators
188692** point to the same rowid, and if not, advances them until they do.
188693** If an EOF is reached before this happens, *pbEof is set to true before
188694** returning.
188695**
188696** SQLITE_OK is returned if an error occurs, or an SQLite error code
188697** otherwise. It is not considered an error code if an iterator reaches
188698** EOF.
188699*/
188700static int fts5ExprNodeTest_STRING(
188701  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
188702  Fts5ExprNode *pNode
188703){
188704  Fts5ExprNearset *pNear = pNode->pNear;
188705  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
188706  int rc = SQLITE_OK;
188707  i64 iLast;                      /* Lastest rowid any iterator points to */
188708  int i, j;                       /* Phrase and token index, respectively */
188709  int bMatch;                     /* True if all terms are at the same rowid */
188710  const int bDesc = pExpr->bDesc;
188711
188712  /* Check that this node should not be FTS5_TERM */
188713  assert( pNear->nPhrase>1
188714       || pNear->apPhrase[0]->nTerm>1
188715       || pNear->apPhrase[0]->aTerm[0].pSynonym
188716  );
188717
188718  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
188719  ** iterator skips through rowids in the default ascending order, this means
188720  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
188721  ** means the minimum rowid.  */
188722  if( pLeft->aTerm[0].pSynonym ){
188723    iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
188724  }else{
188725    iLast = pLeft->aTerm[0].pIter->iRowid;
188726  }
188727
188728  do {
188729    bMatch = 1;
188730    for(i=0; i<pNear->nPhrase; i++){
188731      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
188732      for(j=0; j<pPhrase->nTerm; j++){
188733        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
188734        if( pTerm->pSynonym ){
188735          i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
188736          if( iRowid==iLast ) continue;
188737          bMatch = 0;
188738          if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
188739            pNode->bNomatch = 0;
188740            pNode->bEof = 1;
188741            return rc;
188742          }
188743        }else{
188744          Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
188745          if( pIter->iRowid==iLast || pIter->bEof ) continue;
188746          bMatch = 0;
188747          if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
188748            return rc;
188749          }
188750        }
188751      }
188752    }
188753  }while( bMatch==0 );
188754
188755  pNode->iRowid = iLast;
188756  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
188757  assert( pNode->bEof==0 || pNode->bNomatch==0 );
188758
188759  return rc;
188760}
188761
188762/*
188763** Advance the first term iterator in the first phrase of pNear. Set output
188764** variable *pbEof to true if it reaches EOF or if an error occurs.
188765**
188766** Return SQLITE_OK if successful, or an SQLite error code if an error
188767** occurs.
188768*/
188769static int fts5ExprNodeNext_STRING(
188770  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
188771  Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
188772  int bFromValid,
188773  i64 iFrom
188774){
188775  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
188776  int rc = SQLITE_OK;
188777
188778  pNode->bNomatch = 0;
188779  if( pTerm->pSynonym ){
188780    int bEof = 1;
188781    Fts5ExprTerm *p;
188782
188783    /* Find the firstest rowid any synonym points to. */
188784    i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
188785
188786    /* Advance each iterator that currently points to iRowid. Or, if iFrom
188787    ** is valid - each iterator that points to a rowid before iFrom.  */
188788    for(p=pTerm; p; p=p->pSynonym){
188789      if( sqlite3Fts5IterEof(p->pIter)==0 ){
188790        i64 ii = p->pIter->iRowid;
188791        if( ii==iRowid
188792         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
188793        ){
188794          if( bFromValid ){
188795            rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
188796          }else{
188797            rc = sqlite3Fts5IterNext(p->pIter);
188798          }
188799          if( rc!=SQLITE_OK ) break;
188800          if( sqlite3Fts5IterEof(p->pIter)==0 ){
188801            bEof = 0;
188802          }
188803        }else{
188804          bEof = 0;
188805        }
188806      }
188807    }
188808
188809    /* Set the EOF flag if either all synonym iterators are at EOF or an
188810    ** error has occurred.  */
188811    pNode->bEof = (rc || bEof);
188812  }else{
188813    Fts5IndexIter *pIter = pTerm->pIter;
188814
188815    assert( Fts5NodeIsString(pNode) );
188816    if( bFromValid ){
188817      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
188818    }else{
188819      rc = sqlite3Fts5IterNext(pIter);
188820    }
188821
188822    pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
188823  }
188824
188825  if( pNode->bEof==0 ){
188826    assert( rc==SQLITE_OK );
188827    rc = fts5ExprNodeTest_STRING(pExpr, pNode);
188828  }
188829
188830  return rc;
188831}
188832
188833
188834static int fts5ExprNodeTest_TERM(
188835  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
188836  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
188837){
188838  /* As this "NEAR" object is actually a single phrase that consists
188839  ** of a single term only, grab pointers into the poslist managed by the
188840  ** fts5_index.c iterator object. This is much faster than synthesizing
188841  ** a new poslist the way we have to for more complicated phrase or NEAR
188842  ** expressions.  */
188843  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
188844  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
188845
188846  assert( pNode->eType==FTS5_TERM );
188847  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
188848  assert( pPhrase->aTerm[0].pSynonym==0 );
188849
188850  pPhrase->poslist.n = pIter->nData;
188851  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
188852    pPhrase->poslist.p = (u8*)pIter->pData;
188853  }
188854  pNode->iRowid = pIter->iRowid;
188855  pNode->bNomatch = (pPhrase->poslist.n==0);
188856  return SQLITE_OK;
188857}
188858
188859/*
188860** xNext() method for a node of type FTS5_TERM.
188861*/
188862static int fts5ExprNodeNext_TERM(
188863  Fts5Expr *pExpr,
188864  Fts5ExprNode *pNode,
188865  int bFromValid,
188866  i64 iFrom
188867){
188868  int rc;
188869  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
188870
188871  assert( pNode->bEof==0 );
188872  if( bFromValid ){
188873    rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
188874  }else{
188875    rc = sqlite3Fts5IterNext(pIter);
188876  }
188877  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
188878    rc = fts5ExprNodeTest_TERM(pExpr, pNode);
188879  }else{
188880    pNode->bEof = 1;
188881    pNode->bNomatch = 0;
188882  }
188883  return rc;
188884}
188885
188886static void fts5ExprNodeTest_OR(
188887  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
188888  Fts5ExprNode *pNode             /* Expression node to test */
188889){
188890  Fts5ExprNode *pNext = pNode->apChild[0];
188891  int i;
188892
188893  for(i=1; i<pNode->nChild; i++){
188894    Fts5ExprNode *pChild = pNode->apChild[i];
188895    int cmp = fts5NodeCompare(pExpr, pNext, pChild);
188896    if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
188897      pNext = pChild;
188898    }
188899  }
188900  pNode->iRowid = pNext->iRowid;
188901  pNode->bEof = pNext->bEof;
188902  pNode->bNomatch = pNext->bNomatch;
188903}
188904
188905static int fts5ExprNodeNext_OR(
188906  Fts5Expr *pExpr,
188907  Fts5ExprNode *pNode,
188908  int bFromValid,
188909  i64 iFrom
188910){
188911  int i;
188912  i64 iLast = pNode->iRowid;
188913
188914  for(i=0; i<pNode->nChild; i++){
188915    Fts5ExprNode *p1 = pNode->apChild[i];
188916    assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
188917    if( p1->bEof==0 ){
188918      if( (p1->iRowid==iLast)
188919       || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
188920      ){
188921        int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
188922        if( rc!=SQLITE_OK ){
188923          pNode->bNomatch = 0;
188924          return rc;
188925        }
188926      }
188927    }
188928  }
188929
188930  fts5ExprNodeTest_OR(pExpr, pNode);
188931  return SQLITE_OK;
188932}
188933
188934/*
188935** Argument pNode is an FTS5_AND node.
188936*/
188937static int fts5ExprNodeTest_AND(
188938  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
188939  Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
188940){
188941  int iChild;
188942  i64 iLast = pAnd->iRowid;
188943  int rc = SQLITE_OK;
188944  int bMatch;
188945
188946  assert( pAnd->bEof==0 );
188947  do {
188948    pAnd->bNomatch = 0;
188949    bMatch = 1;
188950    for(iChild=0; iChild<pAnd->nChild; iChild++){
188951      Fts5ExprNode *pChild = pAnd->apChild[iChild];
188952      int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
188953      if( cmp>0 ){
188954        /* Advance pChild until it points to iLast or laster */
188955        rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
188956        if( rc!=SQLITE_OK ){
188957          pAnd->bNomatch = 0;
188958          return rc;
188959        }
188960      }
188961
188962      /* If the child node is now at EOF, so is the parent AND node. Otherwise,
188963      ** the child node is guaranteed to have advanced at least as far as
188964      ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
188965      ** new lastest rowid seen so far.  */
188966      assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
188967      if( pChild->bEof ){
188968        fts5ExprSetEof(pAnd);
188969        bMatch = 1;
188970        break;
188971      }else if( iLast!=pChild->iRowid ){
188972        bMatch = 0;
188973        iLast = pChild->iRowid;
188974      }
188975
188976      if( pChild->bNomatch ){
188977        pAnd->bNomatch = 1;
188978      }
188979    }
188980  }while( bMatch==0 );
188981
188982  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
188983    fts5ExprNodeZeroPoslist(pAnd);
188984  }
188985  pAnd->iRowid = iLast;
188986  return SQLITE_OK;
188987}
188988
188989static int fts5ExprNodeNext_AND(
188990  Fts5Expr *pExpr,
188991  Fts5ExprNode *pNode,
188992  int bFromValid,
188993  i64 iFrom
188994){
188995  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
188996  if( rc==SQLITE_OK ){
188997    rc = fts5ExprNodeTest_AND(pExpr, pNode);
188998  }else{
188999    pNode->bNomatch = 0;
189000  }
189001  return rc;
189002}
189003
189004static int fts5ExprNodeTest_NOT(
189005  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
189006  Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
189007){
189008  int rc = SQLITE_OK;
189009  Fts5ExprNode *p1 = pNode->apChild[0];
189010  Fts5ExprNode *p2 = pNode->apChild[1];
189011  assert( pNode->nChild==2 );
189012
189013  while( rc==SQLITE_OK && p1->bEof==0 ){
189014    int cmp = fts5NodeCompare(pExpr, p1, p2);
189015    if( cmp>0 ){
189016      rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
189017      cmp = fts5NodeCompare(pExpr, p1, p2);
189018    }
189019    assert( rc!=SQLITE_OK || cmp<=0 );
189020    if( cmp || p2->bNomatch ) break;
189021    rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
189022  }
189023  pNode->bEof = p1->bEof;
189024  pNode->bNomatch = p1->bNomatch;
189025  pNode->iRowid = p1->iRowid;
189026  if( p1->bEof ){
189027    fts5ExprNodeZeroPoslist(p2);
189028  }
189029  return rc;
189030}
189031
189032static int fts5ExprNodeNext_NOT(
189033  Fts5Expr *pExpr,
189034  Fts5ExprNode *pNode,
189035  int bFromValid,
189036  i64 iFrom
189037){
189038  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
189039  if( rc==SQLITE_OK ){
189040    rc = fts5ExprNodeTest_NOT(pExpr, pNode);
189041  }
189042  if( rc!=SQLITE_OK ){
189043    pNode->bNomatch = 0;
189044  }
189045  return rc;
189046}
189047
189048/*
189049** If pNode currently points to a match, this function returns SQLITE_OK
189050** without modifying it. Otherwise, pNode is advanced until it does point
189051** to a match or EOF is reached.
189052*/
189053static int fts5ExprNodeTest(
189054  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
189055  Fts5ExprNode *pNode             /* Expression node to test */
189056){
189057  int rc = SQLITE_OK;
189058  if( pNode->bEof==0 ){
189059    switch( pNode->eType ){
189060
189061      case FTS5_STRING: {
189062        rc = fts5ExprNodeTest_STRING(pExpr, pNode);
189063        break;
189064      }
189065
189066      case FTS5_TERM: {
189067        rc = fts5ExprNodeTest_TERM(pExpr, pNode);
189068        break;
189069      }
189070
189071      case FTS5_AND: {
189072        rc = fts5ExprNodeTest_AND(pExpr, pNode);
189073        break;
189074      }
189075
189076      case FTS5_OR: {
189077        fts5ExprNodeTest_OR(pExpr, pNode);
189078        break;
189079      }
189080
189081      default: assert( pNode->eType==FTS5_NOT ); {
189082        rc = fts5ExprNodeTest_NOT(pExpr, pNode);
189083        break;
189084      }
189085    }
189086  }
189087  return rc;
189088}
189089
189090
189091/*
189092** Set node pNode, which is part of expression pExpr, to point to the first
189093** match. If there are no matches, set the Node.bEof flag to indicate EOF.
189094**
189095** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
189096** It is not an error if there are no matches.
189097*/
189098static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
189099  int rc = SQLITE_OK;
189100  pNode->bEof = 0;
189101  pNode->bNomatch = 0;
189102
189103  if( Fts5NodeIsString(pNode) ){
189104    /* Initialize all term iterators in the NEAR object. */
189105    rc = fts5ExprNearInitAll(pExpr, pNode);
189106  }else if( pNode->xNext==0 ){
189107    pNode->bEof = 1;
189108  }else{
189109    int i;
189110    int nEof = 0;
189111    for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
189112      Fts5ExprNode *pChild = pNode->apChild[i];
189113      rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
189114      assert( pChild->bEof==0 || pChild->bEof==1 );
189115      nEof += pChild->bEof;
189116    }
189117    pNode->iRowid = pNode->apChild[0]->iRowid;
189118
189119    switch( pNode->eType ){
189120      case FTS5_AND:
189121        if( nEof>0 ) fts5ExprSetEof(pNode);
189122        break;
189123
189124      case FTS5_OR:
189125        if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
189126        break;
189127
189128      default:
189129        assert( pNode->eType==FTS5_NOT );
189130        pNode->bEof = pNode->apChild[0]->bEof;
189131        break;
189132    }
189133  }
189134
189135  if( rc==SQLITE_OK ){
189136    rc = fts5ExprNodeTest(pExpr, pNode);
189137  }
189138  return rc;
189139}
189140
189141
189142/*
189143** Begin iterating through the set of documents in index pIdx matched by
189144** the MATCH expression passed as the first argument. If the "bDesc"
189145** parameter is passed a non-zero value, iteration is in descending rowid
189146** order. Or, if it is zero, in ascending order.
189147**
189148** If iterating in ascending rowid order (bDesc==0), the first document
189149** visited is that with the smallest rowid that is larger than or equal
189150** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
189151** then the first document visited must have a rowid smaller than or
189152** equal to iFirst.
189153**
189154** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
189155** is not considered an error if the query does not match any documents.
189156*/
189157static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
189158  Fts5ExprNode *pRoot = p->pRoot;
189159  int rc;                         /* Return code */
189160
189161  p->pIndex = pIdx;
189162  p->bDesc = bDesc;
189163  rc = fts5ExprNodeFirst(p, pRoot);
189164
189165  /* If not at EOF but the current rowid occurs earlier than iFirst in
189166  ** the iteration order, move to document iFirst or later. */
189167  if( rc==SQLITE_OK
189168   && 0==pRoot->bEof
189169   && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
189170  ){
189171    rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
189172  }
189173
189174  /* If the iterator is not at a real match, skip forward until it is. */
189175  while( pRoot->bNomatch ){
189176    assert( pRoot->bEof==0 && rc==SQLITE_OK );
189177    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
189178  }
189179  return rc;
189180}
189181
189182/*
189183** Move to the next document
189184**
189185** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
189186** is not considered an error if the query does not match any documents.
189187*/
189188static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
189189  int rc;
189190  Fts5ExprNode *pRoot = p->pRoot;
189191  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
189192  do {
189193    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
189194    assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
189195  }while( pRoot->bNomatch );
189196  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
189197    pRoot->bEof = 1;
189198  }
189199  return rc;
189200}
189201
189202static int sqlite3Fts5ExprEof(Fts5Expr *p){
189203  return p->pRoot->bEof;
189204}
189205
189206static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
189207  return p->pRoot->iRowid;
189208}
189209
189210static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
189211  int rc = SQLITE_OK;
189212  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
189213  return rc;
189214}
189215
189216/*
189217** Free the phrase object passed as the only argument.
189218*/
189219static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
189220  if( pPhrase ){
189221    int i;
189222    for(i=0; i<pPhrase->nTerm; i++){
189223      Fts5ExprTerm *pSyn;
189224      Fts5ExprTerm *pNext;
189225      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
189226      sqlite3_free(pTerm->zTerm);
189227      sqlite3Fts5IterClose(pTerm->pIter);
189228      for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
189229        pNext = pSyn->pSynonym;
189230        sqlite3Fts5IterClose(pSyn->pIter);
189231        fts5BufferFree((Fts5Buffer*)&pSyn[1]);
189232        sqlite3_free(pSyn);
189233      }
189234    }
189235    if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
189236    sqlite3_free(pPhrase);
189237  }
189238}
189239
189240/*
189241** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
189242** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
189243** appended to it and the results returned.
189244**
189245** If an OOM error occurs, both the pNear and pPhrase objects are freed and
189246** NULL returned.
189247*/
189248static Fts5ExprNearset *sqlite3Fts5ParseNearset(
189249  Fts5Parse *pParse,              /* Parse context */
189250  Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
189251  Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
189252){
189253  const int SZALLOC = 8;
189254  Fts5ExprNearset *pRet = 0;
189255
189256  if( pParse->rc==SQLITE_OK ){
189257    if( pPhrase==0 ){
189258      return pNear;
189259    }
189260    if( pNear==0 ){
189261      int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
189262      pRet = sqlite3_malloc(nByte);
189263      if( pRet==0 ){
189264        pParse->rc = SQLITE_NOMEM;
189265      }else{
189266        memset(pRet, 0, nByte);
189267      }
189268    }else if( (pNear->nPhrase % SZALLOC)==0 ){
189269      int nNew = pNear->nPhrase + SZALLOC;
189270      int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
189271
189272      pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
189273      if( pRet==0 ){
189274        pParse->rc = SQLITE_NOMEM;
189275      }
189276    }else{
189277      pRet = pNear;
189278    }
189279  }
189280
189281  if( pRet==0 ){
189282    assert( pParse->rc!=SQLITE_OK );
189283    sqlite3Fts5ParseNearsetFree(pNear);
189284    sqlite3Fts5ParsePhraseFree(pPhrase);
189285  }else{
189286    if( pRet->nPhrase>0 ){
189287      Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
189288      assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
189289      if( pPhrase->nTerm==0 ){
189290        fts5ExprPhraseFree(pPhrase);
189291        pRet->nPhrase--;
189292        pParse->nPhrase--;
189293        pPhrase = pLast;
189294      }else if( pLast->nTerm==0 ){
189295        fts5ExprPhraseFree(pLast);
189296        pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
189297        pParse->nPhrase--;
189298        pRet->nPhrase--;
189299      }
189300    }
189301    pRet->apPhrase[pRet->nPhrase++] = pPhrase;
189302  }
189303  return pRet;
189304}
189305
189306typedef struct TokenCtx TokenCtx;
189307struct TokenCtx {
189308  Fts5ExprPhrase *pPhrase;
189309  int rc;
189310};
189311
189312/*
189313** Callback for tokenizing terms used by ParseTerm().
189314*/
189315static int fts5ParseTokenize(
189316  void *pContext,                 /* Pointer to Fts5InsertCtx object */
189317  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
189318  const char *pToken,             /* Buffer containing token */
189319  int nToken,                     /* Size of token in bytes */
189320  int iUnused1,                   /* Start offset of token */
189321  int iUnused2                    /* End offset of token */
189322){
189323  int rc = SQLITE_OK;
189324  const int SZALLOC = 8;
189325  TokenCtx *pCtx = (TokenCtx*)pContext;
189326  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
189327
189328  UNUSED_PARAM2(iUnused1, iUnused2);
189329
189330  /* If an error has already occurred, this is a no-op */
189331  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
189332  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
189333
189334  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
189335    Fts5ExprTerm *pSyn;
189336    int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
189337    pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
189338    if( pSyn==0 ){
189339      rc = SQLITE_NOMEM;
189340    }else{
189341      memset(pSyn, 0, nByte);
189342      pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
189343      memcpy(pSyn->zTerm, pToken, nToken);
189344      pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
189345      pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
189346    }
189347  }else{
189348    Fts5ExprTerm *pTerm;
189349    if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
189350      Fts5ExprPhrase *pNew;
189351      int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
189352
189353      pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
189354          sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
189355      );
189356      if( pNew==0 ){
189357        rc = SQLITE_NOMEM;
189358      }else{
189359        if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
189360        pCtx->pPhrase = pPhrase = pNew;
189361        pNew->nTerm = nNew - SZALLOC;
189362      }
189363    }
189364
189365    if( rc==SQLITE_OK ){
189366      pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
189367      memset(pTerm, 0, sizeof(Fts5ExprTerm));
189368      pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
189369    }
189370  }
189371
189372  pCtx->rc = rc;
189373  return rc;
189374}
189375
189376
189377/*
189378** Free the phrase object passed as the only argument.
189379*/
189380static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
189381  fts5ExprPhraseFree(pPhrase);
189382}
189383
189384/*
189385** Free the phrase object passed as the second argument.
189386*/
189387static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
189388  if( pNear ){
189389    int i;
189390    for(i=0; i<pNear->nPhrase; i++){
189391      fts5ExprPhraseFree(pNear->apPhrase[i]);
189392    }
189393    sqlite3_free(pNear->pColset);
189394    sqlite3_free(pNear);
189395  }
189396}
189397
189398static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
189399  assert( pParse->pExpr==0 );
189400  pParse->pExpr = p;
189401}
189402
189403/*
189404** This function is called by the parser to process a string token. The
189405** string may or may not be quoted. In any case it is tokenized and a
189406** phrase object consisting of all tokens returned.
189407*/
189408static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
189409  Fts5Parse *pParse,              /* Parse context */
189410  Fts5ExprPhrase *pAppend,        /* Phrase to append to */
189411  Fts5Token *pToken,              /* String to tokenize */
189412  int bPrefix                     /* True if there is a trailing "*" */
189413){
189414  Fts5Config *pConfig = pParse->pConfig;
189415  TokenCtx sCtx;                  /* Context object passed to callback */
189416  int rc;                         /* Tokenize return code */
189417  char *z = 0;
189418
189419  memset(&sCtx, 0, sizeof(TokenCtx));
189420  sCtx.pPhrase = pAppend;
189421
189422  rc = fts5ParseStringFromToken(pToken, &z);
189423  if( rc==SQLITE_OK ){
189424    int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
189425    int n;
189426    sqlite3Fts5Dequote(z);
189427    n = (int)strlen(z);
189428    rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
189429  }
189430  sqlite3_free(z);
189431  if( rc || (rc = sCtx.rc) ){
189432    pParse->rc = rc;
189433    fts5ExprPhraseFree(sCtx.pPhrase);
189434    sCtx.pPhrase = 0;
189435  }else{
189436
189437    if( pAppend==0 ){
189438      if( (pParse->nPhrase % 8)==0 ){
189439        int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
189440        Fts5ExprPhrase **apNew;
189441        apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
189442        if( apNew==0 ){
189443          pParse->rc = SQLITE_NOMEM;
189444          fts5ExprPhraseFree(sCtx.pPhrase);
189445          return 0;
189446        }
189447        pParse->apPhrase = apNew;
189448      }
189449      pParse->nPhrase++;
189450    }
189451
189452    if( sCtx.pPhrase==0 ){
189453      /* This happens when parsing a token or quoted phrase that contains
189454      ** no token characters at all. (e.g ... MATCH '""'). */
189455      sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
189456    }else if( sCtx.pPhrase->nTerm ){
189457      sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
189458    }
189459    pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
189460  }
189461
189462  return sCtx.pPhrase;
189463}
189464
189465/*
189466** Create a new FTS5 expression by cloning phrase iPhrase of the
189467** expression passed as the second argument.
189468*/
189469static int sqlite3Fts5ExprClonePhrase(
189470  Fts5Expr *pExpr,
189471  int iPhrase,
189472  Fts5Expr **ppNew
189473){
189474  int rc = SQLITE_OK;             /* Return code */
189475  Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
189476  Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
189477  TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
189478
189479  pOrig = pExpr->apExprPhrase[iPhrase];
189480  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
189481  if( rc==SQLITE_OK ){
189482    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
189483        sizeof(Fts5ExprPhrase*));
189484  }
189485  if( rc==SQLITE_OK ){
189486    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
189487        sizeof(Fts5ExprNode));
189488  }
189489  if( rc==SQLITE_OK ){
189490    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
189491        sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
189492  }
189493  if( rc==SQLITE_OK ){
189494    Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
189495    if( pColsetOrig ){
189496      int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
189497      Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
189498      if( pColset ){
189499        memcpy(pColset, pColsetOrig, nByte);
189500      }
189501      pNew->pRoot->pNear->pColset = pColset;
189502    }
189503  }
189504
189505  if( pOrig->nTerm ){
189506    int i;                          /* Used to iterate through phrase terms */
189507    for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
189508      int tflags = 0;
189509      Fts5ExprTerm *p;
189510      for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
189511        const char *zTerm = p->zTerm;
189512        rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
189513            0, 0);
189514        tflags = FTS5_TOKEN_COLOCATED;
189515      }
189516      if( rc==SQLITE_OK ){
189517        sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
189518      }
189519    }
189520  }else{
189521    /* This happens when parsing a token or quoted phrase that contains
189522    ** no token characters at all. (e.g ... MATCH '""'). */
189523    sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
189524  }
189525
189526  if( rc==SQLITE_OK ){
189527    /* All the allocations succeeded. Put the expression object together. */
189528    pNew->pIndex = pExpr->pIndex;
189529    pNew->pConfig = pExpr->pConfig;
189530    pNew->nPhrase = 1;
189531    pNew->apExprPhrase[0] = sCtx.pPhrase;
189532    pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
189533    pNew->pRoot->pNear->nPhrase = 1;
189534    sCtx.pPhrase->pNode = pNew->pRoot;
189535
189536    if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
189537      pNew->pRoot->eType = FTS5_TERM;
189538      pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
189539    }else{
189540      pNew->pRoot->eType = FTS5_STRING;
189541      pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
189542    }
189543  }else{
189544    sqlite3Fts5ExprFree(pNew);
189545    fts5ExprPhraseFree(sCtx.pPhrase);
189546    pNew = 0;
189547  }
189548
189549  *ppNew = pNew;
189550  return rc;
189551}
189552
189553
189554/*
189555** Token pTok has appeared in a MATCH expression where the NEAR operator
189556** is expected. If token pTok does not contain "NEAR", store an error
189557** in the pParse object.
189558*/
189559static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
189560  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
189561    sqlite3Fts5ParseError(
189562        pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
189563    );
189564  }
189565}
189566
189567static void sqlite3Fts5ParseSetDistance(
189568  Fts5Parse *pParse,
189569  Fts5ExprNearset *pNear,
189570  Fts5Token *p
189571){
189572  if( pNear ){
189573    int nNear = 0;
189574    int i;
189575    if( p->n ){
189576      for(i=0; i<p->n; i++){
189577        char c = (char)p->p[i];
189578        if( c<'0' || c>'9' ){
189579          sqlite3Fts5ParseError(
189580              pParse, "expected integer, got \"%.*s\"", p->n, p->p
189581              );
189582          return;
189583        }
189584        nNear = nNear * 10 + (p->p[i] - '0');
189585      }
189586    }else{
189587      nNear = FTS5_DEFAULT_NEARDIST;
189588    }
189589    pNear->nNear = nNear;
189590  }
189591}
189592
189593/*
189594** The second argument passed to this function may be NULL, or it may be
189595** an existing Fts5Colset object. This function returns a pointer to
189596** a new colset object containing the contents of (p) with new value column
189597** number iCol appended.
189598**
189599** If an OOM error occurs, store an error code in pParse and return NULL.
189600** The old colset object (if any) is not freed in this case.
189601*/
189602static Fts5Colset *fts5ParseColset(
189603  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
189604  Fts5Colset *p,                  /* Existing colset object */
189605  int iCol                        /* New column to add to colset object */
189606){
189607  int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
189608  Fts5Colset *pNew;               /* New colset object to return */
189609
189610  assert( pParse->rc==SQLITE_OK );
189611  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
189612
189613  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
189614  if( pNew==0 ){
189615    pParse->rc = SQLITE_NOMEM;
189616  }else{
189617    int *aiCol = pNew->aiCol;
189618    int i, j;
189619    for(i=0; i<nCol; i++){
189620      if( aiCol[i]==iCol ) return pNew;
189621      if( aiCol[i]>iCol ) break;
189622    }
189623    for(j=nCol; j>i; j--){
189624      aiCol[j] = aiCol[j-1];
189625    }
189626    aiCol[i] = iCol;
189627    pNew->nCol = nCol+1;
189628
189629#ifndef NDEBUG
189630    /* Check that the array is in order and contains no duplicate entries. */
189631    for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
189632#endif
189633  }
189634
189635  return pNew;
189636}
189637
189638/*
189639** Allocate and return an Fts5Colset object specifying the inverse of
189640** the colset passed as the second argument. Free the colset passed
189641** as the second argument before returning.
189642*/
189643static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
189644  Fts5Colset *pRet;
189645  int nCol = pParse->pConfig->nCol;
189646
189647  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
189648      sizeof(Fts5Colset) + sizeof(int)*nCol
189649  );
189650  if( pRet ){
189651    int i;
189652    int iOld = 0;
189653    for(i=0; i<nCol; i++){
189654      if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
189655        pRet->aiCol[pRet->nCol++] = i;
189656      }else{
189657        iOld++;
189658      }
189659    }
189660  }
189661
189662  sqlite3_free(p);
189663  return pRet;
189664}
189665
189666static Fts5Colset *sqlite3Fts5ParseColset(
189667  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
189668  Fts5Colset *pColset,            /* Existing colset object */
189669  Fts5Token *p
189670){
189671  Fts5Colset *pRet = 0;
189672  int iCol;
189673  char *z;                        /* Dequoted copy of token p */
189674
189675  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
189676  if( pParse->rc==SQLITE_OK ){
189677    Fts5Config *pConfig = pParse->pConfig;
189678    sqlite3Fts5Dequote(z);
189679    for(iCol=0; iCol<pConfig->nCol; iCol++){
189680      if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
189681    }
189682    if( iCol==pConfig->nCol ){
189683      sqlite3Fts5ParseError(pParse, "no such column: %s", z);
189684    }else{
189685      pRet = fts5ParseColset(pParse, pColset, iCol);
189686    }
189687    sqlite3_free(z);
189688  }
189689
189690  if( pRet==0 ){
189691    assert( pParse->rc!=SQLITE_OK );
189692    sqlite3_free(pColset);
189693  }
189694
189695  return pRet;
189696}
189697
189698/*
189699** If argument pOrig is NULL, or if (*pRc) is set to anything other than
189700** SQLITE_OK when this function is called, NULL is returned.
189701**
189702** Otherwise, a copy of (*pOrig) is made into memory obtained from
189703** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
189704** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
189705*/
189706static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
189707  Fts5Colset *pRet;
189708  if( pOrig ){
189709    int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
189710    pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
189711    if( pRet ){
189712      memcpy(pRet, pOrig, nByte);
189713    }
189714  }else{
189715    pRet = 0;
189716  }
189717  return pRet;
189718}
189719
189720/*
189721** Remove from colset pColset any columns that are not also in colset pMerge.
189722*/
189723static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
189724  int iIn = 0;          /* Next input in pColset */
189725  int iMerge = 0;       /* Next input in pMerge */
189726  int iOut = 0;         /* Next output slot in pColset */
189727
189728  while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
189729    int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
189730    if( iDiff==0 ){
189731      pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
189732      iMerge++;
189733      iIn++;
189734    }else if( iDiff>0 ){
189735      iMerge++;
189736    }else{
189737      iIn++;
189738    }
189739  }
189740  pColset->nCol = iOut;
189741}
189742
189743/*
189744** Recursively apply colset pColset to expression node pNode and all of
189745** its decendents. If (*ppFree) is not NULL, it contains a spare copy
189746** of pColset. This function may use the spare copy and set (*ppFree) to
189747** zero, or it may create copies of pColset using fts5CloneColset().
189748*/
189749static void fts5ParseSetColset(
189750  Fts5Parse *pParse,
189751  Fts5ExprNode *pNode,
189752  Fts5Colset *pColset,
189753  Fts5Colset **ppFree
189754){
189755  if( pParse->rc==SQLITE_OK ){
189756    assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
189757         || pNode->eType==FTS5_AND  || pNode->eType==FTS5_OR
189758         || pNode->eType==FTS5_NOT  || pNode->eType==FTS5_EOF
189759    );
189760    if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
189761      Fts5ExprNearset *pNear = pNode->pNear;
189762      if( pNear->pColset ){
189763        fts5MergeColset(pNear->pColset, pColset);
189764        if( pNear->pColset->nCol==0 ){
189765          pNode->eType = FTS5_EOF;
189766          pNode->xNext = 0;
189767        }
189768      }else if( *ppFree ){
189769        pNear->pColset = pColset;
189770        *ppFree = 0;
189771      }else{
189772        pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
189773      }
189774    }else{
189775      int i;
189776      assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
189777      for(i=0; i<pNode->nChild; i++){
189778        fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
189779      }
189780    }
189781  }
189782}
189783
189784/*
189785** Apply colset pColset to expression node pExpr and all of its descendents.
189786*/
189787static void sqlite3Fts5ParseSetColset(
189788  Fts5Parse *pParse,
189789  Fts5ExprNode *pExpr,
189790  Fts5Colset *pColset
189791){
189792  Fts5Colset *pFree = pColset;
189793  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
189794    pParse->rc = SQLITE_ERROR;
189795    pParse->zErr = sqlite3_mprintf(
189796      "fts5: column queries are not supported (detail=none)"
189797    );
189798  }else{
189799    fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
189800  }
189801  sqlite3_free(pFree);
189802}
189803
189804static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
189805  switch( pNode->eType ){
189806    case FTS5_STRING: {
189807      Fts5ExprNearset *pNear = pNode->pNear;
189808      if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
189809       && pNear->apPhrase[0]->aTerm[0].pSynonym==0
189810      ){
189811        pNode->eType = FTS5_TERM;
189812        pNode->xNext = fts5ExprNodeNext_TERM;
189813      }else{
189814        pNode->xNext = fts5ExprNodeNext_STRING;
189815      }
189816      break;
189817    };
189818
189819    case FTS5_OR: {
189820      pNode->xNext = fts5ExprNodeNext_OR;
189821      break;
189822    };
189823
189824    case FTS5_AND: {
189825      pNode->xNext = fts5ExprNodeNext_AND;
189826      break;
189827    };
189828
189829    default: assert( pNode->eType==FTS5_NOT ); {
189830      pNode->xNext = fts5ExprNodeNext_NOT;
189831      break;
189832    };
189833  }
189834}
189835
189836static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
189837  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
189838    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
189839    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
189840    p->nChild += pSub->nChild;
189841    sqlite3_free(pSub);
189842  }else{
189843    p->apChild[p->nChild++] = pSub;
189844  }
189845}
189846
189847/*
189848** Allocate and return a new expression object. If anything goes wrong (i.e.
189849** OOM error), leave an error code in pParse and return NULL.
189850*/
189851static Fts5ExprNode *sqlite3Fts5ParseNode(
189852  Fts5Parse *pParse,              /* Parse context */
189853  int eType,                      /* FTS5_STRING, AND, OR or NOT */
189854  Fts5ExprNode *pLeft,            /* Left hand child expression */
189855  Fts5ExprNode *pRight,           /* Right hand child expression */
189856  Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
189857){
189858  Fts5ExprNode *pRet = 0;
189859
189860  if( pParse->rc==SQLITE_OK ){
189861    int nChild = 0;               /* Number of children of returned node */
189862    int nByte;                    /* Bytes of space to allocate for this node */
189863
189864    assert( (eType!=FTS5_STRING && !pNear)
189865         || (eType==FTS5_STRING && !pLeft && !pRight)
189866    );
189867    if( eType==FTS5_STRING && pNear==0 ) return 0;
189868    if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
189869    if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
189870
189871    if( eType==FTS5_NOT ){
189872      nChild = 2;
189873    }else if( eType==FTS5_AND || eType==FTS5_OR ){
189874      nChild = 2;
189875      if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
189876      if( pRight->eType==eType ) nChild += pRight->nChild-1;
189877    }
189878
189879    nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
189880    pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
189881
189882    if( pRet ){
189883      pRet->eType = eType;
189884      pRet->pNear = pNear;
189885      fts5ExprAssignXNext(pRet);
189886      if( eType==FTS5_STRING ){
189887        int iPhrase;
189888        for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
189889          pNear->apPhrase[iPhrase]->pNode = pRet;
189890          if( pNear->apPhrase[iPhrase]->nTerm==0 ){
189891            pRet->xNext = 0;
189892            pRet->eType = FTS5_EOF;
189893          }
189894        }
189895
189896        if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
189897         && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
189898        ){
189899          assert( pParse->rc==SQLITE_OK );
189900          pParse->rc = SQLITE_ERROR;
189901          assert( pParse->zErr==0 );
189902          pParse->zErr = sqlite3_mprintf(
189903              "fts5: %s queries are not supported (detail!=full)",
189904              pNear->nPhrase==1 ? "phrase": "NEAR"
189905          );
189906          sqlite3_free(pRet);
189907          pRet = 0;
189908        }
189909
189910      }else{
189911        fts5ExprAddChildren(pRet, pLeft);
189912        fts5ExprAddChildren(pRet, pRight);
189913      }
189914    }
189915  }
189916
189917  if( pRet==0 ){
189918    assert( pParse->rc!=SQLITE_OK );
189919    sqlite3Fts5ParseNodeFree(pLeft);
189920    sqlite3Fts5ParseNodeFree(pRight);
189921    sqlite3Fts5ParseNearsetFree(pNear);
189922  }
189923  return pRet;
189924}
189925
189926static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
189927  Fts5Parse *pParse,              /* Parse context */
189928  Fts5ExprNode *pLeft,            /* Left hand child expression */
189929  Fts5ExprNode *pRight            /* Right hand child expression */
189930){
189931  Fts5ExprNode *pRet = 0;
189932  Fts5ExprNode *pPrev;
189933
189934  if( pParse->rc ){
189935    sqlite3Fts5ParseNodeFree(pLeft);
189936    sqlite3Fts5ParseNodeFree(pRight);
189937  }else{
189938
189939    assert( pLeft->eType==FTS5_STRING
189940        || pLeft->eType==FTS5_TERM
189941        || pLeft->eType==FTS5_EOF
189942        || pLeft->eType==FTS5_AND
189943    );
189944    assert( pRight->eType==FTS5_STRING
189945        || pRight->eType==FTS5_TERM
189946        || pRight->eType==FTS5_EOF
189947    );
189948
189949    if( pLeft->eType==FTS5_AND ){
189950      pPrev = pLeft->apChild[pLeft->nChild-1];
189951    }else{
189952      pPrev = pLeft;
189953    }
189954    assert( pPrev->eType==FTS5_STRING
189955        || pPrev->eType==FTS5_TERM
189956        || pPrev->eType==FTS5_EOF
189957        );
189958
189959    if( pRight->eType==FTS5_EOF ){
189960      assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
189961      sqlite3Fts5ParseNodeFree(pRight);
189962      pRet = pLeft;
189963      pParse->nPhrase--;
189964    }
189965    else if( pPrev->eType==FTS5_EOF ){
189966      Fts5ExprPhrase **ap;
189967
189968      if( pPrev==pLeft ){
189969        pRet = pRight;
189970      }else{
189971        pLeft->apChild[pLeft->nChild-1] = pRight;
189972        pRet = pLeft;
189973      }
189974
189975      ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
189976      assert( ap[0]==pPrev->pNear->apPhrase[0] );
189977      memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
189978      pParse->nPhrase--;
189979
189980      sqlite3Fts5ParseNodeFree(pPrev);
189981    }
189982    else{
189983      pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
189984    }
189985  }
189986
189987  return pRet;
189988}
189989
189990static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
189991  int nByte = 0;
189992  Fts5ExprTerm *p;
189993  char *zQuoted;
189994
189995  /* Determine the maximum amount of space required. */
189996  for(p=pTerm; p; p=p->pSynonym){
189997    nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
189998  }
189999  zQuoted = sqlite3_malloc(nByte);
190000
190001  if( zQuoted ){
190002    int i = 0;
190003    for(p=pTerm; p; p=p->pSynonym){
190004      char *zIn = p->zTerm;
190005      zQuoted[i++] = '"';
190006      while( *zIn ){
190007        if( *zIn=='"' ) zQuoted[i++] = '"';
190008        zQuoted[i++] = *zIn++;
190009      }
190010      zQuoted[i++] = '"';
190011      if( p->pSynonym ) zQuoted[i++] = '|';
190012    }
190013    if( pTerm->bPrefix ){
190014      zQuoted[i++] = ' ';
190015      zQuoted[i++] = '*';
190016    }
190017    zQuoted[i++] = '\0';
190018  }
190019  return zQuoted;
190020}
190021
190022static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
190023  char *zNew;
190024  va_list ap;
190025  va_start(ap, zFmt);
190026  zNew = sqlite3_vmprintf(zFmt, ap);
190027  va_end(ap);
190028  if( zApp && zNew ){
190029    char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
190030    sqlite3_free(zNew);
190031    zNew = zNew2;
190032  }
190033  sqlite3_free(zApp);
190034  return zNew;
190035}
190036
190037/*
190038** Compose a tcl-readable representation of expression pExpr. Return a
190039** pointer to a buffer containing that representation. It is the
190040** responsibility of the caller to at some point free the buffer using
190041** sqlite3_free().
190042*/
190043static char *fts5ExprPrintTcl(
190044  Fts5Config *pConfig,
190045  const char *zNearsetCmd,
190046  Fts5ExprNode *pExpr
190047){
190048  char *zRet = 0;
190049  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
190050    Fts5ExprNearset *pNear = pExpr->pNear;
190051    int i;
190052    int iTerm;
190053
190054    zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
190055    if( zRet==0 ) return 0;
190056    if( pNear->pColset ){
190057      int *aiCol = pNear->pColset->aiCol;
190058      int nCol = pNear->pColset->nCol;
190059      if( nCol==1 ){
190060        zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
190061      }else{
190062        zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
190063        for(i=1; i<pNear->pColset->nCol; i++){
190064          zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
190065        }
190066        zRet = fts5PrintfAppend(zRet, "} ");
190067      }
190068      if( zRet==0 ) return 0;
190069    }
190070
190071    if( pNear->nPhrase>1 ){
190072      zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
190073      if( zRet==0 ) return 0;
190074    }
190075
190076    zRet = fts5PrintfAppend(zRet, "--");
190077    if( zRet==0 ) return 0;
190078
190079    for(i=0; i<pNear->nPhrase; i++){
190080      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
190081
190082      zRet = fts5PrintfAppend(zRet, " {");
190083      for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
190084        char *zTerm = pPhrase->aTerm[iTerm].zTerm;
190085        zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
190086        if( pPhrase->aTerm[iTerm].bPrefix ){
190087          zRet = fts5PrintfAppend(zRet, "*");
190088        }
190089      }
190090
190091      if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
190092      if( zRet==0 ) return 0;
190093    }
190094
190095  }else{
190096    char const *zOp = 0;
190097    int i;
190098    switch( pExpr->eType ){
190099      case FTS5_AND: zOp = "AND"; break;
190100      case FTS5_NOT: zOp = "NOT"; break;
190101      default:
190102        assert( pExpr->eType==FTS5_OR );
190103        zOp = "OR";
190104        break;
190105    }
190106
190107    zRet = sqlite3_mprintf("%s", zOp);
190108    for(i=0; zRet && i<pExpr->nChild; i++){
190109      char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
190110      if( !z ){
190111        sqlite3_free(zRet);
190112        zRet = 0;
190113      }else{
190114        zRet = fts5PrintfAppend(zRet, " [%z]", z);
190115      }
190116    }
190117  }
190118
190119  return zRet;
190120}
190121
190122static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
190123  char *zRet = 0;
190124  if( pExpr->eType==0 ){
190125    return sqlite3_mprintf("\"\"");
190126  }else
190127  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
190128    Fts5ExprNearset *pNear = pExpr->pNear;
190129    int i;
190130    int iTerm;
190131
190132    if( pNear->pColset ){
190133      int iCol = pNear->pColset->aiCol[0];
190134      zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
190135      if( zRet==0 ) return 0;
190136    }
190137
190138    if( pNear->nPhrase>1 ){
190139      zRet = fts5PrintfAppend(zRet, "NEAR(");
190140      if( zRet==0 ) return 0;
190141    }
190142
190143    for(i=0; i<pNear->nPhrase; i++){
190144      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
190145      if( i!=0 ){
190146        zRet = fts5PrintfAppend(zRet, " ");
190147        if( zRet==0 ) return 0;
190148      }
190149      for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
190150        char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
190151        if( zTerm ){
190152          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
190153          sqlite3_free(zTerm);
190154        }
190155        if( zTerm==0 || zRet==0 ){
190156          sqlite3_free(zRet);
190157          return 0;
190158        }
190159      }
190160    }
190161
190162    if( pNear->nPhrase>1 ){
190163      zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
190164      if( zRet==0 ) return 0;
190165    }
190166
190167  }else{
190168    char const *zOp = 0;
190169    int i;
190170
190171    switch( pExpr->eType ){
190172      case FTS5_AND: zOp = " AND "; break;
190173      case FTS5_NOT: zOp = " NOT "; break;
190174      default:
190175        assert( pExpr->eType==FTS5_OR );
190176        zOp = " OR ";
190177        break;
190178    }
190179
190180    for(i=0; i<pExpr->nChild; i++){
190181      char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
190182      if( z==0 ){
190183        sqlite3_free(zRet);
190184        zRet = 0;
190185      }else{
190186        int e = pExpr->apChild[i]->eType;
190187        int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
190188        zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
190189            (i==0 ? "" : zOp),
190190            (b?"(":""), z, (b?")":"")
190191        );
190192      }
190193      if( zRet==0 ) break;
190194    }
190195  }
190196
190197  return zRet;
190198}
190199
190200/*
190201** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
190202** and fts5_expr_tcl() (bTcl!=0).
190203*/
190204static void fts5ExprFunction(
190205  sqlite3_context *pCtx,          /* Function call context */
190206  int nArg,                       /* Number of args */
190207  sqlite3_value **apVal,          /* Function arguments */
190208  int bTcl
190209){
190210  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
190211  sqlite3 *db = sqlite3_context_db_handle(pCtx);
190212  const char *zExpr = 0;
190213  char *zErr = 0;
190214  Fts5Expr *pExpr = 0;
190215  int rc;
190216  int i;
190217
190218  const char **azConfig;          /* Array of arguments for Fts5Config */
190219  const char *zNearsetCmd = "nearset";
190220  int nConfig;                    /* Size of azConfig[] */
190221  Fts5Config *pConfig = 0;
190222  int iArg = 1;
190223
190224  if( nArg<1 ){
190225    zErr = sqlite3_mprintf("wrong number of arguments to function %s",
190226        bTcl ? "fts5_expr_tcl" : "fts5_expr"
190227    );
190228    sqlite3_result_error(pCtx, zErr, -1);
190229    sqlite3_free(zErr);
190230    return;
190231  }
190232
190233  if( bTcl && nArg>1 ){
190234    zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
190235    iArg = 2;
190236  }
190237
190238  nConfig = 3 + (nArg-iArg);
190239  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
190240  if( azConfig==0 ){
190241    sqlite3_result_error_nomem(pCtx);
190242    return;
190243  }
190244  azConfig[0] = 0;
190245  azConfig[1] = "main";
190246  azConfig[2] = "tbl";
190247  for(i=3; iArg<nArg; iArg++){
190248    azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
190249  }
190250
190251  zExpr = (const char*)sqlite3_value_text(apVal[0]);
190252
190253  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
190254  if( rc==SQLITE_OK ){
190255    rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
190256  }
190257  if( rc==SQLITE_OK ){
190258    char *zText;
190259    if( pExpr->pRoot->xNext==0 ){
190260      zText = sqlite3_mprintf("");
190261    }else if( bTcl ){
190262      zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
190263    }else{
190264      zText = fts5ExprPrint(pConfig, pExpr->pRoot);
190265    }
190266    if( zText==0 ){
190267      rc = SQLITE_NOMEM;
190268    }else{
190269      sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
190270      sqlite3_free(zText);
190271    }
190272  }
190273
190274  if( rc!=SQLITE_OK ){
190275    if( zErr ){
190276      sqlite3_result_error(pCtx, zErr, -1);
190277      sqlite3_free(zErr);
190278    }else{
190279      sqlite3_result_error_code(pCtx, rc);
190280    }
190281  }
190282  sqlite3_free((void *)azConfig);
190283  sqlite3Fts5ConfigFree(pConfig);
190284  sqlite3Fts5ExprFree(pExpr);
190285}
190286
190287static void fts5ExprFunctionHr(
190288  sqlite3_context *pCtx,          /* Function call context */
190289  int nArg,                       /* Number of args */
190290  sqlite3_value **apVal           /* Function arguments */
190291){
190292  fts5ExprFunction(pCtx, nArg, apVal, 0);
190293}
190294static void fts5ExprFunctionTcl(
190295  sqlite3_context *pCtx,          /* Function call context */
190296  int nArg,                       /* Number of args */
190297  sqlite3_value **apVal           /* Function arguments */
190298){
190299  fts5ExprFunction(pCtx, nArg, apVal, 1);
190300}
190301
190302/*
190303** The implementation of an SQLite user-defined-function that accepts a
190304** single integer as an argument. If the integer is an alpha-numeric
190305** unicode code point, 1 is returned. Otherwise 0.
190306*/
190307static void fts5ExprIsAlnum(
190308  sqlite3_context *pCtx,          /* Function call context */
190309  int nArg,                       /* Number of args */
190310  sqlite3_value **apVal           /* Function arguments */
190311){
190312  int iCode;
190313  if( nArg!=1 ){
190314    sqlite3_result_error(pCtx,
190315        "wrong number of arguments to function fts5_isalnum", -1
190316    );
190317    return;
190318  }
190319  iCode = sqlite3_value_int(apVal[0]);
190320  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
190321}
190322
190323static void fts5ExprFold(
190324  sqlite3_context *pCtx,          /* Function call context */
190325  int nArg,                       /* Number of args */
190326  sqlite3_value **apVal           /* Function arguments */
190327){
190328  if( nArg!=1 && nArg!=2 ){
190329    sqlite3_result_error(pCtx,
190330        "wrong number of arguments to function fts5_fold", -1
190331    );
190332  }else{
190333    int iCode;
190334    int bRemoveDiacritics = 0;
190335    iCode = sqlite3_value_int(apVal[0]);
190336    if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
190337    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
190338  }
190339}
190340
190341/*
190342** This is called during initialization to register the fts5_expr() scalar
190343** UDF with the SQLite handle passed as the only argument.
190344*/
190345static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
190346  struct Fts5ExprFunc {
190347    const char *z;
190348    void (*x)(sqlite3_context*,int,sqlite3_value**);
190349  } aFunc[] = {
190350    { "fts5_expr",     fts5ExprFunctionHr },
190351    { "fts5_expr_tcl", fts5ExprFunctionTcl },
190352    { "fts5_isalnum",  fts5ExprIsAlnum },
190353    { "fts5_fold",     fts5ExprFold },
190354  };
190355  int i;
190356  int rc = SQLITE_OK;
190357  void *pCtx = (void*)pGlobal;
190358
190359  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
190360    struct Fts5ExprFunc *p = &aFunc[i];
190361    rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
190362  }
190363
190364  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
190365#ifndef NDEBUG
190366  (void)sqlite3Fts5ParserTrace;
190367#endif
190368
190369  return rc;
190370}
190371
190372/*
190373** Return the number of phrases in expression pExpr.
190374*/
190375static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
190376  return (pExpr ? pExpr->nPhrase : 0);
190377}
190378
190379/*
190380** Return the number of terms in the iPhrase'th phrase in pExpr.
190381*/
190382static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
190383  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
190384  return pExpr->apExprPhrase[iPhrase]->nTerm;
190385}
190386
190387/*
190388** This function is used to access the current position list for phrase
190389** iPhrase.
190390*/
190391static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
190392  int nRet;
190393  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
190394  Fts5ExprNode *pNode = pPhrase->pNode;
190395  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
190396    *pa = pPhrase->poslist.p;
190397    nRet = pPhrase->poslist.n;
190398  }else{
190399    *pa = 0;
190400    nRet = 0;
190401  }
190402  return nRet;
190403}
190404
190405struct Fts5PoslistPopulator {
190406  Fts5PoslistWriter writer;
190407  int bOk;                        /* True if ok to populate */
190408  int bMiss;
190409};
190410
190411static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
190412  Fts5PoslistPopulator *pRet;
190413  pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
190414  if( pRet ){
190415    int i;
190416    memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
190417    for(i=0; i<pExpr->nPhrase; i++){
190418      Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
190419      Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
190420      assert( pExpr->apExprPhrase[i]->nTerm==1 );
190421      if( bLive &&
190422          (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
190423      ){
190424        pRet[i].bMiss = 1;
190425      }else{
190426        pBuf->n = 0;
190427      }
190428    }
190429  }
190430  return pRet;
190431}
190432
190433struct Fts5ExprCtx {
190434  Fts5Expr *pExpr;
190435  Fts5PoslistPopulator *aPopulator;
190436  i64 iOff;
190437};
190438typedef struct Fts5ExprCtx Fts5ExprCtx;
190439
190440/*
190441** TODO: Make this more efficient!
190442*/
190443static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
190444  int i;
190445  for(i=0; i<pColset->nCol; i++){
190446    if( pColset->aiCol[i]==iCol ) return 1;
190447  }
190448  return 0;
190449}
190450
190451static int fts5ExprPopulatePoslistsCb(
190452  void *pCtx,                /* Copy of 2nd argument to xTokenize() */
190453  int tflags,                /* Mask of FTS5_TOKEN_* flags */
190454  const char *pToken,        /* Pointer to buffer containing token */
190455  int nToken,                /* Size of token in bytes */
190456  int iUnused1,              /* Byte offset of token within input text */
190457  int iUnused2               /* Byte offset of end of token within input text */
190458){
190459  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
190460  Fts5Expr *pExpr = p->pExpr;
190461  int i;
190462
190463  UNUSED_PARAM2(iUnused1, iUnused2);
190464
190465  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
190466  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
190467  for(i=0; i<pExpr->nPhrase; i++){
190468    Fts5ExprTerm *pTerm;
190469    if( p->aPopulator[i].bOk==0 ) continue;
190470    for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
190471      int nTerm = (int)strlen(pTerm->zTerm);
190472      if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
190473       && memcmp(pTerm->zTerm, pToken, nTerm)==0
190474      ){
190475        int rc = sqlite3Fts5PoslistWriterAppend(
190476            &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
190477        );
190478        if( rc ) return rc;
190479        break;
190480      }
190481    }
190482  }
190483  return SQLITE_OK;
190484}
190485
190486static int sqlite3Fts5ExprPopulatePoslists(
190487  Fts5Config *pConfig,
190488  Fts5Expr *pExpr,
190489  Fts5PoslistPopulator *aPopulator,
190490  int iCol,
190491  const char *z, int n
190492){
190493  int i;
190494  Fts5ExprCtx sCtx;
190495  sCtx.pExpr = pExpr;
190496  sCtx.aPopulator = aPopulator;
190497  sCtx.iOff = (((i64)iCol) << 32) - 1;
190498
190499  for(i=0; i<pExpr->nPhrase; i++){
190500    Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
190501    Fts5Colset *pColset = pNode->pNear->pColset;
190502    if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
190503     || aPopulator[i].bMiss
190504    ){
190505      aPopulator[i].bOk = 0;
190506    }else{
190507      aPopulator[i].bOk = 1;
190508    }
190509  }
190510
190511  return sqlite3Fts5Tokenize(pConfig,
190512      FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
190513  );
190514}
190515
190516static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
190517  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
190518    pNode->pNear->apPhrase[0]->poslist.n = 0;
190519  }else{
190520    int i;
190521    for(i=0; i<pNode->nChild; i++){
190522      fts5ExprClearPoslists(pNode->apChild[i]);
190523    }
190524  }
190525}
190526
190527static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
190528  pNode->iRowid = iRowid;
190529  pNode->bEof = 0;
190530  switch( pNode->eType ){
190531    case FTS5_TERM:
190532    case FTS5_STRING:
190533      return (pNode->pNear->apPhrase[0]->poslist.n>0);
190534
190535    case FTS5_AND: {
190536      int i;
190537      for(i=0; i<pNode->nChild; i++){
190538        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
190539          fts5ExprClearPoslists(pNode);
190540          return 0;
190541        }
190542      }
190543      break;
190544    }
190545
190546    case FTS5_OR: {
190547      int i;
190548      int bRet = 0;
190549      for(i=0; i<pNode->nChild; i++){
190550        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
190551          bRet = 1;
190552        }
190553      }
190554      return bRet;
190555    }
190556
190557    default: {
190558      assert( pNode->eType==FTS5_NOT );
190559      if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
190560          || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
190561        ){
190562        fts5ExprClearPoslists(pNode);
190563        return 0;
190564      }
190565      break;
190566    }
190567  }
190568  return 1;
190569}
190570
190571static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
190572  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
190573}
190574
190575/*
190576** This function is only called for detail=columns tables.
190577*/
190578static int sqlite3Fts5ExprPhraseCollist(
190579  Fts5Expr *pExpr,
190580  int iPhrase,
190581  const u8 **ppCollist,
190582  int *pnCollist
190583){
190584  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
190585  Fts5ExprNode *pNode = pPhrase->pNode;
190586  int rc = SQLITE_OK;
190587
190588  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
190589  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
190590
190591  if( pNode->bEof==0
190592   && pNode->iRowid==pExpr->pRoot->iRowid
190593   && pPhrase->poslist.n>0
190594  ){
190595    Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
190596    if( pTerm->pSynonym ){
190597      Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
190598      rc = fts5ExprSynonymList(
190599          pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
190600      );
190601    }else{
190602      *ppCollist = pPhrase->aTerm[0].pIter->pData;
190603      *pnCollist = pPhrase->aTerm[0].pIter->nData;
190604    }
190605  }else{
190606    *ppCollist = 0;
190607    *pnCollist = 0;
190608  }
190609
190610  return rc;
190611}
190612
190613
190614/*
190615** 2014 August 11
190616**
190617** The author disclaims copyright to this source code.  In place of
190618** a legal notice, here is a blessing:
190619**
190620**    May you do good and not evil.
190621**    May you find forgiveness for yourself and forgive others.
190622**    May you share freely, never taking more than you give.
190623**
190624******************************************************************************
190625**
190626*/
190627
190628
190629
190630/* #include "fts5Int.h" */
190631
190632typedef struct Fts5HashEntry Fts5HashEntry;
190633
190634/*
190635** This file contains the implementation of an in-memory hash table used
190636** to accumuluate "term -> doclist" content before it is flused to a level-0
190637** segment.
190638*/
190639
190640
190641struct Fts5Hash {
190642  int eDetail;                    /* Copy of Fts5Config.eDetail */
190643  int *pnByte;                    /* Pointer to bytes counter */
190644  int nEntry;                     /* Number of entries currently in hash */
190645  int nSlot;                      /* Size of aSlot[] array */
190646  Fts5HashEntry *pScan;           /* Current ordered scan item */
190647  Fts5HashEntry **aSlot;          /* Array of hash slots */
190648};
190649
190650/*
190651** Each entry in the hash table is represented by an object of the
190652** following type. Each object, its key (a nul-terminated string) and
190653** its current data are stored in a single memory allocation. The
190654** key immediately follows the object in memory. The position list
190655** data immediately follows the key data in memory.
190656**
190657** The data that follows the key is in a similar, but not identical format
190658** to the doclist data stored in the database. It is:
190659**
190660**   * Rowid, as a varint
190661**   * Position list, without 0x00 terminator.
190662**   * Size of previous position list and rowid, as a 4 byte
190663**     big-endian integer.
190664**
190665** iRowidOff:
190666**   Offset of last rowid written to data area. Relative to first byte of
190667**   structure.
190668**
190669** nData:
190670**   Bytes of data written since iRowidOff.
190671*/
190672struct Fts5HashEntry {
190673  Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
190674  Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
190675
190676  int nAlloc;                     /* Total size of allocation */
190677  int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
190678  int nData;                      /* Total bytes of data (incl. structure) */
190679  int nKey;                       /* Length of key in bytes */
190680  u8 bDel;                        /* Set delete-flag @ iSzPoslist */
190681  u8 bContent;                    /* Set content-flag (detail=none mode) */
190682  i16 iCol;                       /* Column of last value written */
190683  int iPos;                       /* Position of last value written */
190684  i64 iRowid;                     /* Rowid of last value written */
190685};
190686
190687/*
190688** Eqivalent to:
190689**
190690**   char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
190691*/
190692#define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
190693
190694
190695/*
190696** Allocate a new hash table.
190697*/
190698static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
190699  int rc = SQLITE_OK;
190700  Fts5Hash *pNew;
190701
190702  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
190703  if( pNew==0 ){
190704    rc = SQLITE_NOMEM;
190705  }else{
190706    int nByte;
190707    memset(pNew, 0, sizeof(Fts5Hash));
190708    pNew->pnByte = pnByte;
190709    pNew->eDetail = pConfig->eDetail;
190710
190711    pNew->nSlot = 1024;
190712    nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
190713    pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
190714    if( pNew->aSlot==0 ){
190715      sqlite3_free(pNew);
190716      *ppNew = 0;
190717      rc = SQLITE_NOMEM;
190718    }else{
190719      memset(pNew->aSlot, 0, nByte);
190720    }
190721  }
190722  return rc;
190723}
190724
190725/*
190726** Free a hash table object.
190727*/
190728static void sqlite3Fts5HashFree(Fts5Hash *pHash){
190729  if( pHash ){
190730    sqlite3Fts5HashClear(pHash);
190731    sqlite3_free(pHash->aSlot);
190732    sqlite3_free(pHash);
190733  }
190734}
190735
190736/*
190737** Empty (but do not delete) a hash table.
190738*/
190739static void sqlite3Fts5HashClear(Fts5Hash *pHash){
190740  int i;
190741  for(i=0; i<pHash->nSlot; i++){
190742    Fts5HashEntry *pNext;
190743    Fts5HashEntry *pSlot;
190744    for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
190745      pNext = pSlot->pHashNext;
190746      sqlite3_free(pSlot);
190747    }
190748  }
190749  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
190750  pHash->nEntry = 0;
190751}
190752
190753static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
190754  int i;
190755  unsigned int h = 13;
190756  for(i=n-1; i>=0; i--){
190757    h = (h << 3) ^ h ^ p[i];
190758  }
190759  return (h % nSlot);
190760}
190761
190762static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
190763  int i;
190764  unsigned int h = 13;
190765  for(i=n-1; i>=0; i--){
190766    h = (h << 3) ^ h ^ p[i];
190767  }
190768  h = (h << 3) ^ h ^ b;
190769  return (h % nSlot);
190770}
190771
190772/*
190773** Resize the hash table by doubling the number of slots.
190774*/
190775static int fts5HashResize(Fts5Hash *pHash){
190776  int nNew = pHash->nSlot*2;
190777  int i;
190778  Fts5HashEntry **apNew;
190779  Fts5HashEntry **apOld = pHash->aSlot;
190780
190781  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
190782  if( !apNew ) return SQLITE_NOMEM;
190783  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
190784
190785  for(i=0; i<pHash->nSlot; i++){
190786    while( apOld[i] ){
190787      unsigned int iHash;
190788      Fts5HashEntry *p = apOld[i];
190789      apOld[i] = p->pHashNext;
190790      iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
190791                          (int)strlen(fts5EntryKey(p)));
190792      p->pHashNext = apNew[iHash];
190793      apNew[iHash] = p;
190794    }
190795  }
190796
190797  sqlite3_free(apOld);
190798  pHash->nSlot = nNew;
190799  pHash->aSlot = apNew;
190800  return SQLITE_OK;
190801}
190802
190803static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
190804  if( p->iSzPoslist ){
190805    u8 *pPtr = (u8*)p;
190806    if( pHash->eDetail==FTS5_DETAIL_NONE ){
190807      assert( p->nData==p->iSzPoslist );
190808      if( p->bDel ){
190809        pPtr[p->nData++] = 0x00;
190810        if( p->bContent ){
190811          pPtr[p->nData++] = 0x00;
190812        }
190813      }
190814    }else{
190815      int nSz = (p->nData - p->iSzPoslist - 1);       /* Size in bytes */
190816      int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
190817
190818      assert( p->bDel==0 || p->bDel==1 );
190819      if( nPos<=127 ){
190820        pPtr[p->iSzPoslist] = (u8)nPos;
190821      }else{
190822        int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
190823        memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
190824        sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
190825        p->nData += (nByte-1);
190826      }
190827    }
190828
190829    p->iSzPoslist = 0;
190830    p->bDel = 0;
190831    p->bContent = 0;
190832  }
190833}
190834
190835/*
190836** Add an entry to the in-memory hash table. The key is the concatenation
190837** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
190838**
190839**     (bByte || pToken) -> (iRowid,iCol,iPos)
190840**
190841** Or, if iCol is negative, then the value is a delete marker.
190842*/
190843static int sqlite3Fts5HashWrite(
190844  Fts5Hash *pHash,
190845  i64 iRowid,                     /* Rowid for this entry */
190846  int iCol,                       /* Column token appears in (-ve -> delete) */
190847  int iPos,                       /* Position of token within column */
190848  char bByte,                     /* First byte of token */
190849  const char *pToken, int nToken  /* Token to add or remove to or from index */
190850){
190851  unsigned int iHash;
190852  Fts5HashEntry *p;
190853  u8 *pPtr;
190854  int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
190855  int bNew;                       /* If non-delete entry should be written */
190856
190857  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
190858
190859  /* Attempt to locate an existing hash entry */
190860  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
190861  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
190862    char *zKey = fts5EntryKey(p);
190863    if( zKey[0]==bByte
190864     && p->nKey==nToken
190865     && memcmp(&zKey[1], pToken, nToken)==0
190866    ){
190867      break;
190868    }
190869  }
190870
190871  /* If an existing hash entry cannot be found, create a new one. */
190872  if( p==0 ){
190873    /* Figure out how much space to allocate */
190874    char *zKey;
190875    int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
190876    if( nByte<128 ) nByte = 128;
190877
190878    /* Grow the Fts5Hash.aSlot[] array if necessary. */
190879    if( (pHash->nEntry*2)>=pHash->nSlot ){
190880      int rc = fts5HashResize(pHash);
190881      if( rc!=SQLITE_OK ) return rc;
190882      iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
190883    }
190884
190885    /* Allocate new Fts5HashEntry and add it to the hash table. */
190886    p = (Fts5HashEntry*)sqlite3_malloc(nByte);
190887    if( !p ) return SQLITE_NOMEM;
190888    memset(p, 0, sizeof(Fts5HashEntry));
190889    p->nAlloc = nByte;
190890    zKey = fts5EntryKey(p);
190891    zKey[0] = bByte;
190892    memcpy(&zKey[1], pToken, nToken);
190893    assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
190894    p->nKey = nToken;
190895    zKey[nToken+1] = '\0';
190896    p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
190897    p->pHashNext = pHash->aSlot[iHash];
190898    pHash->aSlot[iHash] = p;
190899    pHash->nEntry++;
190900
190901    /* Add the first rowid field to the hash-entry */
190902    p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
190903    p->iRowid = iRowid;
190904
190905    p->iSzPoslist = p->nData;
190906    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
190907      p->nData += 1;
190908      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
190909    }
190910
190911    nIncr += p->nData;
190912  }else{
190913
190914    /* Appending to an existing hash-entry. Check that there is enough
190915    ** space to append the largest possible new entry. Worst case scenario
190916    ** is:
190917    **
190918    **     + 9 bytes for a new rowid,
190919    **     + 4 byte reserved for the "poslist size" varint.
190920    **     + 1 byte for a "new column" byte,
190921    **     + 3 bytes for a new column number (16-bit max) as a varint,
190922    **     + 5 bytes for the new position offset (32-bit max).
190923    */
190924    if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
190925      int nNew = p->nAlloc * 2;
190926      Fts5HashEntry *pNew;
190927      Fts5HashEntry **pp;
190928      pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
190929      if( pNew==0 ) return SQLITE_NOMEM;
190930      pNew->nAlloc = nNew;
190931      for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
190932      *pp = pNew;
190933      p = pNew;
190934    }
190935    nIncr -= p->nData;
190936  }
190937  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
190938
190939  pPtr = (u8*)p;
190940
190941  /* If this is a new rowid, append the 4-byte size field for the previous
190942  ** entry, and the new rowid for this entry.  */
190943  if( iRowid!=p->iRowid ){
190944    fts5HashAddPoslistSize(pHash, p);
190945    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
190946    p->iRowid = iRowid;
190947    bNew = 1;
190948    p->iSzPoslist = p->nData;
190949    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
190950      p->nData += 1;
190951      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
190952      p->iPos = 0;
190953    }
190954  }
190955
190956  if( iCol>=0 ){
190957    if( pHash->eDetail==FTS5_DETAIL_NONE ){
190958      p->bContent = 1;
190959    }else{
190960      /* Append a new column value, if necessary */
190961      assert( iCol>=p->iCol );
190962      if( iCol!=p->iCol ){
190963        if( pHash->eDetail==FTS5_DETAIL_FULL ){
190964          pPtr[p->nData++] = 0x01;
190965          p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
190966          p->iCol = (i16)iCol;
190967          p->iPos = 0;
190968        }else{
190969          bNew = 1;
190970          p->iCol = (i16)(iPos = iCol);
190971        }
190972      }
190973
190974      /* Append the new position offset, if necessary */
190975      if( bNew ){
190976        p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
190977        p->iPos = iPos;
190978      }
190979    }
190980  }else{
190981    /* This is a delete. Set the delete flag. */
190982    p->bDel = 1;
190983  }
190984
190985  nIncr += p->nData;
190986  *pHash->pnByte += nIncr;
190987  return SQLITE_OK;
190988}
190989
190990
190991/*
190992** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
190993** each sorted in key order. This function merges the two lists into a
190994** single list and returns a pointer to its first element.
190995*/
190996static Fts5HashEntry *fts5HashEntryMerge(
190997  Fts5HashEntry *pLeft,
190998  Fts5HashEntry *pRight
190999){
191000  Fts5HashEntry *p1 = pLeft;
191001  Fts5HashEntry *p2 = pRight;
191002  Fts5HashEntry *pRet = 0;
191003  Fts5HashEntry **ppOut = &pRet;
191004
191005  while( p1 || p2 ){
191006    if( p1==0 ){
191007      *ppOut = p2;
191008      p2 = 0;
191009    }else if( p2==0 ){
191010      *ppOut = p1;
191011      p1 = 0;
191012    }else{
191013      int i = 0;
191014      char *zKey1 = fts5EntryKey(p1);
191015      char *zKey2 = fts5EntryKey(p2);
191016      while( zKey1[i]==zKey2[i] ) i++;
191017
191018      if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
191019        /* p2 is smaller */
191020        *ppOut = p2;
191021        ppOut = &p2->pScanNext;
191022        p2 = p2->pScanNext;
191023      }else{
191024        /* p1 is smaller */
191025        *ppOut = p1;
191026        ppOut = &p1->pScanNext;
191027        p1 = p1->pScanNext;
191028      }
191029      *ppOut = 0;
191030    }
191031  }
191032
191033  return pRet;
191034}
191035
191036/*
191037** Extract all tokens from hash table iHash and link them into a list
191038** in sorted order. The hash table is cleared before returning. It is
191039** the responsibility of the caller to free the elements of the returned
191040** list.
191041*/
191042static int fts5HashEntrySort(
191043  Fts5Hash *pHash,
191044  const char *pTerm, int nTerm,   /* Query prefix, if any */
191045  Fts5HashEntry **ppSorted
191046){
191047  const int nMergeSlot = 32;
191048  Fts5HashEntry **ap;
191049  Fts5HashEntry *pList;
191050  int iSlot;
191051  int i;
191052
191053  *ppSorted = 0;
191054  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
191055  if( !ap ) return SQLITE_NOMEM;
191056  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
191057
191058  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
191059    Fts5HashEntry *pIter;
191060    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
191061      if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
191062        Fts5HashEntry *pEntry = pIter;
191063        pEntry->pScanNext = 0;
191064        for(i=0; ap[i]; i++){
191065          pEntry = fts5HashEntryMerge(pEntry, ap[i]);
191066          ap[i] = 0;
191067        }
191068        ap[i] = pEntry;
191069      }
191070    }
191071  }
191072
191073  pList = 0;
191074  for(i=0; i<nMergeSlot; i++){
191075    pList = fts5HashEntryMerge(pList, ap[i]);
191076  }
191077
191078  pHash->nEntry = 0;
191079  sqlite3_free(ap);
191080  *ppSorted = pList;
191081  return SQLITE_OK;
191082}
191083
191084/*
191085** Query the hash table for a doclist associated with term pTerm/nTerm.
191086*/
191087static int sqlite3Fts5HashQuery(
191088  Fts5Hash *pHash,                /* Hash table to query */
191089  const char *pTerm, int nTerm,   /* Query term */
191090  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
191091  int *pnDoclist                  /* OUT: Size of doclist in bytes */
191092){
191093  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
191094  char *zKey = 0;
191095  Fts5HashEntry *p;
191096
191097  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
191098    zKey = fts5EntryKey(p);
191099    if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
191100  }
191101
191102  if( p ){
191103    fts5HashAddPoslistSize(pHash, p);
191104    *ppDoclist = (const u8*)&zKey[nTerm+1];
191105    *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
191106  }else{
191107    *ppDoclist = 0;
191108    *pnDoclist = 0;
191109  }
191110
191111  return SQLITE_OK;
191112}
191113
191114static int sqlite3Fts5HashScanInit(
191115  Fts5Hash *p,                    /* Hash table to query */
191116  const char *pTerm, int nTerm    /* Query prefix */
191117){
191118  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
191119}
191120
191121static void sqlite3Fts5HashScanNext(Fts5Hash *p){
191122  assert( !sqlite3Fts5HashScanEof(p) );
191123  p->pScan = p->pScan->pScanNext;
191124}
191125
191126static int sqlite3Fts5HashScanEof(Fts5Hash *p){
191127  return (p->pScan==0);
191128}
191129
191130static void sqlite3Fts5HashScanEntry(
191131  Fts5Hash *pHash,
191132  const char **pzTerm,            /* OUT: term (nul-terminated) */
191133  const u8 **ppDoclist,           /* OUT: pointer to doclist */
191134  int *pnDoclist                  /* OUT: size of doclist in bytes */
191135){
191136  Fts5HashEntry *p;
191137  if( (p = pHash->pScan) ){
191138    char *zKey = fts5EntryKey(p);
191139    int nTerm = (int)strlen(zKey);
191140    fts5HashAddPoslistSize(pHash, p);
191141    *pzTerm = zKey;
191142    *ppDoclist = (const u8*)&zKey[nTerm+1];
191143    *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
191144  }else{
191145    *pzTerm = 0;
191146    *ppDoclist = 0;
191147    *pnDoclist = 0;
191148  }
191149}
191150
191151
191152/*
191153** 2014 May 31
191154**
191155** The author disclaims copyright to this source code.  In place of
191156** a legal notice, here is a blessing:
191157**
191158**    May you do good and not evil.
191159**    May you find forgiveness for yourself and forgive others.
191160**    May you share freely, never taking more than you give.
191161**
191162******************************************************************************
191163**
191164** Low level access to the FTS index stored in the database file. The
191165** routines in this file file implement all read and write access to the
191166** %_data table. Other parts of the system access this functionality via
191167** the interface defined in fts5Int.h.
191168*/
191169
191170
191171/* #include "fts5Int.h" */
191172
191173/*
191174** Overview:
191175**
191176** The %_data table contains all the FTS indexes for an FTS5 virtual table.
191177** As well as the main term index, there may be up to 31 prefix indexes.
191178** The format is similar to FTS3/4, except that:
191179**
191180**   * all segment b-tree leaf data is stored in fixed size page records
191181**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
191182**     taken to ensure it is possible to iterate in either direction through
191183**     the entries in a doclist, or to seek to a specific entry within a
191184**     doclist, without loading it into memory.
191185**
191186**   * large doclists that span many pages have associated "doclist index"
191187**     records that contain a copy of the first rowid on each page spanned by
191188**     the doclist. This is used to speed up seek operations, and merges of
191189**     large doclists with very small doclists.
191190**
191191**   * extra fields in the "structure record" record the state of ongoing
191192**     incremental merge operations.
191193**
191194*/
191195
191196
191197#define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
191198#define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
191199
191200#define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
191201
191202#define FTS5_MAIN_PREFIX '0'
191203
191204#if FTS5_MAX_PREFIX_INDEXES > 31
191205# error "FTS5_MAX_PREFIX_INDEXES is too large"
191206#endif
191207
191208/*
191209** Details:
191210**
191211** The %_data table managed by this module,
191212**
191213**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
191214**
191215** , contains the following 5 types of records. See the comments surrounding
191216** the FTS5_*_ROWID macros below for a description of how %_data rowids are
191217** assigned to each fo them.
191218**
191219** 1. Structure Records:
191220**
191221**   The set of segments that make up an index - the index structure - are
191222**   recorded in a single record within the %_data table. The record consists
191223**   of a single 32-bit configuration cookie value followed by a list of
191224**   SQLite varints. If the FTS table features more than one index (because
191225**   there are one or more prefix indexes), it is guaranteed that all share
191226**   the same cookie value.
191227**
191228**   Immediately following the configuration cookie, the record begins with
191229**   three varints:
191230**
191231**     + number of levels,
191232**     + total number of segments on all levels,
191233**     + value of write counter.
191234**
191235**   Then, for each level from 0 to nMax:
191236**
191237**     + number of input segments in ongoing merge.
191238**     + total number of segments in level.
191239**     + for each segment from oldest to newest:
191240**         + segment id (always > 0)
191241**         + first leaf page number (often 1, always greater than 0)
191242**         + final leaf page number
191243**
191244** 2. The Averages Record:
191245**
191246**   A single record within the %_data table. The data is a list of varints.
191247**   The first value is the number of rows in the index. Then, for each column
191248**   from left to right, the total number of tokens in the column for all
191249**   rows of the table.
191250**
191251** 3. Segment leaves:
191252**
191253**   TERM/DOCLIST FORMAT:
191254**
191255**     Most of each segment leaf is taken up by term/doclist data. The
191256**     general format of term/doclist, starting with the first term
191257**     on the leaf page, is:
191258**
191259**         varint : size of first term
191260**         blob:    first term data
191261**         doclist: first doclist
191262**         zero-or-more {
191263**           varint:  number of bytes in common with previous term
191264**           varint:  number of bytes of new term data (nNew)
191265**           blob:    nNew bytes of new term data
191266**           doclist: next doclist
191267**         }
191268**
191269**     doclist format:
191270**
191271**         varint:  first rowid
191272**         poslist: first poslist
191273**         zero-or-more {
191274**           varint:  rowid delta (always > 0)
191275**           poslist: next poslist
191276**         }
191277**
191278**     poslist format:
191279**
191280**         varint: size of poslist in bytes multiplied by 2, not including
191281**                 this field. Plus 1 if this entry carries the "delete" flag.
191282**         collist: collist for column 0
191283**         zero-or-more {
191284**           0x01 byte
191285**           varint: column number (I)
191286**           collist: collist for column I
191287**         }
191288**
191289**     collist format:
191290**
191291**         varint: first offset + 2
191292**         zero-or-more {
191293**           varint: offset delta + 2
191294**         }
191295**
191296**   PAGE FORMAT
191297**
191298**     Each leaf page begins with a 4-byte header containing 2 16-bit
191299**     unsigned integer fields in big-endian format. They are:
191300**
191301**       * The byte offset of the first rowid on the page, if it exists
191302**         and occurs before the first term (otherwise 0).
191303**
191304**       * The byte offset of the start of the page footer. If the page
191305**         footer is 0 bytes in size, then this field is the same as the
191306**         size of the leaf page in bytes.
191307**
191308**     The page footer consists of a single varint for each term located
191309**     on the page. Each varint is the byte offset of the current term
191310**     within the page, delta-compressed against the previous value. In
191311**     other words, the first varint in the footer is the byte offset of
191312**     the first term, the second is the byte offset of the second less that
191313**     of the first, and so on.
191314**
191315**     The term/doclist format described above is accurate if the entire
191316**     term/doclist data fits on a single leaf page. If this is not the case,
191317**     the format is changed in two ways:
191318**
191319**       + if the first rowid on a page occurs before the first term, it
191320**         is stored as a literal value:
191321**
191322**             varint:  first rowid
191323**
191324**       + the first term on each page is stored in the same way as the
191325**         very first term of the segment:
191326**
191327**             varint : size of first term
191328**             blob:    first term data
191329**
191330** 5. Segment doclist indexes:
191331**
191332**   Doclist indexes are themselves b-trees, however they usually consist of
191333**   a single leaf record only. The format of each doclist index leaf page
191334**   is:
191335**
191336**     * Flags byte. Bits are:
191337**         0x01: Clear if leaf is also the root page, otherwise set.
191338**
191339**     * Page number of fts index leaf page. As a varint.
191340**
191341**     * First rowid on page indicated by previous field. As a varint.
191342**
191343**     * A list of varints, one for each subsequent termless page. A
191344**       positive delta if the termless page contains at least one rowid,
191345**       or an 0x00 byte otherwise.
191346**
191347**   Internal doclist index nodes are:
191348**
191349**     * Flags byte. Bits are:
191350**         0x01: Clear for root page, otherwise set.
191351**
191352**     * Page number of first child page. As a varint.
191353**
191354**     * Copy of first rowid on page indicated by previous field. As a varint.
191355**
191356**     * A list of delta-encoded varints - the first rowid on each subsequent
191357**       child page.
191358**
191359*/
191360
191361/*
191362** Rowids for the averages and structure records in the %_data table.
191363*/
191364#define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
191365#define FTS5_STRUCTURE_ROWID   10    /* The structure record */
191366
191367/*
191368** Macros determining the rowids used by segment leaves and dlidx leaves
191369** and nodes. All nodes and leaves are stored in the %_data table with large
191370** positive rowids.
191371**
191372** Each segment has a unique non-zero 16-bit id.
191373**
191374** The rowid for each segment leaf is found by passing the segment id and
191375** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
191376** sequentially starting from 1.
191377*/
191378#define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
191379#define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
191380#define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
191381#define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
191382
191383#define fts5_dri(segid, dlidx, height, pgno) (                                 \
191384 ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
191385 ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
191386 ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
191387 ((i64)(pgno))                                                                 \
191388)
191389
191390#define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
191391#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
191392
191393/*
191394** Maximum segments permitted in a single index
191395*/
191396#define FTS5_MAX_SEGMENT 2000
191397
191398#ifdef SQLITE_DEBUG
191399static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
191400#endif
191401
191402
191403/*
191404** Each time a blob is read from the %_data table, it is padded with this
191405** many zero bytes. This makes it easier to decode the various record formats
191406** without overreading if the records are corrupt.
191407*/
191408#define FTS5_DATA_ZERO_PADDING 8
191409#define FTS5_DATA_PADDING 20
191410
191411typedef struct Fts5Data Fts5Data;
191412typedef struct Fts5DlidxIter Fts5DlidxIter;
191413typedef struct Fts5DlidxLvl Fts5DlidxLvl;
191414typedef struct Fts5DlidxWriter Fts5DlidxWriter;
191415typedef struct Fts5Iter Fts5Iter;
191416typedef struct Fts5PageWriter Fts5PageWriter;
191417typedef struct Fts5SegIter Fts5SegIter;
191418typedef struct Fts5DoclistIter Fts5DoclistIter;
191419typedef struct Fts5SegWriter Fts5SegWriter;
191420typedef struct Fts5Structure Fts5Structure;
191421typedef struct Fts5StructureLevel Fts5StructureLevel;
191422typedef struct Fts5StructureSegment Fts5StructureSegment;
191423
191424struct Fts5Data {
191425  u8 *p;                          /* Pointer to buffer containing record */
191426  int nn;                         /* Size of record in bytes */
191427  int szLeaf;                     /* Size of leaf without page-index */
191428};
191429
191430/*
191431** One object per %_data table.
191432*/
191433struct Fts5Index {
191434  Fts5Config *pConfig;            /* Virtual table configuration */
191435  char *zDataTbl;                 /* Name of %_data table */
191436  int nWorkUnit;                  /* Leaf pages in a "unit" of work */
191437
191438  /*
191439  ** Variables related to the accumulation of tokens and doclists within the
191440  ** in-memory hash tables before they are flushed to disk.
191441  */
191442  Fts5Hash *pHash;                /* Hash table for in-memory data */
191443  int nPendingData;               /* Current bytes of pending data */
191444  i64 iWriteRowid;                /* Rowid for current doc being written */
191445  int bDelete;                    /* Current write is a delete */
191446
191447  /* Error state. */
191448  int rc;                         /* Current error code */
191449
191450  /* State used by the fts5DataXXX() functions. */
191451  sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
191452  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
191453  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
191454  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
191455  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
191456  sqlite3_stmt *pIdxSelect;
191457  int nRead;                      /* Total number of blocks read */
191458
191459  sqlite3_stmt *pDataVersion;
191460  i64 iStructVersion;             /* data_version when pStruct read */
191461  Fts5Structure *pStruct;         /* Current db structure (or NULL) */
191462};
191463
191464struct Fts5DoclistIter {
191465  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
191466
191467  /* Output variables. aPoslist==0 at EOF */
191468  i64 iRowid;
191469  u8 *aPoslist;
191470  int nPoslist;
191471  int nSize;
191472};
191473
191474/*
191475** The contents of the "structure" record for each index are represented
191476** using an Fts5Structure record in memory. Which uses instances of the
191477** other Fts5StructureXXX types as components.
191478*/
191479struct Fts5StructureSegment {
191480  int iSegid;                     /* Segment id */
191481  int pgnoFirst;                  /* First leaf page number in segment */
191482  int pgnoLast;                   /* Last leaf page number in segment */
191483};
191484struct Fts5StructureLevel {
191485  int nMerge;                     /* Number of segments in incr-merge */
191486  int nSeg;                       /* Total number of segments on level */
191487  Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
191488};
191489struct Fts5Structure {
191490  int nRef;                       /* Object reference count */
191491  u64 nWriteCounter;              /* Total leaves written to level 0 */
191492  int nSegment;                   /* Total segments in this structure */
191493  int nLevel;                     /* Number of levels in this index */
191494  Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
191495};
191496
191497/*
191498** An object of type Fts5SegWriter is used to write to segments.
191499*/
191500struct Fts5PageWriter {
191501  int pgno;                       /* Page number for this page */
191502  int iPrevPgidx;                 /* Previous value written into pgidx */
191503  Fts5Buffer buf;                 /* Buffer containing leaf data */
191504  Fts5Buffer pgidx;               /* Buffer containing page-index */
191505  Fts5Buffer term;                /* Buffer containing previous term on page */
191506};
191507struct Fts5DlidxWriter {
191508  int pgno;                       /* Page number for this page */
191509  int bPrevValid;                 /* True if iPrev is valid */
191510  i64 iPrev;                      /* Previous rowid value written to page */
191511  Fts5Buffer buf;                 /* Buffer containing page data */
191512};
191513struct Fts5SegWriter {
191514  int iSegid;                     /* Segid to write to */
191515  Fts5PageWriter writer;          /* PageWriter object */
191516  i64 iPrevRowid;                 /* Previous rowid written to current leaf */
191517  u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
191518  u8 bFirstRowidInPage;           /* True if next rowid is first in page */
191519  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
191520  u8 bFirstTermInPage;            /* True if next term will be first in leaf */
191521  int nLeafWritten;               /* Number of leaf pages written */
191522  int nEmpty;                     /* Number of contiguous term-less nodes */
191523
191524  int nDlidx;                     /* Allocated size of aDlidx[] array */
191525  Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
191526
191527  /* Values to insert into the %_idx table */
191528  Fts5Buffer btterm;              /* Next term to insert into %_idx table */
191529  int iBtPage;                    /* Page number corresponding to btterm */
191530};
191531
191532typedef struct Fts5CResult Fts5CResult;
191533struct Fts5CResult {
191534  u16 iFirst;                     /* aSeg[] index of firstest iterator */
191535  u8 bTermEq;                     /* True if the terms are equal */
191536};
191537
191538/*
191539** Object for iterating through a single segment, visiting each term/rowid
191540** pair in the segment.
191541**
191542** pSeg:
191543**   The segment to iterate through.
191544**
191545** iLeafPgno:
191546**   Current leaf page number within segment.
191547**
191548** iLeafOffset:
191549**   Byte offset within the current leaf that is the first byte of the
191550**   position list data (one byte passed the position-list size field).
191551**   rowid field of the current entry. Usually this is the size field of the
191552**   position list data. The exception is if the rowid for the current entry
191553**   is the last thing on the leaf page.
191554**
191555** pLeaf:
191556**   Buffer containing current leaf page data. Set to NULL at EOF.
191557**
191558** iTermLeafPgno, iTermLeafOffset:
191559**   Leaf page number containing the last term read from the segment. And
191560**   the offset immediately following the term data.
191561**
191562** flags:
191563**   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
191564**
191565**   FTS5_SEGITER_ONETERM:
191566**     If set, set the iterator to point to EOF after the current doclist
191567**     has been exhausted. Do not proceed to the next term in the segment.
191568**
191569**   FTS5_SEGITER_REVERSE:
191570**     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
191571**     it is set, iterate through rowid in descending order instead of the
191572**     default ascending order.
191573**
191574** iRowidOffset/nRowidOffset/aRowidOffset:
191575**     These are used if the FTS5_SEGITER_REVERSE flag is set.
191576**
191577**     For each rowid on the page corresponding to the current term, the
191578**     corresponding aRowidOffset[] entry is set to the byte offset of the
191579**     start of the "position-list-size" field within the page.
191580**
191581** iTermIdx:
191582**     Index of current term on iTermLeafPgno.
191583*/
191584struct Fts5SegIter {
191585  Fts5StructureSegment *pSeg;     /* Segment to iterate through */
191586  int flags;                      /* Mask of configuration flags */
191587  int iLeafPgno;                  /* Current leaf page number */
191588  Fts5Data *pLeaf;                /* Current leaf data */
191589  Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
191590  int iLeafOffset;                /* Byte offset within current leaf */
191591
191592  /* Next method */
191593  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
191594
191595  /* The page and offset from which the current term was read. The offset
191596  ** is the offset of the first rowid in the current doclist.  */
191597  int iTermLeafPgno;
191598  int iTermLeafOffset;
191599
191600  int iPgidxOff;                  /* Next offset in pgidx */
191601  int iEndofDoclist;
191602
191603  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
191604  int iRowidOffset;               /* Current entry in aRowidOffset[] */
191605  int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
191606  int *aRowidOffset;              /* Array of offset to rowid fields */
191607
191608  Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
191609
191610  /* Variables populated based on current entry. */
191611  Fts5Buffer term;                /* Current term */
191612  i64 iRowid;                     /* Current rowid */
191613  int nPos;                       /* Number of bytes in current position list */
191614  u8 bDel;                        /* True if the delete flag is set */
191615};
191616
191617/*
191618** Argument is a pointer to an Fts5Data structure that contains a
191619** leaf page.
191620*/
191621#define ASSERT_SZLEAF_OK(x) assert( \
191622    (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
191623)
191624
191625#define FTS5_SEGITER_ONETERM 0x01
191626#define FTS5_SEGITER_REVERSE 0x02
191627
191628/*
191629** Argument is a pointer to an Fts5Data structure that contains a leaf
191630** page. This macro evaluates to true if the leaf contains no terms, or
191631** false if it contains at least one term.
191632*/
191633#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
191634
191635#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
191636
191637#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
191638
191639/*
191640** Object for iterating through the merged results of one or more segments,
191641** visiting each term/rowid pair in the merged data.
191642**
191643** nSeg is always a power of two greater than or equal to the number of
191644** segments that this object is merging data from. Both the aSeg[] and
191645** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
191646** with zeroed objects - these are handled as if they were iterators opened
191647** on empty segments.
191648**
191649** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
191650** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
191651** comparison in this context is the index of the iterator that currently
191652** points to the smaller term/rowid combination. Iterators at EOF are
191653** considered to be greater than all other iterators.
191654**
191655** aFirst[1] contains the index in aSeg[] of the iterator that points to
191656** the smallest key overall. aFirst[0] is unused.
191657**
191658** poslist:
191659**   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
191660**   There is no way to tell if this is populated or not.
191661*/
191662struct Fts5Iter {
191663  Fts5IndexIter base;             /* Base class containing output vars */
191664
191665  Fts5Index *pIndex;              /* Index that owns this iterator */
191666  Fts5Structure *pStruct;         /* Database structure for this iterator */
191667  Fts5Buffer poslist;             /* Buffer containing current poslist */
191668  Fts5Colset *pColset;            /* Restrict matches to these columns */
191669
191670  /* Invoked to set output variables. */
191671  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
191672
191673  int nSeg;                       /* Size of aSeg[] array */
191674  int bRev;                       /* True to iterate in reverse order */
191675  u8 bSkipEmpty;                  /* True to skip deleted entries */
191676
191677  i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
191678  Fts5CResult *aFirst;            /* Current merge state (see above) */
191679  Fts5SegIter aSeg[1];            /* Array of segment iterators */
191680};
191681
191682
191683/*
191684** An instance of the following type is used to iterate through the contents
191685** of a doclist-index record.
191686**
191687** pData:
191688**   Record containing the doclist-index data.
191689**
191690** bEof:
191691**   Set to true once iterator has reached EOF.
191692**
191693** iOff:
191694**   Set to the current offset within record pData.
191695*/
191696struct Fts5DlidxLvl {
191697  Fts5Data *pData;              /* Data for current page of this level */
191698  int iOff;                     /* Current offset into pData */
191699  int bEof;                     /* At EOF already */
191700  int iFirstOff;                /* Used by reverse iterators */
191701
191702  /* Output variables */
191703  int iLeafPgno;                /* Page number of current leaf page */
191704  i64 iRowid;                   /* First rowid on leaf iLeafPgno */
191705};
191706struct Fts5DlidxIter {
191707  int nLvl;
191708  int iSegid;
191709  Fts5DlidxLvl aLvl[1];
191710};
191711
191712static void fts5PutU16(u8 *aOut, u16 iVal){
191713  aOut[0] = (iVal>>8);
191714  aOut[1] = (iVal&0xFF);
191715}
191716
191717static u16 fts5GetU16(const u8 *aIn){
191718  return ((u16)aIn[0] << 8) + aIn[1];
191719}
191720
191721/*
191722** Allocate and return a buffer at least nByte bytes in size.
191723**
191724** If an OOM error is encountered, return NULL and set the error code in
191725** the Fts5Index handle passed as the first argument.
191726*/
191727static void *fts5IdxMalloc(Fts5Index *p, int nByte){
191728  return sqlite3Fts5MallocZero(&p->rc, nByte);
191729}
191730
191731/*
191732** Compare the contents of the pLeft buffer with the pRight/nRight blob.
191733**
191734** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
191735** +ve if pRight is smaller than pLeft. In other words:
191736**
191737**     res = *pLeft - *pRight
191738*/
191739#ifdef SQLITE_DEBUG
191740static int fts5BufferCompareBlob(
191741  Fts5Buffer *pLeft,              /* Left hand side of comparison */
191742  const u8 *pRight, int nRight    /* Right hand side of comparison */
191743){
191744  int nCmp = MIN(pLeft->n, nRight);
191745  int res = memcmp(pLeft->p, pRight, nCmp);
191746  return (res==0 ? (pLeft->n - nRight) : res);
191747}
191748#endif
191749
191750/*
191751** Compare the contents of the two buffers using memcmp(). If one buffer
191752** is a prefix of the other, it is considered the lesser.
191753**
191754** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
191755** +ve if pRight is smaller than pLeft. In other words:
191756**
191757**     res = *pLeft - *pRight
191758*/
191759static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
191760  int nCmp = MIN(pLeft->n, pRight->n);
191761  int res = memcmp(pLeft->p, pRight->p, nCmp);
191762  return (res==0 ? (pLeft->n - pRight->n) : res);
191763}
191764
191765static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
191766  int ret;
191767  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
191768  return ret;
191769}
191770
191771/*
191772** Close the read-only blob handle, if it is open.
191773*/
191774static void fts5CloseReader(Fts5Index *p){
191775  if( p->pReader ){
191776    sqlite3_blob *pReader = p->pReader;
191777    p->pReader = 0;
191778    sqlite3_blob_close(pReader);
191779  }
191780}
191781
191782/*
191783** Retrieve a record from the %_data table.
191784**
191785** If an error occurs, NULL is returned and an error left in the
191786** Fts5Index object.
191787*/
191788static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
191789  Fts5Data *pRet = 0;
191790  if( p->rc==SQLITE_OK ){
191791    int rc = SQLITE_OK;
191792
191793    if( p->pReader ){
191794      /* This call may return SQLITE_ABORT if there has been a savepoint
191795      ** rollback since it was last used. In this case a new blob handle
191796      ** is required.  */
191797      sqlite3_blob *pBlob = p->pReader;
191798      p->pReader = 0;
191799      rc = sqlite3_blob_reopen(pBlob, iRowid);
191800      assert( p->pReader==0 );
191801      p->pReader = pBlob;
191802      if( rc!=SQLITE_OK ){
191803        fts5CloseReader(p);
191804      }
191805      if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
191806    }
191807
191808    /* If the blob handle is not open at this point, open it and seek
191809    ** to the requested entry.  */
191810    if( p->pReader==0 && rc==SQLITE_OK ){
191811      Fts5Config *pConfig = p->pConfig;
191812      rc = sqlite3_blob_open(pConfig->db,
191813          pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
191814      );
191815    }
191816
191817    /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
191818    ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
191819    ** All the reasons those functions might return SQLITE_ERROR - missing
191820    ** table, missing row, non-blob/text in block column - indicate
191821    ** backing store corruption.  */
191822    if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
191823
191824    if( rc==SQLITE_OK ){
191825      u8 *aOut = 0;               /* Read blob data into this buffer */
191826      int nByte = sqlite3_blob_bytes(p->pReader);
191827      int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
191828      pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
191829      if( pRet ){
191830        pRet->nn = nByte;
191831        aOut = pRet->p = (u8*)&pRet[1];
191832      }else{
191833        rc = SQLITE_NOMEM;
191834      }
191835
191836      if( rc==SQLITE_OK ){
191837        rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
191838      }
191839      if( rc!=SQLITE_OK ){
191840        sqlite3_free(pRet);
191841        pRet = 0;
191842      }else{
191843        /* TODO1: Fix this */
191844        pRet->szLeaf = fts5GetU16(&pRet->p[2]);
191845      }
191846    }
191847    p->rc = rc;
191848    p->nRead++;
191849  }
191850
191851  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
191852  return pRet;
191853}
191854
191855/*
191856** Release a reference to data record returned by an earlier call to
191857** fts5DataRead().
191858*/
191859static void fts5DataRelease(Fts5Data *pData){
191860  sqlite3_free(pData);
191861}
191862
191863static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
191864  Fts5Data *pRet = fts5DataRead(p, iRowid);
191865  if( pRet ){
191866    if( pRet->szLeaf>pRet->nn ){
191867      p->rc = FTS5_CORRUPT;
191868      fts5DataRelease(pRet);
191869      pRet = 0;
191870    }
191871  }
191872  return pRet;
191873}
191874
191875static int fts5IndexPrepareStmt(
191876  Fts5Index *p,
191877  sqlite3_stmt **ppStmt,
191878  char *zSql
191879){
191880  if( p->rc==SQLITE_OK ){
191881    if( zSql ){
191882      p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
191883                                 SQLITE_PREPARE_PERSISTENT, ppStmt, 0);
191884    }else{
191885      p->rc = SQLITE_NOMEM;
191886    }
191887  }
191888  sqlite3_free(zSql);
191889  return p->rc;
191890}
191891
191892
191893/*
191894** INSERT OR REPLACE a record into the %_data table.
191895*/
191896static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
191897  if( p->rc!=SQLITE_OK ) return;
191898
191899  if( p->pWriter==0 ){
191900    Fts5Config *pConfig = p->pConfig;
191901    fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
191902          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
191903          pConfig->zDb, pConfig->zName
191904    ));
191905    if( p->rc ) return;
191906  }
191907
191908  sqlite3_bind_int64(p->pWriter, 1, iRowid);
191909  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
191910  sqlite3_step(p->pWriter);
191911  p->rc = sqlite3_reset(p->pWriter);
191912}
191913
191914/*
191915** Execute the following SQL:
191916**
191917**     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
191918*/
191919static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
191920  if( p->rc!=SQLITE_OK ) return;
191921
191922  if( p->pDeleter==0 ){
191923    int rc;
191924    Fts5Config *pConfig = p->pConfig;
191925    char *zSql = sqlite3_mprintf(
191926        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
191927          pConfig->zDb, pConfig->zName
191928    );
191929    if( zSql==0 ){
191930      rc = SQLITE_NOMEM;
191931    }else{
191932      rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
191933                              SQLITE_PREPARE_PERSISTENT, &p->pDeleter, 0);
191934      sqlite3_free(zSql);
191935    }
191936    if( rc!=SQLITE_OK ){
191937      p->rc = rc;
191938      return;
191939    }
191940  }
191941
191942  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
191943  sqlite3_bind_int64(p->pDeleter, 2, iLast);
191944  sqlite3_step(p->pDeleter);
191945  p->rc = sqlite3_reset(p->pDeleter);
191946}
191947
191948/*
191949** Remove all records associated with segment iSegid.
191950*/
191951static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
191952  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
191953  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
191954  fts5DataDelete(p, iFirst, iLast);
191955  if( p->pIdxDeleter==0 ){
191956    Fts5Config *pConfig = p->pConfig;
191957    fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
191958          "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
191959          pConfig->zDb, pConfig->zName
191960    ));
191961  }
191962  if( p->rc==SQLITE_OK ){
191963    sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
191964    sqlite3_step(p->pIdxDeleter);
191965    p->rc = sqlite3_reset(p->pIdxDeleter);
191966  }
191967}
191968
191969/*
191970** Release a reference to an Fts5Structure object returned by an earlier
191971** call to fts5StructureRead() or fts5StructureDecode().
191972*/
191973static void fts5StructureRelease(Fts5Structure *pStruct){
191974  if( pStruct && 0>=(--pStruct->nRef) ){
191975    int i;
191976    assert( pStruct->nRef==0 );
191977    for(i=0; i<pStruct->nLevel; i++){
191978      sqlite3_free(pStruct->aLevel[i].aSeg);
191979    }
191980    sqlite3_free(pStruct);
191981  }
191982}
191983
191984static void fts5StructureRef(Fts5Structure *pStruct){
191985  pStruct->nRef++;
191986}
191987
191988/*
191989** Deserialize and return the structure record currently stored in serialized
191990** form within buffer pData/nData.
191991**
191992** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
191993** are over-allocated by one slot. This allows the structure contents
191994** to be more easily edited.
191995**
191996** If an error occurs, *ppOut is set to NULL and an SQLite error code
191997** returned. Otherwise, *ppOut is set to point to the new object and
191998** SQLITE_OK returned.
191999*/
192000static int fts5StructureDecode(
192001  const u8 *pData,                /* Buffer containing serialized structure */
192002  int nData,                      /* Size of buffer pData in bytes */
192003  int *piCookie,                  /* Configuration cookie value */
192004  Fts5Structure **ppOut           /* OUT: Deserialized object */
192005){
192006  int rc = SQLITE_OK;
192007  int i = 0;
192008  int iLvl;
192009  int nLevel = 0;
192010  int nSegment = 0;
192011  int nByte;                      /* Bytes of space to allocate at pRet */
192012  Fts5Structure *pRet = 0;        /* Structure object to return */
192013
192014  /* Grab the cookie value */
192015  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
192016  i = 4;
192017
192018  /* Read the total number of levels and segments from the start of the
192019  ** structure record.  */
192020  i += fts5GetVarint32(&pData[i], nLevel);
192021  i += fts5GetVarint32(&pData[i], nSegment);
192022  nByte = (
192023      sizeof(Fts5Structure) +                    /* Main structure */
192024      sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
192025  );
192026  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
192027
192028  if( pRet ){
192029    pRet->nRef = 1;
192030    pRet->nLevel = nLevel;
192031    pRet->nSegment = nSegment;
192032    i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
192033
192034    for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
192035      Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
192036      int nTotal = 0;
192037      int iSeg;
192038
192039      if( i>=nData ){
192040        rc = FTS5_CORRUPT;
192041      }else{
192042        i += fts5GetVarint32(&pData[i], pLvl->nMerge);
192043        i += fts5GetVarint32(&pData[i], nTotal);
192044        assert( nTotal>=pLvl->nMerge );
192045        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
192046            nTotal * sizeof(Fts5StructureSegment)
192047        );
192048      }
192049
192050      if( rc==SQLITE_OK ){
192051        pLvl->nSeg = nTotal;
192052        for(iSeg=0; iSeg<nTotal; iSeg++){
192053          if( i>=nData ){
192054            rc = FTS5_CORRUPT;
192055            break;
192056          }
192057          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
192058          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
192059          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
192060        }
192061      }
192062    }
192063    if( rc!=SQLITE_OK ){
192064      fts5StructureRelease(pRet);
192065      pRet = 0;
192066    }
192067  }
192068
192069  *ppOut = pRet;
192070  return rc;
192071}
192072
192073/*
192074**
192075*/
192076static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
192077  if( *pRc==SQLITE_OK ){
192078    Fts5Structure *pStruct = *ppStruct;
192079    int nLevel = pStruct->nLevel;
192080    int nByte = (
192081        sizeof(Fts5Structure) +                  /* Main structure */
192082        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
192083    );
192084
192085    pStruct = sqlite3_realloc(pStruct, nByte);
192086    if( pStruct ){
192087      memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
192088      pStruct->nLevel++;
192089      *ppStruct = pStruct;
192090    }else{
192091      *pRc = SQLITE_NOMEM;
192092    }
192093  }
192094}
192095
192096/*
192097** Extend level iLvl so that there is room for at least nExtra more
192098** segments.
192099*/
192100static void fts5StructureExtendLevel(
192101  int *pRc,
192102  Fts5Structure *pStruct,
192103  int iLvl,
192104  int nExtra,
192105  int bInsert
192106){
192107  if( *pRc==SQLITE_OK ){
192108    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
192109    Fts5StructureSegment *aNew;
192110    int nByte;
192111
192112    nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
192113    aNew = sqlite3_realloc(pLvl->aSeg, nByte);
192114    if( aNew ){
192115      if( bInsert==0 ){
192116        memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
192117      }else{
192118        int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
192119        memmove(&aNew[nExtra], aNew, nMove);
192120        memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
192121      }
192122      pLvl->aSeg = aNew;
192123    }else{
192124      *pRc = SQLITE_NOMEM;
192125    }
192126  }
192127}
192128
192129static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
192130  Fts5Structure *pRet = 0;
192131  Fts5Config *pConfig = p->pConfig;
192132  int iCookie;                    /* Configuration cookie */
192133  Fts5Data *pData;
192134
192135  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
192136  if( p->rc==SQLITE_OK ){
192137    /* TODO: Do we need this if the leaf-index is appended? Probably... */
192138    memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
192139    p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
192140    if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
192141      p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
192142    }
192143    fts5DataRelease(pData);
192144    if( p->rc!=SQLITE_OK ){
192145      fts5StructureRelease(pRet);
192146      pRet = 0;
192147    }
192148  }
192149
192150  return pRet;
192151}
192152
192153static i64 fts5IndexDataVersion(Fts5Index *p){
192154  i64 iVersion = 0;
192155
192156  if( p->rc==SQLITE_OK ){
192157    if( p->pDataVersion==0 ){
192158      p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
192159          sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
192160          );
192161      if( p->rc ) return 0;
192162    }
192163
192164    if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
192165      iVersion = sqlite3_column_int64(p->pDataVersion, 0);
192166    }
192167    p->rc = sqlite3_reset(p->pDataVersion);
192168  }
192169
192170  return iVersion;
192171}
192172
192173/*
192174** Read, deserialize and return the structure record.
192175**
192176** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
192177** are over-allocated as described for function fts5StructureDecode()
192178** above.
192179**
192180** If an error occurs, NULL is returned and an error code left in the
192181** Fts5Index handle. If an error has already occurred when this function
192182** is called, it is a no-op.
192183*/
192184static Fts5Structure *fts5StructureRead(Fts5Index *p){
192185
192186  if( p->pStruct==0 ){
192187    p->iStructVersion = fts5IndexDataVersion(p);
192188    if( p->rc==SQLITE_OK ){
192189      p->pStruct = fts5StructureReadUncached(p);
192190    }
192191  }
192192
192193#if 0
192194  else{
192195    Fts5Structure *pTest = fts5StructureReadUncached(p);
192196    if( pTest ){
192197      int i, j;
192198      assert_nc( p->pStruct->nSegment==pTest->nSegment );
192199      assert_nc( p->pStruct->nLevel==pTest->nLevel );
192200      for(i=0; i<pTest->nLevel; i++){
192201        assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
192202        assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
192203        for(j=0; j<pTest->aLevel[i].nSeg; j++){
192204          Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
192205          Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
192206          assert_nc( p1->iSegid==p2->iSegid );
192207          assert_nc( p1->pgnoFirst==p2->pgnoFirst );
192208          assert_nc( p1->pgnoLast==p2->pgnoLast );
192209        }
192210      }
192211      fts5StructureRelease(pTest);
192212    }
192213  }
192214#endif
192215
192216  if( p->rc!=SQLITE_OK ) return 0;
192217  assert( p->iStructVersion!=0 );
192218  assert( p->pStruct!=0 );
192219  fts5StructureRef(p->pStruct);
192220  return p->pStruct;
192221}
192222
192223static void fts5StructureInvalidate(Fts5Index *p){
192224  if( p->pStruct ){
192225    fts5StructureRelease(p->pStruct);
192226    p->pStruct = 0;
192227  }
192228}
192229
192230/*
192231** Return the total number of segments in index structure pStruct. This
192232** function is only ever used as part of assert() conditions.
192233*/
192234#ifdef SQLITE_DEBUG
192235static int fts5StructureCountSegments(Fts5Structure *pStruct){
192236  int nSegment = 0;               /* Total number of segments */
192237  if( pStruct ){
192238    int iLvl;                     /* Used to iterate through levels */
192239    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
192240      nSegment += pStruct->aLevel[iLvl].nSeg;
192241    }
192242  }
192243
192244  return nSegment;
192245}
192246#endif
192247
192248#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
192249  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
192250  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
192251  (pBuf)->n += nBlob;                                      \
192252}
192253
192254#define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
192255  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
192256  assert( (pBuf)->nSpace>=(pBuf)->n );                          \
192257}
192258
192259
192260/*
192261** Serialize and store the "structure" record.
192262**
192263** If an error occurs, leave an error code in the Fts5Index object. If an
192264** error has already occurred, this function is a no-op.
192265*/
192266static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
192267  if( p->rc==SQLITE_OK ){
192268    Fts5Buffer buf;               /* Buffer to serialize record into */
192269    int iLvl;                     /* Used to iterate through levels */
192270    int iCookie;                  /* Cookie value to store */
192271
192272    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
192273    memset(&buf, 0, sizeof(Fts5Buffer));
192274
192275    /* Append the current configuration cookie */
192276    iCookie = p->pConfig->iCookie;
192277    if( iCookie<0 ) iCookie = 0;
192278
192279    if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
192280      sqlite3Fts5Put32(buf.p, iCookie);
192281      buf.n = 4;
192282      fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
192283      fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
192284      fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
192285    }
192286
192287    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
192288      int iSeg;                     /* Used to iterate through segments */
192289      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
192290      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
192291      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
192292      assert( pLvl->nMerge<=pLvl->nSeg );
192293
192294      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
192295        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
192296        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
192297        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
192298      }
192299    }
192300
192301    fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
192302    fts5BufferFree(&buf);
192303  }
192304}
192305
192306#if 0
192307static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
192308static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
192309  int rc = SQLITE_OK;
192310  Fts5Buffer buf;
192311  memset(&buf, 0, sizeof(buf));
192312  fts5DebugStructure(&rc, &buf, pStruct);
192313  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
192314  fflush(stdout);
192315  fts5BufferFree(&buf);
192316}
192317#else
192318# define fts5PrintStructure(x,y)
192319#endif
192320
192321static int fts5SegmentSize(Fts5StructureSegment *pSeg){
192322  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
192323}
192324
192325/*
192326** Return a copy of index structure pStruct. Except, promote as many
192327** segments as possible to level iPromote. If an OOM occurs, NULL is
192328** returned.
192329*/
192330static void fts5StructurePromoteTo(
192331  Fts5Index *p,
192332  int iPromote,
192333  int szPromote,
192334  Fts5Structure *pStruct
192335){
192336  int il, is;
192337  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
192338
192339  if( pOut->nMerge==0 ){
192340    for(il=iPromote+1; il<pStruct->nLevel; il++){
192341      Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
192342      if( pLvl->nMerge ) return;
192343      for(is=pLvl->nSeg-1; is>=0; is--){
192344        int sz = fts5SegmentSize(&pLvl->aSeg[is]);
192345        if( sz>szPromote ) return;
192346        fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
192347        if( p->rc ) return;
192348        memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
192349        pOut->nSeg++;
192350        pLvl->nSeg--;
192351      }
192352    }
192353  }
192354}
192355
192356/*
192357** A new segment has just been written to level iLvl of index structure
192358** pStruct. This function determines if any segments should be promoted
192359** as a result. Segments are promoted in two scenarios:
192360**
192361**   a) If the segment just written is smaller than one or more segments
192362**      within the previous populated level, it is promoted to the previous
192363**      populated level.
192364**
192365**   b) If the segment just written is larger than the newest segment on
192366**      the next populated level, then that segment, and any other adjacent
192367**      segments that are also smaller than the one just written, are
192368**      promoted.
192369**
192370** If one or more segments are promoted, the structure object is updated
192371** to reflect this.
192372*/
192373static void fts5StructurePromote(
192374  Fts5Index *p,                   /* FTS5 backend object */
192375  int iLvl,                       /* Index level just updated */
192376  Fts5Structure *pStruct          /* Index structure */
192377){
192378  if( p->rc==SQLITE_OK ){
192379    int iTst;
192380    int iPromote = -1;
192381    int szPromote = 0;            /* Promote anything this size or smaller */
192382    Fts5StructureSegment *pSeg;   /* Segment just written */
192383    int szSeg;                    /* Size of segment just written */
192384    int nSeg = pStruct->aLevel[iLvl].nSeg;
192385
192386    if( nSeg==0 ) return;
192387    pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
192388    szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
192389
192390    /* Check for condition (a) */
192391    for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
192392    if( iTst>=0 ){
192393      int i;
192394      int szMax = 0;
192395      Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
192396      assert( pTst->nMerge==0 );
192397      for(i=0; i<pTst->nSeg; i++){
192398        int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
192399        if( sz>szMax ) szMax = sz;
192400      }
192401      if( szMax>=szSeg ){
192402        /* Condition (a) is true. Promote the newest segment on level
192403        ** iLvl to level iTst.  */
192404        iPromote = iTst;
192405        szPromote = szMax;
192406      }
192407    }
192408
192409    /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
192410    ** is a no-op if it is not.  */
192411    if( iPromote<0 ){
192412      iPromote = iLvl;
192413      szPromote = szSeg;
192414    }
192415    fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
192416  }
192417}
192418
192419
192420/*
192421** Advance the iterator passed as the only argument. If the end of the
192422** doclist-index page is reached, return non-zero.
192423*/
192424static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
192425  Fts5Data *pData = pLvl->pData;
192426
192427  if( pLvl->iOff==0 ){
192428    assert( pLvl->bEof==0 );
192429    pLvl->iOff = 1;
192430    pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
192431    pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
192432    pLvl->iFirstOff = pLvl->iOff;
192433  }else{
192434    int iOff;
192435    for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
192436      if( pData->p[iOff] ) break;
192437    }
192438
192439    if( iOff<pData->nn ){
192440      i64 iVal;
192441      pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
192442      iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
192443      pLvl->iRowid += iVal;
192444      pLvl->iOff = iOff;
192445    }else{
192446      pLvl->bEof = 1;
192447    }
192448  }
192449
192450  return pLvl->bEof;
192451}
192452
192453/*
192454** Advance the iterator passed as the only argument.
192455*/
192456static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
192457  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
192458
192459  assert( iLvl<pIter->nLvl );
192460  if( fts5DlidxLvlNext(pLvl) ){
192461    if( (iLvl+1) < pIter->nLvl ){
192462      fts5DlidxIterNextR(p, pIter, iLvl+1);
192463      if( pLvl[1].bEof==0 ){
192464        fts5DataRelease(pLvl->pData);
192465        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
192466        pLvl->pData = fts5DataRead(p,
192467            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
192468        );
192469        if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
192470      }
192471    }
192472  }
192473
192474  return pIter->aLvl[0].bEof;
192475}
192476static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
192477  return fts5DlidxIterNextR(p, pIter, 0);
192478}
192479
192480/*
192481** The iterator passed as the first argument has the following fields set
192482** as follows. This function sets up the rest of the iterator so that it
192483** points to the first rowid in the doclist-index.
192484**
192485**   pData:
192486**     pointer to doclist-index record,
192487**
192488** When this function is called pIter->iLeafPgno is the page number the
192489** doclist is associated with (the one featuring the term).
192490*/
192491static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
192492  int i;
192493  for(i=0; i<pIter->nLvl; i++){
192494    fts5DlidxLvlNext(&pIter->aLvl[i]);
192495  }
192496  return pIter->aLvl[0].bEof;
192497}
192498
192499
192500static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
192501  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
192502}
192503
192504static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
192505  int i;
192506
192507  /* Advance each level to the last entry on the last page */
192508  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
192509    Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
192510    while( fts5DlidxLvlNext(pLvl)==0 );
192511    pLvl->bEof = 0;
192512
192513    if( i>0 ){
192514      Fts5DlidxLvl *pChild = &pLvl[-1];
192515      fts5DataRelease(pChild->pData);
192516      memset(pChild, 0, sizeof(Fts5DlidxLvl));
192517      pChild->pData = fts5DataRead(p,
192518          FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
192519      );
192520    }
192521  }
192522}
192523
192524/*
192525** Move the iterator passed as the only argument to the previous entry.
192526*/
192527static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
192528  int iOff = pLvl->iOff;
192529
192530  assert( pLvl->bEof==0 );
192531  if( iOff<=pLvl->iFirstOff ){
192532    pLvl->bEof = 1;
192533  }else{
192534    u8 *a = pLvl->pData->p;
192535    i64 iVal;
192536    int iLimit;
192537    int ii;
192538    int nZero = 0;
192539
192540    /* Currently iOff points to the first byte of a varint. This block
192541    ** decrements iOff until it points to the first byte of the previous
192542    ** varint. Taking care not to read any memory locations that occur
192543    ** before the buffer in memory.  */
192544    iLimit = (iOff>9 ? iOff-9 : 0);
192545    for(iOff--; iOff>iLimit; iOff--){
192546      if( (a[iOff-1] & 0x80)==0 ) break;
192547    }
192548
192549    fts5GetVarint(&a[iOff], (u64*)&iVal);
192550    pLvl->iRowid -= iVal;
192551    pLvl->iLeafPgno--;
192552
192553    /* Skip backwards past any 0x00 varints. */
192554    for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
192555      nZero++;
192556    }
192557    if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
192558      /* The byte immediately before the last 0x00 byte has the 0x80 bit
192559      ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
192560      ** bytes before a[ii]. */
192561      int bZero = 0;              /* True if last 0x00 counts */
192562      if( (ii-8)>=pLvl->iFirstOff ){
192563        int j;
192564        for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
192565        bZero = (j>8);
192566      }
192567      if( bZero==0 ) nZero--;
192568    }
192569    pLvl->iLeafPgno -= nZero;
192570    pLvl->iOff = iOff - nZero;
192571  }
192572
192573  return pLvl->bEof;
192574}
192575
192576static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
192577  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
192578
192579  assert( iLvl<pIter->nLvl );
192580  if( fts5DlidxLvlPrev(pLvl) ){
192581    if( (iLvl+1) < pIter->nLvl ){
192582      fts5DlidxIterPrevR(p, pIter, iLvl+1);
192583      if( pLvl[1].bEof==0 ){
192584        fts5DataRelease(pLvl->pData);
192585        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
192586        pLvl->pData = fts5DataRead(p,
192587            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
192588        );
192589        if( pLvl->pData ){
192590          while( fts5DlidxLvlNext(pLvl)==0 );
192591          pLvl->bEof = 0;
192592        }
192593      }
192594    }
192595  }
192596
192597  return pIter->aLvl[0].bEof;
192598}
192599static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
192600  return fts5DlidxIterPrevR(p, pIter, 0);
192601}
192602
192603/*
192604** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
192605*/
192606static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
192607  if( pIter ){
192608    int i;
192609    for(i=0; i<pIter->nLvl; i++){
192610      fts5DataRelease(pIter->aLvl[i].pData);
192611    }
192612    sqlite3_free(pIter);
192613  }
192614}
192615
192616static Fts5DlidxIter *fts5DlidxIterInit(
192617  Fts5Index *p,                   /* Fts5 Backend to iterate within */
192618  int bRev,                       /* True for ORDER BY ASC */
192619  int iSegid,                     /* Segment id */
192620  int iLeafPg                     /* Leaf page number to load dlidx for */
192621){
192622  Fts5DlidxIter *pIter = 0;
192623  int i;
192624  int bDone = 0;
192625
192626  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
192627    int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
192628    Fts5DlidxIter *pNew;
192629
192630    pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
192631    if( pNew==0 ){
192632      p->rc = SQLITE_NOMEM;
192633    }else{
192634      i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
192635      Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
192636      pIter = pNew;
192637      memset(pLvl, 0, sizeof(Fts5DlidxLvl));
192638      pLvl->pData = fts5DataRead(p, iRowid);
192639      if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
192640        bDone = 1;
192641      }
192642      pIter->nLvl = i+1;
192643    }
192644  }
192645
192646  if( p->rc==SQLITE_OK ){
192647    pIter->iSegid = iSegid;
192648    if( bRev==0 ){
192649      fts5DlidxIterFirst(pIter);
192650    }else{
192651      fts5DlidxIterLast(p, pIter);
192652    }
192653  }
192654
192655  if( p->rc!=SQLITE_OK ){
192656    fts5DlidxIterFree(pIter);
192657    pIter = 0;
192658  }
192659
192660  return pIter;
192661}
192662
192663static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
192664  return pIter->aLvl[0].iRowid;
192665}
192666static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
192667  return pIter->aLvl[0].iLeafPgno;
192668}
192669
192670/*
192671** Load the next leaf page into the segment iterator.
192672*/
192673static void fts5SegIterNextPage(
192674  Fts5Index *p,                   /* FTS5 backend object */
192675  Fts5SegIter *pIter              /* Iterator to advance to next page */
192676){
192677  Fts5Data *pLeaf;
192678  Fts5StructureSegment *pSeg = pIter->pSeg;
192679  fts5DataRelease(pIter->pLeaf);
192680  pIter->iLeafPgno++;
192681  if( pIter->pNextLeaf ){
192682    pIter->pLeaf = pIter->pNextLeaf;
192683    pIter->pNextLeaf = 0;
192684  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
192685    pIter->pLeaf = fts5LeafRead(p,
192686        FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
192687    );
192688  }else{
192689    pIter->pLeaf = 0;
192690  }
192691  pLeaf = pIter->pLeaf;
192692
192693  if( pLeaf ){
192694    pIter->iPgidxOff = pLeaf->szLeaf;
192695    if( fts5LeafIsTermless(pLeaf) ){
192696      pIter->iEndofDoclist = pLeaf->nn+1;
192697    }else{
192698      pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
192699          pIter->iEndofDoclist
192700      );
192701    }
192702  }
192703}
192704
192705/*
192706** Argument p points to a buffer containing a varint to be interpreted as a
192707** position list size field. Read the varint and return the number of bytes
192708** read. Before returning, set *pnSz to the number of bytes in the position
192709** list, and *pbDel to true if the delete flag is set, or false otherwise.
192710*/
192711static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
192712  int nSz;
192713  int n = 0;
192714  fts5FastGetVarint32(p, n, nSz);
192715  assert_nc( nSz>=0 );
192716  *pnSz = nSz/2;
192717  *pbDel = nSz & 0x0001;
192718  return n;
192719}
192720
192721/*
192722** Fts5SegIter.iLeafOffset currently points to the first byte of a
192723** position-list size field. Read the value of the field and store it
192724** in the following variables:
192725**
192726**   Fts5SegIter.nPos
192727**   Fts5SegIter.bDel
192728**
192729** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
192730** position list content (if any).
192731*/
192732static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
192733  if( p->rc==SQLITE_OK ){
192734    int iOff = pIter->iLeafOffset;  /* Offset to read at */
192735    ASSERT_SZLEAF_OK(pIter->pLeaf);
192736    if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
192737      int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
192738      pIter->bDel = 0;
192739      pIter->nPos = 1;
192740      if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
192741        pIter->bDel = 1;
192742        iOff++;
192743        if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
192744          pIter->nPos = 1;
192745          iOff++;
192746        }else{
192747          pIter->nPos = 0;
192748        }
192749      }
192750    }else{
192751      int nSz;
192752      fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
192753      pIter->bDel = (nSz & 0x0001);
192754      pIter->nPos = nSz>>1;
192755      assert_nc( pIter->nPos>=0 );
192756    }
192757    pIter->iLeafOffset = iOff;
192758  }
192759}
192760
192761static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
192762  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
192763  int iOff = pIter->iLeafOffset;
192764
192765  ASSERT_SZLEAF_OK(pIter->pLeaf);
192766  if( iOff>=pIter->pLeaf->szLeaf ){
192767    fts5SegIterNextPage(p, pIter);
192768    if( pIter->pLeaf==0 ){
192769      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
192770      return;
192771    }
192772    iOff = 4;
192773    a = pIter->pLeaf->p;
192774  }
192775  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
192776  pIter->iLeafOffset = iOff;
192777}
192778
192779/*
192780** Fts5SegIter.iLeafOffset currently points to the first byte of the
192781** "nSuffix" field of a term. Function parameter nKeep contains the value
192782** of the "nPrefix" field (if there was one - it is passed 0 if this is
192783** the first term in the segment).
192784**
192785** This function populates:
192786**
192787**   Fts5SegIter.term
192788**   Fts5SegIter.rowid
192789**
192790** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
192791** the first position list. The position list belonging to document
192792** (Fts5SegIter.iRowid).
192793*/
192794static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
192795  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
192796  int iOff = pIter->iLeafOffset;  /* Offset to read at */
192797  int nNew;                       /* Bytes of new data */
192798
192799  iOff += fts5GetVarint32(&a[iOff], nNew);
192800  if( iOff+nNew>pIter->pLeaf->nn ){
192801    p->rc = FTS5_CORRUPT;
192802    return;
192803  }
192804  pIter->term.n = nKeep;
192805  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
192806  iOff += nNew;
192807  pIter->iTermLeafOffset = iOff;
192808  pIter->iTermLeafPgno = pIter->iLeafPgno;
192809  pIter->iLeafOffset = iOff;
192810
192811  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
192812    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
192813  }else{
192814    int nExtra;
192815    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
192816    pIter->iEndofDoclist += nExtra;
192817  }
192818
192819  fts5SegIterLoadRowid(p, pIter);
192820}
192821
192822static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
192823static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
192824static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
192825
192826static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
192827  if( pIter->flags & FTS5_SEGITER_REVERSE ){
192828    pIter->xNext = fts5SegIterNext_Reverse;
192829  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
192830    pIter->xNext = fts5SegIterNext_None;
192831  }else{
192832    pIter->xNext = fts5SegIterNext;
192833  }
192834}
192835
192836/*
192837** Initialize the iterator object pIter to iterate through the entries in
192838** segment pSeg. The iterator is left pointing to the first entry when
192839** this function returns.
192840**
192841** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
192842** an error has already occurred when this function is called, it is a no-op.
192843*/
192844static void fts5SegIterInit(
192845  Fts5Index *p,                   /* FTS index object */
192846  Fts5StructureSegment *pSeg,     /* Description of segment */
192847  Fts5SegIter *pIter              /* Object to populate */
192848){
192849  if( pSeg->pgnoFirst==0 ){
192850    /* This happens if the segment is being used as an input to an incremental
192851    ** merge and all data has already been "trimmed". See function
192852    ** fts5TrimSegments() for details. In this case leave the iterator empty.
192853    ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
192854    ** at EOF already. */
192855    assert( pIter->pLeaf==0 );
192856    return;
192857  }
192858
192859  if( p->rc==SQLITE_OK ){
192860    memset(pIter, 0, sizeof(*pIter));
192861    fts5SegIterSetNext(p, pIter);
192862    pIter->pSeg = pSeg;
192863    pIter->iLeafPgno = pSeg->pgnoFirst-1;
192864    fts5SegIterNextPage(p, pIter);
192865  }
192866
192867  if( p->rc==SQLITE_OK ){
192868    pIter->iLeafOffset = 4;
192869    assert_nc( pIter->pLeaf->nn>4 );
192870    assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
192871    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
192872    fts5SegIterLoadTerm(p, pIter, 0);
192873    fts5SegIterLoadNPos(p, pIter);
192874  }
192875}
192876
192877/*
192878** This function is only ever called on iterators created by calls to
192879** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
192880**
192881** The iterator is in an unusual state when this function is called: the
192882** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
192883** the position-list size field for the first relevant rowid on the page.
192884** Fts5SegIter.rowid is set, but nPos and bDel are not.
192885**
192886** This function advances the iterator so that it points to the last
192887** relevant rowid on the page and, if necessary, initializes the
192888** aRowidOffset[] and iRowidOffset variables. At this point the iterator
192889** is in its regular state - Fts5SegIter.iLeafOffset points to the first
192890** byte of the position list content associated with said rowid.
192891*/
192892static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
192893  int eDetail = p->pConfig->eDetail;
192894  int n = pIter->pLeaf->szLeaf;
192895  int i = pIter->iLeafOffset;
192896  u8 *a = pIter->pLeaf->p;
192897  int iRowidOffset = 0;
192898
192899  if( n>pIter->iEndofDoclist ){
192900    n = pIter->iEndofDoclist;
192901  }
192902
192903  ASSERT_SZLEAF_OK(pIter->pLeaf);
192904  while( 1 ){
192905    i64 iDelta = 0;
192906
192907    if( eDetail==FTS5_DETAIL_NONE ){
192908      /* todo */
192909      if( i<n && a[i]==0 ){
192910        i++;
192911        if( i<n && a[i]==0 ) i++;
192912      }
192913    }else{
192914      int nPos;
192915      int bDummy;
192916      i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
192917      i += nPos;
192918    }
192919    if( i>=n ) break;
192920    i += fts5GetVarint(&a[i], (u64*)&iDelta);
192921    pIter->iRowid += iDelta;
192922
192923    /* If necessary, grow the pIter->aRowidOffset[] array. */
192924    if( iRowidOffset>=pIter->nRowidOffset ){
192925      int nNew = pIter->nRowidOffset + 8;
192926      int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
192927      if( aNew==0 ){
192928        p->rc = SQLITE_NOMEM;
192929        break;
192930      }
192931      pIter->aRowidOffset = aNew;
192932      pIter->nRowidOffset = nNew;
192933    }
192934
192935    pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
192936    pIter->iLeafOffset = i;
192937  }
192938  pIter->iRowidOffset = iRowidOffset;
192939  fts5SegIterLoadNPos(p, pIter);
192940}
192941
192942/*
192943**
192944*/
192945static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
192946  assert( pIter->flags & FTS5_SEGITER_REVERSE );
192947  assert( pIter->flags & FTS5_SEGITER_ONETERM );
192948
192949  fts5DataRelease(pIter->pLeaf);
192950  pIter->pLeaf = 0;
192951  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
192952    Fts5Data *pNew;
192953    pIter->iLeafPgno--;
192954    pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
192955          pIter->pSeg->iSegid, pIter->iLeafPgno
192956    ));
192957    if( pNew ){
192958      /* iTermLeafOffset may be equal to szLeaf if the term is the last
192959      ** thing on the page - i.e. the first rowid is on the following page.
192960      ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
192961      if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
192962        assert( pIter->pLeaf==0 );
192963        if( pIter->iTermLeafOffset<pNew->szLeaf ){
192964          pIter->pLeaf = pNew;
192965          pIter->iLeafOffset = pIter->iTermLeafOffset;
192966        }
192967      }else{
192968        int iRowidOff;
192969        iRowidOff = fts5LeafFirstRowidOff(pNew);
192970        if( iRowidOff ){
192971          pIter->pLeaf = pNew;
192972          pIter->iLeafOffset = iRowidOff;
192973        }
192974      }
192975
192976      if( pIter->pLeaf ){
192977        u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
192978        pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
192979        break;
192980      }else{
192981        fts5DataRelease(pNew);
192982      }
192983    }
192984  }
192985
192986  if( pIter->pLeaf ){
192987    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
192988    fts5SegIterReverseInitPage(p, pIter);
192989  }
192990}
192991
192992/*
192993** Return true if the iterator passed as the second argument currently
192994** points to a delete marker. A delete marker is an entry with a 0 byte
192995** position-list.
192996*/
192997static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
192998  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
192999  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
193000}
193001
193002/*
193003** Advance iterator pIter to the next entry.
193004**
193005** This version of fts5SegIterNext() is only used by reverse iterators.
193006*/
193007static void fts5SegIterNext_Reverse(
193008  Fts5Index *p,                   /* FTS5 backend object */
193009  Fts5SegIter *pIter,             /* Iterator to advance */
193010  int *pbUnused                   /* Unused */
193011){
193012  assert( pIter->flags & FTS5_SEGITER_REVERSE );
193013  assert( pIter->pNextLeaf==0 );
193014  UNUSED_PARAM(pbUnused);
193015
193016  if( pIter->iRowidOffset>0 ){
193017    u8 *a = pIter->pLeaf->p;
193018    int iOff;
193019    i64 iDelta;
193020
193021    pIter->iRowidOffset--;
193022    pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
193023    fts5SegIterLoadNPos(p, pIter);
193024    iOff = pIter->iLeafOffset;
193025    if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
193026      iOff += pIter->nPos;
193027    }
193028    fts5GetVarint(&a[iOff], (u64*)&iDelta);
193029    pIter->iRowid -= iDelta;
193030  }else{
193031    fts5SegIterReverseNewPage(p, pIter);
193032  }
193033}
193034
193035/*
193036** Advance iterator pIter to the next entry.
193037**
193038** This version of fts5SegIterNext() is only used if detail=none and the
193039** iterator is not a reverse direction iterator.
193040*/
193041static void fts5SegIterNext_None(
193042  Fts5Index *p,                   /* FTS5 backend object */
193043  Fts5SegIter *pIter,             /* Iterator to advance */
193044  int *pbNewTerm                  /* OUT: Set for new term */
193045){
193046  int iOff;
193047
193048  assert( p->rc==SQLITE_OK );
193049  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
193050  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
193051
193052  ASSERT_SZLEAF_OK(pIter->pLeaf);
193053  iOff = pIter->iLeafOffset;
193054
193055  /* Next entry is on the next page */
193056  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
193057    fts5SegIterNextPage(p, pIter);
193058    if( p->rc || pIter->pLeaf==0 ) return;
193059    pIter->iRowid = 0;
193060    iOff = 4;
193061  }
193062
193063  if( iOff<pIter->iEndofDoclist ){
193064    /* Next entry is on the current page */
193065    i64 iDelta;
193066    iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
193067    pIter->iLeafOffset = iOff;
193068    pIter->iRowid += iDelta;
193069  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
193070    if( pIter->pSeg ){
193071      int nKeep = 0;
193072      if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
193073        iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
193074      }
193075      pIter->iLeafOffset = iOff;
193076      fts5SegIterLoadTerm(p, pIter, nKeep);
193077    }else{
193078      const u8 *pList = 0;
193079      const char *zTerm = 0;
193080      int nList;
193081      sqlite3Fts5HashScanNext(p->pHash);
193082      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
193083      if( pList==0 ) goto next_none_eof;
193084      pIter->pLeaf->p = (u8*)pList;
193085      pIter->pLeaf->nn = nList;
193086      pIter->pLeaf->szLeaf = nList;
193087      pIter->iEndofDoclist = nList;
193088      sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
193089      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
193090    }
193091
193092    if( pbNewTerm ) *pbNewTerm = 1;
193093  }else{
193094    goto next_none_eof;
193095  }
193096
193097  fts5SegIterLoadNPos(p, pIter);
193098
193099  return;
193100 next_none_eof:
193101  fts5DataRelease(pIter->pLeaf);
193102  pIter->pLeaf = 0;
193103}
193104
193105
193106/*
193107** Advance iterator pIter to the next entry.
193108**
193109** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
193110** is not considered an error if the iterator reaches EOF. If an error has
193111** already occurred when this function is called, it is a no-op.
193112*/
193113static void fts5SegIterNext(
193114  Fts5Index *p,                   /* FTS5 backend object */
193115  Fts5SegIter *pIter,             /* Iterator to advance */
193116  int *pbNewTerm                  /* OUT: Set for new term */
193117){
193118  Fts5Data *pLeaf = pIter->pLeaf;
193119  int iOff;
193120  int bNewTerm = 0;
193121  int nKeep = 0;
193122  u8 *a;
193123  int n;
193124
193125  assert( pbNewTerm==0 || *pbNewTerm==0 );
193126  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
193127
193128  /* Search for the end of the position list within the current page. */
193129  a = pLeaf->p;
193130  n = pLeaf->szLeaf;
193131
193132  ASSERT_SZLEAF_OK(pLeaf);
193133  iOff = pIter->iLeafOffset + pIter->nPos;
193134
193135  if( iOff<n ){
193136    /* The next entry is on the current page. */
193137    assert_nc( iOff<=pIter->iEndofDoclist );
193138    if( iOff>=pIter->iEndofDoclist ){
193139      bNewTerm = 1;
193140      if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
193141        iOff += fts5GetVarint32(&a[iOff], nKeep);
193142      }
193143    }else{
193144      u64 iDelta;
193145      iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
193146      pIter->iRowid += iDelta;
193147      assert_nc( iDelta>0 );
193148    }
193149    pIter->iLeafOffset = iOff;
193150
193151  }else if( pIter->pSeg==0 ){
193152    const u8 *pList = 0;
193153    const char *zTerm = 0;
193154    int nList = 0;
193155    assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
193156    if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
193157      sqlite3Fts5HashScanNext(p->pHash);
193158      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
193159    }
193160    if( pList==0 ){
193161      fts5DataRelease(pIter->pLeaf);
193162      pIter->pLeaf = 0;
193163    }else{
193164      pIter->pLeaf->p = (u8*)pList;
193165      pIter->pLeaf->nn = nList;
193166      pIter->pLeaf->szLeaf = nList;
193167      pIter->iEndofDoclist = nList+1;
193168      sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
193169          (u8*)zTerm);
193170      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
193171      *pbNewTerm = 1;
193172    }
193173  }else{
193174    iOff = 0;
193175    /* Next entry is not on the current page */
193176    while( iOff==0 ){
193177      fts5SegIterNextPage(p, pIter);
193178      pLeaf = pIter->pLeaf;
193179      if( pLeaf==0 ) break;
193180      ASSERT_SZLEAF_OK(pLeaf);
193181      if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
193182        iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
193183        pIter->iLeafOffset = iOff;
193184
193185        if( pLeaf->nn>pLeaf->szLeaf ){
193186          pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
193187              &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
193188          );
193189        }
193190      }
193191      else if( pLeaf->nn>pLeaf->szLeaf ){
193192        pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
193193            &pLeaf->p[pLeaf->szLeaf], iOff
193194        );
193195        pIter->iLeafOffset = iOff;
193196        pIter->iEndofDoclist = iOff;
193197        bNewTerm = 1;
193198      }
193199      assert_nc( iOff<pLeaf->szLeaf );
193200      if( iOff>pLeaf->szLeaf ){
193201        p->rc = FTS5_CORRUPT;
193202        return;
193203      }
193204    }
193205  }
193206
193207  /* Check if the iterator is now at EOF. If so, return early. */
193208  if( pIter->pLeaf ){
193209    if( bNewTerm ){
193210      if( pIter->flags & FTS5_SEGITER_ONETERM ){
193211        fts5DataRelease(pIter->pLeaf);
193212        pIter->pLeaf = 0;
193213      }else{
193214        fts5SegIterLoadTerm(p, pIter, nKeep);
193215        fts5SegIterLoadNPos(p, pIter);
193216        if( pbNewTerm ) *pbNewTerm = 1;
193217      }
193218    }else{
193219      /* The following could be done by calling fts5SegIterLoadNPos(). But
193220      ** this block is particularly performance critical, so equivalent
193221      ** code is inlined.
193222      **
193223      ** Later: Switched back to fts5SegIterLoadNPos() because it supports
193224      ** detail=none mode. Not ideal.
193225      */
193226      int nSz;
193227      assert( p->rc==SQLITE_OK );
193228      assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
193229      fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
193230      pIter->bDel = (nSz & 0x0001);
193231      pIter->nPos = nSz>>1;
193232      assert_nc( pIter->nPos>=0 );
193233    }
193234  }
193235}
193236
193237#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
193238
193239#define fts5IndexSkipVarint(a, iOff) {            \
193240  int iEnd = iOff+9;                              \
193241  while( (a[iOff++] & 0x80) && iOff<iEnd );       \
193242}
193243
193244/*
193245** Iterator pIter currently points to the first rowid in a doclist. This
193246** function sets the iterator up so that iterates in reverse order through
193247** the doclist.
193248*/
193249static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
193250  Fts5DlidxIter *pDlidx = pIter->pDlidx;
193251  Fts5Data *pLast = 0;
193252  int pgnoLast = 0;
193253
193254  if( pDlidx ){
193255    int iSegid = pIter->pSeg->iSegid;
193256    pgnoLast = fts5DlidxIterPgno(pDlidx);
193257    pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
193258  }else{
193259    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
193260
193261    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
193262    ** position-list content for the current rowid. Back it up so that it
193263    ** points to the start of the position-list size field. */
193264    int iPoslist;
193265    if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
193266      iPoslist = pIter->iTermLeafOffset;
193267    }else{
193268      iPoslist = 4;
193269    }
193270    fts5IndexSkipVarint(pLeaf->p, iPoslist);
193271    pIter->iLeafOffset = iPoslist;
193272
193273    /* If this condition is true then the largest rowid for the current
193274    ** term may not be stored on the current page. So search forward to
193275    ** see where said rowid really is.  */
193276    if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
193277      int pgno;
193278      Fts5StructureSegment *pSeg = pIter->pSeg;
193279
193280      /* The last rowid in the doclist may not be on the current page. Search
193281      ** forward to find the page containing the last rowid.  */
193282      for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
193283        i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
193284        Fts5Data *pNew = fts5DataRead(p, iAbs);
193285        if( pNew ){
193286          int iRowid, bTermless;
193287          iRowid = fts5LeafFirstRowidOff(pNew);
193288          bTermless = fts5LeafIsTermless(pNew);
193289          if( iRowid ){
193290            SWAPVAL(Fts5Data*, pNew, pLast);
193291            pgnoLast = pgno;
193292          }
193293          fts5DataRelease(pNew);
193294          if( bTermless==0 ) break;
193295        }
193296      }
193297    }
193298  }
193299
193300  /* If pLast is NULL at this point, then the last rowid for this doclist
193301  ** lies on the page currently indicated by the iterator. In this case
193302  ** pIter->iLeafOffset is already set to point to the position-list size
193303  ** field associated with the first relevant rowid on the page.
193304  **
193305  ** Or, if pLast is non-NULL, then it is the page that contains the last
193306  ** rowid. In this case configure the iterator so that it points to the
193307  ** first rowid on this page.
193308  */
193309  if( pLast ){
193310    int iOff;
193311    fts5DataRelease(pIter->pLeaf);
193312    pIter->pLeaf = pLast;
193313    pIter->iLeafPgno = pgnoLast;
193314    iOff = fts5LeafFirstRowidOff(pLast);
193315    iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
193316    pIter->iLeafOffset = iOff;
193317
193318    if( fts5LeafIsTermless(pLast) ){
193319      pIter->iEndofDoclist = pLast->nn+1;
193320    }else{
193321      pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
193322    }
193323
193324  }
193325
193326  fts5SegIterReverseInitPage(p, pIter);
193327}
193328
193329/*
193330** Iterator pIter currently points to the first rowid of a doclist.
193331** There is a doclist-index associated with the final term on the current
193332** page. If the current term is the last term on the page, load the
193333** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
193334*/
193335static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
193336  int iSeg = pIter->pSeg->iSegid;
193337  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
193338  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
193339
193340  assert( pIter->flags & FTS5_SEGITER_ONETERM );
193341  assert( pIter->pDlidx==0 );
193342
193343  /* Check if the current doclist ends on this page. If it does, return
193344  ** early without loading the doclist-index (as it belongs to a different
193345  ** term. */
193346  if( pIter->iTermLeafPgno==pIter->iLeafPgno
193347   && pIter->iEndofDoclist<pLeaf->szLeaf
193348  ){
193349    return;
193350  }
193351
193352  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
193353}
193354
193355/*
193356** The iterator object passed as the second argument currently contains
193357** no valid values except for the Fts5SegIter.pLeaf member variable. This
193358** function searches the leaf page for a term matching (pTerm/nTerm).
193359**
193360** If the specified term is found on the page, then the iterator is left
193361** pointing to it. If argument bGe is zero and the term is not found,
193362** the iterator is left pointing at EOF.
193363**
193364** If bGe is non-zero and the specified term is not found, then the
193365** iterator is left pointing to the smallest term in the segment that
193366** is larger than the specified term, even if this term is not on the
193367** current page.
193368*/
193369static void fts5LeafSeek(
193370  Fts5Index *p,                   /* Leave any error code here */
193371  int bGe,                        /* True for a >= search */
193372  Fts5SegIter *pIter,             /* Iterator to seek */
193373  const u8 *pTerm, int nTerm      /* Term to search for */
193374){
193375  int iOff;
193376  const u8 *a = pIter->pLeaf->p;
193377  int szLeaf = pIter->pLeaf->szLeaf;
193378  int n = pIter->pLeaf->nn;
193379
193380  int nMatch = 0;
193381  int nKeep = 0;
193382  int nNew = 0;
193383  int iTermOff;
193384  int iPgidx;                     /* Current offset in pgidx */
193385  int bEndOfPage = 0;
193386
193387  assert( p->rc==SQLITE_OK );
193388
193389  iPgidx = szLeaf;
193390  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
193391  iOff = iTermOff;
193392  if( iOff>n ){
193393    p->rc = FTS5_CORRUPT;
193394    return;
193395  }
193396
193397  while( 1 ){
193398
193399    /* Figure out how many new bytes are in this term */
193400    fts5FastGetVarint32(a, iOff, nNew);
193401    if( nKeep<nMatch ){
193402      goto search_failed;
193403    }
193404
193405    assert( nKeep>=nMatch );
193406    if( nKeep==nMatch ){
193407      int nCmp;
193408      int i;
193409      nCmp = MIN(nNew, nTerm-nMatch);
193410      for(i=0; i<nCmp; i++){
193411        if( a[iOff+i]!=pTerm[nMatch+i] ) break;
193412      }
193413      nMatch += i;
193414
193415      if( nTerm==nMatch ){
193416        if( i==nNew ){
193417          goto search_success;
193418        }else{
193419          goto search_failed;
193420        }
193421      }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
193422        goto search_failed;
193423      }
193424    }
193425
193426    if( iPgidx>=n ){
193427      bEndOfPage = 1;
193428      break;
193429    }
193430
193431    iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
193432    iTermOff += nKeep;
193433    iOff = iTermOff;
193434
193435    if( iOff>=n ){
193436      p->rc = FTS5_CORRUPT;
193437      return;
193438    }
193439
193440    /* Read the nKeep field of the next term. */
193441    fts5FastGetVarint32(a, iOff, nKeep);
193442  }
193443
193444 search_failed:
193445  if( bGe==0 ){
193446    fts5DataRelease(pIter->pLeaf);
193447    pIter->pLeaf = 0;
193448    return;
193449  }else if( bEndOfPage ){
193450    do {
193451      fts5SegIterNextPage(p, pIter);
193452      if( pIter->pLeaf==0 ) return;
193453      a = pIter->pLeaf->p;
193454      if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
193455        iPgidx = pIter->pLeaf->szLeaf;
193456        iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
193457        if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
193458          p->rc = FTS5_CORRUPT;
193459        }else{
193460          nKeep = 0;
193461          iTermOff = iOff;
193462          n = pIter->pLeaf->nn;
193463          iOff += fts5GetVarint32(&a[iOff], nNew);
193464          break;
193465        }
193466      }
193467    }while( 1 );
193468  }
193469
193470 search_success:
193471
193472  pIter->iLeafOffset = iOff + nNew;
193473  pIter->iTermLeafOffset = pIter->iLeafOffset;
193474  pIter->iTermLeafPgno = pIter->iLeafPgno;
193475
193476  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
193477  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
193478
193479  if( iPgidx>=n ){
193480    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
193481  }else{
193482    int nExtra;
193483    iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
193484    pIter->iEndofDoclist = iTermOff + nExtra;
193485  }
193486  pIter->iPgidxOff = iPgidx;
193487
193488  fts5SegIterLoadRowid(p, pIter);
193489  fts5SegIterLoadNPos(p, pIter);
193490}
193491
193492static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
193493  if( p->pIdxSelect==0 ){
193494    Fts5Config *pConfig = p->pConfig;
193495    fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
193496          "SELECT pgno FROM '%q'.'%q_idx' WHERE "
193497          "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
193498          pConfig->zDb, pConfig->zName
193499    ));
193500  }
193501  return p->pIdxSelect;
193502}
193503
193504/*
193505** Initialize the object pIter to point to term pTerm/nTerm within segment
193506** pSeg. If there is no such term in the index, the iterator is set to EOF.
193507**
193508** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
193509** an error has already occurred when this function is called, it is a no-op.
193510*/
193511static void fts5SegIterSeekInit(
193512  Fts5Index *p,                   /* FTS5 backend */
193513  const u8 *pTerm, int nTerm,     /* Term to seek to */
193514  int flags,                      /* Mask of FTS5INDEX_XXX flags */
193515  Fts5StructureSegment *pSeg,     /* Description of segment */
193516  Fts5SegIter *pIter              /* Object to populate */
193517){
193518  int iPg = 1;
193519  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
193520  int bDlidx = 0;                 /* True if there is a doclist-index */
193521  sqlite3_stmt *pIdxSelect = 0;
193522
193523  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
193524  assert( pTerm && nTerm );
193525  memset(pIter, 0, sizeof(*pIter));
193526  pIter->pSeg = pSeg;
193527
193528  /* This block sets stack variable iPg to the leaf page number that may
193529  ** contain term (pTerm/nTerm), if it is present in the segment. */
193530  pIdxSelect = fts5IdxSelectStmt(p);
193531  if( p->rc ) return;
193532  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
193533  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
193534  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
193535    i64 val = sqlite3_column_int(pIdxSelect, 0);
193536    iPg = (int)(val>>1);
193537    bDlidx = (val & 0x0001);
193538  }
193539  p->rc = sqlite3_reset(pIdxSelect);
193540
193541  if( iPg<pSeg->pgnoFirst ){
193542    iPg = pSeg->pgnoFirst;
193543    bDlidx = 0;
193544  }
193545
193546  pIter->iLeafPgno = iPg - 1;
193547  fts5SegIterNextPage(p, pIter);
193548
193549  if( pIter->pLeaf ){
193550    fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
193551  }
193552
193553  if( p->rc==SQLITE_OK && bGe==0 ){
193554    pIter->flags |= FTS5_SEGITER_ONETERM;
193555    if( pIter->pLeaf ){
193556      if( flags & FTS5INDEX_QUERY_DESC ){
193557        pIter->flags |= FTS5_SEGITER_REVERSE;
193558      }
193559      if( bDlidx ){
193560        fts5SegIterLoadDlidx(p, pIter);
193561      }
193562      if( flags & FTS5INDEX_QUERY_DESC ){
193563        fts5SegIterReverse(p, pIter);
193564      }
193565    }
193566  }
193567
193568  fts5SegIterSetNext(p, pIter);
193569
193570  /* Either:
193571  **
193572  **   1) an error has occurred, or
193573  **   2) the iterator points to EOF, or
193574  **   3) the iterator points to an entry with term (pTerm/nTerm), or
193575  **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
193576  **      to an entry with a term greater than or equal to (pTerm/nTerm).
193577  */
193578  assert( p->rc!=SQLITE_OK                                          /* 1 */
193579   || pIter->pLeaf==0                                               /* 2 */
193580   || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
193581   || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
193582  );
193583}
193584
193585/*
193586** Initialize the object pIter to point to term pTerm/nTerm within the
193587** in-memory hash table. If there is no such term in the hash-table, the
193588** iterator is set to EOF.
193589**
193590** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
193591** an error has already occurred when this function is called, it is a no-op.
193592*/
193593static void fts5SegIterHashInit(
193594  Fts5Index *p,                   /* FTS5 backend */
193595  const u8 *pTerm, int nTerm,     /* Term to seek to */
193596  int flags,                      /* Mask of FTS5INDEX_XXX flags */
193597  Fts5SegIter *pIter              /* Object to populate */
193598){
193599  const u8 *pList = 0;
193600  int nList = 0;
193601  const u8 *z = 0;
193602  int n = 0;
193603
193604  assert( p->pHash );
193605  assert( p->rc==SQLITE_OK );
193606
193607  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
193608    p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
193609    sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
193610    n = (z ? (int)strlen((const char*)z) : 0);
193611  }else{
193612    pIter->flags |= FTS5_SEGITER_ONETERM;
193613    sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
193614    z = pTerm;
193615    n = nTerm;
193616  }
193617
193618  if( pList ){
193619    Fts5Data *pLeaf;
193620    sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
193621    pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
193622    if( pLeaf==0 ) return;
193623    pLeaf->p = (u8*)pList;
193624    pLeaf->nn = pLeaf->szLeaf = nList;
193625    pIter->pLeaf = pLeaf;
193626    pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
193627    pIter->iEndofDoclist = pLeaf->nn;
193628
193629    if( flags & FTS5INDEX_QUERY_DESC ){
193630      pIter->flags |= FTS5_SEGITER_REVERSE;
193631      fts5SegIterReverseInitPage(p, pIter);
193632    }else{
193633      fts5SegIterLoadNPos(p, pIter);
193634    }
193635  }
193636
193637  fts5SegIterSetNext(p, pIter);
193638}
193639
193640/*
193641** Zero the iterator passed as the only argument.
193642*/
193643static void fts5SegIterClear(Fts5SegIter *pIter){
193644  fts5BufferFree(&pIter->term);
193645  fts5DataRelease(pIter->pLeaf);
193646  fts5DataRelease(pIter->pNextLeaf);
193647  fts5DlidxIterFree(pIter->pDlidx);
193648  sqlite3_free(pIter->aRowidOffset);
193649  memset(pIter, 0, sizeof(Fts5SegIter));
193650}
193651
193652#ifdef SQLITE_DEBUG
193653
193654/*
193655** This function is used as part of the big assert() procedure implemented by
193656** fts5AssertMultiIterSetup(). It ensures that the result currently stored
193657** in *pRes is the correct result of comparing the current positions of the
193658** two iterators.
193659*/
193660static void fts5AssertComparisonResult(
193661  Fts5Iter *pIter,
193662  Fts5SegIter *p1,
193663  Fts5SegIter *p2,
193664  Fts5CResult *pRes
193665){
193666  int i1 = p1 - pIter->aSeg;
193667  int i2 = p2 - pIter->aSeg;
193668
193669  if( p1->pLeaf || p2->pLeaf ){
193670    if( p1->pLeaf==0 ){
193671      assert( pRes->iFirst==i2 );
193672    }else if( p2->pLeaf==0 ){
193673      assert( pRes->iFirst==i1 );
193674    }else{
193675      int nMin = MIN(p1->term.n, p2->term.n);
193676      int res = memcmp(p1->term.p, p2->term.p, nMin);
193677      if( res==0 ) res = p1->term.n - p2->term.n;
193678
193679      if( res==0 ){
193680        assert( pRes->bTermEq==1 );
193681        assert( p1->iRowid!=p2->iRowid );
193682        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
193683      }else{
193684        assert( pRes->bTermEq==0 );
193685      }
193686
193687      if( res<0 ){
193688        assert( pRes->iFirst==i1 );
193689      }else{
193690        assert( pRes->iFirst==i2 );
193691      }
193692    }
193693  }
193694}
193695
193696/*
193697** This function is a no-op unless SQLITE_DEBUG is defined when this module
193698** is compiled. In that case, this function is essentially an assert()
193699** statement used to verify that the contents of the pIter->aFirst[] array
193700** are correct.
193701*/
193702static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
193703  if( p->rc==SQLITE_OK ){
193704    Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
193705    int i;
193706
193707    assert( (pFirst->pLeaf==0)==pIter->base.bEof );
193708
193709    /* Check that pIter->iSwitchRowid is set correctly. */
193710    for(i=0; i<pIter->nSeg; i++){
193711      Fts5SegIter *p1 = &pIter->aSeg[i];
193712      assert( p1==pFirst
193713           || p1->pLeaf==0
193714           || fts5BufferCompare(&pFirst->term, &p1->term)
193715           || p1->iRowid==pIter->iSwitchRowid
193716           || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
193717      );
193718    }
193719
193720    for(i=0; i<pIter->nSeg; i+=2){
193721      Fts5SegIter *p1 = &pIter->aSeg[i];
193722      Fts5SegIter *p2 = &pIter->aSeg[i+1];
193723      Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
193724      fts5AssertComparisonResult(pIter, p1, p2, pRes);
193725    }
193726
193727    for(i=1; i<(pIter->nSeg / 2); i+=2){
193728      Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
193729      Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
193730      Fts5CResult *pRes = &pIter->aFirst[i];
193731      fts5AssertComparisonResult(pIter, p1, p2, pRes);
193732    }
193733  }
193734}
193735#else
193736# define fts5AssertMultiIterSetup(x,y)
193737#endif
193738
193739/*
193740** Do the comparison necessary to populate pIter->aFirst[iOut].
193741**
193742** If the returned value is non-zero, then it is the index of an entry
193743** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
193744** to a key that is a duplicate of another, higher priority,
193745** segment-iterator in the pSeg->aSeg[] array.
193746*/
193747static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
193748  int i1;                         /* Index of left-hand Fts5SegIter */
193749  int i2;                         /* Index of right-hand Fts5SegIter */
193750  int iRes;
193751  Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
193752  Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
193753  Fts5CResult *pRes = &pIter->aFirst[iOut];
193754
193755  assert( iOut<pIter->nSeg && iOut>0 );
193756  assert( pIter->bRev==0 || pIter->bRev==1 );
193757
193758  if( iOut>=(pIter->nSeg/2) ){
193759    i1 = (iOut - pIter->nSeg/2) * 2;
193760    i2 = i1 + 1;
193761  }else{
193762    i1 = pIter->aFirst[iOut*2].iFirst;
193763    i2 = pIter->aFirst[iOut*2+1].iFirst;
193764  }
193765  p1 = &pIter->aSeg[i1];
193766  p2 = &pIter->aSeg[i2];
193767
193768  pRes->bTermEq = 0;
193769  if( p1->pLeaf==0 ){           /* If p1 is at EOF */
193770    iRes = i2;
193771  }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
193772    iRes = i1;
193773  }else{
193774    int res = fts5BufferCompare(&p1->term, &p2->term);
193775    if( res==0 ){
193776      assert( i2>i1 );
193777      assert( i2!=0 );
193778      pRes->bTermEq = 1;
193779      if( p1->iRowid==p2->iRowid ){
193780        p1->bDel = p2->bDel;
193781        return i2;
193782      }
193783      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
193784    }
193785    assert( res!=0 );
193786    if( res<0 ){
193787      iRes = i1;
193788    }else{
193789      iRes = i2;
193790    }
193791  }
193792
193793  pRes->iFirst = (u16)iRes;
193794  return 0;
193795}
193796
193797/*
193798** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
193799** It is an error if leaf iLeafPgno does not exist or contains no rowids.
193800*/
193801static void fts5SegIterGotoPage(
193802  Fts5Index *p,                   /* FTS5 backend object */
193803  Fts5SegIter *pIter,             /* Iterator to advance */
193804  int iLeafPgno
193805){
193806  assert( iLeafPgno>pIter->iLeafPgno );
193807
193808  if( iLeafPgno>pIter->pSeg->pgnoLast ){
193809    p->rc = FTS5_CORRUPT;
193810  }else{
193811    fts5DataRelease(pIter->pNextLeaf);
193812    pIter->pNextLeaf = 0;
193813    pIter->iLeafPgno = iLeafPgno-1;
193814    fts5SegIterNextPage(p, pIter);
193815    assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
193816
193817    if( p->rc==SQLITE_OK ){
193818      int iOff;
193819      u8 *a = pIter->pLeaf->p;
193820      int n = pIter->pLeaf->szLeaf;
193821
193822      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
193823      if( iOff<4 || iOff>=n ){
193824        p->rc = FTS5_CORRUPT;
193825      }else{
193826        iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
193827        pIter->iLeafOffset = iOff;
193828        fts5SegIterLoadNPos(p, pIter);
193829      }
193830    }
193831  }
193832}
193833
193834/*
193835** Advance the iterator passed as the second argument until it is at or
193836** past rowid iFrom. Regardless of the value of iFrom, the iterator is
193837** always advanced at least once.
193838*/
193839static void fts5SegIterNextFrom(
193840  Fts5Index *p,                   /* FTS5 backend object */
193841  Fts5SegIter *pIter,             /* Iterator to advance */
193842  i64 iMatch                      /* Advance iterator at least this far */
193843){
193844  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
193845  Fts5DlidxIter *pDlidx = pIter->pDlidx;
193846  int iLeafPgno = pIter->iLeafPgno;
193847  int bMove = 1;
193848
193849  assert( pIter->flags & FTS5_SEGITER_ONETERM );
193850  assert( pIter->pDlidx );
193851  assert( pIter->pLeaf );
193852
193853  if( bRev==0 ){
193854    while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
193855      iLeafPgno = fts5DlidxIterPgno(pDlidx);
193856      fts5DlidxIterNext(p, pDlidx);
193857    }
193858    assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
193859    if( iLeafPgno>pIter->iLeafPgno ){
193860      fts5SegIterGotoPage(p, pIter, iLeafPgno);
193861      bMove = 0;
193862    }
193863  }else{
193864    assert( pIter->pNextLeaf==0 );
193865    assert( iMatch<pIter->iRowid );
193866    while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
193867      fts5DlidxIterPrev(p, pDlidx);
193868    }
193869    iLeafPgno = fts5DlidxIterPgno(pDlidx);
193870
193871    assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
193872
193873    if( iLeafPgno<pIter->iLeafPgno ){
193874      pIter->iLeafPgno = iLeafPgno+1;
193875      fts5SegIterReverseNewPage(p, pIter);
193876      bMove = 0;
193877    }
193878  }
193879
193880  do{
193881    if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
193882    if( pIter->pLeaf==0 ) break;
193883    if( bRev==0 && pIter->iRowid>=iMatch ) break;
193884    if( bRev!=0 && pIter->iRowid<=iMatch ) break;
193885    bMove = 1;
193886  }while( p->rc==SQLITE_OK );
193887}
193888
193889
193890/*
193891** Free the iterator object passed as the second argument.
193892*/
193893static void fts5MultiIterFree(Fts5Iter *pIter){
193894  if( pIter ){
193895    int i;
193896    for(i=0; i<pIter->nSeg; i++){
193897      fts5SegIterClear(&pIter->aSeg[i]);
193898    }
193899    fts5StructureRelease(pIter->pStruct);
193900    fts5BufferFree(&pIter->poslist);
193901    sqlite3_free(pIter);
193902  }
193903}
193904
193905static void fts5MultiIterAdvanced(
193906  Fts5Index *p,                   /* FTS5 backend to iterate within */
193907  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
193908  int iChanged,                   /* Index of sub-iterator just advanced */
193909  int iMinset                     /* Minimum entry in aFirst[] to set */
193910){
193911  int i;
193912  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
193913    int iEq;
193914    if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
193915      Fts5SegIter *pSeg = &pIter->aSeg[iEq];
193916      assert( p->rc==SQLITE_OK );
193917      pSeg->xNext(p, pSeg, 0);
193918      i = pIter->nSeg + iEq;
193919    }
193920  }
193921}
193922
193923/*
193924** Sub-iterator iChanged of iterator pIter has just been advanced. It still
193925** points to the same term though - just a different rowid. This function
193926** attempts to update the contents of the pIter->aFirst[] accordingly.
193927** If it does so successfully, 0 is returned. Otherwise 1.
193928**
193929** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
193930** on the iterator instead. That function does the same as this one, except
193931** that it deals with more complicated cases as well.
193932*/
193933static int fts5MultiIterAdvanceRowid(
193934  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
193935  int iChanged,                   /* Index of sub-iterator just advanced */
193936  Fts5SegIter **ppFirst
193937){
193938  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
193939
193940  if( pNew->iRowid==pIter->iSwitchRowid
193941   || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
193942  ){
193943    int i;
193944    Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
193945    pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
193946    for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
193947      Fts5CResult *pRes = &pIter->aFirst[i];
193948
193949      assert( pNew->pLeaf );
193950      assert( pRes->bTermEq==0 || pOther->pLeaf );
193951
193952      if( pRes->bTermEq ){
193953        if( pNew->iRowid==pOther->iRowid ){
193954          return 1;
193955        }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
193956          pIter->iSwitchRowid = pOther->iRowid;
193957          pNew = pOther;
193958        }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
193959          pIter->iSwitchRowid = pOther->iRowid;
193960        }
193961      }
193962      pRes->iFirst = (u16)(pNew - pIter->aSeg);
193963      if( i==1 ) break;
193964
193965      pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
193966    }
193967  }
193968
193969  *ppFirst = pNew;
193970  return 0;
193971}
193972
193973/*
193974** Set the pIter->bEof variable based on the state of the sub-iterators.
193975*/
193976static void fts5MultiIterSetEof(Fts5Iter *pIter){
193977  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
193978  pIter->base.bEof = pSeg->pLeaf==0;
193979  pIter->iSwitchRowid = pSeg->iRowid;
193980}
193981
193982/*
193983** Move the iterator to the next entry.
193984**
193985** If an error occurs, an error code is left in Fts5Index.rc. It is not
193986** considered an error if the iterator reaches EOF, or if it is already at
193987** EOF when this function is called.
193988*/
193989static void fts5MultiIterNext(
193990  Fts5Index *p,
193991  Fts5Iter *pIter,
193992  int bFrom,                      /* True if argument iFrom is valid */
193993  i64 iFrom                       /* Advance at least as far as this */
193994){
193995  int bUseFrom = bFrom;
193996  assert( pIter->base.bEof==0 );
193997  while( p->rc==SQLITE_OK ){
193998    int iFirst = pIter->aFirst[1].iFirst;
193999    int bNewTerm = 0;
194000    Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
194001    assert( p->rc==SQLITE_OK );
194002    if( bUseFrom && pSeg->pDlidx ){
194003      fts5SegIterNextFrom(p, pSeg, iFrom);
194004    }else{
194005      pSeg->xNext(p, pSeg, &bNewTerm);
194006    }
194007
194008    if( pSeg->pLeaf==0 || bNewTerm
194009     || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
194010    ){
194011      fts5MultiIterAdvanced(p, pIter, iFirst, 1);
194012      fts5MultiIterSetEof(pIter);
194013      pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
194014      if( pSeg->pLeaf==0 ) return;
194015    }
194016
194017    fts5AssertMultiIterSetup(p, pIter);
194018    assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
194019    if( pIter->bSkipEmpty==0 || pSeg->nPos ){
194020      pIter->xSetOutputs(pIter, pSeg);
194021      return;
194022    }
194023    bUseFrom = 0;
194024  }
194025}
194026
194027static void fts5MultiIterNext2(
194028  Fts5Index *p,
194029  Fts5Iter *pIter,
194030  int *pbNewTerm                  /* OUT: True if *might* be new term */
194031){
194032  assert( pIter->bSkipEmpty );
194033  if( p->rc==SQLITE_OK ){
194034    *pbNewTerm = 0;
194035    do{
194036      int iFirst = pIter->aFirst[1].iFirst;
194037      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
194038      int bNewTerm = 0;
194039
194040      assert( p->rc==SQLITE_OK );
194041      pSeg->xNext(p, pSeg, &bNewTerm);
194042      if( pSeg->pLeaf==0 || bNewTerm
194043       || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
194044      ){
194045        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
194046        fts5MultiIterSetEof(pIter);
194047        *pbNewTerm = 1;
194048      }
194049      fts5AssertMultiIterSetup(p, pIter);
194050
194051    }while( fts5MultiIterIsEmpty(p, pIter) );
194052  }
194053}
194054
194055static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
194056  UNUSED_PARAM2(pUnused1, pUnused2);
194057}
194058
194059static Fts5Iter *fts5MultiIterAlloc(
194060  Fts5Index *p,                   /* FTS5 backend to iterate within */
194061  int nSeg
194062){
194063  Fts5Iter *pNew;
194064  int nSlot;                      /* Power of two >= nSeg */
194065
194066  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
194067  pNew = fts5IdxMalloc(p,
194068      sizeof(Fts5Iter) +                  /* pNew */
194069      sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
194070      sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
194071  );
194072  if( pNew ){
194073    pNew->nSeg = nSlot;
194074    pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
194075    pNew->pIndex = p;
194076    pNew->xSetOutputs = fts5IterSetOutputs_Noop;
194077  }
194078  return pNew;
194079}
194080
194081static void fts5PoslistCallback(
194082  Fts5Index *pUnused,
194083  void *pContext,
194084  const u8 *pChunk, int nChunk
194085){
194086  UNUSED_PARAM(pUnused);
194087  assert_nc( nChunk>=0 );
194088  if( nChunk>0 ){
194089    fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
194090  }
194091}
194092
194093typedef struct PoslistCallbackCtx PoslistCallbackCtx;
194094struct PoslistCallbackCtx {
194095  Fts5Buffer *pBuf;               /* Append to this buffer */
194096  Fts5Colset *pColset;            /* Restrict matches to this column */
194097  int eState;                     /* See above */
194098};
194099
194100typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
194101struct PoslistOffsetsCtx {
194102  Fts5Buffer *pBuf;               /* Append to this buffer */
194103  Fts5Colset *pColset;            /* Restrict matches to this column */
194104  int iRead;
194105  int iWrite;
194106};
194107
194108/*
194109** TODO: Make this more efficient!
194110*/
194111static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
194112  int i;
194113  for(i=0; i<pColset->nCol; i++){
194114    if( pColset->aiCol[i]==iCol ) return 1;
194115  }
194116  return 0;
194117}
194118
194119static void fts5PoslistOffsetsCallback(
194120  Fts5Index *pUnused,
194121  void *pContext,
194122  const u8 *pChunk, int nChunk
194123){
194124  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
194125  UNUSED_PARAM(pUnused);
194126  assert_nc( nChunk>=0 );
194127  if( nChunk>0 ){
194128    int i = 0;
194129    while( i<nChunk ){
194130      int iVal;
194131      i += fts5GetVarint32(&pChunk[i], iVal);
194132      iVal += pCtx->iRead - 2;
194133      pCtx->iRead = iVal;
194134      if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
194135        fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
194136        pCtx->iWrite = iVal;
194137      }
194138    }
194139  }
194140}
194141
194142static void fts5PoslistFilterCallback(
194143  Fts5Index *pUnused,
194144  void *pContext,
194145  const u8 *pChunk, int nChunk
194146){
194147  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
194148  UNUSED_PARAM(pUnused);
194149  assert_nc( nChunk>=0 );
194150  if( nChunk>0 ){
194151    /* Search through to find the first varint with value 1. This is the
194152    ** start of the next columns hits. */
194153    int i = 0;
194154    int iStart = 0;
194155
194156    if( pCtx->eState==2 ){
194157      int iCol;
194158      fts5FastGetVarint32(pChunk, i, iCol);
194159      if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
194160        pCtx->eState = 1;
194161        fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
194162      }else{
194163        pCtx->eState = 0;
194164      }
194165    }
194166
194167    do {
194168      while( i<nChunk && pChunk[i]!=0x01 ){
194169        while( pChunk[i] & 0x80 ) i++;
194170        i++;
194171      }
194172      if( pCtx->eState ){
194173        fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
194174      }
194175      if( i<nChunk ){
194176        int iCol;
194177        iStart = i;
194178        i++;
194179        if( i>=nChunk ){
194180          pCtx->eState = 2;
194181        }else{
194182          fts5FastGetVarint32(pChunk, i, iCol);
194183          pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
194184          if( pCtx->eState ){
194185            fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
194186            iStart = i;
194187          }
194188        }
194189      }
194190    }while( i<nChunk );
194191  }
194192}
194193
194194static void fts5ChunkIterate(
194195  Fts5Index *p,                   /* Index object */
194196  Fts5SegIter *pSeg,              /* Poslist of this iterator */
194197  void *pCtx,                     /* Context pointer for xChunk callback */
194198  void (*xChunk)(Fts5Index*, void*, const u8*, int)
194199){
194200  int nRem = pSeg->nPos;          /* Number of bytes still to come */
194201  Fts5Data *pData = 0;
194202  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
194203  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
194204  int pgno = pSeg->iLeafPgno;
194205  int pgnoSave = 0;
194206
194207  /* This function does notmwork with detail=none databases. */
194208  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
194209
194210  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
194211    pgnoSave = pgno+1;
194212  }
194213
194214  while( 1 ){
194215    xChunk(p, pCtx, pChunk, nChunk);
194216    nRem -= nChunk;
194217    fts5DataRelease(pData);
194218    if( nRem<=0 ){
194219      break;
194220    }else{
194221      pgno++;
194222      pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
194223      if( pData==0 ) break;
194224      pChunk = &pData->p[4];
194225      nChunk = MIN(nRem, pData->szLeaf - 4);
194226      if( pgno==pgnoSave ){
194227        assert( pSeg->pNextLeaf==0 );
194228        pSeg->pNextLeaf = pData;
194229        pData = 0;
194230      }
194231    }
194232  }
194233}
194234
194235/*
194236** Iterator pIter currently points to a valid entry (not EOF). This
194237** function appends the position list data for the current entry to
194238** buffer pBuf. It does not make a copy of the position-list size
194239** field.
194240*/
194241static void fts5SegiterPoslist(
194242  Fts5Index *p,
194243  Fts5SegIter *pSeg,
194244  Fts5Colset *pColset,
194245  Fts5Buffer *pBuf
194246){
194247  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
194248    if( pColset==0 ){
194249      fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
194250    }else{
194251      if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
194252        PoslistCallbackCtx sCtx;
194253        sCtx.pBuf = pBuf;
194254        sCtx.pColset = pColset;
194255        sCtx.eState = fts5IndexColsetTest(pColset, 0);
194256        assert( sCtx.eState==0 || sCtx.eState==1 );
194257        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
194258      }else{
194259        PoslistOffsetsCtx sCtx;
194260        memset(&sCtx, 0, sizeof(sCtx));
194261        sCtx.pBuf = pBuf;
194262        sCtx.pColset = pColset;
194263        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
194264      }
194265    }
194266  }
194267}
194268
194269/*
194270** IN/OUT parameter (*pa) points to a position list n bytes in size. If
194271** the position list contains entries for column iCol, then (*pa) is set
194272** to point to the sub-position-list for that column and the number of
194273** bytes in it returned. Or, if the argument position list does not
194274** contain any entries for column iCol, return 0.
194275*/
194276static int fts5IndexExtractCol(
194277  const u8 **pa,                  /* IN/OUT: Pointer to poslist */
194278  int n,                          /* IN: Size of poslist in bytes */
194279  int iCol                        /* Column to extract from poslist */
194280){
194281  int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
194282  const u8 *p = *pa;
194283  const u8 *pEnd = &p[n];         /* One byte past end of position list */
194284
194285  while( iCol>iCurrent ){
194286    /* Advance pointer p until it points to pEnd or an 0x01 byte that is
194287    ** not part of a varint. Note that it is not possible for a negative
194288    ** or extremely large varint to occur within an uncorrupted position
194289    ** list. So the last byte of each varint may be assumed to have a clear
194290    ** 0x80 bit.  */
194291    while( *p!=0x01 ){
194292      while( *p++ & 0x80 );
194293      if( p>=pEnd ) return 0;
194294    }
194295    *pa = p++;
194296    iCurrent = *p++;
194297    if( iCurrent & 0x80 ){
194298      p--;
194299      p += fts5GetVarint32(p, iCurrent);
194300    }
194301  }
194302  if( iCol!=iCurrent ) return 0;
194303
194304  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
194305  ** not part of a varint */
194306  while( p<pEnd && *p!=0x01 ){
194307    while( *p++ & 0x80 );
194308  }
194309
194310  return p - (*pa);
194311}
194312
194313static void fts5IndexExtractColset(
194314  int *pRc,
194315  Fts5Colset *pColset,            /* Colset to filter on */
194316  const u8 *pPos, int nPos,       /* Position list */
194317  Fts5Buffer *pBuf                /* Output buffer */
194318){
194319  if( *pRc==SQLITE_OK ){
194320    int i;
194321    fts5BufferZero(pBuf);
194322    for(i=0; i<pColset->nCol; i++){
194323      const u8 *pSub = pPos;
194324      int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
194325      if( nSub ){
194326        fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
194327      }
194328    }
194329  }
194330}
194331
194332/*
194333** xSetOutputs callback used by detail=none tables.
194334*/
194335static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
194336  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
194337  pIter->base.iRowid = pSeg->iRowid;
194338  pIter->base.nData = pSeg->nPos;
194339}
194340
194341/*
194342** xSetOutputs callback used by detail=full and detail=col tables when no
194343** column filters are specified.
194344*/
194345static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
194346  pIter->base.iRowid = pSeg->iRowid;
194347  pIter->base.nData = pSeg->nPos;
194348
194349  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
194350  assert( pIter->pColset==0 );
194351
194352  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
194353    /* All data is stored on the current page. Populate the output
194354    ** variables to point into the body of the page object. */
194355    pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
194356  }else{
194357    /* The data is distributed over two or more pages. Copy it into the
194358    ** Fts5Iter.poslist buffer and then set the output pointer to point
194359    ** to this buffer.  */
194360    fts5BufferZero(&pIter->poslist);
194361    fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
194362    pIter->base.pData = pIter->poslist.p;
194363  }
194364}
194365
194366/*
194367** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
194368** against no columns at all).
194369*/
194370static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
194371  UNUSED_PARAM(pSeg);
194372  pIter->base.nData = 0;
194373}
194374
194375/*
194376** xSetOutputs callback used by detail=col when there is a column filter
194377** and there are 100 or more columns. Also called as a fallback from
194378** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
194379*/
194380static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
194381  fts5BufferZero(&pIter->poslist);
194382  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
194383  pIter->base.iRowid = pSeg->iRowid;
194384  pIter->base.pData = pIter->poslist.p;
194385  pIter->base.nData = pIter->poslist.n;
194386}
194387
194388/*
194389** xSetOutputs callback used when:
194390**
194391**   * detail=col,
194392**   * there is a column filter, and
194393**   * the table contains 100 or fewer columns.
194394**
194395** The last point is to ensure all column numbers are stored as
194396** single-byte varints.
194397*/
194398static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
194399
194400  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
194401  assert( pIter->pColset );
194402
194403  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
194404    fts5IterSetOutputs_Col(pIter, pSeg);
194405  }else{
194406    u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
194407    u8 *pEnd = (u8*)&a[pSeg->nPos];
194408    int iPrev = 0;
194409    int *aiCol = pIter->pColset->aiCol;
194410    int *aiColEnd = &aiCol[pIter->pColset->nCol];
194411
194412    u8 *aOut = pIter->poslist.p;
194413    int iPrevOut = 0;
194414
194415    pIter->base.iRowid = pSeg->iRowid;
194416
194417    while( a<pEnd ){
194418      iPrev += (int)a++[0] - 2;
194419      while( *aiCol<iPrev ){
194420        aiCol++;
194421        if( aiCol==aiColEnd ) goto setoutputs_col_out;
194422      }
194423      if( *aiCol==iPrev ){
194424        *aOut++ = (u8)((iPrev - iPrevOut) + 2);
194425        iPrevOut = iPrev;
194426      }
194427    }
194428
194429setoutputs_col_out:
194430    pIter->base.pData = pIter->poslist.p;
194431    pIter->base.nData = aOut - pIter->poslist.p;
194432  }
194433}
194434
194435/*
194436** xSetOutputs callback used by detail=full when there is a column filter.
194437*/
194438static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
194439  Fts5Colset *pColset = pIter->pColset;
194440  pIter->base.iRowid = pSeg->iRowid;
194441
194442  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
194443  assert( pColset );
194444
194445  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
194446    /* All data is stored on the current page. Populate the output
194447    ** variables to point into the body of the page object. */
194448    const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
194449    if( pColset->nCol==1 ){
194450      pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
194451      pIter->base.pData = a;
194452    }else{
194453      int *pRc = &pIter->pIndex->rc;
194454      fts5BufferZero(&pIter->poslist);
194455      fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
194456      pIter->base.pData = pIter->poslist.p;
194457      pIter->base.nData = pIter->poslist.n;
194458    }
194459  }else{
194460    /* The data is distributed over two or more pages. Copy it into the
194461    ** Fts5Iter.poslist buffer and then set the output pointer to point
194462    ** to this buffer.  */
194463    fts5BufferZero(&pIter->poslist);
194464    fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
194465    pIter->base.pData = pIter->poslist.p;
194466    pIter->base.nData = pIter->poslist.n;
194467  }
194468}
194469
194470static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
194471  if( *pRc==SQLITE_OK ){
194472    Fts5Config *pConfig = pIter->pIndex->pConfig;
194473    if( pConfig->eDetail==FTS5_DETAIL_NONE ){
194474      pIter->xSetOutputs = fts5IterSetOutputs_None;
194475    }
194476
194477    else if( pIter->pColset==0 ){
194478      pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
194479    }
194480
194481    else if( pIter->pColset->nCol==0 ){
194482      pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
194483    }
194484
194485    else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
194486      pIter->xSetOutputs = fts5IterSetOutputs_Full;
194487    }
194488
194489    else{
194490      assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
194491      if( pConfig->nCol<=100 ){
194492        pIter->xSetOutputs = fts5IterSetOutputs_Col100;
194493        sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
194494      }else{
194495        pIter->xSetOutputs = fts5IterSetOutputs_Col;
194496      }
194497    }
194498  }
194499}
194500
194501
194502/*
194503** Allocate a new Fts5Iter object.
194504**
194505** The new object will be used to iterate through data in structure pStruct.
194506** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
194507** is zero or greater, data from the first nSegment segments on level iLevel
194508** is merged.
194509**
194510** The iterator initially points to the first term/rowid entry in the
194511** iterated data.
194512*/
194513static void fts5MultiIterNew(
194514  Fts5Index *p,                   /* FTS5 backend to iterate within */
194515  Fts5Structure *pStruct,         /* Structure of specific index */
194516  int flags,                      /* FTS5INDEX_QUERY_XXX flags */
194517  Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
194518  const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
194519  int iLevel,                     /* Level to iterate (-1 for all) */
194520  int nSegment,                   /* Number of segments to merge (iLevel>=0) */
194521  Fts5Iter **ppOut                /* New object */
194522){
194523  int nSeg = 0;                   /* Number of segment-iters in use */
194524  int iIter = 0;                  /* */
194525  int iSeg;                       /* Used to iterate through segments */
194526  Fts5StructureLevel *pLvl;
194527  Fts5Iter *pNew;
194528
194529  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
194530
194531  /* Allocate space for the new multi-seg-iterator. */
194532  if( p->rc==SQLITE_OK ){
194533    if( iLevel<0 ){
194534      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
194535      nSeg = pStruct->nSegment;
194536      nSeg += (p->pHash ? 1 : 0);
194537    }else{
194538      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
194539    }
194540  }
194541  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
194542  if( pNew==0 ) return;
194543  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
194544  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
194545  pNew->pStruct = pStruct;
194546  pNew->pColset = pColset;
194547  fts5StructureRef(pStruct);
194548  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
194549    fts5IterSetOutputCb(&p->rc, pNew);
194550  }
194551
194552  /* Initialize each of the component segment iterators. */
194553  if( p->rc==SQLITE_OK ){
194554    if( iLevel<0 ){
194555      Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
194556      if( p->pHash ){
194557        /* Add a segment iterator for the current contents of the hash table. */
194558        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
194559        fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
194560      }
194561      for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
194562        for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
194563          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
194564          Fts5SegIter *pIter = &pNew->aSeg[iIter++];
194565          if( pTerm==0 ){
194566            fts5SegIterInit(p, pSeg, pIter);
194567          }else{
194568            fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
194569          }
194570        }
194571      }
194572    }else{
194573      pLvl = &pStruct->aLevel[iLevel];
194574      for(iSeg=nSeg-1; iSeg>=0; iSeg--){
194575        fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
194576      }
194577    }
194578    assert( iIter==nSeg );
194579  }
194580
194581  /* If the above was successful, each component iterators now points
194582  ** to the first entry in its segment. In this case initialize the
194583  ** aFirst[] array. Or, if an error has occurred, free the iterator
194584  ** object and set the output variable to NULL.  */
194585  if( p->rc==SQLITE_OK ){
194586    for(iIter=pNew->nSeg-1; iIter>0; iIter--){
194587      int iEq;
194588      if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
194589        Fts5SegIter *pSeg = &pNew->aSeg[iEq];
194590        if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
194591        fts5MultiIterAdvanced(p, pNew, iEq, iIter);
194592      }
194593    }
194594    fts5MultiIterSetEof(pNew);
194595    fts5AssertMultiIterSetup(p, pNew);
194596
194597    if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
194598      fts5MultiIterNext(p, pNew, 0, 0);
194599    }else if( pNew->base.bEof==0 ){
194600      Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
194601      pNew->xSetOutputs(pNew, pSeg);
194602    }
194603
194604  }else{
194605    fts5MultiIterFree(pNew);
194606    *ppOut = 0;
194607  }
194608}
194609
194610/*
194611** Create an Fts5Iter that iterates through the doclist provided
194612** as the second argument.
194613*/
194614static void fts5MultiIterNew2(
194615  Fts5Index *p,                   /* FTS5 backend to iterate within */
194616  Fts5Data *pData,                /* Doclist to iterate through */
194617  int bDesc,                      /* True for descending rowid order */
194618  Fts5Iter **ppOut                /* New object */
194619){
194620  Fts5Iter *pNew;
194621  pNew = fts5MultiIterAlloc(p, 2);
194622  if( pNew ){
194623    Fts5SegIter *pIter = &pNew->aSeg[1];
194624
194625    pIter->flags = FTS5_SEGITER_ONETERM;
194626    if( pData->szLeaf>0 ){
194627      pIter->pLeaf = pData;
194628      pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
194629      pIter->iEndofDoclist = pData->nn;
194630      pNew->aFirst[1].iFirst = 1;
194631      if( bDesc ){
194632        pNew->bRev = 1;
194633        pIter->flags |= FTS5_SEGITER_REVERSE;
194634        fts5SegIterReverseInitPage(p, pIter);
194635      }else{
194636        fts5SegIterLoadNPos(p, pIter);
194637      }
194638      pData = 0;
194639    }else{
194640      pNew->base.bEof = 1;
194641    }
194642    fts5SegIterSetNext(p, pIter);
194643
194644    *ppOut = pNew;
194645  }
194646
194647  fts5DataRelease(pData);
194648}
194649
194650/*
194651** Return true if the iterator is at EOF or if an error has occurred.
194652** False otherwise.
194653*/
194654static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
194655  assert( p->rc
194656      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
194657  );
194658  return (p->rc || pIter->base.bEof);
194659}
194660
194661/*
194662** Return the rowid of the entry that the iterator currently points
194663** to. If the iterator points to EOF when this function is called the
194664** results are undefined.
194665*/
194666static i64 fts5MultiIterRowid(Fts5Iter *pIter){
194667  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
194668  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
194669}
194670
194671/*
194672** Move the iterator to the next entry at or following iMatch.
194673*/
194674static void fts5MultiIterNextFrom(
194675  Fts5Index *p,
194676  Fts5Iter *pIter,
194677  i64 iMatch
194678){
194679  while( 1 ){
194680    i64 iRowid;
194681    fts5MultiIterNext(p, pIter, 1, iMatch);
194682    if( fts5MultiIterEof(p, pIter) ) break;
194683    iRowid = fts5MultiIterRowid(pIter);
194684    if( pIter->bRev==0 && iRowid>=iMatch ) break;
194685    if( pIter->bRev!=0 && iRowid<=iMatch ) break;
194686  }
194687}
194688
194689/*
194690** Return a pointer to a buffer containing the term associated with the
194691** entry that the iterator currently points to.
194692*/
194693static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
194694  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
194695  *pn = p->term.n;
194696  return p->term.p;
194697}
194698
194699/*
194700** Allocate a new segment-id for the structure pStruct. The new segment
194701** id must be between 1 and 65335 inclusive, and must not be used by
194702** any currently existing segment. If a free segment id cannot be found,
194703** SQLITE_FULL is returned.
194704**
194705** If an error has already occurred, this function is a no-op. 0 is
194706** returned in this case.
194707*/
194708static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
194709  int iSegid = 0;
194710
194711  if( p->rc==SQLITE_OK ){
194712    if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
194713      p->rc = SQLITE_FULL;
194714    }else{
194715      /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
194716      ** array is 63 elements, or 252 bytes, in size.  */
194717      u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
194718      int iLvl, iSeg;
194719      int i;
194720      u32 mask;
194721      memset(aUsed, 0, sizeof(aUsed));
194722      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
194723        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
194724          int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
194725          if( iId<=FTS5_MAX_SEGMENT ){
194726            aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
194727          }
194728        }
194729      }
194730
194731      for(i=0; aUsed[i]==0xFFFFFFFF; i++);
194732      mask = aUsed[i];
194733      for(iSegid=0; mask & (1 << iSegid); iSegid++);
194734      iSegid += 1 + i*32;
194735
194736#ifdef SQLITE_DEBUG
194737      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
194738        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
194739          assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
194740        }
194741      }
194742      assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
194743
194744      {
194745        sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
194746        if( p->rc==SQLITE_OK ){
194747          u8 aBlob[2] = {0xff, 0xff};
194748          sqlite3_bind_int(pIdxSelect, 1, iSegid);
194749          sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
194750          assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
194751          p->rc = sqlite3_reset(pIdxSelect);
194752        }
194753      }
194754#endif
194755    }
194756  }
194757
194758  return iSegid;
194759}
194760
194761/*
194762** Discard all data currently cached in the hash-tables.
194763*/
194764static void fts5IndexDiscardData(Fts5Index *p){
194765  assert( p->pHash || p->nPendingData==0 );
194766  if( p->pHash ){
194767    sqlite3Fts5HashClear(p->pHash);
194768    p->nPendingData = 0;
194769  }
194770}
194771
194772/*
194773** Return the size of the prefix, in bytes, that buffer
194774** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
194775**
194776** Buffer (pNew/<length-unknown>) is guaranteed to be greater
194777** than buffer (pOld/nOld).
194778*/
194779static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
194780  int i;
194781  for(i=0; i<nOld; i++){
194782    if( pOld[i]!=pNew[i] ) break;
194783  }
194784  return i;
194785}
194786
194787static void fts5WriteDlidxClear(
194788  Fts5Index *p,
194789  Fts5SegWriter *pWriter,
194790  int bFlush                      /* If true, write dlidx to disk */
194791){
194792  int i;
194793  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
194794  for(i=0; i<pWriter->nDlidx; i++){
194795    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
194796    if( pDlidx->buf.n==0 ) break;
194797    if( bFlush ){
194798      assert( pDlidx->pgno!=0 );
194799      fts5DataWrite(p,
194800          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
194801          pDlidx->buf.p, pDlidx->buf.n
194802      );
194803    }
194804    sqlite3Fts5BufferZero(&pDlidx->buf);
194805    pDlidx->bPrevValid = 0;
194806  }
194807}
194808
194809/*
194810** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
194811** Any new array elements are zeroed before returning.
194812*/
194813static int fts5WriteDlidxGrow(
194814  Fts5Index *p,
194815  Fts5SegWriter *pWriter,
194816  int nLvl
194817){
194818  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
194819    Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
194820        pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
194821    );
194822    if( aDlidx==0 ){
194823      p->rc = SQLITE_NOMEM;
194824    }else{
194825      int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
194826      memset(&aDlidx[pWriter->nDlidx], 0, nByte);
194827      pWriter->aDlidx = aDlidx;
194828      pWriter->nDlidx = nLvl;
194829    }
194830  }
194831  return p->rc;
194832}
194833
194834/*
194835** If the current doclist-index accumulating in pWriter->aDlidx[] is large
194836** enough, flush it to disk and return 1. Otherwise discard it and return
194837** zero.
194838*/
194839static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
194840  int bFlag = 0;
194841
194842  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
194843  ** to the database, also write the doclist-index to disk.  */
194844  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
194845    bFlag = 1;
194846  }
194847  fts5WriteDlidxClear(p, pWriter, bFlag);
194848  pWriter->nEmpty = 0;
194849  return bFlag;
194850}
194851
194852/*
194853** This function is called whenever processing of the doclist for the
194854** last term on leaf page (pWriter->iBtPage) is completed.
194855**
194856** The doclist-index for that term is currently stored in-memory within the
194857** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
194858** writes it out to disk. Or, if it is too small to bother with, discards
194859** it.
194860**
194861** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
194862*/
194863static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
194864  int bFlag;
194865
194866  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
194867  if( pWriter->iBtPage==0 ) return;
194868  bFlag = fts5WriteFlushDlidx(p, pWriter);
194869
194870  if( p->rc==SQLITE_OK ){
194871    const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
194872    /* The following was already done in fts5WriteInit(): */
194873    /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
194874    sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
194875    sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
194876    sqlite3_step(p->pIdxWriter);
194877    p->rc = sqlite3_reset(p->pIdxWriter);
194878  }
194879  pWriter->iBtPage = 0;
194880}
194881
194882/*
194883** This is called once for each leaf page except the first that contains
194884** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
194885** is larger than all terms written to earlier leaves, and equal to or
194886** smaller than the first term on the new leaf.
194887**
194888** If an error occurs, an error code is left in Fts5Index.rc. If an error
194889** has already occurred when this function is called, it is a no-op.
194890*/
194891static void fts5WriteBtreeTerm(
194892  Fts5Index *p,                   /* FTS5 backend object */
194893  Fts5SegWriter *pWriter,         /* Writer object */
194894  int nTerm, const u8 *pTerm      /* First term on new page */
194895){
194896  fts5WriteFlushBtree(p, pWriter);
194897  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
194898  pWriter->iBtPage = pWriter->writer.pgno;
194899}
194900
194901/*
194902** This function is called when flushing a leaf page that contains no
194903** terms at all to disk.
194904*/
194905static void fts5WriteBtreeNoTerm(
194906  Fts5Index *p,                   /* FTS5 backend object */
194907  Fts5SegWriter *pWriter          /* Writer object */
194908){
194909  /* If there were no rowids on the leaf page either and the doclist-index
194910  ** has already been started, append an 0x00 byte to it.  */
194911  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
194912    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
194913    assert( pDlidx->bPrevValid );
194914    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
194915  }
194916
194917  /* Increment the "number of sequential leaves without a term" counter. */
194918  pWriter->nEmpty++;
194919}
194920
194921static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
194922  i64 iRowid;
194923  int iOff;
194924
194925  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
194926  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
194927  return iRowid;
194928}
194929
194930/*
194931** Rowid iRowid has just been appended to the current leaf page. It is the
194932** first on the page. This function appends an appropriate entry to the current
194933** doclist-index.
194934*/
194935static void fts5WriteDlidxAppend(
194936  Fts5Index *p,
194937  Fts5SegWriter *pWriter,
194938  i64 iRowid
194939){
194940  int i;
194941  int bDone = 0;
194942
194943  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
194944    i64 iVal;
194945    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
194946
194947    if( pDlidx->buf.n>=p->pConfig->pgsz ){
194948      /* The current doclist-index page is full. Write it to disk and push
194949      ** a copy of iRowid (which will become the first rowid on the next
194950      ** doclist-index leaf page) up into the next level of the b-tree
194951      ** hierarchy. If the node being flushed is currently the root node,
194952      ** also push its first rowid upwards. */
194953      pDlidx->buf.p[0] = 0x01;    /* Not the root node */
194954      fts5DataWrite(p,
194955          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
194956          pDlidx->buf.p, pDlidx->buf.n
194957      );
194958      fts5WriteDlidxGrow(p, pWriter, i+2);
194959      pDlidx = &pWriter->aDlidx[i];
194960      if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
194961        i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
194962
194963        /* This was the root node. Push its first rowid up to the new root. */
194964        pDlidx[1].pgno = pDlidx->pgno;
194965        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
194966        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
194967        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
194968        pDlidx[1].bPrevValid = 1;
194969        pDlidx[1].iPrev = iFirst;
194970      }
194971
194972      sqlite3Fts5BufferZero(&pDlidx->buf);
194973      pDlidx->bPrevValid = 0;
194974      pDlidx->pgno++;
194975    }else{
194976      bDone = 1;
194977    }
194978
194979    if( pDlidx->bPrevValid ){
194980      iVal = iRowid - pDlidx->iPrev;
194981    }else{
194982      i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
194983      assert( pDlidx->buf.n==0 );
194984      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
194985      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
194986      iVal = iRowid;
194987    }
194988
194989    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
194990    pDlidx->bPrevValid = 1;
194991    pDlidx->iPrev = iRowid;
194992  }
194993}
194994
194995static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
194996  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
194997  Fts5PageWriter *pPage = &pWriter->writer;
194998  i64 iRowid;
194999
195000  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
195001
195002  /* Set the szLeaf header field. */
195003  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
195004  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
195005
195006  if( pWriter->bFirstTermInPage ){
195007    /* No term was written to this page. */
195008    assert( pPage->pgidx.n==0 );
195009    fts5WriteBtreeNoTerm(p, pWriter);
195010  }else{
195011    /* Append the pgidx to the page buffer. Set the szLeaf header field. */
195012    fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
195013  }
195014
195015  /* Write the page out to disk */
195016  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
195017  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
195018
195019  /* Initialize the next page. */
195020  fts5BufferZero(&pPage->buf);
195021  fts5BufferZero(&pPage->pgidx);
195022  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
195023  pPage->iPrevPgidx = 0;
195024  pPage->pgno++;
195025
195026  /* Increase the leaves written counter */
195027  pWriter->nLeafWritten++;
195028
195029  /* The new leaf holds no terms or rowids */
195030  pWriter->bFirstTermInPage = 1;
195031  pWriter->bFirstRowidInPage = 1;
195032}
195033
195034/*
195035** Append term pTerm/nTerm to the segment being written by the writer passed
195036** as the second argument.
195037**
195038** If an error occurs, set the Fts5Index.rc error code. If an error has
195039** already occurred, this function is a no-op.
195040*/
195041static void fts5WriteAppendTerm(
195042  Fts5Index *p,
195043  Fts5SegWriter *pWriter,
195044  int nTerm, const u8 *pTerm
195045){
195046  int nPrefix;                    /* Bytes of prefix compression for term */
195047  Fts5PageWriter *pPage = &pWriter->writer;
195048  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
195049
195050  assert( p->rc==SQLITE_OK );
195051  assert( pPage->buf.n>=4 );
195052  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
195053
195054  /* If the current leaf page is full, flush it to disk. */
195055  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
195056    if( pPage->buf.n>4 ){
195057      fts5WriteFlushLeaf(p, pWriter);
195058    }
195059    fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
195060  }
195061
195062  /* TODO1: Updating pgidx here. */
195063  pPgidx->n += sqlite3Fts5PutVarint(
195064      &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
195065  );
195066  pPage->iPrevPgidx = pPage->buf.n;
195067#if 0
195068  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
195069  pPgidx->n += 2;
195070#endif
195071
195072  if( pWriter->bFirstTermInPage ){
195073    nPrefix = 0;
195074    if( pPage->pgno!=1 ){
195075      /* This is the first term on a leaf that is not the leftmost leaf in
195076      ** the segment b-tree. In this case it is necessary to add a term to
195077      ** the b-tree hierarchy that is (a) larger than the largest term
195078      ** already written to the segment and (b) smaller than or equal to
195079      ** this term. In other words, a prefix of (pTerm/nTerm) that is one
195080      ** byte longer than the longest prefix (pTerm/nTerm) shares with the
195081      ** previous term.
195082      **
195083      ** Usually, the previous term is available in pPage->term. The exception
195084      ** is if this is the first term written in an incremental-merge step.
195085      ** In this case the previous term is not available, so just write a
195086      ** copy of (pTerm/nTerm) into the parent node. This is slightly
195087      ** inefficient, but still correct.  */
195088      int n = nTerm;
195089      if( pPage->term.n ){
195090        n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
195091      }
195092      fts5WriteBtreeTerm(p, pWriter, n, pTerm);
195093      pPage = &pWriter->writer;
195094    }
195095  }else{
195096    nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
195097    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
195098  }
195099
195100  /* Append the number of bytes of new data, then the term data itself
195101  ** to the page. */
195102  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
195103  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
195104
195105  /* Update the Fts5PageWriter.term field. */
195106  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
195107  pWriter->bFirstTermInPage = 0;
195108
195109  pWriter->bFirstRowidInPage = 0;
195110  pWriter->bFirstRowidInDoclist = 1;
195111
195112  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
195113  pWriter->aDlidx[0].pgno = pPage->pgno;
195114}
195115
195116/*
195117** Append a rowid and position-list size field to the writers output.
195118*/
195119static void fts5WriteAppendRowid(
195120  Fts5Index *p,
195121  Fts5SegWriter *pWriter,
195122  i64 iRowid
195123){
195124  if( p->rc==SQLITE_OK ){
195125    Fts5PageWriter *pPage = &pWriter->writer;
195126
195127    if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
195128      fts5WriteFlushLeaf(p, pWriter);
195129    }
195130
195131    /* If this is to be the first rowid written to the page, set the
195132    ** rowid-pointer in the page-header. Also append a value to the dlidx
195133    ** buffer, in case a doclist-index is required.  */
195134    if( pWriter->bFirstRowidInPage ){
195135      fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
195136      fts5WriteDlidxAppend(p, pWriter, iRowid);
195137    }
195138
195139    /* Write the rowid. */
195140    if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
195141      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
195142    }else{
195143      assert( p->rc || iRowid>pWriter->iPrevRowid );
195144      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
195145    }
195146    pWriter->iPrevRowid = iRowid;
195147    pWriter->bFirstRowidInDoclist = 0;
195148    pWriter->bFirstRowidInPage = 0;
195149  }
195150}
195151
195152static void fts5WriteAppendPoslistData(
195153  Fts5Index *p,
195154  Fts5SegWriter *pWriter,
195155  const u8 *aData,
195156  int nData
195157){
195158  Fts5PageWriter *pPage = &pWriter->writer;
195159  const u8 *a = aData;
195160  int n = nData;
195161
195162  assert( p->pConfig->pgsz>0 );
195163  while( p->rc==SQLITE_OK
195164     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
195165  ){
195166    int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
195167    int nCopy = 0;
195168    while( nCopy<nReq ){
195169      i64 dummy;
195170      nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
195171    }
195172    fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
195173    a += nCopy;
195174    n -= nCopy;
195175    fts5WriteFlushLeaf(p, pWriter);
195176  }
195177  if( n>0 ){
195178    fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
195179  }
195180}
195181
195182/*
195183** Flush any data cached by the writer object to the database. Free any
195184** allocations associated with the writer.
195185*/
195186static void fts5WriteFinish(
195187  Fts5Index *p,
195188  Fts5SegWriter *pWriter,         /* Writer object */
195189  int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
195190){
195191  int i;
195192  Fts5PageWriter *pLeaf = &pWriter->writer;
195193  if( p->rc==SQLITE_OK ){
195194    assert( pLeaf->pgno>=1 );
195195    if( pLeaf->buf.n>4 ){
195196      fts5WriteFlushLeaf(p, pWriter);
195197    }
195198    *pnLeaf = pLeaf->pgno-1;
195199    if( pLeaf->pgno>1 ){
195200      fts5WriteFlushBtree(p, pWriter);
195201    }
195202  }
195203  fts5BufferFree(&pLeaf->term);
195204  fts5BufferFree(&pLeaf->buf);
195205  fts5BufferFree(&pLeaf->pgidx);
195206  fts5BufferFree(&pWriter->btterm);
195207
195208  for(i=0; i<pWriter->nDlidx; i++){
195209    sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
195210  }
195211  sqlite3_free(pWriter->aDlidx);
195212}
195213
195214static void fts5WriteInit(
195215  Fts5Index *p,
195216  Fts5SegWriter *pWriter,
195217  int iSegid
195218){
195219  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
195220
195221  memset(pWriter, 0, sizeof(Fts5SegWriter));
195222  pWriter->iSegid = iSegid;
195223
195224  fts5WriteDlidxGrow(p, pWriter, 1);
195225  pWriter->writer.pgno = 1;
195226  pWriter->bFirstTermInPage = 1;
195227  pWriter->iBtPage = 1;
195228
195229  assert( pWriter->writer.buf.n==0 );
195230  assert( pWriter->writer.pgidx.n==0 );
195231
195232  /* Grow the two buffers to pgsz + padding bytes in size. */
195233  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
195234  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
195235
195236  if( p->pIdxWriter==0 ){
195237    Fts5Config *pConfig = p->pConfig;
195238    fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
195239          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
195240          pConfig->zDb, pConfig->zName
195241    ));
195242  }
195243
195244  if( p->rc==SQLITE_OK ){
195245    /* Initialize the 4-byte leaf-page header to 0x00. */
195246    memset(pWriter->writer.buf.p, 0, 4);
195247    pWriter->writer.buf.n = 4;
195248
195249    /* Bind the current output segment id to the index-writer. This is an
195250    ** optimization over binding the same value over and over as rows are
195251    ** inserted into %_idx by the current writer.  */
195252    sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
195253  }
195254}
195255
195256/*
195257** Iterator pIter was used to iterate through the input segments of on an
195258** incremental merge operation. This function is called if the incremental
195259** merge step has finished but the input has not been completely exhausted.
195260*/
195261static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
195262  int i;
195263  Fts5Buffer buf;
195264  memset(&buf, 0, sizeof(Fts5Buffer));
195265  for(i=0; i<pIter->nSeg; i++){
195266    Fts5SegIter *pSeg = &pIter->aSeg[i];
195267    if( pSeg->pSeg==0 ){
195268      /* no-op */
195269    }else if( pSeg->pLeaf==0 ){
195270      /* All keys from this input segment have been transfered to the output.
195271      ** Set both the first and last page-numbers to 0 to indicate that the
195272      ** segment is now empty. */
195273      pSeg->pSeg->pgnoLast = 0;
195274      pSeg->pSeg->pgnoFirst = 0;
195275    }else{
195276      int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
195277      i64 iLeafRowid;
195278      Fts5Data *pData;
195279      int iId = pSeg->pSeg->iSegid;
195280      u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
195281
195282      iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
195283      pData = fts5DataRead(p, iLeafRowid);
195284      if( pData ){
195285        fts5BufferZero(&buf);
195286        fts5BufferGrow(&p->rc, &buf, pData->nn);
195287        fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
195288        fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
195289        fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
195290        fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
195291        if( p->rc==SQLITE_OK ){
195292          /* Set the szLeaf field */
195293          fts5PutU16(&buf.p[2], (u16)buf.n);
195294        }
195295
195296        /* Set up the new page-index array */
195297        fts5BufferAppendVarint(&p->rc, &buf, 4);
195298        if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
195299         && pSeg->iEndofDoclist<pData->szLeaf
195300        ){
195301          int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
195302          fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
195303          fts5BufferAppendBlob(&p->rc, &buf,
195304              pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
195305          );
195306        }
195307
195308        fts5DataRelease(pData);
195309        pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
195310        fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
195311        fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
195312      }
195313    }
195314  }
195315  fts5BufferFree(&buf);
195316}
195317
195318static void fts5MergeChunkCallback(
195319  Fts5Index *p,
195320  void *pCtx,
195321  const u8 *pChunk, int nChunk
195322){
195323  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
195324  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
195325}
195326
195327/*
195328**
195329*/
195330static void fts5IndexMergeLevel(
195331  Fts5Index *p,                   /* FTS5 backend object */
195332  Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
195333  int iLvl,                       /* Level to read input from */
195334  int *pnRem                      /* Write up to this many output leaves */
195335){
195336  Fts5Structure *pStruct = *ppStruct;
195337  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
195338  Fts5StructureLevel *pLvlOut;
195339  Fts5Iter *pIter = 0;       /* Iterator to read input data */
195340  int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
195341  int nInput;                     /* Number of input segments */
195342  Fts5SegWriter writer;           /* Writer object */
195343  Fts5StructureSegment *pSeg;     /* Output segment */
195344  Fts5Buffer term;
195345  int bOldest;                    /* True if the output segment is the oldest */
195346  int eDetail = p->pConfig->eDetail;
195347  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
195348  int bTermWritten = 0;           /* True if current term already output */
195349
195350  assert( iLvl<pStruct->nLevel );
195351  assert( pLvl->nMerge<=pLvl->nSeg );
195352
195353  memset(&writer, 0, sizeof(Fts5SegWriter));
195354  memset(&term, 0, sizeof(Fts5Buffer));
195355  if( pLvl->nMerge ){
195356    pLvlOut = &pStruct->aLevel[iLvl+1];
195357    assert( pLvlOut->nSeg>0 );
195358    nInput = pLvl->nMerge;
195359    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
195360
195361    fts5WriteInit(p, &writer, pSeg->iSegid);
195362    writer.writer.pgno = pSeg->pgnoLast+1;
195363    writer.iBtPage = 0;
195364  }else{
195365    int iSegid = fts5AllocateSegid(p, pStruct);
195366
195367    /* Extend the Fts5Structure object as required to ensure the output
195368    ** segment exists. */
195369    if( iLvl==pStruct->nLevel-1 ){
195370      fts5StructureAddLevel(&p->rc, ppStruct);
195371      pStruct = *ppStruct;
195372    }
195373    fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
195374    if( p->rc ) return;
195375    pLvl = &pStruct->aLevel[iLvl];
195376    pLvlOut = &pStruct->aLevel[iLvl+1];
195377
195378    fts5WriteInit(p, &writer, iSegid);
195379
195380    /* Add the new segment to the output level */
195381    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
195382    pLvlOut->nSeg++;
195383    pSeg->pgnoFirst = 1;
195384    pSeg->iSegid = iSegid;
195385    pStruct->nSegment++;
195386
195387    /* Read input from all segments in the input level */
195388    nInput = pLvl->nSeg;
195389  }
195390  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
195391
195392  assert( iLvl>=0 );
195393  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
195394      fts5MultiIterEof(p, pIter)==0;
195395      fts5MultiIterNext(p, pIter, 0, 0)
195396  ){
195397    Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
195398    int nPos;                     /* position-list size field value */
195399    int nTerm;
195400    const u8 *pTerm;
195401
195402    pTerm = fts5MultiIterTerm(pIter, &nTerm);
195403    if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
195404      if( pnRem && writer.nLeafWritten>nRem ){
195405        break;
195406      }
195407      fts5BufferSet(&p->rc, &term, nTerm, pTerm);
195408      bTermWritten =0;
195409    }
195410
195411    /* Check for key annihilation. */
195412    if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
195413
195414    if( p->rc==SQLITE_OK && bTermWritten==0 ){
195415      /* This is a new term. Append a term to the output segment. */
195416      fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
195417      bTermWritten = 1;
195418    }
195419
195420    /* Append the rowid to the output */
195421    /* WRITEPOSLISTSIZE */
195422    fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
195423
195424    if( eDetail==FTS5_DETAIL_NONE ){
195425      if( pSegIter->bDel ){
195426        fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
195427        if( pSegIter->nPos>0 ){
195428          fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
195429        }
195430      }
195431    }else{
195432      /* Append the position-list data to the output */
195433      nPos = pSegIter->nPos*2 + pSegIter->bDel;
195434      fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
195435      fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
195436    }
195437  }
195438
195439  /* Flush the last leaf page to disk. Set the output segment b-tree height
195440  ** and last leaf page number at the same time.  */
195441  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
195442
195443  if( fts5MultiIterEof(p, pIter) ){
195444    int i;
195445
195446    /* Remove the redundant segments from the %_data table */
195447    for(i=0; i<nInput; i++){
195448      fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
195449    }
195450
195451    /* Remove the redundant segments from the input level */
195452    if( pLvl->nSeg!=nInput ){
195453      int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
195454      memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
195455    }
195456    pStruct->nSegment -= nInput;
195457    pLvl->nSeg -= nInput;
195458    pLvl->nMerge = 0;
195459    if( pSeg->pgnoLast==0 ){
195460      pLvlOut->nSeg--;
195461      pStruct->nSegment--;
195462    }
195463  }else{
195464    assert( pSeg->pgnoLast>0 );
195465    fts5TrimSegments(p, pIter);
195466    pLvl->nMerge = nInput;
195467  }
195468
195469  fts5MultiIterFree(pIter);
195470  fts5BufferFree(&term);
195471  if( pnRem ) *pnRem -= writer.nLeafWritten;
195472}
195473
195474/*
195475** Do up to nPg pages of automerge work on the index.
195476**
195477** Return true if any changes were actually made, or false otherwise.
195478*/
195479static int fts5IndexMerge(
195480  Fts5Index *p,                   /* FTS5 backend object */
195481  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
195482  int nPg,                        /* Pages of work to do */
195483  int nMin                        /* Minimum number of segments to merge */
195484){
195485  int nRem = nPg;
195486  int bRet = 0;
195487  Fts5Structure *pStruct = *ppStruct;
195488  while( nRem>0 && p->rc==SQLITE_OK ){
195489    int iLvl;                   /* To iterate through levels */
195490    int iBestLvl = 0;           /* Level offering the most input segments */
195491    int nBest = 0;              /* Number of input segments on best level */
195492
195493    /* Set iBestLvl to the level to read input segments from. */
195494    assert( pStruct->nLevel>0 );
195495    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
195496      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
195497      if( pLvl->nMerge ){
195498        if( pLvl->nMerge>nBest ){
195499          iBestLvl = iLvl;
195500          nBest = pLvl->nMerge;
195501        }
195502        break;
195503      }
195504      if( pLvl->nSeg>nBest ){
195505        nBest = pLvl->nSeg;
195506        iBestLvl = iLvl;
195507      }
195508    }
195509
195510    /* If nBest is still 0, then the index must be empty. */
195511#ifdef SQLITE_DEBUG
195512    for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
195513      assert( pStruct->aLevel[iLvl].nSeg==0 );
195514    }
195515#endif
195516
195517    if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
195518      break;
195519    }
195520    bRet = 1;
195521    fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
195522    if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
195523      fts5StructurePromote(p, iBestLvl+1, pStruct);
195524    }
195525  }
195526  *ppStruct = pStruct;
195527  return bRet;
195528}
195529
195530/*
195531** A total of nLeaf leaf pages of data has just been flushed to a level-0
195532** segment. This function updates the write-counter accordingly and, if
195533** necessary, performs incremental merge work.
195534**
195535** If an error occurs, set the Fts5Index.rc error code. If an error has
195536** already occurred, this function is a no-op.
195537*/
195538static void fts5IndexAutomerge(
195539  Fts5Index *p,                   /* FTS5 backend object */
195540  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
195541  int nLeaf                       /* Number of output leaves just written */
195542){
195543  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
195544    Fts5Structure *pStruct = *ppStruct;
195545    u64 nWrite;                   /* Initial value of write-counter */
195546    int nWork;                    /* Number of work-quanta to perform */
195547    int nRem;                     /* Number of leaf pages left to write */
195548
195549    /* Update the write-counter. While doing so, set nWork. */
195550    nWrite = pStruct->nWriteCounter;
195551    nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
195552    pStruct->nWriteCounter += nLeaf;
195553    nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
195554
195555    fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
195556  }
195557}
195558
195559static void fts5IndexCrisismerge(
195560  Fts5Index *p,                   /* FTS5 backend object */
195561  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
195562){
195563  const int nCrisis = p->pConfig->nCrisisMerge;
195564  Fts5Structure *pStruct = *ppStruct;
195565  int iLvl = 0;
195566
195567  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
195568  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
195569    fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
195570    assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
195571    fts5StructurePromote(p, iLvl+1, pStruct);
195572    iLvl++;
195573  }
195574  *ppStruct = pStruct;
195575}
195576
195577static int fts5IndexReturn(Fts5Index *p){
195578  int rc = p->rc;
195579  p->rc = SQLITE_OK;
195580  return rc;
195581}
195582
195583typedef struct Fts5FlushCtx Fts5FlushCtx;
195584struct Fts5FlushCtx {
195585  Fts5Index *pIdx;
195586  Fts5SegWriter writer;
195587};
195588
195589/*
195590** Buffer aBuf[] contains a list of varints, all small enough to fit
195591** in a 32-bit integer. Return the size of the largest prefix of this
195592** list nMax bytes or less in size.
195593*/
195594static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
195595  int ret;
195596  u32 dummy;
195597  ret = fts5GetVarint32(aBuf, dummy);
195598  if( ret<nMax ){
195599    while( 1 ){
195600      int i = fts5GetVarint32(&aBuf[ret], dummy);
195601      if( (ret + i) > nMax ) break;
195602      ret += i;
195603    }
195604  }
195605  return ret;
195606}
195607
195608/*
195609** Flush the contents of in-memory hash table iHash to a new level-0
195610** segment on disk. Also update the corresponding structure record.
195611**
195612** If an error occurs, set the Fts5Index.rc error code. If an error has
195613** already occurred, this function is a no-op.
195614*/
195615static void fts5FlushOneHash(Fts5Index *p){
195616  Fts5Hash *pHash = p->pHash;
195617  Fts5Structure *pStruct;
195618  int iSegid;
195619  int pgnoLast = 0;                 /* Last leaf page number in segment */
195620
195621  /* Obtain a reference to the index structure and allocate a new segment-id
195622  ** for the new level-0 segment.  */
195623  pStruct = fts5StructureRead(p);
195624  iSegid = fts5AllocateSegid(p, pStruct);
195625  fts5StructureInvalidate(p);
195626
195627  if( iSegid ){
195628    const int pgsz = p->pConfig->pgsz;
195629    int eDetail = p->pConfig->eDetail;
195630    Fts5StructureSegment *pSeg;   /* New segment within pStruct */
195631    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
195632    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
195633
195634    Fts5SegWriter writer;
195635    fts5WriteInit(p, &writer, iSegid);
195636
195637    pBuf = &writer.writer.buf;
195638    pPgidx = &writer.writer.pgidx;
195639
195640    /* fts5WriteInit() should have initialized the buffers to (most likely)
195641    ** the maximum space required. */
195642    assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
195643    assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
195644
195645    /* Begin scanning through hash table entries. This loop runs once for each
195646    ** term/doclist currently stored within the hash table. */
195647    if( p->rc==SQLITE_OK ){
195648      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
195649    }
195650    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
195651      const char *zTerm;          /* Buffer containing term */
195652      const u8 *pDoclist;         /* Pointer to doclist for this term */
195653      int nDoclist;               /* Size of doclist in bytes */
195654
195655      /* Write the term for this entry to disk. */
195656      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
195657      fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
195658
195659      assert( writer.bFirstRowidInPage==0 );
195660      if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
195661        /* The entire doclist will fit on the current leaf. */
195662        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
195663      }else{
195664        i64 iRowid = 0;
195665        i64 iDelta = 0;
195666        int iOff = 0;
195667
195668        /* The entire doclist will not fit on this leaf. The following
195669        ** loop iterates through the poslists that make up the current
195670        ** doclist.  */
195671        while( p->rc==SQLITE_OK && iOff<nDoclist ){
195672          iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
195673          iRowid += iDelta;
195674
195675          if( writer.bFirstRowidInPage ){
195676            fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
195677            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
195678            writer.bFirstRowidInPage = 0;
195679            fts5WriteDlidxAppend(p, &writer, iRowid);
195680          }else{
195681            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
195682          }
195683          assert( pBuf->n<=pBuf->nSpace );
195684
195685          if( eDetail==FTS5_DETAIL_NONE ){
195686            if( iOff<nDoclist && pDoclist[iOff]==0 ){
195687              pBuf->p[pBuf->n++] = 0;
195688              iOff++;
195689              if( iOff<nDoclist && pDoclist[iOff]==0 ){
195690                pBuf->p[pBuf->n++] = 0;
195691                iOff++;
195692              }
195693            }
195694            if( (pBuf->n + pPgidx->n)>=pgsz ){
195695              fts5WriteFlushLeaf(p, &writer);
195696            }
195697          }else{
195698            int bDummy;
195699            int nPos;
195700            int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
195701            nCopy += nPos;
195702            if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
195703              /* The entire poslist will fit on the current leaf. So copy
195704              ** it in one go. */
195705              fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
195706            }else{
195707              /* The entire poslist will not fit on this leaf. So it needs
195708              ** to be broken into sections. The only qualification being
195709              ** that each varint must be stored contiguously.  */
195710              const u8 *pPoslist = &pDoclist[iOff];
195711              int iPos = 0;
195712              while( p->rc==SQLITE_OK ){
195713                int nSpace = pgsz - pBuf->n - pPgidx->n;
195714                int n = 0;
195715                if( (nCopy - iPos)<=nSpace ){
195716                  n = nCopy - iPos;
195717                }else{
195718                  n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
195719                }
195720                assert( n>0 );
195721                fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
195722                iPos += n;
195723                if( (pBuf->n + pPgidx->n)>=pgsz ){
195724                  fts5WriteFlushLeaf(p, &writer);
195725                }
195726                if( iPos>=nCopy ) break;
195727              }
195728            }
195729            iOff += nCopy;
195730          }
195731        }
195732      }
195733
195734      /* TODO2: Doclist terminator written here. */
195735      /* pBuf->p[pBuf->n++] = '\0'; */
195736      assert( pBuf->n<=pBuf->nSpace );
195737      sqlite3Fts5HashScanNext(pHash);
195738    }
195739    sqlite3Fts5HashClear(pHash);
195740    fts5WriteFinish(p, &writer, &pgnoLast);
195741
195742    /* Update the Fts5Structure. It is written back to the database by the
195743    ** fts5StructureRelease() call below.  */
195744    if( pStruct->nLevel==0 ){
195745      fts5StructureAddLevel(&p->rc, &pStruct);
195746    }
195747    fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
195748    if( p->rc==SQLITE_OK ){
195749      pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
195750      pSeg->iSegid = iSegid;
195751      pSeg->pgnoFirst = 1;
195752      pSeg->pgnoLast = pgnoLast;
195753      pStruct->nSegment++;
195754    }
195755    fts5StructurePromote(p, 0, pStruct);
195756  }
195757
195758  fts5IndexAutomerge(p, &pStruct, pgnoLast);
195759  fts5IndexCrisismerge(p, &pStruct);
195760  fts5StructureWrite(p, pStruct);
195761  fts5StructureRelease(pStruct);
195762}
195763
195764/*
195765** Flush any data stored in the in-memory hash tables to the database.
195766*/
195767static void fts5IndexFlush(Fts5Index *p){
195768  /* Unless it is empty, flush the hash table to disk */
195769  if( p->nPendingData ){
195770    assert( p->pHash );
195771    p->nPendingData = 0;
195772    fts5FlushOneHash(p);
195773  }
195774}
195775
195776static Fts5Structure *fts5IndexOptimizeStruct(
195777  Fts5Index *p,
195778  Fts5Structure *pStruct
195779){
195780  Fts5Structure *pNew = 0;
195781  int nByte = sizeof(Fts5Structure);
195782  int nSeg = pStruct->nSegment;
195783  int i;
195784
195785  /* Figure out if this structure requires optimization. A structure does
195786  ** not require optimization if either:
195787  **
195788  **  + it consists of fewer than two segments, or
195789  **  + all segments are on the same level, or
195790  **  + all segments except one are currently inputs to a merge operation.
195791  **
195792  ** In the first case, return NULL. In the second, increment the ref-count
195793  ** on *pStruct and return a copy of the pointer to it.
195794  */
195795  if( nSeg<2 ) return 0;
195796  for(i=0; i<pStruct->nLevel; i++){
195797    int nThis = pStruct->aLevel[i].nSeg;
195798    if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
195799      fts5StructureRef(pStruct);
195800      return pStruct;
195801    }
195802    assert( pStruct->aLevel[i].nMerge<=nThis );
195803  }
195804
195805  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
195806  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
195807
195808  if( pNew ){
195809    Fts5StructureLevel *pLvl;
195810    nByte = nSeg * sizeof(Fts5StructureSegment);
195811    pNew->nLevel = pStruct->nLevel+1;
195812    pNew->nRef = 1;
195813    pNew->nWriteCounter = pStruct->nWriteCounter;
195814    pLvl = &pNew->aLevel[pStruct->nLevel];
195815    pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
195816    if( pLvl->aSeg ){
195817      int iLvl, iSeg;
195818      int iSegOut = 0;
195819      /* Iterate through all segments, from oldest to newest. Add them to
195820      ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
195821      ** segment in the data structure.  */
195822      for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
195823        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
195824          pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
195825          iSegOut++;
195826        }
195827      }
195828      pNew->nSegment = pLvl->nSeg = nSeg;
195829    }else{
195830      sqlite3_free(pNew);
195831      pNew = 0;
195832    }
195833  }
195834
195835  return pNew;
195836}
195837
195838static int sqlite3Fts5IndexOptimize(Fts5Index *p){
195839  Fts5Structure *pStruct;
195840  Fts5Structure *pNew = 0;
195841
195842  assert( p->rc==SQLITE_OK );
195843  fts5IndexFlush(p);
195844  pStruct = fts5StructureRead(p);
195845  fts5StructureInvalidate(p);
195846
195847  if( pStruct ){
195848    pNew = fts5IndexOptimizeStruct(p, pStruct);
195849  }
195850  fts5StructureRelease(pStruct);
195851
195852  assert( pNew==0 || pNew->nSegment>0 );
195853  if( pNew ){
195854    int iLvl;
195855    for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
195856    while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
195857      int nRem = FTS5_OPT_WORK_UNIT;
195858      fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
195859    }
195860
195861    fts5StructureWrite(p, pNew);
195862    fts5StructureRelease(pNew);
195863  }
195864
195865  return fts5IndexReturn(p);
195866}
195867
195868/*
195869** This is called to implement the special "VALUES('merge', $nMerge)"
195870** INSERT command.
195871*/
195872static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
195873  Fts5Structure *pStruct = fts5StructureRead(p);
195874  if( pStruct ){
195875    int nMin = p->pConfig->nUsermerge;
195876    fts5StructureInvalidate(p);
195877    if( nMerge<0 ){
195878      Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
195879      fts5StructureRelease(pStruct);
195880      pStruct = pNew;
195881      nMin = 2;
195882      nMerge = nMerge*-1;
195883    }
195884    if( pStruct && pStruct->nLevel ){
195885      if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
195886        fts5StructureWrite(p, pStruct);
195887      }
195888    }
195889    fts5StructureRelease(pStruct);
195890  }
195891  return fts5IndexReturn(p);
195892}
195893
195894static void fts5AppendRowid(
195895  Fts5Index *p,
195896  i64 iDelta,
195897  Fts5Iter *pUnused,
195898  Fts5Buffer *pBuf
195899){
195900  UNUSED_PARAM(pUnused);
195901  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
195902}
195903
195904static void fts5AppendPoslist(
195905  Fts5Index *p,
195906  i64 iDelta,
195907  Fts5Iter *pMulti,
195908  Fts5Buffer *pBuf
195909){
195910  int nData = pMulti->base.nData;
195911  assert( nData>0 );
195912  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
195913    fts5BufferSafeAppendVarint(pBuf, iDelta);
195914    fts5BufferSafeAppendVarint(pBuf, nData*2);
195915    fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
195916  }
195917}
195918
195919
195920static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
195921  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
195922
195923  assert( pIter->aPoslist );
195924  if( p>=pIter->aEof ){
195925    pIter->aPoslist = 0;
195926  }else{
195927    i64 iDelta;
195928
195929    p += fts5GetVarint(p, (u64*)&iDelta);
195930    pIter->iRowid += iDelta;
195931
195932    /* Read position list size */
195933    if( p[0] & 0x80 ){
195934      int nPos;
195935      pIter->nSize = fts5GetVarint32(p, nPos);
195936      pIter->nPoslist = (nPos>>1);
195937    }else{
195938      pIter->nPoslist = ((int)(p[0])) >> 1;
195939      pIter->nSize = 1;
195940    }
195941
195942    pIter->aPoslist = p;
195943  }
195944}
195945
195946static void fts5DoclistIterInit(
195947  Fts5Buffer *pBuf,
195948  Fts5DoclistIter *pIter
195949){
195950  memset(pIter, 0, sizeof(*pIter));
195951  pIter->aPoslist = pBuf->p;
195952  pIter->aEof = &pBuf->p[pBuf->n];
195953  fts5DoclistIterNext(pIter);
195954}
195955
195956#if 0
195957/*
195958** Append a doclist to buffer pBuf.
195959**
195960** This function assumes that space within the buffer has already been
195961** allocated.
195962*/
195963static void fts5MergeAppendDocid(
195964  Fts5Buffer *pBuf,               /* Buffer to write to */
195965  i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
195966  i64 iRowid                      /* Rowid to append */
195967){
195968  assert( pBuf->n!=0 || (*piLastRowid)==0 );
195969  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
195970  *piLastRowid = iRowid;
195971}
195972#endif
195973
195974#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
195975  assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
195976  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
195977  (iLastRowid) = (iRowid);                                     \
195978}
195979
195980/*
195981** Swap the contents of buffer *p1 with that of *p2.
195982*/
195983static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
195984  Fts5Buffer tmp = *p1;
195985  *p1 = *p2;
195986  *p2 = tmp;
195987}
195988
195989static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
195990  int i = *piOff;
195991  if( i>=pBuf->n ){
195992    *piOff = -1;
195993  }else{
195994    u64 iVal;
195995    *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
195996    *piRowid += iVal;
195997  }
195998}
195999
196000/*
196001** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
196002** In this case the buffers consist of a delta-encoded list of rowids only.
196003*/
196004static void fts5MergeRowidLists(
196005  Fts5Index *p,                   /* FTS5 backend object */
196006  Fts5Buffer *p1,                 /* First list to merge */
196007  Fts5Buffer *p2                  /* Second list to merge */
196008){
196009  int i1 = 0;
196010  int i2 = 0;
196011  i64 iRowid1 = 0;
196012  i64 iRowid2 = 0;
196013  i64 iOut = 0;
196014
196015  Fts5Buffer out;
196016  memset(&out, 0, sizeof(out));
196017  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
196018  if( p->rc ) return;
196019
196020  fts5NextRowid(p1, &i1, &iRowid1);
196021  fts5NextRowid(p2, &i2, &iRowid2);
196022  while( i1>=0 || i2>=0 ){
196023    if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
196024      assert( iOut==0 || iRowid1>iOut );
196025      fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
196026      iOut = iRowid1;
196027      fts5NextRowid(p1, &i1, &iRowid1);
196028    }else{
196029      assert( iOut==0 || iRowid2>iOut );
196030      fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
196031      iOut = iRowid2;
196032      if( i1>=0 && iRowid1==iRowid2 ){
196033        fts5NextRowid(p1, &i1, &iRowid1);
196034      }
196035      fts5NextRowid(p2, &i2, &iRowid2);
196036    }
196037  }
196038
196039  fts5BufferSwap(&out, p1);
196040  fts5BufferFree(&out);
196041}
196042
196043/*
196044** Buffers p1 and p2 contain doclists. This function merges the content
196045** of the two doclists together and sets buffer p1 to the result before
196046** returning.
196047**
196048** If an error occurs, an error code is left in p->rc. If an error has
196049** already occurred, this function is a no-op.
196050*/
196051static void fts5MergePrefixLists(
196052  Fts5Index *p,                   /* FTS5 backend object */
196053  Fts5Buffer *p1,                 /* First list to merge */
196054  Fts5Buffer *p2                  /* Second list to merge */
196055){
196056  if( p2->n ){
196057    i64 iLastRowid = 0;
196058    Fts5DoclistIter i1;
196059    Fts5DoclistIter i2;
196060    Fts5Buffer out = {0, 0, 0};
196061    Fts5Buffer tmp = {0, 0, 0};
196062
196063    if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
196064    fts5DoclistIterInit(p1, &i1);
196065    fts5DoclistIterInit(p2, &i2);
196066
196067    while( 1 ){
196068      if( i1.iRowid<i2.iRowid ){
196069        /* Copy entry from i1 */
196070        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
196071        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
196072        fts5DoclistIterNext(&i1);
196073        if( i1.aPoslist==0 ) break;
196074      }
196075      else if( i2.iRowid!=i1.iRowid ){
196076        /* Copy entry from i2 */
196077        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196078        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
196079        fts5DoclistIterNext(&i2);
196080        if( i2.aPoslist==0 ) break;
196081      }
196082      else{
196083        /* Merge the two position lists. */
196084        i64 iPos1 = 0;
196085        i64 iPos2 = 0;
196086        int iOff1 = 0;
196087        int iOff2 = 0;
196088        u8 *a1 = &i1.aPoslist[i1.nSize];
196089        u8 *a2 = &i2.aPoslist[i2.nSize];
196090
196091        i64 iPrev = 0;
196092        Fts5PoslistWriter writer;
196093        memset(&writer, 0, sizeof(writer));
196094
196095        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196096        fts5BufferZero(&tmp);
196097        sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
196098        if( p->rc ) break;
196099
196100        sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196101        sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196102        assert( iPos1>=0 && iPos2>=0 );
196103
196104        if( iPos1<iPos2 ){
196105          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196106          sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196107        }else{
196108          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196109          sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196110        }
196111
196112        if( iPos1>=0 && iPos2>=0 ){
196113          while( 1 ){
196114            if( iPos1<iPos2 ){
196115              if( iPos1!=iPrev ){
196116                sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196117              }
196118              sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
196119              if( iPos1<0 ) break;
196120            }else{
196121              assert( iPos2!=iPrev );
196122              sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196123              sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
196124              if( iPos2<0 ) break;
196125            }
196126          }
196127        }
196128
196129        if( iPos1>=0 ){
196130          if( iPos1!=iPrev ){
196131            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
196132          }
196133          fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
196134        }else{
196135          assert( iPos2>=0 && iPos2!=iPrev );
196136          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
196137          fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
196138        }
196139
196140        /* WRITEPOSLISTSIZE */
196141        fts5BufferSafeAppendVarint(&out, tmp.n * 2);
196142        fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
196143        fts5DoclistIterNext(&i1);
196144        fts5DoclistIterNext(&i2);
196145        if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
196146      }
196147    }
196148
196149    if( i1.aPoslist ){
196150      fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
196151      fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
196152    }
196153    else if( i2.aPoslist ){
196154      fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
196155      fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
196156    }
196157
196158    fts5BufferSet(&p->rc, p1, out.n, out.p);
196159    fts5BufferFree(&tmp);
196160    fts5BufferFree(&out);
196161  }
196162}
196163
196164static void fts5SetupPrefixIter(
196165  Fts5Index *p,                   /* Index to read from */
196166  int bDesc,                      /* True for "ORDER BY rowid DESC" */
196167  const u8 *pToken,               /* Buffer containing prefix to match */
196168  int nToken,                     /* Size of buffer pToken in bytes */
196169  Fts5Colset *pColset,            /* Restrict matches to these columns */
196170  Fts5Iter **ppIter          /* OUT: New iterator */
196171){
196172  Fts5Structure *pStruct;
196173  Fts5Buffer *aBuf;
196174  const int nBuf = 32;
196175
196176  void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
196177  void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
196178  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
196179    xMerge = fts5MergeRowidLists;
196180    xAppend = fts5AppendRowid;
196181  }else{
196182    xMerge = fts5MergePrefixLists;
196183    xAppend = fts5AppendPoslist;
196184  }
196185
196186  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
196187  pStruct = fts5StructureRead(p);
196188
196189  if( aBuf && pStruct ){
196190    const int flags = FTS5INDEX_QUERY_SCAN
196191                    | FTS5INDEX_QUERY_SKIPEMPTY
196192                    | FTS5INDEX_QUERY_NOOUTPUT;
196193    int i;
196194    i64 iLastRowid = 0;
196195    Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
196196    Fts5Data *pData;
196197    Fts5Buffer doclist;
196198    int bNewTerm = 1;
196199
196200    memset(&doclist, 0, sizeof(doclist));
196201    fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
196202    fts5IterSetOutputCb(&p->rc, p1);
196203    for( /* no-op */ ;
196204        fts5MultiIterEof(p, p1)==0;
196205        fts5MultiIterNext2(p, p1, &bNewTerm)
196206    ){
196207      Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
196208      int nTerm = pSeg->term.n;
196209      const u8 *pTerm = pSeg->term.p;
196210      p1->xSetOutputs(p1, pSeg);
196211
196212      assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
196213      if( bNewTerm ){
196214        if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
196215      }
196216
196217      if( p1->base.nData==0 ) continue;
196218
196219      if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
196220        for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
196221          assert( i<nBuf );
196222          if( aBuf[i].n==0 ){
196223            fts5BufferSwap(&doclist, &aBuf[i]);
196224            fts5BufferZero(&doclist);
196225          }else{
196226            xMerge(p, &doclist, &aBuf[i]);
196227            fts5BufferZero(&aBuf[i]);
196228          }
196229        }
196230        iLastRowid = 0;
196231      }
196232
196233      xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
196234      iLastRowid = p1->base.iRowid;
196235    }
196236
196237    for(i=0; i<nBuf; i++){
196238      if( p->rc==SQLITE_OK ){
196239        xMerge(p, &doclist, &aBuf[i]);
196240      }
196241      fts5BufferFree(&aBuf[i]);
196242    }
196243    fts5MultiIterFree(p1);
196244
196245    pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
196246    if( pData ){
196247      pData->p = (u8*)&pData[1];
196248      pData->nn = pData->szLeaf = doclist.n;
196249      if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
196250      fts5MultiIterNew2(p, pData, bDesc, ppIter);
196251    }
196252    fts5BufferFree(&doclist);
196253  }
196254
196255  fts5StructureRelease(pStruct);
196256  sqlite3_free(aBuf);
196257}
196258
196259
196260/*
196261** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
196262** to the document with rowid iRowid.
196263*/
196264static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
196265  assert( p->rc==SQLITE_OK );
196266
196267  /* Allocate the hash table if it has not already been allocated */
196268  if( p->pHash==0 ){
196269    p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
196270  }
196271
196272  /* Flush the hash table to disk if required */
196273  if( iRowid<p->iWriteRowid
196274   || (iRowid==p->iWriteRowid && p->bDelete==0)
196275   || (p->nPendingData > p->pConfig->nHashSize)
196276  ){
196277    fts5IndexFlush(p);
196278  }
196279
196280  p->iWriteRowid = iRowid;
196281  p->bDelete = bDelete;
196282  return fts5IndexReturn(p);
196283}
196284
196285/*
196286** Commit data to disk.
196287*/
196288static int sqlite3Fts5IndexSync(Fts5Index *p){
196289  assert( p->rc==SQLITE_OK );
196290  fts5IndexFlush(p);
196291  fts5CloseReader(p);
196292  return fts5IndexReturn(p);
196293}
196294
196295/*
196296** Discard any data stored in the in-memory hash tables. Do not write it
196297** to the database. Additionally, assume that the contents of the %_data
196298** table may have changed on disk. So any in-memory caches of %_data
196299** records must be invalidated.
196300*/
196301static int sqlite3Fts5IndexRollback(Fts5Index *p){
196302  fts5CloseReader(p);
196303  fts5IndexDiscardData(p);
196304  fts5StructureInvalidate(p);
196305  /* assert( p->rc==SQLITE_OK ); */
196306  return SQLITE_OK;
196307}
196308
196309/*
196310** The %_data table is completely empty when this function is called. This
196311** function populates it with the initial structure objects for each index,
196312** and the initial version of the "averages" record (a zero-byte blob).
196313*/
196314static int sqlite3Fts5IndexReinit(Fts5Index *p){
196315  Fts5Structure s;
196316  fts5StructureInvalidate(p);
196317  memset(&s, 0, sizeof(Fts5Structure));
196318  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
196319  fts5StructureWrite(p, &s);
196320  return fts5IndexReturn(p);
196321}
196322
196323/*
196324** Open a new Fts5Index handle. If the bCreate argument is true, create
196325** and initialize the underlying %_data table.
196326**
196327** If successful, set *pp to point to the new object and return SQLITE_OK.
196328** Otherwise, set *pp to NULL and return an SQLite error code.
196329*/
196330static int sqlite3Fts5IndexOpen(
196331  Fts5Config *pConfig,
196332  int bCreate,
196333  Fts5Index **pp,
196334  char **pzErr
196335){
196336  int rc = SQLITE_OK;
196337  Fts5Index *p;                   /* New object */
196338
196339  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
196340  if( rc==SQLITE_OK ){
196341    p->pConfig = pConfig;
196342    p->nWorkUnit = FTS5_WORK_UNIT;
196343    p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
196344    if( p->zDataTbl && bCreate ){
196345      rc = sqlite3Fts5CreateTable(
196346          pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
196347      );
196348      if( rc==SQLITE_OK ){
196349        rc = sqlite3Fts5CreateTable(pConfig, "idx",
196350            "segid, term, pgno, PRIMARY KEY(segid, term)",
196351            1, pzErr
196352        );
196353      }
196354      if( rc==SQLITE_OK ){
196355        rc = sqlite3Fts5IndexReinit(p);
196356      }
196357    }
196358  }
196359
196360  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
196361  if( rc ){
196362    sqlite3Fts5IndexClose(p);
196363    *pp = 0;
196364  }
196365  return rc;
196366}
196367
196368/*
196369** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
196370*/
196371static int sqlite3Fts5IndexClose(Fts5Index *p){
196372  int rc = SQLITE_OK;
196373  if( p ){
196374    assert( p->pReader==0 );
196375    fts5StructureInvalidate(p);
196376    sqlite3_finalize(p->pWriter);
196377    sqlite3_finalize(p->pDeleter);
196378    sqlite3_finalize(p->pIdxWriter);
196379    sqlite3_finalize(p->pIdxDeleter);
196380    sqlite3_finalize(p->pIdxSelect);
196381    sqlite3_finalize(p->pDataVersion);
196382    sqlite3Fts5HashFree(p->pHash);
196383    sqlite3_free(p->zDataTbl);
196384    sqlite3_free(p);
196385  }
196386  return rc;
196387}
196388
196389/*
196390** Argument p points to a buffer containing utf-8 text that is n bytes in
196391** size. Return the number of bytes in the nChar character prefix of the
196392** buffer, or 0 if there are less than nChar characters in total.
196393*/
196394static int sqlite3Fts5IndexCharlenToBytelen(
196395  const char *p,
196396  int nByte,
196397  int nChar
196398){
196399  int n = 0;
196400  int i;
196401  for(i=0; i<nChar; i++){
196402    if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
196403    if( (unsigned char)p[n++]>=0xc0 ){
196404      while( (p[n] & 0xc0)==0x80 ) n++;
196405    }
196406  }
196407  return n;
196408}
196409
196410/*
196411** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
196412** unicode characters in the string.
196413*/
196414static int fts5IndexCharlen(const char *pIn, int nIn){
196415  int nChar = 0;
196416  int i = 0;
196417  while( i<nIn ){
196418    if( (unsigned char)pIn[i++]>=0xc0 ){
196419      while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
196420    }
196421    nChar++;
196422  }
196423  return nChar;
196424}
196425
196426/*
196427** Insert or remove data to or from the index. Each time a document is
196428** added to or removed from the index, this function is called one or more
196429** times.
196430**
196431** For an insert, it must be called once for each token in the new document.
196432** If the operation is a delete, it must be called (at least) once for each
196433** unique token in the document with an iCol value less than zero. The iPos
196434** argument is ignored for a delete.
196435*/
196436static int sqlite3Fts5IndexWrite(
196437  Fts5Index *p,                   /* Index to write to */
196438  int iCol,                       /* Column token appears in (-ve -> delete) */
196439  int iPos,                       /* Position of token within column */
196440  const char *pToken, int nToken  /* Token to add or remove to or from index */
196441){
196442  int i;                          /* Used to iterate through indexes */
196443  int rc = SQLITE_OK;             /* Return code */
196444  Fts5Config *pConfig = p->pConfig;
196445
196446  assert( p->rc==SQLITE_OK );
196447  assert( (iCol<0)==p->bDelete );
196448
196449  /* Add the entry to the main terms index. */
196450  rc = sqlite3Fts5HashWrite(
196451      p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
196452  );
196453
196454  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
196455    const int nChar = pConfig->aPrefix[i];
196456    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
196457    if( nByte ){
196458      rc = sqlite3Fts5HashWrite(p->pHash,
196459          p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
196460          nByte
196461      );
196462    }
196463  }
196464
196465  return rc;
196466}
196467
196468/*
196469** Open a new iterator to iterate though all rowid that match the
196470** specified token or token prefix.
196471*/
196472static int sqlite3Fts5IndexQuery(
196473  Fts5Index *p,                   /* FTS index to query */
196474  const char *pToken, int nToken, /* Token (or prefix) to query for */
196475  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
196476  Fts5Colset *pColset,            /* Match these columns only */
196477  Fts5IndexIter **ppIter          /* OUT: New iterator object */
196478){
196479  Fts5Config *pConfig = p->pConfig;
196480  Fts5Iter *pRet = 0;
196481  Fts5Buffer buf = {0, 0, 0};
196482
196483  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
196484  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
196485
196486  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
196487    int iIdx = 0;                 /* Index to search */
196488    if( nToken ) memcpy(&buf.p[1], pToken, nToken);
196489
196490    /* Figure out which index to search and set iIdx accordingly. If this
196491    ** is a prefix query for which there is no prefix index, set iIdx to
196492    ** greater than pConfig->nPrefix to indicate that the query will be
196493    ** satisfied by scanning multiple terms in the main index.
196494    **
196495    ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
196496    ** prefix-query. Instead of using a prefix-index (if one exists),
196497    ** evaluate the prefix query using the main FTS index. This is used
196498    ** for internal sanity checking by the integrity-check in debug
196499    ** mode only.  */
196500#ifdef SQLITE_DEBUG
196501    if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
196502      assert( flags & FTS5INDEX_QUERY_PREFIX );
196503      iIdx = 1+pConfig->nPrefix;
196504    }else
196505#endif
196506    if( flags & FTS5INDEX_QUERY_PREFIX ){
196507      int nChar = fts5IndexCharlen(pToken, nToken);
196508      for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
196509        if( pConfig->aPrefix[iIdx-1]==nChar ) break;
196510      }
196511    }
196512
196513    if( iIdx<=pConfig->nPrefix ){
196514      /* Straight index lookup */
196515      Fts5Structure *pStruct = fts5StructureRead(p);
196516      buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
196517      if( pStruct ){
196518        fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
196519            pColset, buf.p, nToken+1, -1, 0, &pRet
196520        );
196521        fts5StructureRelease(pStruct);
196522      }
196523    }else{
196524      /* Scan multiple terms in the main index */
196525      int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
196526      buf.p[0] = FTS5_MAIN_PREFIX;
196527      fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
196528      assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
196529      fts5IterSetOutputCb(&p->rc, pRet);
196530      if( p->rc==SQLITE_OK ){
196531        Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
196532        if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
196533      }
196534    }
196535
196536    if( p->rc ){
196537      sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
196538      pRet = 0;
196539      fts5CloseReader(p);
196540    }
196541
196542    *ppIter = &pRet->base;
196543    sqlite3Fts5BufferFree(&buf);
196544  }
196545  return fts5IndexReturn(p);
196546}
196547
196548/*
196549** Return true if the iterator passed as the only argument is at EOF.
196550*/
196551/*
196552** Move to the next matching rowid.
196553*/
196554static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
196555  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
196556  assert( pIter->pIndex->rc==SQLITE_OK );
196557  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
196558  return fts5IndexReturn(pIter->pIndex);
196559}
196560
196561/*
196562** Move to the next matching term/rowid. Used by the fts5vocab module.
196563*/
196564static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
196565  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
196566  Fts5Index *p = pIter->pIndex;
196567
196568  assert( pIter->pIndex->rc==SQLITE_OK );
196569
196570  fts5MultiIterNext(p, pIter, 0, 0);
196571  if( p->rc==SQLITE_OK ){
196572    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
196573    if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
196574      fts5DataRelease(pSeg->pLeaf);
196575      pSeg->pLeaf = 0;
196576      pIter->base.bEof = 1;
196577    }
196578  }
196579
196580  return fts5IndexReturn(pIter->pIndex);
196581}
196582
196583/*
196584** Move to the next matching rowid that occurs at or after iMatch. The
196585** definition of "at or after" depends on whether this iterator iterates
196586** in ascending or descending rowid order.
196587*/
196588static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
196589  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
196590  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
196591  return fts5IndexReturn(pIter->pIndex);
196592}
196593
196594/*
196595** Return the current term.
196596*/
196597static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
196598  int n;
196599  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
196600  *pn = n-1;
196601  return &z[1];
196602}
196603
196604/*
196605** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
196606*/
196607static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
196608  if( pIndexIter ){
196609    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
196610    Fts5Index *pIndex = pIter->pIndex;
196611    fts5MultiIterFree(pIter);
196612    fts5CloseReader(pIndex);
196613  }
196614}
196615
196616/*
196617** Read and decode the "averages" record from the database.
196618**
196619** Parameter anSize must point to an array of size nCol, where nCol is
196620** the number of user defined columns in the FTS table.
196621*/
196622static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
196623  int nCol = p->pConfig->nCol;
196624  Fts5Data *pData;
196625
196626  *pnRow = 0;
196627  memset(anSize, 0, sizeof(i64) * nCol);
196628  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
196629  if( p->rc==SQLITE_OK && pData->nn ){
196630    int i = 0;
196631    int iCol;
196632    i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
196633    for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
196634      i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
196635    }
196636  }
196637
196638  fts5DataRelease(pData);
196639  return fts5IndexReturn(p);
196640}
196641
196642/*
196643** Replace the current "averages" record with the contents of the buffer
196644** supplied as the second argument.
196645*/
196646static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
196647  assert( p->rc==SQLITE_OK );
196648  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
196649  return fts5IndexReturn(p);
196650}
196651
196652/*
196653** Return the total number of blocks this module has read from the %_data
196654** table since it was created.
196655*/
196656static int sqlite3Fts5IndexReads(Fts5Index *p){
196657  return p->nRead;
196658}
196659
196660/*
196661** Set the 32-bit cookie value stored at the start of all structure
196662** records to the value passed as the second argument.
196663**
196664** Return SQLITE_OK if successful, or an SQLite error code if an error
196665** occurs.
196666*/
196667static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
196668  int rc;                              /* Return code */
196669  Fts5Config *pConfig = p->pConfig;    /* Configuration object */
196670  u8 aCookie[4];                       /* Binary representation of iNew */
196671  sqlite3_blob *pBlob = 0;
196672
196673  assert( p->rc==SQLITE_OK );
196674  sqlite3Fts5Put32(aCookie, iNew);
196675
196676  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
196677      "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
196678  );
196679  if( rc==SQLITE_OK ){
196680    sqlite3_blob_write(pBlob, aCookie, 4, 0);
196681    rc = sqlite3_blob_close(pBlob);
196682  }
196683
196684  return rc;
196685}
196686
196687static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
196688  Fts5Structure *pStruct;
196689  pStruct = fts5StructureRead(p);
196690  fts5StructureRelease(pStruct);
196691  return fts5IndexReturn(p);
196692}
196693
196694
196695/*************************************************************************
196696**************************************************************************
196697** Below this point is the implementation of the integrity-check
196698** functionality.
196699*/
196700
196701/*
196702** Return a simple checksum value based on the arguments.
196703*/
196704static u64 sqlite3Fts5IndexEntryCksum(
196705  i64 iRowid,
196706  int iCol,
196707  int iPos,
196708  int iIdx,
196709  const char *pTerm,
196710  int nTerm
196711){
196712  int i;
196713  u64 ret = iRowid;
196714  ret += (ret<<3) + iCol;
196715  ret += (ret<<3) + iPos;
196716  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
196717  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
196718  return ret;
196719}
196720
196721#ifdef SQLITE_DEBUG
196722/*
196723** This function is purely an internal test. It does not contribute to
196724** FTS functionality, or even the integrity-check, in any way.
196725**
196726** Instead, it tests that the same set of pgno/rowid combinations are
196727** visited regardless of whether the doclist-index identified by parameters
196728** iSegid/iLeaf is iterated in forwards or reverse order.
196729*/
196730static void fts5TestDlidxReverse(
196731  Fts5Index *p,
196732  int iSegid,                     /* Segment id to load from */
196733  int iLeaf                       /* Load doclist-index for this leaf */
196734){
196735  Fts5DlidxIter *pDlidx = 0;
196736  u64 cksum1 = 13;
196737  u64 cksum2 = 13;
196738
196739  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
196740      fts5DlidxIterEof(p, pDlidx)==0;
196741      fts5DlidxIterNext(p, pDlidx)
196742  ){
196743    i64 iRowid = fts5DlidxIterRowid(pDlidx);
196744    int pgno = fts5DlidxIterPgno(pDlidx);
196745    assert( pgno>iLeaf );
196746    cksum1 += iRowid + ((i64)pgno<<32);
196747  }
196748  fts5DlidxIterFree(pDlidx);
196749  pDlidx = 0;
196750
196751  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
196752      fts5DlidxIterEof(p, pDlidx)==0;
196753      fts5DlidxIterPrev(p, pDlidx)
196754  ){
196755    i64 iRowid = fts5DlidxIterRowid(pDlidx);
196756    int pgno = fts5DlidxIterPgno(pDlidx);
196757    assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
196758    cksum2 += iRowid + ((i64)pgno<<32);
196759  }
196760  fts5DlidxIterFree(pDlidx);
196761  pDlidx = 0;
196762
196763  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
196764}
196765
196766static int fts5QueryCksum(
196767  Fts5Index *p,                   /* Fts5 index object */
196768  int iIdx,
196769  const char *z,                  /* Index key to query for */
196770  int n,                          /* Size of index key in bytes */
196771  int flags,                      /* Flags for Fts5IndexQuery */
196772  u64 *pCksum                     /* IN/OUT: Checksum value */
196773){
196774  int eDetail = p->pConfig->eDetail;
196775  u64 cksum = *pCksum;
196776  Fts5IndexIter *pIter = 0;
196777  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
196778
196779  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
196780    i64 rowid = pIter->iRowid;
196781
196782    if( eDetail==FTS5_DETAIL_NONE ){
196783      cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
196784    }else{
196785      Fts5PoslistReader sReader;
196786      for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
196787          sReader.bEof==0;
196788          sqlite3Fts5PoslistReaderNext(&sReader)
196789      ){
196790        int iCol = FTS5_POS2COLUMN(sReader.iPos);
196791        int iOff = FTS5_POS2OFFSET(sReader.iPos);
196792        cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
196793      }
196794    }
196795    if( rc==SQLITE_OK ){
196796      rc = sqlite3Fts5IterNext(pIter);
196797    }
196798  }
196799  sqlite3Fts5IterClose(pIter);
196800
196801  *pCksum = cksum;
196802  return rc;
196803}
196804
196805
196806/*
196807** This function is also purely an internal test. It does not contribute to
196808** FTS functionality, or even the integrity-check, in any way.
196809*/
196810static void fts5TestTerm(
196811  Fts5Index *p,
196812  Fts5Buffer *pPrev,              /* Previous term */
196813  const char *z, int n,           /* Possibly new term to test */
196814  u64 expected,
196815  u64 *pCksum
196816){
196817  int rc = p->rc;
196818  if( pPrev->n==0 ){
196819    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
196820  }else
196821  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
196822    u64 cksum3 = *pCksum;
196823    const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
196824    int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
196825    int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
196826    int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
196827    u64 ck1 = 0;
196828    u64 ck2 = 0;
196829
196830    /* Check that the results returned for ASC and DESC queries are
196831    ** the same. If not, call this corruption.  */
196832    rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
196833    if( rc==SQLITE_OK ){
196834      int f = flags|FTS5INDEX_QUERY_DESC;
196835      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
196836    }
196837    if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
196838
196839    /* If this is a prefix query, check that the results returned if the
196840    ** the index is disabled are the same. In both ASC and DESC order.
196841    **
196842    ** This check may only be performed if the hash table is empty. This
196843    ** is because the hash table only supports a single scan query at
196844    ** a time, and the multi-iter loop from which this function is called
196845    ** is already performing such a scan. */
196846    if( p->nPendingData==0 ){
196847      if( iIdx>0 && rc==SQLITE_OK ){
196848        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
196849        ck2 = 0;
196850        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
196851        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
196852      }
196853      if( iIdx>0 && rc==SQLITE_OK ){
196854        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
196855        ck2 = 0;
196856        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
196857        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
196858      }
196859    }
196860
196861    cksum3 ^= ck1;
196862    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
196863
196864    if( rc==SQLITE_OK && cksum3!=expected ){
196865      rc = FTS5_CORRUPT;
196866    }
196867    *pCksum = cksum3;
196868  }
196869  p->rc = rc;
196870}
196871
196872#else
196873# define fts5TestDlidxReverse(x,y,z)
196874# define fts5TestTerm(u,v,w,x,y,z)
196875#endif
196876
196877/*
196878** Check that:
196879**
196880**   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
196881**      contain zero terms.
196882**   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
196883**      contain zero rowids.
196884*/
196885static void fts5IndexIntegrityCheckEmpty(
196886  Fts5Index *p,
196887  Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
196888  int iFirst,
196889  int iNoRowid,
196890  int iLast
196891){
196892  int i;
196893
196894  /* Now check that the iter.nEmpty leaves following the current leaf
196895  ** (a) exist and (b) contain no terms. */
196896  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
196897    Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
196898    if( pLeaf ){
196899      if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
196900      if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
196901    }
196902    fts5DataRelease(pLeaf);
196903  }
196904}
196905
196906static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
196907  int iTermOff = 0;
196908  int ii;
196909
196910  Fts5Buffer buf1 = {0,0,0};
196911  Fts5Buffer buf2 = {0,0,0};
196912
196913  ii = pLeaf->szLeaf;
196914  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
196915    int res;
196916    int iOff;
196917    int nIncr;
196918
196919    ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
196920    iTermOff += nIncr;
196921    iOff = iTermOff;
196922
196923    if( iOff>=pLeaf->szLeaf ){
196924      p->rc = FTS5_CORRUPT;
196925    }else if( iTermOff==nIncr ){
196926      int nByte;
196927      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
196928      if( (iOff+nByte)>pLeaf->szLeaf ){
196929        p->rc = FTS5_CORRUPT;
196930      }else{
196931        fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
196932      }
196933    }else{
196934      int nKeep, nByte;
196935      iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
196936      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
196937      if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
196938        p->rc = FTS5_CORRUPT;
196939      }else{
196940        buf1.n = nKeep;
196941        fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
196942      }
196943
196944      if( p->rc==SQLITE_OK ){
196945        res = fts5BufferCompare(&buf1, &buf2);
196946        if( res<=0 ) p->rc = FTS5_CORRUPT;
196947      }
196948    }
196949    fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
196950  }
196951
196952  fts5BufferFree(&buf1);
196953  fts5BufferFree(&buf2);
196954}
196955
196956static void fts5IndexIntegrityCheckSegment(
196957  Fts5Index *p,                   /* FTS5 backend object */
196958  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
196959){
196960  Fts5Config *pConfig = p->pConfig;
196961  sqlite3_stmt *pStmt = 0;
196962  int rc2;
196963  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
196964  int iDlidxPrevLeaf = pSeg->pgnoLast;
196965
196966  if( pSeg->pgnoFirst==0 ) return;
196967
196968  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
196969      "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
196970      pConfig->zDb, pConfig->zName, pSeg->iSegid
196971  ));
196972
196973  /* Iterate through the b-tree hierarchy.  */
196974  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
196975    i64 iRow;                     /* Rowid for this leaf */
196976    Fts5Data *pLeaf;              /* Data for this leaf */
196977
196978    int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
196979    const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
196980    int iIdxLeaf = sqlite3_column_int(pStmt, 2);
196981    int bIdxDlidx = sqlite3_column_int(pStmt, 3);
196982
196983    /* If the leaf in question has already been trimmed from the segment,
196984    ** ignore this b-tree entry. Otherwise, load it into memory. */
196985    if( iIdxLeaf<pSeg->pgnoFirst ) continue;
196986    iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
196987    pLeaf = fts5LeafRead(p, iRow);
196988    if( pLeaf==0 ) break;
196989
196990    /* Check that the leaf contains at least one term, and that it is equal
196991    ** to or larger than the split-key in zIdxTerm.  Also check that if there
196992    ** is also a rowid pointer within the leaf page header, it points to a
196993    ** location before the term.  */
196994    if( pLeaf->nn<=pLeaf->szLeaf ){
196995      p->rc = FTS5_CORRUPT;
196996    }else{
196997      int iOff;                   /* Offset of first term on leaf */
196998      int iRowidOff;              /* Offset of first rowid on leaf */
196999      int nTerm;                  /* Size of term on leaf in bytes */
197000      int res;                    /* Comparison of term and split-key */
197001
197002      iOff = fts5LeafFirstTermOff(pLeaf);
197003      iRowidOff = fts5LeafFirstRowidOff(pLeaf);
197004      if( iRowidOff>=iOff ){
197005        p->rc = FTS5_CORRUPT;
197006      }else{
197007        iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
197008        res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
197009        if( res==0 ) res = nTerm - nIdxTerm;
197010        if( res<0 ) p->rc = FTS5_CORRUPT;
197011      }
197012
197013      fts5IntegrityCheckPgidx(p, pLeaf);
197014    }
197015    fts5DataRelease(pLeaf);
197016    if( p->rc ) break;
197017
197018    /* Now check that the iter.nEmpty leaves following the current leaf
197019    ** (a) exist and (b) contain no terms. */
197020    fts5IndexIntegrityCheckEmpty(
197021        p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
197022    );
197023    if( p->rc ) break;
197024
197025    /* If there is a doclist-index, check that it looks right. */
197026    if( bIdxDlidx ){
197027      Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
197028      int iPrevLeaf = iIdxLeaf;
197029      int iSegid = pSeg->iSegid;
197030      int iPg = 0;
197031      i64 iKey;
197032
197033      for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
197034          fts5DlidxIterEof(p, pDlidx)==0;
197035          fts5DlidxIterNext(p, pDlidx)
197036      ){
197037
197038        /* Check any rowid-less pages that occur before the current leaf. */
197039        for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
197040          iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
197041          pLeaf = fts5DataRead(p, iKey);
197042          if( pLeaf ){
197043            if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
197044            fts5DataRelease(pLeaf);
197045          }
197046        }
197047        iPrevLeaf = fts5DlidxIterPgno(pDlidx);
197048
197049        /* Check that the leaf page indicated by the iterator really does
197050        ** contain the rowid suggested by the same. */
197051        iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
197052        pLeaf = fts5DataRead(p, iKey);
197053        if( pLeaf ){
197054          i64 iRowid;
197055          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
197056          ASSERT_SZLEAF_OK(pLeaf);
197057          if( iRowidOff>=pLeaf->szLeaf ){
197058            p->rc = FTS5_CORRUPT;
197059          }else{
197060            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
197061            if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
197062          }
197063          fts5DataRelease(pLeaf);
197064        }
197065      }
197066
197067      iDlidxPrevLeaf = iPg;
197068      fts5DlidxIterFree(pDlidx);
197069      fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
197070    }else{
197071      iDlidxPrevLeaf = pSeg->pgnoLast;
197072      /* TODO: Check there is no doclist index */
197073    }
197074
197075    iIdxPrevLeaf = iIdxLeaf;
197076  }
197077
197078  rc2 = sqlite3_finalize(pStmt);
197079  if( p->rc==SQLITE_OK ) p->rc = rc2;
197080
197081  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
197082#if 0
197083  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
197084    p->rc = FTS5_CORRUPT;
197085  }
197086#endif
197087}
197088
197089
197090/*
197091** Run internal checks to ensure that the FTS index (a) is internally
197092** consistent and (b) contains entries for which the XOR of the checksums
197093** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
197094**
197095** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
197096** checksum does not match. Return SQLITE_OK if all checks pass without
197097** error, or some other SQLite error code if another error (e.g. OOM)
197098** occurs.
197099*/
197100static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
197101  int eDetail = p->pConfig->eDetail;
197102  u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
197103  Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
197104  Fts5Iter *pIter;                /* Used to iterate through entire index */
197105  Fts5Structure *pStruct;         /* Index structure */
197106
197107#ifdef SQLITE_DEBUG
197108  /* Used by extra internal tests only run if NDEBUG is not defined */
197109  u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
197110  Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
197111#endif
197112  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
197113
197114  /* Load the FTS index structure */
197115  pStruct = fts5StructureRead(p);
197116
197117  /* Check that the internal nodes of each segment match the leaves */
197118  if( pStruct ){
197119    int iLvl, iSeg;
197120    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
197121      for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
197122        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
197123        fts5IndexIntegrityCheckSegment(p, pSeg);
197124      }
197125    }
197126  }
197127
197128  /* The cksum argument passed to this function is a checksum calculated
197129  ** based on all expected entries in the FTS index (including prefix index
197130  ** entries). This block checks that a checksum calculated based on the
197131  ** actual contents of FTS index is identical.
197132  **
197133  ** Two versions of the same checksum are calculated. The first (stack
197134  ** variable cksum2) based on entries extracted from the full-text index
197135  ** while doing a linear scan of each individual index in turn.
197136  **
197137  ** As each term visited by the linear scans, a separate query for the
197138  ** same term is performed. cksum3 is calculated based on the entries
197139  ** extracted by these queries.
197140  */
197141  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
197142      fts5MultiIterEof(p, pIter)==0;
197143      fts5MultiIterNext(p, pIter, 0, 0)
197144  ){
197145    int n;                      /* Size of term in bytes */
197146    i64 iPos = 0;               /* Position read from poslist */
197147    int iOff = 0;               /* Offset within poslist */
197148    i64 iRowid = fts5MultiIterRowid(pIter);
197149    char *z = (char*)fts5MultiIterTerm(pIter, &n);
197150
197151    /* If this is a new term, query for it. Update cksum3 with the results. */
197152    fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
197153
197154    if( eDetail==FTS5_DETAIL_NONE ){
197155      if( 0==fts5MultiIterIsEmpty(p, pIter) ){
197156        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
197157      }
197158    }else{
197159      poslist.n = 0;
197160      fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
197161      while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
197162        int iCol = FTS5_POS2COLUMN(iPos);
197163        int iTokOff = FTS5_POS2OFFSET(iPos);
197164        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
197165      }
197166    }
197167  }
197168  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
197169
197170  fts5MultiIterFree(pIter);
197171  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
197172
197173  fts5StructureRelease(pStruct);
197174#ifdef SQLITE_DEBUG
197175  fts5BufferFree(&term);
197176#endif
197177  fts5BufferFree(&poslist);
197178  return fts5IndexReturn(p);
197179}
197180
197181/*************************************************************************
197182**************************************************************************
197183** Below this point is the implementation of the fts5_decode() scalar
197184** function only.
197185*/
197186
197187/*
197188** Decode a segment-data rowid from the %_data table. This function is
197189** the opposite of macro FTS5_SEGMENT_ROWID().
197190*/
197191static void fts5DecodeRowid(
197192  i64 iRowid,                     /* Rowid from %_data table */
197193  int *piSegid,                   /* OUT: Segment id */
197194  int *pbDlidx,                   /* OUT: Dlidx flag */
197195  int *piHeight,                  /* OUT: Height */
197196  int *piPgno                     /* OUT: Page number */
197197){
197198  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
197199  iRowid >>= FTS5_DATA_PAGE_B;
197200
197201  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
197202  iRowid >>= FTS5_DATA_HEIGHT_B;
197203
197204  *pbDlidx = (int)(iRowid & 0x0001);
197205  iRowid >>= FTS5_DATA_DLI_B;
197206
197207  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
197208}
197209
197210static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
197211  int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
197212  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
197213
197214  if( iSegid==0 ){
197215    if( iKey==FTS5_AVERAGES_ROWID ){
197216      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
197217    }else{
197218      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
197219    }
197220  }
197221  else{
197222    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
197223        bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
197224    );
197225  }
197226}
197227
197228static void fts5DebugStructure(
197229  int *pRc,                       /* IN/OUT: error code */
197230  Fts5Buffer *pBuf,
197231  Fts5Structure *p
197232){
197233  int iLvl, iSeg;                 /* Iterate through levels, segments */
197234
197235  for(iLvl=0; iLvl<p->nLevel; iLvl++){
197236    Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
197237    sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
197238        " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
197239    );
197240    for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
197241      Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
197242      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
197243          pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
197244      );
197245    }
197246    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
197247  }
197248}
197249
197250/*
197251** This is part of the fts5_decode() debugging aid.
197252**
197253** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
197254** function appends a human-readable representation of the same object
197255** to the buffer passed as the second argument.
197256*/
197257static void fts5DecodeStructure(
197258  int *pRc,                       /* IN/OUT: error code */
197259  Fts5Buffer *pBuf,
197260  const u8 *pBlob, int nBlob
197261){
197262  int rc;                         /* Return code */
197263  Fts5Structure *p = 0;           /* Decoded structure object */
197264
197265  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
197266  if( rc!=SQLITE_OK ){
197267    *pRc = rc;
197268    return;
197269  }
197270
197271  fts5DebugStructure(pRc, pBuf, p);
197272  fts5StructureRelease(p);
197273}
197274
197275/*
197276** This is part of the fts5_decode() debugging aid.
197277**
197278** Arguments pBlob/nBlob contain an "averages" record. This function
197279** appends a human-readable representation of record to the buffer passed
197280** as the second argument.
197281*/
197282static void fts5DecodeAverages(
197283  int *pRc,                       /* IN/OUT: error code */
197284  Fts5Buffer *pBuf,
197285  const u8 *pBlob, int nBlob
197286){
197287  int i = 0;
197288  const char *zSpace = "";
197289
197290  while( i<nBlob ){
197291    u64 iVal;
197292    i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
197293    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
197294    zSpace = " ";
197295  }
197296}
197297
197298/*
197299** Buffer (a/n) is assumed to contain a list of serialized varints. Read
197300** each varint and append its string representation to buffer pBuf. Return
197301** after either the input buffer is exhausted or a 0 value is read.
197302**
197303** The return value is the number of bytes read from the input buffer.
197304*/
197305static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
197306  int iOff = 0;
197307  while( iOff<n ){
197308    int iVal;
197309    iOff += fts5GetVarint32(&a[iOff], iVal);
197310    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
197311  }
197312  return iOff;
197313}
197314
197315/*
197316** The start of buffer (a/n) contains the start of a doclist. The doclist
197317** may or may not finish within the buffer. This function appends a text
197318** representation of the part of the doclist that is present to buffer
197319** pBuf.
197320**
197321** The return value is the number of bytes read from the input buffer.
197322*/
197323static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
197324  i64 iDocid = 0;
197325  int iOff = 0;
197326
197327  if( n>0 ){
197328    iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
197329    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
197330  }
197331  while( iOff<n ){
197332    int nPos;
197333    int bDel;
197334    iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
197335    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
197336    iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
197337    if( iOff<n ){
197338      i64 iDelta;
197339      iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
197340      iDocid += iDelta;
197341      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
197342    }
197343  }
197344
197345  return iOff;
197346}
197347
197348/*
197349** This function is part of the fts5_decode() debugging function. It is
197350** only ever used with detail=none tables.
197351**
197352** Buffer (pData/nData) contains a doclist in the format used by detail=none
197353** tables. This function appends a human-readable version of that list to
197354** buffer pBuf.
197355**
197356** If *pRc is other than SQLITE_OK when this function is called, it is a
197357** no-op. If an OOM or other error occurs within this function, *pRc is
197358** set to an SQLite error code before returning. The final state of buffer
197359** pBuf is undefined in this case.
197360*/
197361static void fts5DecodeRowidList(
197362  int *pRc,                       /* IN/OUT: Error code */
197363  Fts5Buffer *pBuf,               /* Buffer to append text to */
197364  const u8 *pData, int nData      /* Data to decode list-of-rowids from */
197365){
197366  int i = 0;
197367  i64 iRowid = 0;
197368
197369  while( i<nData ){
197370    const char *zApp = "";
197371    u64 iVal;
197372    i += sqlite3Fts5GetVarint(&pData[i], &iVal);
197373    iRowid += iVal;
197374
197375    if( i<nData && pData[i]==0x00 ){
197376      i++;
197377      if( i<nData && pData[i]==0x00 ){
197378        i++;
197379        zApp = "+";
197380      }else{
197381        zApp = "*";
197382      }
197383    }
197384
197385    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
197386  }
197387}
197388
197389/*
197390** The implementation of user-defined scalar function fts5_decode().
197391*/
197392static void fts5DecodeFunction(
197393  sqlite3_context *pCtx,          /* Function call context */
197394  int nArg,                       /* Number of args (always 2) */
197395  sqlite3_value **apVal           /* Function arguments */
197396){
197397  i64 iRowid;                     /* Rowid for record being decoded */
197398  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
197399  const u8 *aBlob; int n;         /* Record to decode */
197400  u8 *a = 0;
197401  Fts5Buffer s;                   /* Build up text to return here */
197402  int rc = SQLITE_OK;             /* Return code */
197403  int nSpace = 0;
197404  int eDetailNone = (sqlite3_user_data(pCtx)!=0);
197405
197406  assert( nArg==2 );
197407  UNUSED_PARAM(nArg);
197408  memset(&s, 0, sizeof(Fts5Buffer));
197409  iRowid = sqlite3_value_int64(apVal[0]);
197410
197411  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
197412  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
197413  ** buffer overreads even if the record is corrupt.  */
197414  n = sqlite3_value_bytes(apVal[1]);
197415  aBlob = sqlite3_value_blob(apVal[1]);
197416  nSpace = n + FTS5_DATA_ZERO_PADDING;
197417  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
197418  if( a==0 ) goto decode_out;
197419  memcpy(a, aBlob, n);
197420
197421
197422  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
197423
197424  fts5DebugRowid(&rc, &s, iRowid);
197425  if( bDlidx ){
197426    Fts5Data dlidx;
197427    Fts5DlidxLvl lvl;
197428
197429    dlidx.p = a;
197430    dlidx.nn = n;
197431
197432    memset(&lvl, 0, sizeof(Fts5DlidxLvl));
197433    lvl.pData = &dlidx;
197434    lvl.iLeafPgno = iPgno;
197435
197436    for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
197437      sqlite3Fts5BufferAppendPrintf(&rc, &s,
197438          " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
197439      );
197440    }
197441  }else if( iSegid==0 ){
197442    if( iRowid==FTS5_AVERAGES_ROWID ){
197443      fts5DecodeAverages(&rc, &s, a, n);
197444    }else{
197445      fts5DecodeStructure(&rc, &s, a, n);
197446    }
197447  }else if( eDetailNone ){
197448    Fts5Buffer term;              /* Current term read from page */
197449    int szLeaf;
197450    int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
197451    int iTermOff;
197452    int nKeep = 0;
197453    int iOff;
197454
197455    memset(&term, 0, sizeof(Fts5Buffer));
197456
197457    /* Decode any entries that occur before the first term. */
197458    if( szLeaf<n ){
197459      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
197460    }else{
197461      iTermOff = szLeaf;
197462    }
197463    fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
197464
197465    iOff = iTermOff;
197466    while( iOff<szLeaf ){
197467      int nAppend;
197468
197469      /* Read the term data for the next term*/
197470      iOff += fts5GetVarint32(&a[iOff], nAppend);
197471      term.n = nKeep;
197472      fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
197473      sqlite3Fts5BufferAppendPrintf(
197474          &rc, &s, " term=%.*s", term.n, (const char*)term.p
197475      );
197476      iOff += nAppend;
197477
197478      /* Figure out where the doclist for this term ends */
197479      if( iPgidxOff<n ){
197480        int nIncr;
197481        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
197482        iTermOff += nIncr;
197483      }else{
197484        iTermOff = szLeaf;
197485      }
197486
197487      fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
197488      iOff = iTermOff;
197489      if( iOff<szLeaf ){
197490        iOff += fts5GetVarint32(&a[iOff], nKeep);
197491      }
197492    }
197493
197494    fts5BufferFree(&term);
197495  }else{
197496    Fts5Buffer term;              /* Current term read from page */
197497    int szLeaf;                   /* Offset of pgidx in a[] */
197498    int iPgidxOff;
197499    int iPgidxPrev = 0;           /* Previous value read from pgidx */
197500    int iTermOff = 0;
197501    int iRowidOff = 0;
197502    int iOff;
197503    int nDoclist;
197504
197505    memset(&term, 0, sizeof(Fts5Buffer));
197506
197507    if( n<4 ){
197508      sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
197509      goto decode_out;
197510    }else{
197511      iRowidOff = fts5GetU16(&a[0]);
197512      iPgidxOff = szLeaf = fts5GetU16(&a[2]);
197513      if( iPgidxOff<n ){
197514        fts5GetVarint32(&a[iPgidxOff], iTermOff);
197515      }
197516    }
197517
197518    /* Decode the position list tail at the start of the page */
197519    if( iRowidOff!=0 ){
197520      iOff = iRowidOff;
197521    }else if( iTermOff!=0 ){
197522      iOff = iTermOff;
197523    }else{
197524      iOff = szLeaf;
197525    }
197526    fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
197527
197528    /* Decode any more doclist data that appears on the page before the
197529    ** first term. */
197530    nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
197531    fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
197532
197533    while( iPgidxOff<n ){
197534      int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
197535      int nByte;                            /* Bytes of data */
197536      int iEnd;
197537
197538      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
197539      iPgidxPrev += nByte;
197540      iOff = iPgidxPrev;
197541
197542      if( iPgidxOff<n ){
197543        fts5GetVarint32(&a[iPgidxOff], nByte);
197544        iEnd = iPgidxPrev + nByte;
197545      }else{
197546        iEnd = szLeaf;
197547      }
197548
197549      if( bFirst==0 ){
197550        iOff += fts5GetVarint32(&a[iOff], nByte);
197551        term.n = nByte;
197552      }
197553      iOff += fts5GetVarint32(&a[iOff], nByte);
197554      fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
197555      iOff += nByte;
197556
197557      sqlite3Fts5BufferAppendPrintf(
197558          &rc, &s, " term=%.*s", term.n, (const char*)term.p
197559      );
197560      iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
197561    }
197562
197563    fts5BufferFree(&term);
197564  }
197565
197566 decode_out:
197567  sqlite3_free(a);
197568  if( rc==SQLITE_OK ){
197569    sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
197570  }else{
197571    sqlite3_result_error_code(pCtx, rc);
197572  }
197573  fts5BufferFree(&s);
197574}
197575
197576/*
197577** The implementation of user-defined scalar function fts5_rowid().
197578*/
197579static void fts5RowidFunction(
197580  sqlite3_context *pCtx,          /* Function call context */
197581  int nArg,                       /* Number of args (always 2) */
197582  sqlite3_value **apVal           /* Function arguments */
197583){
197584  const char *zArg;
197585  if( nArg==0 ){
197586    sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
197587  }else{
197588    zArg = (const char*)sqlite3_value_text(apVal[0]);
197589    if( 0==sqlite3_stricmp(zArg, "segment") ){
197590      i64 iRowid;
197591      int segid, pgno;
197592      if( nArg!=3 ){
197593        sqlite3_result_error(pCtx,
197594            "should be: fts5_rowid('segment', segid, pgno))", -1
197595        );
197596      }else{
197597        segid = sqlite3_value_int(apVal[1]);
197598        pgno = sqlite3_value_int(apVal[2]);
197599        iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
197600        sqlite3_result_int64(pCtx, iRowid);
197601      }
197602    }else{
197603      sqlite3_result_error(pCtx,
197604        "first arg to fts5_rowid() must be 'segment'" , -1
197605      );
197606    }
197607  }
197608}
197609
197610/*
197611** This is called as part of registering the FTS5 module with database
197612** connection db. It registers several user-defined scalar functions useful
197613** with FTS5.
197614**
197615** If successful, SQLITE_OK is returned. If an error occurs, some other
197616** SQLite error code is returned instead.
197617*/
197618static int sqlite3Fts5IndexInit(sqlite3 *db){
197619  int rc = sqlite3_create_function(
197620      db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
197621  );
197622
197623  if( rc==SQLITE_OK ){
197624    rc = sqlite3_create_function(
197625        db, "fts5_decode_none", 2,
197626        SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
197627    );
197628  }
197629
197630  if( rc==SQLITE_OK ){
197631    rc = sqlite3_create_function(
197632        db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
197633    );
197634  }
197635  return rc;
197636}
197637
197638
197639static int sqlite3Fts5IndexReset(Fts5Index *p){
197640  assert( p->pStruct==0 || p->iStructVersion!=0 );
197641  if( fts5IndexDataVersion(p)!=p->iStructVersion ){
197642    fts5StructureInvalidate(p);
197643  }
197644  return fts5IndexReturn(p);
197645}
197646
197647/*
197648** 2014 Jun 09
197649**
197650** The author disclaims copyright to this source code.  In place of
197651** a legal notice, here is a blessing:
197652**
197653**    May you do good and not evil.
197654**    May you find forgiveness for yourself and forgive others.
197655**    May you share freely, never taking more than you give.
197656**
197657******************************************************************************
197658**
197659** This is an SQLite module implementing full-text search.
197660*/
197661
197662
197663/* #include "fts5Int.h" */
197664
197665/*
197666** This variable is set to false when running tests for which the on disk
197667** structures should not be corrupt. Otherwise, true. If it is false, extra
197668** assert() conditions in the fts5 code are activated - conditions that are
197669** only true if it is guaranteed that the fts5 database is not corrupt.
197670*/
197671SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
197672
197673
197674typedef struct Fts5Auxdata Fts5Auxdata;
197675typedef struct Fts5Auxiliary Fts5Auxiliary;
197676typedef struct Fts5Cursor Fts5Cursor;
197677typedef struct Fts5Sorter Fts5Sorter;
197678typedef struct Fts5Table Fts5Table;
197679typedef struct Fts5TokenizerModule Fts5TokenizerModule;
197680
197681/*
197682** NOTES ON TRANSACTIONS:
197683**
197684** SQLite invokes the following virtual table methods as transactions are
197685** opened and closed by the user:
197686**
197687**     xBegin():    Start of a new transaction.
197688**     xSync():     Initial part of two-phase commit.
197689**     xCommit():   Final part of two-phase commit.
197690**     xRollback(): Rollback the transaction.
197691**
197692** Anything that is required as part of a commit that may fail is performed
197693** in the xSync() callback. Current versions of SQLite ignore any errors
197694** returned by xCommit().
197695**
197696** And as sub-transactions are opened/closed:
197697**
197698**     xSavepoint(int S):  Open savepoint S.
197699**     xRelease(int S):    Commit and close savepoint S.
197700**     xRollbackTo(int S): Rollback to start of savepoint S.
197701**
197702** During a write-transaction the fts5_index.c module may cache some data
197703** in-memory. It is flushed to disk whenever xSync(), xRelease() or
197704** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
197705** is called.
197706**
197707** Additionally, if SQLITE_DEBUG is defined, an instance of the following
197708** structure is used to record the current transaction state. This information
197709** is not required, but it is used in the assert() statements executed by
197710** function fts5CheckTransactionState() (see below).
197711*/
197712struct Fts5TransactionState {
197713  int eState;                     /* 0==closed, 1==open, 2==synced */
197714  int iSavepoint;                 /* Number of open savepoints (0 -> none) */
197715};
197716
197717/*
197718** A single object of this type is allocated when the FTS5 module is
197719** registered with a database handle. It is used to store pointers to
197720** all registered FTS5 extensions - tokenizers and auxiliary functions.
197721*/
197722struct Fts5Global {
197723  fts5_api api;                   /* User visible part of object (see fts5.h) */
197724  sqlite3 *db;                    /* Associated database connection */
197725  i64 iNextId;                    /* Used to allocate unique cursor ids */
197726  Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
197727  Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
197728  Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
197729  Fts5Cursor *pCsr;               /* First in list of all open cursors */
197730};
197731
197732/*
197733** Each auxiliary function registered with the FTS5 module is represented
197734** by an object of the following type. All such objects are stored as part
197735** of the Fts5Global.pAux list.
197736*/
197737struct Fts5Auxiliary {
197738  Fts5Global *pGlobal;            /* Global context for this function */
197739  char *zFunc;                    /* Function name (nul-terminated) */
197740  void *pUserData;                /* User-data pointer */
197741  fts5_extension_function xFunc;  /* Callback function */
197742  void (*xDestroy)(void*);        /* Destructor function */
197743  Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
197744};
197745
197746/*
197747** Each tokenizer module registered with the FTS5 module is represented
197748** by an object of the following type. All such objects are stored as part
197749** of the Fts5Global.pTok list.
197750*/
197751struct Fts5TokenizerModule {
197752  char *zName;                    /* Name of tokenizer */
197753  void *pUserData;                /* User pointer passed to xCreate() */
197754  fts5_tokenizer x;               /* Tokenizer functions */
197755  void (*xDestroy)(void*);        /* Destructor function */
197756  Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
197757};
197758
197759/*
197760** Virtual-table object.
197761*/
197762struct Fts5Table {
197763  sqlite3_vtab base;              /* Base class used by SQLite core */
197764  Fts5Config *pConfig;            /* Virtual table configuration */
197765  Fts5Index *pIndex;              /* Full-text index */
197766  Fts5Storage *pStorage;          /* Document store */
197767  Fts5Global *pGlobal;            /* Global (connection wide) data */
197768  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
197769#ifdef SQLITE_DEBUG
197770  struct Fts5TransactionState ts;
197771#endif
197772};
197773
197774struct Fts5MatchPhrase {
197775  Fts5Buffer *pPoslist;           /* Pointer to current poslist */
197776  int nTerm;                      /* Size of phrase in terms */
197777};
197778
197779/*
197780** pStmt:
197781**   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
197782**
197783** aIdx[]:
197784**   There is one entry in the aIdx[] array for each phrase in the query,
197785**   the value of which is the offset within aPoslist[] following the last
197786**   byte of the position list for the corresponding phrase.
197787*/
197788struct Fts5Sorter {
197789  sqlite3_stmt *pStmt;
197790  i64 iRowid;                     /* Current rowid */
197791  const u8 *aPoslist;             /* Position lists for current row */
197792  int nIdx;                       /* Number of entries in aIdx[] */
197793  int aIdx[1];                    /* Offsets into aPoslist for current row */
197794};
197795
197796
197797/*
197798** Virtual-table cursor object.
197799**
197800** iSpecial:
197801**   If this is a 'special' query (refer to function fts5SpecialMatch()),
197802**   then this variable contains the result of the query.
197803**
197804** iFirstRowid, iLastRowid:
197805**   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
197806**   cursor iterates in ascending order of rowids, iFirstRowid is the lower
197807**   limit of rowids to return, and iLastRowid the upper. In other words, the
197808**   WHERE clause in the user's query might have been:
197809**
197810**       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
197811**
197812**   If the cursor iterates in descending order of rowid, iFirstRowid
197813**   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
197814**   the lower.
197815*/
197816struct Fts5Cursor {
197817  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
197818  Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
197819  int *aColumnSize;               /* Values for xColumnSize() */
197820  i64 iCsrId;                     /* Cursor id */
197821
197822  /* Zero from this point onwards on cursor reset */
197823  int ePlan;                      /* FTS5_PLAN_XXX value */
197824  int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
197825  i64 iFirstRowid;                /* Return no rowids earlier than this */
197826  i64 iLastRowid;                 /* Return no rowids later than this */
197827  sqlite3_stmt *pStmt;            /* Statement used to read %_content */
197828  Fts5Expr *pExpr;                /* Expression for MATCH queries */
197829  Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
197830  int csrflags;                   /* Mask of cursor flags (see below) */
197831  i64 iSpecial;                   /* Result of special query */
197832
197833  /* "rank" function. Populated on demand from vtab.xColumn(). */
197834  char *zRank;                    /* Custom rank function */
197835  char *zRankArgs;                /* Custom rank function args */
197836  Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
197837  int nRankArg;                   /* Number of trailing arguments for rank() */
197838  sqlite3_value **apRankArg;      /* Array of trailing arguments */
197839  sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
197840
197841  /* Auxiliary data storage */
197842  Fts5Auxiliary *pAux;            /* Currently executing extension function */
197843  Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
197844
197845  /* Cache used by auxiliary functions xInst() and xInstCount() */
197846  Fts5PoslistReader *aInstIter;   /* One for each phrase */
197847  int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
197848  int nInstCount;                 /* Number of phrase instances */
197849  int *aInst;                     /* 3 integers per phrase instance */
197850};
197851
197852/*
197853** Bits that make up the "idxNum" parameter passed indirectly by
197854** xBestIndex() to xFilter().
197855*/
197856#define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
197857#define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
197858#define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
197859#define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
197860#define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
197861
197862#define FTS5_BI_ORDER_RANK   0x0020
197863#define FTS5_BI_ORDER_ROWID  0x0040
197864#define FTS5_BI_ORDER_DESC   0x0080
197865
197866/*
197867** Values for Fts5Cursor.csrflags
197868*/
197869#define FTS5CSR_EOF               0x01
197870#define FTS5CSR_REQUIRE_CONTENT   0x02
197871#define FTS5CSR_REQUIRE_DOCSIZE   0x04
197872#define FTS5CSR_REQUIRE_INST      0x08
197873#define FTS5CSR_FREE_ZRANK        0x10
197874#define FTS5CSR_REQUIRE_RESEEK    0x20
197875#define FTS5CSR_REQUIRE_POSLIST   0x40
197876
197877#define BitFlagAllTest(x,y) (((x) & (y))==(y))
197878#define BitFlagTest(x,y)    (((x) & (y))!=0)
197879
197880
197881/*
197882** Macros to Set(), Clear() and Test() cursor flags.
197883*/
197884#define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
197885#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
197886#define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
197887
197888struct Fts5Auxdata {
197889  Fts5Auxiliary *pAux;            /* Extension to which this belongs */
197890  void *pPtr;                     /* Pointer value */
197891  void(*xDelete)(void*);          /* Destructor */
197892  Fts5Auxdata *pNext;             /* Next object in linked list */
197893};
197894
197895#ifdef SQLITE_DEBUG
197896#define FTS5_BEGIN      1
197897#define FTS5_SYNC       2
197898#define FTS5_COMMIT     3
197899#define FTS5_ROLLBACK   4
197900#define FTS5_SAVEPOINT  5
197901#define FTS5_RELEASE    6
197902#define FTS5_ROLLBACKTO 7
197903static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
197904  switch( op ){
197905    case FTS5_BEGIN:
197906      assert( p->ts.eState==0 );
197907      p->ts.eState = 1;
197908      p->ts.iSavepoint = -1;
197909      break;
197910
197911    case FTS5_SYNC:
197912      assert( p->ts.eState==1 );
197913      p->ts.eState = 2;
197914      break;
197915
197916    case FTS5_COMMIT:
197917      assert( p->ts.eState==2 );
197918      p->ts.eState = 0;
197919      break;
197920
197921    case FTS5_ROLLBACK:
197922      assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
197923      p->ts.eState = 0;
197924      break;
197925
197926    case FTS5_SAVEPOINT:
197927      assert( p->ts.eState==1 );
197928      assert( iSavepoint>=0 );
197929      assert( iSavepoint>p->ts.iSavepoint );
197930      p->ts.iSavepoint = iSavepoint;
197931      break;
197932
197933    case FTS5_RELEASE:
197934      assert( p->ts.eState==1 );
197935      assert( iSavepoint>=0 );
197936      assert( iSavepoint<=p->ts.iSavepoint );
197937      p->ts.iSavepoint = iSavepoint-1;
197938      break;
197939
197940    case FTS5_ROLLBACKTO:
197941      assert( p->ts.eState==1 );
197942      assert( iSavepoint>=0 );
197943      assert( iSavepoint<=p->ts.iSavepoint );
197944      p->ts.iSavepoint = iSavepoint;
197945      break;
197946  }
197947}
197948#else
197949# define fts5CheckTransactionState(x,y,z)
197950#endif
197951
197952/*
197953** Return true if pTab is a contentless table.
197954*/
197955static int fts5IsContentless(Fts5Table *pTab){
197956  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
197957}
197958
197959/*
197960** Delete a virtual table handle allocated by fts5InitVtab().
197961*/
197962static void fts5FreeVtab(Fts5Table *pTab){
197963  if( pTab ){
197964    sqlite3Fts5IndexClose(pTab->pIndex);
197965    sqlite3Fts5StorageClose(pTab->pStorage);
197966    sqlite3Fts5ConfigFree(pTab->pConfig);
197967    sqlite3_free(pTab);
197968  }
197969}
197970
197971/*
197972** The xDisconnect() virtual table method.
197973*/
197974static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
197975  fts5FreeVtab((Fts5Table*)pVtab);
197976  return SQLITE_OK;
197977}
197978
197979/*
197980** The xDestroy() virtual table method.
197981*/
197982static int fts5DestroyMethod(sqlite3_vtab *pVtab){
197983  Fts5Table *pTab = (Fts5Table*)pVtab;
197984  int rc = sqlite3Fts5DropAll(pTab->pConfig);
197985  if( rc==SQLITE_OK ){
197986    fts5FreeVtab((Fts5Table*)pVtab);
197987  }
197988  return rc;
197989}
197990
197991/*
197992** This function is the implementation of both the xConnect and xCreate
197993** methods of the FTS3 virtual table.
197994**
197995** The argv[] array contains the following:
197996**
197997**   argv[0]   -> module name  ("fts5")
197998**   argv[1]   -> database name
197999**   argv[2]   -> table name
198000**   argv[...] -> "column name" and other module argument fields.
198001*/
198002static int fts5InitVtab(
198003  int bCreate,                    /* True for xCreate, false for xConnect */
198004  sqlite3 *db,                    /* The SQLite database connection */
198005  void *pAux,                     /* Hash table containing tokenizers */
198006  int argc,                       /* Number of elements in argv array */
198007  const char * const *argv,       /* xCreate/xConnect argument array */
198008  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
198009  char **pzErr                    /* Write any error message here */
198010){
198011  Fts5Global *pGlobal = (Fts5Global*)pAux;
198012  const char **azConfig = (const char**)argv;
198013  int rc = SQLITE_OK;             /* Return code */
198014  Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
198015  Fts5Table *pTab = 0;            /* New virtual table object */
198016
198017  /* Allocate the new vtab object and parse the configuration */
198018  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
198019  if( rc==SQLITE_OK ){
198020    rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
198021    assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
198022  }
198023  if( rc==SQLITE_OK ){
198024    pTab->pConfig = pConfig;
198025    pTab->pGlobal = pGlobal;
198026  }
198027
198028  /* Open the index sub-system */
198029  if( rc==SQLITE_OK ){
198030    rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
198031  }
198032
198033  /* Open the storage sub-system */
198034  if( rc==SQLITE_OK ){
198035    rc = sqlite3Fts5StorageOpen(
198036        pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
198037    );
198038  }
198039
198040  /* Call sqlite3_declare_vtab() */
198041  if( rc==SQLITE_OK ){
198042    rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
198043  }
198044
198045  /* Load the initial configuration */
198046  if( rc==SQLITE_OK ){
198047    assert( pConfig->pzErrmsg==0 );
198048    pConfig->pzErrmsg = pzErr;
198049    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
198050    sqlite3Fts5IndexRollback(pTab->pIndex);
198051    pConfig->pzErrmsg = 0;
198052  }
198053
198054  if( rc!=SQLITE_OK ){
198055    fts5FreeVtab(pTab);
198056    pTab = 0;
198057  }else if( bCreate ){
198058    fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
198059  }
198060  *ppVTab = (sqlite3_vtab*)pTab;
198061  return rc;
198062}
198063
198064/*
198065** The xConnect() and xCreate() methods for the virtual table. All the
198066** work is done in function fts5InitVtab().
198067*/
198068static int fts5ConnectMethod(
198069  sqlite3 *db,                    /* Database connection */
198070  void *pAux,                     /* Pointer to tokenizer hash table */
198071  int argc,                       /* Number of elements in argv array */
198072  const char * const *argv,       /* xCreate/xConnect argument array */
198073  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
198074  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
198075){
198076  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
198077}
198078static int fts5CreateMethod(
198079  sqlite3 *db,                    /* Database connection */
198080  void *pAux,                     /* Pointer to tokenizer hash table */
198081  int argc,                       /* Number of elements in argv array */
198082  const char * const *argv,       /* xCreate/xConnect argument array */
198083  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
198084  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
198085){
198086  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
198087}
198088
198089/*
198090** The different query plans.
198091*/
198092#define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
198093#define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
198094#define FTS5_PLAN_SPECIAL        3       /* An internal query */
198095#define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
198096#define FTS5_PLAN_SCAN           5       /* No usable constraint */
198097#define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
198098
198099/*
198100** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
198101** extension is currently being used by a version of SQLite too old to
198102** support index-info flags. In that case this function is a no-op.
198103*/
198104static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
198105#if SQLITE_VERSION_NUMBER>=3008012
198106#ifndef SQLITE_CORE
198107  if( sqlite3_libversion_number()>=3008012 )
198108#endif
198109  {
198110    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
198111  }
198112#endif
198113}
198114
198115/*
198116** Implementation of the xBestIndex method for FTS5 tables. Within the
198117** WHERE constraint, it searches for the following:
198118**
198119**   1. A MATCH constraint against the special column.
198120**   2. A MATCH constraint against the "rank" column.
198121**   3. An == constraint against the rowid column.
198122**   4. A < or <= constraint against the rowid column.
198123**   5. A > or >= constraint against the rowid column.
198124**
198125** Within the ORDER BY, either:
198126**
198127**   5. ORDER BY rank [ASC|DESC]
198128**   6. ORDER BY rowid [ASC|DESC]
198129**
198130** Costs are assigned as follows:
198131**
198132**  a) If an unusable MATCH operator is present in the WHERE clause, the
198133**     cost is unconditionally set to 1e50 (a really big number).
198134**
198135**  a) If a MATCH operator is present, the cost depends on the other
198136**     constraints also present. As follows:
198137**
198138**       * No other constraints:         cost=1000.0
198139**       * One rowid range constraint:   cost=750.0
198140**       * Both rowid range constraints: cost=500.0
198141**       * An == rowid constraint:       cost=100.0
198142**
198143**  b) Otherwise, if there is no MATCH:
198144**
198145**       * No other constraints:         cost=1000000.0
198146**       * One rowid range constraint:   cost=750000.0
198147**       * Both rowid range constraints: cost=250000.0
198148**       * An == rowid constraint:       cost=10.0
198149**
198150** Costs are not modified by the ORDER BY clause.
198151*/
198152static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
198153  Fts5Table *pTab = (Fts5Table*)pVTab;
198154  Fts5Config *pConfig = pTab->pConfig;
198155  const int nCol = pConfig->nCol;
198156  int idxFlags = 0;               /* Parameter passed through to xFilter() */
198157  int bHasMatch;
198158  int iNext;
198159  int i;
198160
198161  struct Constraint {
198162    int op;                       /* Mask against sqlite3_index_constraint.op */
198163    int fts5op;                   /* FTS5 mask for idxFlags */
198164    int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
198165    int omit;                     /* True to omit this if found */
198166    int iConsIndex;               /* Index in pInfo->aConstraint[] */
198167  } aConstraint[] = {
198168    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
198169                                    FTS5_BI_MATCH,    1, 1, -1},
198170    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
198171                                    FTS5_BI_RANK,     2, 1, -1},
198172    {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
198173    {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
198174                                    FTS5_BI_ROWID_LE, 0, 0, -1},
198175    {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
198176                                    FTS5_BI_ROWID_GE, 0, 0, -1},
198177  };
198178
198179  int aColMap[3];
198180  aColMap[0] = -1;
198181  aColMap[1] = nCol;
198182  aColMap[2] = nCol+1;
198183
198184  /* Set idxFlags flags for all WHERE clause terms that will be used. */
198185  for(i=0; i<pInfo->nConstraint; i++){
198186    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
198187    int iCol = p->iColumn;
198188
198189    if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
198190     || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
198191    ){
198192      /* A MATCH operator or equivalent */
198193      if( p->usable ){
198194        idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
198195        aConstraint[0].iConsIndex = i;
198196      }else{
198197        /* As there exists an unusable MATCH constraint this is an
198198        ** unusable plan. Set a prohibitively high cost. */
198199        pInfo->estimatedCost = 1e50;
198200        return SQLITE_OK;
198201      }
198202    }else{
198203      int j;
198204      for(j=1; j<ArraySize(aConstraint); j++){
198205        struct Constraint *pC = &aConstraint[j];
198206        if( iCol==aColMap[pC->iCol] && p->op & pC->op && p->usable ){
198207          pC->iConsIndex = i;
198208          idxFlags |= pC->fts5op;
198209        }
198210      }
198211    }
198212  }
198213
198214  /* Set idxFlags flags for the ORDER BY clause */
198215  if( pInfo->nOrderBy==1 ){
198216    int iSort = pInfo->aOrderBy[0].iColumn;
198217    if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
198218      idxFlags |= FTS5_BI_ORDER_RANK;
198219    }else if( iSort==-1 ){
198220      idxFlags |= FTS5_BI_ORDER_ROWID;
198221    }
198222    if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
198223      pInfo->orderByConsumed = 1;
198224      if( pInfo->aOrderBy[0].desc ){
198225        idxFlags |= FTS5_BI_ORDER_DESC;
198226      }
198227    }
198228  }
198229
198230  /* Calculate the estimated cost based on the flags set in idxFlags. */
198231  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
198232  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
198233    pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
198234    if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
198235  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
198236    pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
198237  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
198238    pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
198239  }else{
198240    pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
198241  }
198242
198243  /* Assign argvIndex values to each constraint in use. */
198244  iNext = 1;
198245  for(i=0; i<ArraySize(aConstraint); i++){
198246    struct Constraint *pC = &aConstraint[i];
198247    if( pC->iConsIndex>=0 ){
198248      pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
198249      pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
198250    }
198251  }
198252
198253  pInfo->idxNum = idxFlags;
198254  return SQLITE_OK;
198255}
198256
198257static int fts5NewTransaction(Fts5Table *pTab){
198258  Fts5Cursor *pCsr;
198259  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
198260    if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
198261  }
198262  return sqlite3Fts5StorageReset(pTab->pStorage);
198263}
198264
198265/*
198266** Implementation of xOpen method.
198267*/
198268static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
198269  Fts5Table *pTab = (Fts5Table*)pVTab;
198270  Fts5Config *pConfig = pTab->pConfig;
198271  Fts5Cursor *pCsr = 0;           /* New cursor object */
198272  int nByte;                      /* Bytes of space to allocate */
198273  int rc;                         /* Return code */
198274
198275  rc = fts5NewTransaction(pTab);
198276  if( rc==SQLITE_OK ){
198277    nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
198278    pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
198279    if( pCsr ){
198280      Fts5Global *pGlobal = pTab->pGlobal;
198281      memset(pCsr, 0, nByte);
198282      pCsr->aColumnSize = (int*)&pCsr[1];
198283      pCsr->pNext = pGlobal->pCsr;
198284      pGlobal->pCsr = pCsr;
198285      pCsr->iCsrId = ++pGlobal->iNextId;
198286    }else{
198287      rc = SQLITE_NOMEM;
198288    }
198289  }
198290  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
198291  return rc;
198292}
198293
198294static int fts5StmtType(Fts5Cursor *pCsr){
198295  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
198296    return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
198297  }
198298  return FTS5_STMT_LOOKUP;
198299}
198300
198301/*
198302** This function is called after the cursor passed as the only argument
198303** is moved to point at a different row. It clears all cached data
198304** specific to the previous row stored by the cursor object.
198305*/
198306static void fts5CsrNewrow(Fts5Cursor *pCsr){
198307  CsrFlagSet(pCsr,
198308      FTS5CSR_REQUIRE_CONTENT
198309    | FTS5CSR_REQUIRE_DOCSIZE
198310    | FTS5CSR_REQUIRE_INST
198311    | FTS5CSR_REQUIRE_POSLIST
198312  );
198313}
198314
198315static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
198316  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
198317  Fts5Auxdata *pData;
198318  Fts5Auxdata *pNext;
198319
198320  sqlite3_free(pCsr->aInstIter);
198321  sqlite3_free(pCsr->aInst);
198322  if( pCsr->pStmt ){
198323    int eStmt = fts5StmtType(pCsr);
198324    sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
198325  }
198326  if( pCsr->pSorter ){
198327    Fts5Sorter *pSorter = pCsr->pSorter;
198328    sqlite3_finalize(pSorter->pStmt);
198329    sqlite3_free(pSorter);
198330  }
198331
198332  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
198333    sqlite3Fts5ExprFree(pCsr->pExpr);
198334  }
198335
198336  for(pData=pCsr->pAuxdata; pData; pData=pNext){
198337    pNext = pData->pNext;
198338    if( pData->xDelete ) pData->xDelete(pData->pPtr);
198339    sqlite3_free(pData);
198340  }
198341
198342  sqlite3_finalize(pCsr->pRankArgStmt);
198343  sqlite3_free(pCsr->apRankArg);
198344
198345  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
198346    sqlite3_free(pCsr->zRank);
198347    sqlite3_free(pCsr->zRankArgs);
198348  }
198349
198350  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
198351}
198352
198353
198354/*
198355** Close the cursor.  For additional information see the documentation
198356** on the xClose method of the virtual table interface.
198357*/
198358static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
198359  if( pCursor ){
198360    Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
198361    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
198362    Fts5Cursor **pp;
198363
198364    fts5FreeCursorComponents(pCsr);
198365    /* Remove the cursor from the Fts5Global.pCsr list */
198366    for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
198367    *pp = pCsr->pNext;
198368
198369    sqlite3_free(pCsr);
198370  }
198371  return SQLITE_OK;
198372}
198373
198374static int fts5SorterNext(Fts5Cursor *pCsr){
198375  Fts5Sorter *pSorter = pCsr->pSorter;
198376  int rc;
198377
198378  rc = sqlite3_step(pSorter->pStmt);
198379  if( rc==SQLITE_DONE ){
198380    rc = SQLITE_OK;
198381    CsrFlagSet(pCsr, FTS5CSR_EOF);
198382  }else if( rc==SQLITE_ROW ){
198383    const u8 *a;
198384    const u8 *aBlob;
198385    int nBlob;
198386    int i;
198387    int iOff = 0;
198388    rc = SQLITE_OK;
198389
198390    pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
198391    nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
198392    aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
198393
198394    /* nBlob==0 in detail=none mode. */
198395    if( nBlob>0 ){
198396      for(i=0; i<(pSorter->nIdx-1); i++){
198397        int iVal;
198398        a += fts5GetVarint32(a, iVal);
198399        iOff += iVal;
198400        pSorter->aIdx[i] = iOff;
198401      }
198402      pSorter->aIdx[i] = &aBlob[nBlob] - a;
198403      pSorter->aPoslist = a;
198404    }
198405
198406    fts5CsrNewrow(pCsr);
198407  }
198408
198409  return rc;
198410}
198411
198412
198413/*
198414** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
198415** open on table pTab.
198416*/
198417static void fts5TripCursors(Fts5Table *pTab){
198418  Fts5Cursor *pCsr;
198419  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
198420    if( pCsr->ePlan==FTS5_PLAN_MATCH
198421     && pCsr->base.pVtab==(sqlite3_vtab*)pTab
198422    ){
198423      CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
198424    }
198425  }
198426}
198427
198428/*
198429** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
198430** argument, close and reopen all Fts5IndexIter iterators that the cursor
198431** is using. Then attempt to move the cursor to a rowid equal to or laster
198432** (in the cursors sort order - ASC or DESC) than the current rowid.
198433**
198434** If the new rowid is not equal to the old, set output parameter *pbSkip
198435** to 1 before returning. Otherwise, leave it unchanged.
198436**
198437** Return SQLITE_OK if successful or if no reseek was required, or an
198438** error code if an error occurred.
198439*/
198440static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
198441  int rc = SQLITE_OK;
198442  assert( *pbSkip==0 );
198443  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
198444    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
198445    int bDesc = pCsr->bDesc;
198446    i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
198447
198448    rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
198449    if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
198450      *pbSkip = 1;
198451    }
198452
198453    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
198454    fts5CsrNewrow(pCsr);
198455    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
198456      CsrFlagSet(pCsr, FTS5CSR_EOF);
198457      *pbSkip = 1;
198458    }
198459  }
198460  return rc;
198461}
198462
198463
198464/*
198465** Advance the cursor to the next row in the table that matches the
198466** search criteria.
198467**
198468** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
198469** even if we reach end-of-file.  The fts5EofMethod() will be called
198470** subsequently to determine whether or not an EOF was hit.
198471*/
198472static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
198473  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
198474  int rc;
198475
198476  assert( (pCsr->ePlan<3)==
198477          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
198478  );
198479  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
198480
198481  if( pCsr->ePlan<3 ){
198482    int bSkip = 0;
198483    if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
198484    rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
198485    CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
198486    fts5CsrNewrow(pCsr);
198487  }else{
198488    switch( pCsr->ePlan ){
198489      case FTS5_PLAN_SPECIAL: {
198490        CsrFlagSet(pCsr, FTS5CSR_EOF);
198491        rc = SQLITE_OK;
198492        break;
198493      }
198494
198495      case FTS5_PLAN_SORTED_MATCH: {
198496        rc = fts5SorterNext(pCsr);
198497        break;
198498      }
198499
198500      default:
198501        rc = sqlite3_step(pCsr->pStmt);
198502        if( rc!=SQLITE_ROW ){
198503          CsrFlagSet(pCsr, FTS5CSR_EOF);
198504          rc = sqlite3_reset(pCsr->pStmt);
198505        }else{
198506          rc = SQLITE_OK;
198507        }
198508        break;
198509    }
198510  }
198511
198512  return rc;
198513}
198514
198515
198516static int fts5PrepareStatement(
198517  sqlite3_stmt **ppStmt,
198518  Fts5Config *pConfig,
198519  const char *zFmt,
198520  ...
198521){
198522  sqlite3_stmt *pRet = 0;
198523  int rc;
198524  char *zSql;
198525  va_list ap;
198526
198527  va_start(ap, zFmt);
198528  zSql = sqlite3_vmprintf(zFmt, ap);
198529  if( zSql==0 ){
198530    rc = SQLITE_NOMEM;
198531  }else{
198532    rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
198533                            SQLITE_PREPARE_PERSISTENT, &pRet, 0);
198534    if( rc!=SQLITE_OK ){
198535      *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
198536    }
198537    sqlite3_free(zSql);
198538  }
198539
198540  va_end(ap);
198541  *ppStmt = pRet;
198542  return rc;
198543}
198544
198545static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
198546  Fts5Config *pConfig = pTab->pConfig;
198547  Fts5Sorter *pSorter;
198548  int nPhrase;
198549  int nByte;
198550  int rc;
198551  const char *zRank = pCsr->zRank;
198552  const char *zRankArgs = pCsr->zRankArgs;
198553
198554  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
198555  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
198556  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
198557  if( pSorter==0 ) return SQLITE_NOMEM;
198558  memset(pSorter, 0, nByte);
198559  pSorter->nIdx = nPhrase;
198560
198561  /* TODO: It would be better to have some system for reusing statement
198562  ** handles here, rather than preparing a new one for each query. But that
198563  ** is not possible as SQLite reference counts the virtual table objects.
198564  ** And since the statement required here reads from this very virtual
198565  ** table, saving it creates a circular reference.
198566  **
198567  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
198568  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
198569      "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
198570      pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
198571      (zRankArgs ? ", " : ""),
198572      (zRankArgs ? zRankArgs : ""),
198573      bDesc ? "DESC" : "ASC"
198574  );
198575
198576  pCsr->pSorter = pSorter;
198577  if( rc==SQLITE_OK ){
198578    assert( pTab->pSortCsr==0 );
198579    pTab->pSortCsr = pCsr;
198580    rc = fts5SorterNext(pCsr);
198581    pTab->pSortCsr = 0;
198582  }
198583
198584  if( rc!=SQLITE_OK ){
198585    sqlite3_finalize(pSorter->pStmt);
198586    sqlite3_free(pSorter);
198587    pCsr->pSorter = 0;
198588  }
198589
198590  return rc;
198591}
198592
198593static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
198594  int rc;
198595  Fts5Expr *pExpr = pCsr->pExpr;
198596  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
198597  if( sqlite3Fts5ExprEof(pExpr) ){
198598    CsrFlagSet(pCsr, FTS5CSR_EOF);
198599  }
198600  fts5CsrNewrow(pCsr);
198601  return rc;
198602}
198603
198604/*
198605** Process a "special" query. A special query is identified as one with a
198606** MATCH expression that begins with a '*' character. The remainder of
198607** the text passed to the MATCH operator are used as  the special query
198608** parameters.
198609*/
198610static int fts5SpecialMatch(
198611  Fts5Table *pTab,
198612  Fts5Cursor *pCsr,
198613  const char *zQuery
198614){
198615  int rc = SQLITE_OK;             /* Return code */
198616  const char *z = zQuery;         /* Special query text */
198617  int n;                          /* Number of bytes in text at z */
198618
198619  while( z[0]==' ' ) z++;
198620  for(n=0; z[n] && z[n]!=' '; n++);
198621
198622  assert( pTab->base.zErrMsg==0 );
198623  pCsr->ePlan = FTS5_PLAN_SPECIAL;
198624
198625  if( 0==sqlite3_strnicmp("reads", z, n) ){
198626    pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
198627  }
198628  else if( 0==sqlite3_strnicmp("id", z, n) ){
198629    pCsr->iSpecial = pCsr->iCsrId;
198630  }
198631  else{
198632    /* An unrecognized directive. Return an error message. */
198633    pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
198634    rc = SQLITE_ERROR;
198635  }
198636
198637  return rc;
198638}
198639
198640/*
198641** Search for an auxiliary function named zName that can be used with table
198642** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
198643** structure. Otherwise, if no such function exists, return NULL.
198644*/
198645static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
198646  Fts5Auxiliary *pAux;
198647
198648  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
198649    if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
198650  }
198651
198652  /* No function of the specified name was found. Return 0. */
198653  return 0;
198654}
198655
198656
198657static int fts5FindRankFunction(Fts5Cursor *pCsr){
198658  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
198659  Fts5Config *pConfig = pTab->pConfig;
198660  int rc = SQLITE_OK;
198661  Fts5Auxiliary *pAux = 0;
198662  const char *zRank = pCsr->zRank;
198663  const char *zRankArgs = pCsr->zRankArgs;
198664
198665  if( zRankArgs ){
198666    char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
198667    if( zSql ){
198668      sqlite3_stmt *pStmt = 0;
198669      rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
198670                              SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
198671      sqlite3_free(zSql);
198672      assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
198673      if( rc==SQLITE_OK ){
198674        if( SQLITE_ROW==sqlite3_step(pStmt) ){
198675          int nByte;
198676          pCsr->nRankArg = sqlite3_column_count(pStmt);
198677          nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
198678          pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
198679          if( rc==SQLITE_OK ){
198680            int i;
198681            for(i=0; i<pCsr->nRankArg; i++){
198682              pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
198683            }
198684          }
198685          pCsr->pRankArgStmt = pStmt;
198686        }else{
198687          rc = sqlite3_finalize(pStmt);
198688          assert( rc!=SQLITE_OK );
198689        }
198690      }
198691    }
198692  }
198693
198694  if( rc==SQLITE_OK ){
198695    pAux = fts5FindAuxiliary(pTab, zRank);
198696    if( pAux==0 ){
198697      assert( pTab->base.zErrMsg==0 );
198698      pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
198699      rc = SQLITE_ERROR;
198700    }
198701  }
198702
198703  pCsr->pRank = pAux;
198704  return rc;
198705}
198706
198707
198708static int fts5CursorParseRank(
198709  Fts5Config *pConfig,
198710  Fts5Cursor *pCsr,
198711  sqlite3_value *pRank
198712){
198713  int rc = SQLITE_OK;
198714  if( pRank ){
198715    const char *z = (const char*)sqlite3_value_text(pRank);
198716    char *zRank = 0;
198717    char *zRankArgs = 0;
198718
198719    if( z==0 ){
198720      if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
198721    }else{
198722      rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
198723    }
198724    if( rc==SQLITE_OK ){
198725      pCsr->zRank = zRank;
198726      pCsr->zRankArgs = zRankArgs;
198727      CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
198728    }else if( rc==SQLITE_ERROR ){
198729      pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
198730          "parse error in rank function: %s", z
198731      );
198732    }
198733  }else{
198734    if( pConfig->zRank ){
198735      pCsr->zRank = (char*)pConfig->zRank;
198736      pCsr->zRankArgs = (char*)pConfig->zRankArgs;
198737    }else{
198738      pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
198739      pCsr->zRankArgs = 0;
198740    }
198741  }
198742  return rc;
198743}
198744
198745static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
198746  if( pVal ){
198747    int eType = sqlite3_value_numeric_type(pVal);
198748    if( eType==SQLITE_INTEGER ){
198749      return sqlite3_value_int64(pVal);
198750    }
198751  }
198752  return iDefault;
198753}
198754
198755/*
198756** This is the xFilter interface for the virtual table.  See
198757** the virtual table xFilter method documentation for additional
198758** information.
198759**
198760** There are three possible query strategies:
198761**
198762**   1. Full-text search using a MATCH operator.
198763**   2. A by-rowid lookup.
198764**   3. A full-table scan.
198765*/
198766static int fts5FilterMethod(
198767  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
198768  int idxNum,                     /* Strategy index */
198769  const char *zUnused,            /* Unused */
198770  int nVal,                       /* Number of elements in apVal */
198771  sqlite3_value **apVal           /* Arguments for the indexing scheme */
198772){
198773  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
198774  Fts5Config *pConfig = pTab->pConfig;
198775  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
198776  int rc = SQLITE_OK;             /* Error code */
198777  int iVal = 0;                   /* Counter for apVal[] */
198778  int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
198779  int bOrderByRank;               /* True if ORDER BY rank */
198780  sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
198781  sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
198782  sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
198783  sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
198784  sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
198785  int iCol;                       /* Column on LHS of MATCH operator */
198786  char **pzErrmsg = pConfig->pzErrmsg;
198787
198788  UNUSED_PARAM(zUnused);
198789  UNUSED_PARAM(nVal);
198790
198791  if( pCsr->ePlan ){
198792    fts5FreeCursorComponents(pCsr);
198793    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
198794  }
198795
198796  assert( pCsr->pStmt==0 );
198797  assert( pCsr->pExpr==0 );
198798  assert( pCsr->csrflags==0 );
198799  assert( pCsr->pRank==0 );
198800  assert( pCsr->zRank==0 );
198801  assert( pCsr->zRankArgs==0 );
198802
198803  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
198804  pConfig->pzErrmsg = &pTab->base.zErrMsg;
198805
198806  /* Decode the arguments passed through to this function.
198807  **
198808  ** Note: The following set of if(...) statements must be in the same
198809  ** order as the corresponding entries in the struct at the top of
198810  ** fts5BestIndexMethod().  */
198811  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
198812  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
198813  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
198814  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
198815  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
198816  iCol = (idxNum>>16);
198817  assert( iCol>=0 && iCol<=pConfig->nCol );
198818  assert( iVal==nVal );
198819  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
198820  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
198821
198822  /* Set the cursor upper and lower rowid limits. Only some strategies
198823  ** actually use them. This is ok, as the xBestIndex() method leaves the
198824  ** sqlite3_index_constraint.omit flag clear for range constraints
198825  ** on the rowid field.  */
198826  if( pRowidEq ){
198827    pRowidLe = pRowidGe = pRowidEq;
198828  }
198829  if( bDesc ){
198830    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
198831    pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
198832  }else{
198833    pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
198834    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
198835  }
198836
198837  if( pTab->pSortCsr ){
198838    /* If pSortCsr is non-NULL, then this call is being made as part of
198839    ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
198840    ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
198841    ** return results to the user for this query. The current cursor
198842    ** (pCursor) is used to execute the query issued by function
198843    ** fts5CursorFirstSorted() above.  */
198844    assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
198845    assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
198846    assert( pCsr->iLastRowid==LARGEST_INT64 );
198847    assert( pCsr->iFirstRowid==SMALLEST_INT64 );
198848    pCsr->ePlan = FTS5_PLAN_SOURCE;
198849    pCsr->pExpr = pTab->pSortCsr->pExpr;
198850    rc = fts5CursorFirst(pTab, pCsr, bDesc);
198851  }else if( pMatch ){
198852    const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
198853    if( zExpr==0 ) zExpr = "";
198854
198855    rc = fts5CursorParseRank(pConfig, pCsr, pRank);
198856    if( rc==SQLITE_OK ){
198857      if( zExpr[0]=='*' ){
198858        /* The user has issued a query of the form "MATCH '*...'". This
198859        ** indicates that the MATCH expression is not a full text query,
198860        ** but a request for an internal parameter.  */
198861        rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
198862      }else{
198863        char **pzErr = &pTab->base.zErrMsg;
198864        rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
198865        if( rc==SQLITE_OK ){
198866          if( bOrderByRank ){
198867            pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
198868            rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
198869          }else{
198870            pCsr->ePlan = FTS5_PLAN_MATCH;
198871            rc = fts5CursorFirst(pTab, pCsr, bDesc);
198872          }
198873        }
198874      }
198875    }
198876  }else if( pConfig->zContent==0 ){
198877    *pConfig->pzErrmsg = sqlite3_mprintf(
198878        "%s: table does not support scanning", pConfig->zName
198879    );
198880    rc = SQLITE_ERROR;
198881  }else{
198882    /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
198883    ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
198884    pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
198885    rc = sqlite3Fts5StorageStmt(
198886        pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
198887    );
198888    if( rc==SQLITE_OK ){
198889      if( pCsr->ePlan==FTS5_PLAN_ROWID ){
198890        sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
198891      }else{
198892        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
198893        sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
198894      }
198895      rc = fts5NextMethod(pCursor);
198896    }
198897  }
198898
198899  pConfig->pzErrmsg = pzErrmsg;
198900  return rc;
198901}
198902
198903/*
198904** This is the xEof method of the virtual table. SQLite calls this
198905** routine to find out if it has reached the end of a result set.
198906*/
198907static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
198908  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
198909  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
198910}
198911
198912/*
198913** Return the rowid that the cursor currently points to.
198914*/
198915static i64 fts5CursorRowid(Fts5Cursor *pCsr){
198916  assert( pCsr->ePlan==FTS5_PLAN_MATCH
198917       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
198918       || pCsr->ePlan==FTS5_PLAN_SOURCE
198919  );
198920  if( pCsr->pSorter ){
198921    return pCsr->pSorter->iRowid;
198922  }else{
198923    return sqlite3Fts5ExprRowid(pCsr->pExpr);
198924  }
198925}
198926
198927/*
198928** This is the xRowid method. The SQLite core calls this routine to
198929** retrieve the rowid for the current row of the result set. fts5
198930** exposes %_content.rowid as the rowid for the virtual table. The
198931** rowid should be written to *pRowid.
198932*/
198933static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
198934  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
198935  int ePlan = pCsr->ePlan;
198936
198937  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
198938  switch( ePlan ){
198939    case FTS5_PLAN_SPECIAL:
198940      *pRowid = 0;
198941      break;
198942
198943    case FTS5_PLAN_SOURCE:
198944    case FTS5_PLAN_MATCH:
198945    case FTS5_PLAN_SORTED_MATCH:
198946      *pRowid = fts5CursorRowid(pCsr);
198947      break;
198948
198949    default:
198950      *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
198951      break;
198952  }
198953
198954  return SQLITE_OK;
198955}
198956
198957/*
198958** If the cursor requires seeking (bSeekRequired flag is set), seek it.
198959** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
198960**
198961** If argument bErrormsg is true and an error occurs, an error message may
198962** be left in sqlite3_vtab.zErrMsg.
198963*/
198964static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
198965  int rc = SQLITE_OK;
198966
198967  /* If the cursor does not yet have a statement handle, obtain one now. */
198968  if( pCsr->pStmt==0 ){
198969    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
198970    int eStmt = fts5StmtType(pCsr);
198971    rc = sqlite3Fts5StorageStmt(
198972        pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
198973    );
198974    assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
198975    assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
198976  }
198977
198978  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
198979    assert( pCsr->pExpr );
198980    sqlite3_reset(pCsr->pStmt);
198981    sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
198982    rc = sqlite3_step(pCsr->pStmt);
198983    if( rc==SQLITE_ROW ){
198984      rc = SQLITE_OK;
198985      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
198986    }else{
198987      rc = sqlite3_reset(pCsr->pStmt);
198988      if( rc==SQLITE_OK ){
198989        rc = FTS5_CORRUPT;
198990      }
198991    }
198992  }
198993  return rc;
198994}
198995
198996static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
198997  va_list ap;                     /* ... printf arguments */
198998  va_start(ap, zFormat);
198999  assert( p->base.zErrMsg==0 );
199000  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
199001  va_end(ap);
199002}
199003
199004/*
199005** This function is called to handle an FTS INSERT command. In other words,
199006** an INSERT statement of the form:
199007**
199008**     INSERT INTO fts(fts) VALUES($pCmd)
199009**     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
199010**
199011** Argument pVal is the value assigned to column "fts" by the INSERT
199012** statement. This function returns SQLITE_OK if successful, or an SQLite
199013** error code if an error occurs.
199014**
199015** The commands implemented by this function are documented in the "Special
199016** INSERT Directives" section of the documentation. It should be updated if
199017** more commands are added to this function.
199018*/
199019static int fts5SpecialInsert(
199020  Fts5Table *pTab,                /* Fts5 table object */
199021  const char *zCmd,               /* Text inserted into table-name column */
199022  sqlite3_value *pVal             /* Value inserted into rank column */
199023){
199024  Fts5Config *pConfig = pTab->pConfig;
199025  int rc = SQLITE_OK;
199026  int bError = 0;
199027
199028  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
199029    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
199030      fts5SetVtabError(pTab,
199031          "'delete-all' may only be used with a "
199032          "contentless or external content fts5 table"
199033      );
199034      rc = SQLITE_ERROR;
199035    }else{
199036      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
199037    }
199038  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
199039    if( pConfig->eContent==FTS5_CONTENT_NONE ){
199040      fts5SetVtabError(pTab,
199041          "'rebuild' may not be used with a contentless fts5 table"
199042      );
199043      rc = SQLITE_ERROR;
199044    }else{
199045      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
199046    }
199047  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
199048    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
199049  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
199050    int nMerge = sqlite3_value_int(pVal);
199051    rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
199052  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
199053    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
199054#ifdef SQLITE_DEBUG
199055  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
199056    pConfig->bPrefixIndex = sqlite3_value_int(pVal);
199057#endif
199058  }else{
199059    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
199060    if( rc==SQLITE_OK ){
199061      rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
199062    }
199063    if( rc==SQLITE_OK ){
199064      if( bError ){
199065        rc = SQLITE_ERROR;
199066      }else{
199067        rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
199068      }
199069    }
199070  }
199071  return rc;
199072}
199073
199074static int fts5SpecialDelete(
199075  Fts5Table *pTab,
199076  sqlite3_value **apVal
199077){
199078  int rc = SQLITE_OK;
199079  int eType1 = sqlite3_value_type(apVal[1]);
199080  if( eType1==SQLITE_INTEGER ){
199081    sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
199082    rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
199083  }
199084  return rc;
199085}
199086
199087static void fts5StorageInsert(
199088  int *pRc,
199089  Fts5Table *pTab,
199090  sqlite3_value **apVal,
199091  i64 *piRowid
199092){
199093  int rc = *pRc;
199094  if( rc==SQLITE_OK ){
199095    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
199096  }
199097  if( rc==SQLITE_OK ){
199098    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
199099  }
199100  *pRc = rc;
199101}
199102
199103/*
199104** This function is the implementation of the xUpdate callback used by
199105** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
199106** inserted, updated or deleted.
199107**
199108** A delete specifies a single argument - the rowid of the row to remove.
199109**
199110** Update and insert operations pass:
199111**
199112**   1. The "old" rowid, or NULL.
199113**   2. The "new" rowid.
199114**   3. Values for each of the nCol matchable columns.
199115**   4. Values for the two hidden columns (<tablename> and "rank").
199116*/
199117static int fts5UpdateMethod(
199118  sqlite3_vtab *pVtab,            /* Virtual table handle */
199119  int nArg,                       /* Size of argument array */
199120  sqlite3_value **apVal,          /* Array of arguments */
199121  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
199122){
199123  Fts5Table *pTab = (Fts5Table*)pVtab;
199124  Fts5Config *pConfig = pTab->pConfig;
199125  int eType0;                     /* value_type() of apVal[0] */
199126  int rc = SQLITE_OK;             /* Return code */
199127
199128  /* A transaction must be open when this is called. */
199129  assert( pTab->ts.eState==1 );
199130
199131  assert( pVtab->zErrMsg==0 );
199132  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
199133  assert( nArg==1
199134      || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
199135      || sqlite3_value_type(apVal[1])==SQLITE_NULL
199136  );
199137  assert( pTab->pConfig->pzErrmsg==0 );
199138  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
199139
199140  /* Put any active cursors into REQUIRE_SEEK state. */
199141  fts5TripCursors(pTab);
199142
199143  eType0 = sqlite3_value_type(apVal[0]);
199144  if( eType0==SQLITE_NULL
199145   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
199146  ){
199147    /* A "special" INSERT op. These are handled separately. */
199148    const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
199149    if( pConfig->eContent!=FTS5_CONTENT_NORMAL
199150      && 0==sqlite3_stricmp("delete", z)
199151    ){
199152      rc = fts5SpecialDelete(pTab, apVal);
199153    }else{
199154      rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
199155    }
199156  }else{
199157    /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
199158    ** any conflict on the rowid value must be detected before any
199159    ** modifications are made to the database file. There are 4 cases:
199160    **
199161    **   1) DELETE
199162    **   2) UPDATE (rowid not modified)
199163    **   3) UPDATE (rowid modified)
199164    **   4) INSERT
199165    **
199166    ** Cases 3 and 4 may violate the rowid constraint.
199167    */
199168    int eConflict = SQLITE_ABORT;
199169    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
199170      eConflict = sqlite3_vtab_on_conflict(pConfig->db);
199171    }
199172
199173    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
199174    assert( nArg!=1 || eType0==SQLITE_INTEGER );
199175
199176    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
199177    ** This is not suported.  */
199178    if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
199179      pTab->base.zErrMsg = sqlite3_mprintf(
199180          "cannot %s contentless fts5 table: %s",
199181          (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
199182      );
199183      rc = SQLITE_ERROR;
199184    }
199185
199186    /* DELETE */
199187    else if( nArg==1 ){
199188      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
199189      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
199190    }
199191
199192    /* INSERT */
199193    else if( eType0!=SQLITE_INTEGER ){
199194      /* If this is a REPLACE, first remove the current entry (if any) */
199195      if( eConflict==SQLITE_REPLACE
199196       && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
199197      ){
199198        i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
199199        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
199200      }
199201      fts5StorageInsert(&rc, pTab, apVal, pRowid);
199202    }
199203
199204    /* UPDATE */
199205    else{
199206      i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
199207      i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
199208      if( iOld!=iNew ){
199209        if( eConflict==SQLITE_REPLACE ){
199210          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
199211          if( rc==SQLITE_OK ){
199212            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
199213          }
199214          fts5StorageInsert(&rc, pTab, apVal, pRowid);
199215        }else{
199216          rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
199217          if( rc==SQLITE_OK ){
199218            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
199219          }
199220          if( rc==SQLITE_OK ){
199221            rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
199222          }
199223        }
199224      }else{
199225        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
199226        fts5StorageInsert(&rc, pTab, apVal, pRowid);
199227      }
199228    }
199229  }
199230
199231  pTab->pConfig->pzErrmsg = 0;
199232  return rc;
199233}
199234
199235/*
199236** Implementation of xSync() method.
199237*/
199238static int fts5SyncMethod(sqlite3_vtab *pVtab){
199239  int rc;
199240  Fts5Table *pTab = (Fts5Table*)pVtab;
199241  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
199242  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
199243  fts5TripCursors(pTab);
199244  rc = sqlite3Fts5StorageSync(pTab->pStorage);
199245  pTab->pConfig->pzErrmsg = 0;
199246  return rc;
199247}
199248
199249/*
199250** Implementation of xBegin() method.
199251*/
199252static int fts5BeginMethod(sqlite3_vtab *pVtab){
199253  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
199254  fts5NewTransaction((Fts5Table*)pVtab);
199255  return SQLITE_OK;
199256}
199257
199258/*
199259** Implementation of xCommit() method. This is a no-op. The contents of
199260** the pending-terms hash-table have already been flushed into the database
199261** by fts5SyncMethod().
199262*/
199263static int fts5CommitMethod(sqlite3_vtab *pVtab){
199264  UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
199265  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
199266  return SQLITE_OK;
199267}
199268
199269/*
199270** Implementation of xRollback(). Discard the contents of the pending-terms
199271** hash-table. Any changes made to the database are reverted by SQLite.
199272*/
199273static int fts5RollbackMethod(sqlite3_vtab *pVtab){
199274  int rc;
199275  Fts5Table *pTab = (Fts5Table*)pVtab;
199276  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
199277  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
199278  return rc;
199279}
199280
199281static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
199282
199283static void *fts5ApiUserData(Fts5Context *pCtx){
199284  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199285  return pCsr->pAux->pUserData;
199286}
199287
199288static int fts5ApiColumnCount(Fts5Context *pCtx){
199289  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199290  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
199291}
199292
199293static int fts5ApiColumnTotalSize(
199294  Fts5Context *pCtx,
199295  int iCol,
199296  sqlite3_int64 *pnToken
199297){
199298  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199299  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199300  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
199301}
199302
199303static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
199304  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199305  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199306  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
199307}
199308
199309static int fts5ApiTokenize(
199310  Fts5Context *pCtx,
199311  const char *pText, int nText,
199312  void *pUserData,
199313  int (*xToken)(void*, int, const char*, int, int, int)
199314){
199315  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199316  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199317  return sqlite3Fts5Tokenize(
199318      pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
199319  );
199320}
199321
199322static int fts5ApiPhraseCount(Fts5Context *pCtx){
199323  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199324  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
199325}
199326
199327static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
199328  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199329  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
199330}
199331
199332static int fts5ApiColumnText(
199333  Fts5Context *pCtx,
199334  int iCol,
199335  const char **pz,
199336  int *pn
199337){
199338  int rc = SQLITE_OK;
199339  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199340  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
199341    *pz = 0;
199342    *pn = 0;
199343  }else{
199344    rc = fts5SeekCursor(pCsr, 0);
199345    if( rc==SQLITE_OK ){
199346      *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
199347      *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
199348    }
199349  }
199350  return rc;
199351}
199352
199353static int fts5CsrPoslist(
199354  Fts5Cursor *pCsr,
199355  int iPhrase,
199356  const u8 **pa,
199357  int *pn
199358){
199359  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
199360  int rc = SQLITE_OK;
199361  int bLive = (pCsr->pSorter==0);
199362
199363  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
199364
199365    if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
199366      Fts5PoslistPopulator *aPopulator;
199367      int i;
199368      aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
199369      if( aPopulator==0 ) rc = SQLITE_NOMEM;
199370      for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
199371        int n; const char *z;
199372        rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
199373        if( rc==SQLITE_OK ){
199374          rc = sqlite3Fts5ExprPopulatePoslists(
199375              pConfig, pCsr->pExpr, aPopulator, i, z, n
199376          );
199377        }
199378      }
199379      sqlite3_free(aPopulator);
199380
199381      if( pCsr->pSorter ){
199382        sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
199383      }
199384    }
199385    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
199386  }
199387
199388  if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
199389    Fts5Sorter *pSorter = pCsr->pSorter;
199390    int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
199391    *pn = pSorter->aIdx[iPhrase] - i1;
199392    *pa = &pSorter->aPoslist[i1];
199393  }else{
199394    *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
199395  }
199396
199397  return rc;
199398}
199399
199400/*
199401** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
199402** correctly for the current view. Return SQLITE_OK if successful, or an
199403** SQLite error code otherwise.
199404*/
199405static int fts5CacheInstArray(Fts5Cursor *pCsr){
199406  int rc = SQLITE_OK;
199407  Fts5PoslistReader *aIter;       /* One iterator for each phrase */
199408  int nIter;                      /* Number of iterators/phrases */
199409
199410  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
199411  if( pCsr->aInstIter==0 ){
199412    int nByte = sizeof(Fts5PoslistReader) * nIter;
199413    pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
199414  }
199415  aIter = pCsr->aInstIter;
199416
199417  if( aIter ){
199418    int nInst = 0;                /* Number instances seen so far */
199419    int i;
199420
199421    /* Initialize all iterators */
199422    for(i=0; i<nIter && rc==SQLITE_OK; i++){
199423      const u8 *a;
199424      int n;
199425      rc = fts5CsrPoslist(pCsr, i, &a, &n);
199426      if( rc==SQLITE_OK ){
199427        sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
199428      }
199429    }
199430
199431    if( rc==SQLITE_OK ){
199432      while( 1 ){
199433        int *aInst;
199434        int iBest = -1;
199435        for(i=0; i<nIter; i++){
199436          if( (aIter[i].bEof==0)
199437              && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
199438            ){
199439            iBest = i;
199440          }
199441        }
199442        if( iBest<0 ) break;
199443
199444        nInst++;
199445        if( nInst>=pCsr->nInstAlloc ){
199446          pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
199447          aInst = (int*)sqlite3_realloc(
199448              pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
199449              );
199450          if( aInst ){
199451            pCsr->aInst = aInst;
199452          }else{
199453            rc = SQLITE_NOMEM;
199454            break;
199455          }
199456        }
199457
199458        aInst = &pCsr->aInst[3 * (nInst-1)];
199459        aInst[0] = iBest;
199460        aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
199461        aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
199462        sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
199463      }
199464    }
199465
199466    pCsr->nInstCount = nInst;
199467    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
199468  }
199469  return rc;
199470}
199471
199472static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
199473  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199474  int rc = SQLITE_OK;
199475  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
199476   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
199477    *pnInst = pCsr->nInstCount;
199478  }
199479  return rc;
199480}
199481
199482static int fts5ApiInst(
199483  Fts5Context *pCtx,
199484  int iIdx,
199485  int *piPhrase,
199486  int *piCol,
199487  int *piOff
199488){
199489  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199490  int rc = SQLITE_OK;
199491  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
199492   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
199493  ){
199494    if( iIdx<0 || iIdx>=pCsr->nInstCount ){
199495      rc = SQLITE_RANGE;
199496#if 0
199497    }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
199498      *piPhrase = pCsr->aInst[iIdx*3];
199499      *piCol = pCsr->aInst[iIdx*3 + 2];
199500      *piOff = -1;
199501#endif
199502    }else{
199503      *piPhrase = pCsr->aInst[iIdx*3];
199504      *piCol = pCsr->aInst[iIdx*3 + 1];
199505      *piOff = pCsr->aInst[iIdx*3 + 2];
199506    }
199507  }
199508  return rc;
199509}
199510
199511static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
199512  return fts5CursorRowid((Fts5Cursor*)pCtx);
199513}
199514
199515static int fts5ColumnSizeCb(
199516  void *pContext,                 /* Pointer to int */
199517  int tflags,
199518  const char *pUnused,            /* Buffer containing token */
199519  int nUnused,                    /* Size of token in bytes */
199520  int iUnused1,                   /* Start offset of token */
199521  int iUnused2                    /* End offset of token */
199522){
199523  int *pCnt = (int*)pContext;
199524  UNUSED_PARAM2(pUnused, nUnused);
199525  UNUSED_PARAM2(iUnused1, iUnused2);
199526  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
199527    (*pCnt)++;
199528  }
199529  return SQLITE_OK;
199530}
199531
199532static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
199533  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199534  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199535  Fts5Config *pConfig = pTab->pConfig;
199536  int rc = SQLITE_OK;
199537
199538  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
199539    if( pConfig->bColumnsize ){
199540      i64 iRowid = fts5CursorRowid(pCsr);
199541      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
199542    }else if( pConfig->zContent==0 ){
199543      int i;
199544      for(i=0; i<pConfig->nCol; i++){
199545        if( pConfig->abUnindexed[i]==0 ){
199546          pCsr->aColumnSize[i] = -1;
199547        }
199548      }
199549    }else{
199550      int i;
199551      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
199552        if( pConfig->abUnindexed[i]==0 ){
199553          const char *z; int n;
199554          void *p = (void*)(&pCsr->aColumnSize[i]);
199555          pCsr->aColumnSize[i] = 0;
199556          rc = fts5ApiColumnText(pCtx, i, &z, &n);
199557          if( rc==SQLITE_OK ){
199558            rc = sqlite3Fts5Tokenize(
199559                pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
199560            );
199561          }
199562        }
199563      }
199564    }
199565    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
199566  }
199567  if( iCol<0 ){
199568    int i;
199569    *pnToken = 0;
199570    for(i=0; i<pConfig->nCol; i++){
199571      *pnToken += pCsr->aColumnSize[i];
199572    }
199573  }else if( iCol<pConfig->nCol ){
199574    *pnToken = pCsr->aColumnSize[iCol];
199575  }else{
199576    *pnToken = 0;
199577    rc = SQLITE_RANGE;
199578  }
199579  return rc;
199580}
199581
199582/*
199583** Implementation of the xSetAuxdata() method.
199584*/
199585static int fts5ApiSetAuxdata(
199586  Fts5Context *pCtx,              /* Fts5 context */
199587  void *pPtr,                     /* Pointer to save as auxdata */
199588  void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
199589){
199590  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199591  Fts5Auxdata *pData;
199592
199593  /* Search through the cursors list of Fts5Auxdata objects for one that
199594  ** corresponds to the currently executing auxiliary function.  */
199595  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
199596    if( pData->pAux==pCsr->pAux ) break;
199597  }
199598
199599  if( pData ){
199600    if( pData->xDelete ){
199601      pData->xDelete(pData->pPtr);
199602    }
199603  }else{
199604    int rc = SQLITE_OK;
199605    pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
199606    if( pData==0 ){
199607      if( xDelete ) xDelete(pPtr);
199608      return rc;
199609    }
199610    pData->pAux = pCsr->pAux;
199611    pData->pNext = pCsr->pAuxdata;
199612    pCsr->pAuxdata = pData;
199613  }
199614
199615  pData->xDelete = xDelete;
199616  pData->pPtr = pPtr;
199617  return SQLITE_OK;
199618}
199619
199620static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
199621  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199622  Fts5Auxdata *pData;
199623  void *pRet = 0;
199624
199625  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
199626    if( pData->pAux==pCsr->pAux ) break;
199627  }
199628
199629  if( pData ){
199630    pRet = pData->pPtr;
199631    if( bClear ){
199632      pData->pPtr = 0;
199633      pData->xDelete = 0;
199634    }
199635  }
199636
199637  return pRet;
199638}
199639
199640static void fts5ApiPhraseNext(
199641  Fts5Context *pUnused,
199642  Fts5PhraseIter *pIter,
199643  int *piCol, int *piOff
199644){
199645  UNUSED_PARAM(pUnused);
199646  if( pIter->a>=pIter->b ){
199647    *piCol = -1;
199648    *piOff = -1;
199649  }else{
199650    int iVal;
199651    pIter->a += fts5GetVarint32(pIter->a, iVal);
199652    if( iVal==1 ){
199653      pIter->a += fts5GetVarint32(pIter->a, iVal);
199654      *piCol = iVal;
199655      *piOff = 0;
199656      pIter->a += fts5GetVarint32(pIter->a, iVal);
199657    }
199658    *piOff += (iVal-2);
199659  }
199660}
199661
199662static int fts5ApiPhraseFirst(
199663  Fts5Context *pCtx,
199664  int iPhrase,
199665  Fts5PhraseIter *pIter,
199666  int *piCol, int *piOff
199667){
199668  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199669  int n;
199670  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
199671  if( rc==SQLITE_OK ){
199672    pIter->b = &pIter->a[n];
199673    *piCol = 0;
199674    *piOff = 0;
199675    fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
199676  }
199677  return rc;
199678}
199679
199680static void fts5ApiPhraseNextColumn(
199681  Fts5Context *pCtx,
199682  Fts5PhraseIter *pIter,
199683  int *piCol
199684){
199685  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199686  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
199687
199688  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
199689    if( pIter->a>=pIter->b ){
199690      *piCol = -1;
199691    }else{
199692      int iIncr;
199693      pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
199694      *piCol += (iIncr-2);
199695    }
199696  }else{
199697    while( 1 ){
199698      int dummy;
199699      if( pIter->a>=pIter->b ){
199700        *piCol = -1;
199701        return;
199702      }
199703      if( pIter->a[0]==0x01 ) break;
199704      pIter->a += fts5GetVarint32(pIter->a, dummy);
199705    }
199706    pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
199707  }
199708}
199709
199710static int fts5ApiPhraseFirstColumn(
199711  Fts5Context *pCtx,
199712  int iPhrase,
199713  Fts5PhraseIter *pIter,
199714  int *piCol
199715){
199716  int rc = SQLITE_OK;
199717  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199718  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
199719
199720  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
199721    Fts5Sorter *pSorter = pCsr->pSorter;
199722    int n;
199723    if( pSorter ){
199724      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
199725      n = pSorter->aIdx[iPhrase] - i1;
199726      pIter->a = &pSorter->aPoslist[i1];
199727    }else{
199728      rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
199729    }
199730    if( rc==SQLITE_OK ){
199731      pIter->b = &pIter->a[n];
199732      *piCol = 0;
199733      fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
199734    }
199735  }else{
199736    int n;
199737    rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
199738    if( rc==SQLITE_OK ){
199739      pIter->b = &pIter->a[n];
199740      if( n<=0 ){
199741        *piCol = -1;
199742      }else if( pIter->a[0]==0x01 ){
199743        pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
199744      }else{
199745        *piCol = 0;
199746      }
199747    }
199748  }
199749
199750  return rc;
199751}
199752
199753
199754static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
199755    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
199756);
199757
199758static const Fts5ExtensionApi sFts5Api = {
199759  2,                            /* iVersion */
199760  fts5ApiUserData,
199761  fts5ApiColumnCount,
199762  fts5ApiRowCount,
199763  fts5ApiColumnTotalSize,
199764  fts5ApiTokenize,
199765  fts5ApiPhraseCount,
199766  fts5ApiPhraseSize,
199767  fts5ApiInstCount,
199768  fts5ApiInst,
199769  fts5ApiRowid,
199770  fts5ApiColumnText,
199771  fts5ApiColumnSize,
199772  fts5ApiQueryPhrase,
199773  fts5ApiSetAuxdata,
199774  fts5ApiGetAuxdata,
199775  fts5ApiPhraseFirst,
199776  fts5ApiPhraseNext,
199777  fts5ApiPhraseFirstColumn,
199778  fts5ApiPhraseNextColumn,
199779};
199780
199781/*
199782** Implementation of API function xQueryPhrase().
199783*/
199784static int fts5ApiQueryPhrase(
199785  Fts5Context *pCtx,
199786  int iPhrase,
199787  void *pUserData,
199788  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
199789){
199790  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
199791  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
199792  int rc;
199793  Fts5Cursor *pNew = 0;
199794
199795  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
199796  if( rc==SQLITE_OK ){
199797    pNew->ePlan = FTS5_PLAN_MATCH;
199798    pNew->iFirstRowid = SMALLEST_INT64;
199799    pNew->iLastRowid = LARGEST_INT64;
199800    pNew->base.pVtab = (sqlite3_vtab*)pTab;
199801    rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
199802  }
199803
199804  if( rc==SQLITE_OK ){
199805    for(rc = fts5CursorFirst(pTab, pNew, 0);
199806        rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
199807        rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
199808    ){
199809      rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
199810      if( rc!=SQLITE_OK ){
199811        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
199812        break;
199813      }
199814    }
199815  }
199816
199817  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
199818  return rc;
199819}
199820
199821static void fts5ApiInvoke(
199822  Fts5Auxiliary *pAux,
199823  Fts5Cursor *pCsr,
199824  sqlite3_context *context,
199825  int argc,
199826  sqlite3_value **argv
199827){
199828  assert( pCsr->pAux==0 );
199829  pCsr->pAux = pAux;
199830  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
199831  pCsr->pAux = 0;
199832}
199833
199834static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
199835  Fts5Cursor *pCsr;
199836  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
199837    if( pCsr->iCsrId==iCsrId ) break;
199838  }
199839  return pCsr;
199840}
199841
199842static void fts5ApiCallback(
199843  sqlite3_context *context,
199844  int argc,
199845  sqlite3_value **argv
199846){
199847
199848  Fts5Auxiliary *pAux;
199849  Fts5Cursor *pCsr;
199850  i64 iCsrId;
199851
199852  assert( argc>=1 );
199853  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
199854  iCsrId = sqlite3_value_int64(argv[0]);
199855
199856  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
199857  if( pCsr==0 ){
199858    char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
199859    sqlite3_result_error(context, zErr, -1);
199860    sqlite3_free(zErr);
199861  }else{
199862    fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
199863  }
199864}
199865
199866
199867/*
199868** Given cursor id iId, return a pointer to the corresponding Fts5Index
199869** object. Or NULL If the cursor id does not exist.
199870**
199871** If successful, set *ppConfig to point to the associated config object
199872** before returning.
199873*/
199874static Fts5Index *sqlite3Fts5IndexFromCsrid(
199875  Fts5Global *pGlobal,            /* FTS5 global context for db handle */
199876  i64 iCsrId,                     /* Id of cursor to find */
199877  Fts5Config **ppConfig           /* OUT: Configuration object */
199878){
199879  Fts5Cursor *pCsr;
199880  Fts5Table *pTab;
199881
199882  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
199883  pTab = (Fts5Table*)pCsr->base.pVtab;
199884  *ppConfig = pTab->pConfig;
199885
199886  return pTab->pIndex;
199887}
199888
199889/*
199890** Return a "position-list blob" corresponding to the current position of
199891** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
199892** the current position-list for each phrase in the query associated with
199893** cursor pCsr.
199894**
199895** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
199896** the number of phrases in the query. Following the varints are the
199897** concatenated position lists for each phrase, in order.
199898**
199899** The first varint (if it exists) contains the size of the position list
199900** for phrase 0. The second (same disclaimer) contains the size of position
199901** list 1. And so on. There is no size field for the final position list,
199902** as it can be derived from the total size of the blob.
199903*/
199904static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
199905  int i;
199906  int rc = SQLITE_OK;
199907  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
199908  Fts5Buffer val;
199909
199910  memset(&val, 0, sizeof(Fts5Buffer));
199911  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
199912    case FTS5_DETAIL_FULL:
199913
199914      /* Append the varints */
199915      for(i=0; i<(nPhrase-1); i++){
199916        const u8 *dummy;
199917        int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
199918        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
199919      }
199920
199921      /* Append the position lists */
199922      for(i=0; i<nPhrase; i++){
199923        const u8 *pPoslist;
199924        int nPoslist;
199925        nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
199926        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
199927      }
199928      break;
199929
199930    case FTS5_DETAIL_COLUMNS:
199931
199932      /* Append the varints */
199933      for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
199934        const u8 *dummy;
199935        int nByte;
199936        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
199937        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
199938      }
199939
199940      /* Append the position lists */
199941      for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
199942        const u8 *pPoslist;
199943        int nPoslist;
199944        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
199945        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
199946      }
199947      break;
199948
199949    default:
199950      break;
199951  }
199952
199953  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
199954  return rc;
199955}
199956
199957/*
199958** This is the xColumn method, called by SQLite to request a value from
199959** the row that the supplied cursor currently points to.
199960*/
199961static int fts5ColumnMethod(
199962  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
199963  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
199964  int iCol                        /* Index of column to read value from */
199965){
199966  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
199967  Fts5Config *pConfig = pTab->pConfig;
199968  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
199969  int rc = SQLITE_OK;
199970
199971  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
199972
199973  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
199974    if( iCol==pConfig->nCol ){
199975      sqlite3_result_int64(pCtx, pCsr->iSpecial);
199976    }
199977  }else
199978
199979  if( iCol==pConfig->nCol ){
199980    /* User is requesting the value of the special column with the same name
199981    ** as the table. Return the cursor integer id number. This value is only
199982    ** useful in that it may be passed as the first argument to an FTS5
199983    ** auxiliary function.  */
199984    sqlite3_result_int64(pCtx, pCsr->iCsrId);
199985  }else if( iCol==pConfig->nCol+1 ){
199986
199987    /* The value of the "rank" column. */
199988    if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
199989      fts5PoslistBlob(pCtx, pCsr);
199990    }else if(
199991        pCsr->ePlan==FTS5_PLAN_MATCH
199992     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
199993    ){
199994      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
199995        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
199996      }
199997    }
199998  }else if( !fts5IsContentless(pTab) ){
199999    rc = fts5SeekCursor(pCsr, 1);
200000    if( rc==SQLITE_OK ){
200001      sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
200002    }
200003  }
200004  return rc;
200005}
200006
200007
200008/*
200009** This routine implements the xFindFunction method for the FTS3
200010** virtual table.
200011*/
200012static int fts5FindFunctionMethod(
200013  sqlite3_vtab *pVtab,            /* Virtual table handle */
200014  int nUnused,                    /* Number of SQL function arguments */
200015  const char *zName,              /* Name of SQL function */
200016  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
200017  void **ppArg                    /* OUT: User data for *pxFunc */
200018){
200019  Fts5Table *pTab = (Fts5Table*)pVtab;
200020  Fts5Auxiliary *pAux;
200021
200022  UNUSED_PARAM(nUnused);
200023  pAux = fts5FindAuxiliary(pTab, zName);
200024  if( pAux ){
200025    *pxFunc = fts5ApiCallback;
200026    *ppArg = (void*)pAux;
200027    return 1;
200028  }
200029
200030  /* No function of the specified name was found. Return 0. */
200031  return 0;
200032}
200033
200034/*
200035** Implementation of FTS5 xRename method. Rename an fts5 table.
200036*/
200037static int fts5RenameMethod(
200038  sqlite3_vtab *pVtab,            /* Virtual table handle */
200039  const char *zName               /* New name of table */
200040){
200041  Fts5Table *pTab = (Fts5Table*)pVtab;
200042  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
200043}
200044
200045/*
200046** The xSavepoint() method.
200047**
200048** Flush the contents of the pending-terms table to disk.
200049*/
200050static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
200051  Fts5Table *pTab = (Fts5Table*)pVtab;
200052  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
200053  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
200054  fts5TripCursors(pTab);
200055  return sqlite3Fts5StorageSync(pTab->pStorage);
200056}
200057
200058/*
200059** The xRelease() method.
200060**
200061** This is a no-op.
200062*/
200063static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
200064  Fts5Table *pTab = (Fts5Table*)pVtab;
200065  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
200066  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
200067  fts5TripCursors(pTab);
200068  return sqlite3Fts5StorageSync(pTab->pStorage);
200069}
200070
200071/*
200072** The xRollbackTo() method.
200073**
200074** Discard the contents of the pending terms table.
200075*/
200076static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
200077  Fts5Table *pTab = (Fts5Table*)pVtab;
200078  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
200079  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
200080  fts5TripCursors(pTab);
200081  return sqlite3Fts5StorageRollback(pTab->pStorage);
200082}
200083
200084/*
200085** Register a new auxiliary function with global context pGlobal.
200086*/
200087static int fts5CreateAux(
200088  fts5_api *pApi,                 /* Global context (one per db handle) */
200089  const char *zName,              /* Name of new function */
200090  void *pUserData,                /* User data for aux. function */
200091  fts5_extension_function xFunc,  /* Aux. function implementation */
200092  void(*xDestroy)(void*)          /* Destructor for pUserData */
200093){
200094  Fts5Global *pGlobal = (Fts5Global*)pApi;
200095  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
200096  if( rc==SQLITE_OK ){
200097    Fts5Auxiliary *pAux;
200098    int nName;                      /* Size of zName in bytes, including \0 */
200099    int nByte;                      /* Bytes of space to allocate */
200100
200101    nName = (int)strlen(zName) + 1;
200102    nByte = sizeof(Fts5Auxiliary) + nName;
200103    pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
200104    if( pAux ){
200105      memset(pAux, 0, nByte);
200106      pAux->zFunc = (char*)&pAux[1];
200107      memcpy(pAux->zFunc, zName, nName);
200108      pAux->pGlobal = pGlobal;
200109      pAux->pUserData = pUserData;
200110      pAux->xFunc = xFunc;
200111      pAux->xDestroy = xDestroy;
200112      pAux->pNext = pGlobal->pAux;
200113      pGlobal->pAux = pAux;
200114    }else{
200115      rc = SQLITE_NOMEM;
200116    }
200117  }
200118
200119  return rc;
200120}
200121
200122/*
200123** Register a new tokenizer. This is the implementation of the
200124** fts5_api.xCreateTokenizer() method.
200125*/
200126static int fts5CreateTokenizer(
200127  fts5_api *pApi,                 /* Global context (one per db handle) */
200128  const char *zName,              /* Name of new function */
200129  void *pUserData,                /* User data for aux. function */
200130  fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
200131  void(*xDestroy)(void*)          /* Destructor for pUserData */
200132){
200133  Fts5Global *pGlobal = (Fts5Global*)pApi;
200134  Fts5TokenizerModule *pNew;
200135  int nName;                      /* Size of zName and its \0 terminator */
200136  int nByte;                      /* Bytes of space to allocate */
200137  int rc = SQLITE_OK;
200138
200139  nName = (int)strlen(zName) + 1;
200140  nByte = sizeof(Fts5TokenizerModule) + nName;
200141  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
200142  if( pNew ){
200143    memset(pNew, 0, nByte);
200144    pNew->zName = (char*)&pNew[1];
200145    memcpy(pNew->zName, zName, nName);
200146    pNew->pUserData = pUserData;
200147    pNew->x = *pTokenizer;
200148    pNew->xDestroy = xDestroy;
200149    pNew->pNext = pGlobal->pTok;
200150    pGlobal->pTok = pNew;
200151    if( pNew->pNext==0 ){
200152      pGlobal->pDfltTok = pNew;
200153    }
200154  }else{
200155    rc = SQLITE_NOMEM;
200156  }
200157
200158  return rc;
200159}
200160
200161static Fts5TokenizerModule *fts5LocateTokenizer(
200162  Fts5Global *pGlobal,
200163  const char *zName
200164){
200165  Fts5TokenizerModule *pMod = 0;
200166
200167  if( zName==0 ){
200168    pMod = pGlobal->pDfltTok;
200169  }else{
200170    for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
200171      if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
200172    }
200173  }
200174
200175  return pMod;
200176}
200177
200178/*
200179** Find a tokenizer. This is the implementation of the
200180** fts5_api.xFindTokenizer() method.
200181*/
200182static int fts5FindTokenizer(
200183  fts5_api *pApi,                 /* Global context (one per db handle) */
200184  const char *zName,              /* Name of new function */
200185  void **ppUserData,
200186  fts5_tokenizer *pTokenizer      /* Populate this object */
200187){
200188  int rc = SQLITE_OK;
200189  Fts5TokenizerModule *pMod;
200190
200191  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
200192  if( pMod ){
200193    *pTokenizer = pMod->x;
200194    *ppUserData = pMod->pUserData;
200195  }else{
200196    memset(pTokenizer, 0, sizeof(fts5_tokenizer));
200197    rc = SQLITE_ERROR;
200198  }
200199
200200  return rc;
200201}
200202
200203static int sqlite3Fts5GetTokenizer(
200204  Fts5Global *pGlobal,
200205  const char **azArg,
200206  int nArg,
200207  Fts5Tokenizer **ppTok,
200208  fts5_tokenizer **ppTokApi,
200209  char **pzErr
200210){
200211  Fts5TokenizerModule *pMod;
200212  int rc = SQLITE_OK;
200213
200214  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
200215  if( pMod==0 ){
200216    assert( nArg>0 );
200217    rc = SQLITE_ERROR;
200218    *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
200219  }else{
200220    rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
200221    *ppTokApi = &pMod->x;
200222    if( rc!=SQLITE_OK && pzErr ){
200223      *pzErr = sqlite3_mprintf("error in tokenizer constructor");
200224    }
200225  }
200226
200227  if( rc!=SQLITE_OK ){
200228    *ppTokApi = 0;
200229    *ppTok = 0;
200230  }
200231
200232  return rc;
200233}
200234
200235static void fts5ModuleDestroy(void *pCtx){
200236  Fts5TokenizerModule *pTok, *pNextTok;
200237  Fts5Auxiliary *pAux, *pNextAux;
200238  Fts5Global *pGlobal = (Fts5Global*)pCtx;
200239
200240  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
200241    pNextAux = pAux->pNext;
200242    if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
200243    sqlite3_free(pAux);
200244  }
200245
200246  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
200247    pNextTok = pTok->pNext;
200248    if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
200249    sqlite3_free(pTok);
200250  }
200251
200252  sqlite3_free(pGlobal);
200253}
200254
200255static void fts5Fts5Func(
200256  sqlite3_context *pCtx,          /* Function call context */
200257  int nArg,                       /* Number of args */
200258  sqlite3_value **apArg           /* Function arguments */
200259){
200260  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
200261  fts5_api **ppApi;
200262  UNUSED_PARAM(nArg);
200263  assert( nArg==1 );
200264  ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
200265  if( ppApi ) *ppApi = &pGlobal->api;
200266}
200267
200268/*
200269** Implementation of fts5_source_id() function.
200270*/
200271static void fts5SourceIdFunc(
200272  sqlite3_context *pCtx,          /* Function call context */
200273  int nArg,                       /* Number of args */
200274  sqlite3_value **apUnused        /* Function arguments */
200275){
200276  assert( nArg==0 );
200277  UNUSED_PARAM2(nArg, apUnused);
200278  sqlite3_result_text(pCtx, "fts5: 2017-08-01 13:24:15 9501e22dfeebdcefa783575e47c60b514d7c2e0cad73b2a496c0bc4b680900a8", -1, SQLITE_TRANSIENT);
200279}
200280
200281static int fts5Init(sqlite3 *db){
200282  static const sqlite3_module fts5Mod = {
200283    /* iVersion      */ 2,
200284    /* xCreate       */ fts5CreateMethod,
200285    /* xConnect      */ fts5ConnectMethod,
200286    /* xBestIndex    */ fts5BestIndexMethod,
200287    /* xDisconnect   */ fts5DisconnectMethod,
200288    /* xDestroy      */ fts5DestroyMethod,
200289    /* xOpen         */ fts5OpenMethod,
200290    /* xClose        */ fts5CloseMethod,
200291    /* xFilter       */ fts5FilterMethod,
200292    /* xNext         */ fts5NextMethod,
200293    /* xEof          */ fts5EofMethod,
200294    /* xColumn       */ fts5ColumnMethod,
200295    /* xRowid        */ fts5RowidMethod,
200296    /* xUpdate       */ fts5UpdateMethod,
200297    /* xBegin        */ fts5BeginMethod,
200298    /* xSync         */ fts5SyncMethod,
200299    /* xCommit       */ fts5CommitMethod,
200300    /* xRollback     */ fts5RollbackMethod,
200301    /* xFindFunction */ fts5FindFunctionMethod,
200302    /* xRename       */ fts5RenameMethod,
200303    /* xSavepoint    */ fts5SavepointMethod,
200304    /* xRelease      */ fts5ReleaseMethod,
200305    /* xRollbackTo   */ fts5RollbackToMethod,
200306  };
200307
200308  int rc;
200309  Fts5Global *pGlobal = 0;
200310
200311  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
200312  if( pGlobal==0 ){
200313    rc = SQLITE_NOMEM;
200314  }else{
200315    void *p = (void*)pGlobal;
200316    memset(pGlobal, 0, sizeof(Fts5Global));
200317    pGlobal->db = db;
200318    pGlobal->api.iVersion = 2;
200319    pGlobal->api.xCreateFunction = fts5CreateAux;
200320    pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
200321    pGlobal->api.xFindTokenizer = fts5FindTokenizer;
200322    rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
200323    if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
200324    if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
200325    if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
200326    if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
200327    if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
200328    if( rc==SQLITE_OK ){
200329      rc = sqlite3_create_function(
200330          db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
200331      );
200332    }
200333    if( rc==SQLITE_OK ){
200334      rc = sqlite3_create_function(
200335          db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
200336      );
200337    }
200338  }
200339
200340  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
200341  ** fts5_test_mi.c is compiled and linked into the executable. And call
200342  ** its entry point to enable the matchinfo() demo.  */
200343#ifdef SQLITE_FTS5_ENABLE_TEST_MI
200344  if( rc==SQLITE_OK ){
200345    extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
200346    rc = sqlite3Fts5TestRegisterMatchinfo(db);
200347  }
200348#endif
200349
200350  return rc;
200351}
200352
200353/*
200354** The following functions are used to register the module with SQLite. If
200355** this module is being built as part of the SQLite core (SQLITE_CORE is
200356** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
200357**
200358** Or, if this module is being built as a loadable extension,
200359** sqlite3Fts5Init() is omitted and the two standard entry points
200360** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
200361*/
200362#ifndef SQLITE_CORE
200363#ifdef _WIN32
200364__declspec(dllexport)
200365#endif
200366SQLITE_API int sqlite3_fts_init(
200367  sqlite3 *db,
200368  char **pzErrMsg,
200369  const sqlite3_api_routines *pApi
200370){
200371  SQLITE_EXTENSION_INIT2(pApi);
200372  (void)pzErrMsg;  /* Unused parameter */
200373  return fts5Init(db);
200374}
200375
200376#ifdef _WIN32
200377__declspec(dllexport)
200378#endif
200379SQLITE_API int sqlite3_fts5_init(
200380  sqlite3 *db,
200381  char **pzErrMsg,
200382  const sqlite3_api_routines *pApi
200383){
200384  SQLITE_EXTENSION_INIT2(pApi);
200385  (void)pzErrMsg;  /* Unused parameter */
200386  return fts5Init(db);
200387}
200388#else
200389SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
200390  return fts5Init(db);
200391}
200392#endif
200393
200394/*
200395** 2014 May 31
200396**
200397** The author disclaims copyright to this source code.  In place of
200398** a legal notice, here is a blessing:
200399**
200400**    May you do good and not evil.
200401**    May you find forgiveness for yourself and forgive others.
200402**    May you share freely, never taking more than you give.
200403**
200404******************************************************************************
200405**
200406*/
200407
200408
200409
200410/* #include "fts5Int.h" */
200411
200412struct Fts5Storage {
200413  Fts5Config *pConfig;
200414  Fts5Index *pIndex;
200415  int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
200416  i64 nTotalRow;                  /* Total number of rows in FTS table */
200417  i64 *aTotalSize;                /* Total sizes of each column */
200418  sqlite3_stmt *aStmt[11];
200419};
200420
200421
200422#if FTS5_STMT_SCAN_ASC!=0
200423# error "FTS5_STMT_SCAN_ASC mismatch"
200424#endif
200425#if FTS5_STMT_SCAN_DESC!=1
200426# error "FTS5_STMT_SCAN_DESC mismatch"
200427#endif
200428#if FTS5_STMT_LOOKUP!=2
200429# error "FTS5_STMT_LOOKUP mismatch"
200430#endif
200431
200432#define FTS5_STMT_INSERT_CONTENT  3
200433#define FTS5_STMT_REPLACE_CONTENT 4
200434#define FTS5_STMT_DELETE_CONTENT  5
200435#define FTS5_STMT_REPLACE_DOCSIZE  6
200436#define FTS5_STMT_DELETE_DOCSIZE  7
200437#define FTS5_STMT_LOOKUP_DOCSIZE  8
200438#define FTS5_STMT_REPLACE_CONFIG 9
200439#define FTS5_STMT_SCAN 10
200440
200441/*
200442** Prepare the two insert statements - Fts5Storage.pInsertContent and
200443** Fts5Storage.pInsertDocsize - if they have not already been prepared.
200444** Return SQLITE_OK if successful, or an SQLite error code if an error
200445** occurs.
200446*/
200447static int fts5StorageGetStmt(
200448  Fts5Storage *p,                 /* Storage handle */
200449  int eStmt,                      /* FTS5_STMT_XXX constant */
200450  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
200451  char **pzErrMsg                 /* OUT: Error message (if any) */
200452){
200453  int rc = SQLITE_OK;
200454
200455  /* If there is no %_docsize table, there should be no requests for
200456  ** statements to operate on it.  */
200457  assert( p->pConfig->bColumnsize || (
200458        eStmt!=FTS5_STMT_REPLACE_DOCSIZE
200459     && eStmt!=FTS5_STMT_DELETE_DOCSIZE
200460     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
200461  ));
200462
200463  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
200464  if( p->aStmt[eStmt]==0 ){
200465    const char *azStmt[] = {
200466      "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
200467      "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
200468      "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
200469
200470      "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
200471      "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
200472      "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
200473      "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
200474      "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
200475
200476      "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
200477
200478      "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
200479      "SELECT %s FROM %s AS T",                         /* SCAN */
200480    };
200481    Fts5Config *pC = p->pConfig;
200482    char *zSql = 0;
200483
200484    switch( eStmt ){
200485      case FTS5_STMT_SCAN:
200486        zSql = sqlite3_mprintf(azStmt[eStmt],
200487            pC->zContentExprlist, pC->zContent
200488        );
200489        break;
200490
200491      case FTS5_STMT_SCAN_ASC:
200492      case FTS5_STMT_SCAN_DESC:
200493        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
200494            pC->zContent, pC->zContentRowid, pC->zContentRowid,
200495            pC->zContentRowid
200496        );
200497        break;
200498
200499      case FTS5_STMT_LOOKUP:
200500        zSql = sqlite3_mprintf(azStmt[eStmt],
200501            pC->zContentExprlist, pC->zContent, pC->zContentRowid
200502        );
200503        break;
200504
200505      case FTS5_STMT_INSERT_CONTENT:
200506      case FTS5_STMT_REPLACE_CONTENT: {
200507        int nCol = pC->nCol + 1;
200508        char *zBind;
200509        int i;
200510
200511        zBind = sqlite3_malloc(1 + nCol*2);
200512        if( zBind ){
200513          for(i=0; i<nCol; i++){
200514            zBind[i*2] = '?';
200515            zBind[i*2 + 1] = ',';
200516          }
200517          zBind[i*2-1] = '\0';
200518          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
200519          sqlite3_free(zBind);
200520        }
200521        break;
200522      }
200523
200524      default:
200525        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
200526        break;
200527    }
200528
200529    if( zSql==0 ){
200530      rc = SQLITE_NOMEM;
200531    }else{
200532      rc = sqlite3_prepare_v3(pC->db, zSql, -1,
200533                              SQLITE_PREPARE_PERSISTENT, &p->aStmt[eStmt], 0);
200534      sqlite3_free(zSql);
200535      if( rc!=SQLITE_OK && pzErrMsg ){
200536        *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
200537      }
200538    }
200539  }
200540
200541  *ppStmt = p->aStmt[eStmt];
200542  sqlite3_reset(*ppStmt);
200543  return rc;
200544}
200545
200546
200547static int fts5ExecPrintf(
200548  sqlite3 *db,
200549  char **pzErr,
200550  const char *zFormat,
200551  ...
200552){
200553  int rc;
200554  va_list ap;                     /* ... printf arguments */
200555  char *zSql;
200556
200557  va_start(ap, zFormat);
200558  zSql = sqlite3_vmprintf(zFormat, ap);
200559
200560  if( zSql==0 ){
200561    rc = SQLITE_NOMEM;
200562  }else{
200563    rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
200564    sqlite3_free(zSql);
200565  }
200566
200567  va_end(ap);
200568  return rc;
200569}
200570
200571/*
200572** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
200573** code otherwise.
200574*/
200575static int sqlite3Fts5DropAll(Fts5Config *pConfig){
200576  int rc = fts5ExecPrintf(pConfig->db, 0,
200577      "DROP TABLE IF EXISTS %Q.'%q_data';"
200578      "DROP TABLE IF EXISTS %Q.'%q_idx';"
200579      "DROP TABLE IF EXISTS %Q.'%q_config';",
200580      pConfig->zDb, pConfig->zName,
200581      pConfig->zDb, pConfig->zName,
200582      pConfig->zDb, pConfig->zName
200583  );
200584  if( rc==SQLITE_OK && pConfig->bColumnsize ){
200585    rc = fts5ExecPrintf(pConfig->db, 0,
200586        "DROP TABLE IF EXISTS %Q.'%q_docsize';",
200587        pConfig->zDb, pConfig->zName
200588    );
200589  }
200590  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
200591    rc = fts5ExecPrintf(pConfig->db, 0,
200592        "DROP TABLE IF EXISTS %Q.'%q_content';",
200593        pConfig->zDb, pConfig->zName
200594    );
200595  }
200596  return rc;
200597}
200598
200599static void fts5StorageRenameOne(
200600  Fts5Config *pConfig,            /* Current FTS5 configuration */
200601  int *pRc,                       /* IN/OUT: Error code */
200602  const char *zTail,              /* Tail of table name e.g. "data", "config" */
200603  const char *zName               /* New name of FTS5 table */
200604){
200605  if( *pRc==SQLITE_OK ){
200606    *pRc = fts5ExecPrintf(pConfig->db, 0,
200607        "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
200608        pConfig->zDb, pConfig->zName, zTail, zName, zTail
200609    );
200610  }
200611}
200612
200613static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
200614  Fts5Config *pConfig = pStorage->pConfig;
200615  int rc = sqlite3Fts5StorageSync(pStorage);
200616
200617  fts5StorageRenameOne(pConfig, &rc, "data", zName);
200618  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
200619  fts5StorageRenameOne(pConfig, &rc, "config", zName);
200620  if( pConfig->bColumnsize ){
200621    fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
200622  }
200623  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
200624    fts5StorageRenameOne(pConfig, &rc, "content", zName);
200625  }
200626  return rc;
200627}
200628
200629/*
200630** Create the shadow table named zPost, with definition zDefn. Return
200631** SQLITE_OK if successful, or an SQLite error code otherwise.
200632*/
200633static int sqlite3Fts5CreateTable(
200634  Fts5Config *pConfig,            /* FTS5 configuration */
200635  const char *zPost,              /* Shadow table to create (e.g. "content") */
200636  const char *zDefn,              /* Columns etc. for shadow table */
200637  int bWithout,                   /* True for without rowid */
200638  char **pzErr                    /* OUT: Error message */
200639){
200640  int rc;
200641  char *zErr = 0;
200642
200643  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
200644      pConfig->zDb, pConfig->zName, zPost, zDefn,
200645#ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
200646      bWithout?" WITHOUT ROWID":
200647#endif
200648      ""
200649  );
200650  if( zErr ){
200651    *pzErr = sqlite3_mprintf(
200652        "fts5: error creating shadow table %q_%s: %s",
200653        pConfig->zName, zPost, zErr
200654    );
200655    sqlite3_free(zErr);
200656  }
200657
200658  return rc;
200659}
200660
200661/*
200662** Open a new Fts5Index handle. If the bCreate argument is true, create
200663** and initialize the underlying tables
200664**
200665** If successful, set *pp to point to the new object and return SQLITE_OK.
200666** Otherwise, set *pp to NULL and return an SQLite error code.
200667*/
200668static int sqlite3Fts5StorageOpen(
200669  Fts5Config *pConfig,
200670  Fts5Index *pIndex,
200671  int bCreate,
200672  Fts5Storage **pp,
200673  char **pzErr                    /* OUT: Error message */
200674){
200675  int rc = SQLITE_OK;
200676  Fts5Storage *p;                 /* New object */
200677  int nByte;                      /* Bytes of space to allocate */
200678
200679  nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
200680        + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
200681  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
200682  if( !p ) return SQLITE_NOMEM;
200683
200684  memset(p, 0, nByte);
200685  p->aTotalSize = (i64*)&p[1];
200686  p->pConfig = pConfig;
200687  p->pIndex = pIndex;
200688
200689  if( bCreate ){
200690    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
200691      int nDefn = 32 + pConfig->nCol*10;
200692      char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
200693      if( zDefn==0 ){
200694        rc = SQLITE_NOMEM;
200695      }else{
200696        int i;
200697        int iOff;
200698        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
200699        iOff = (int)strlen(zDefn);
200700        for(i=0; i<pConfig->nCol; i++){
200701          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
200702          iOff += (int)strlen(&zDefn[iOff]);
200703        }
200704        rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
200705      }
200706      sqlite3_free(zDefn);
200707    }
200708
200709    if( rc==SQLITE_OK && pConfig->bColumnsize ){
200710      rc = sqlite3Fts5CreateTable(
200711          pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
200712      );
200713    }
200714    if( rc==SQLITE_OK ){
200715      rc = sqlite3Fts5CreateTable(
200716          pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
200717      );
200718    }
200719    if( rc==SQLITE_OK ){
200720      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
200721    }
200722  }
200723
200724  if( rc ){
200725    sqlite3Fts5StorageClose(p);
200726    *pp = 0;
200727  }
200728  return rc;
200729}
200730
200731/*
200732** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
200733*/
200734static int sqlite3Fts5StorageClose(Fts5Storage *p){
200735  int rc = SQLITE_OK;
200736  if( p ){
200737    int i;
200738
200739    /* Finalize all SQL statements */
200740    for(i=0; i<ArraySize(p->aStmt); i++){
200741      sqlite3_finalize(p->aStmt[i]);
200742    }
200743
200744    sqlite3_free(p);
200745  }
200746  return rc;
200747}
200748
200749typedef struct Fts5InsertCtx Fts5InsertCtx;
200750struct Fts5InsertCtx {
200751  Fts5Storage *pStorage;
200752  int iCol;
200753  int szCol;                      /* Size of column value in tokens */
200754};
200755
200756/*
200757** Tokenization callback used when inserting tokens into the FTS index.
200758*/
200759static int fts5StorageInsertCallback(
200760  void *pContext,                 /* Pointer to Fts5InsertCtx object */
200761  int tflags,
200762  const char *pToken,             /* Buffer containing token */
200763  int nToken,                     /* Size of token in bytes */
200764  int iUnused1,                   /* Start offset of token */
200765  int iUnused2                    /* End offset of token */
200766){
200767  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
200768  Fts5Index *pIdx = pCtx->pStorage->pIndex;
200769  UNUSED_PARAM2(iUnused1, iUnused2);
200770  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
200771  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
200772    pCtx->szCol++;
200773  }
200774  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
200775}
200776
200777/*
200778** If a row with rowid iDel is present in the %_content table, add the
200779** delete-markers to the FTS index necessary to delete it. Do not actually
200780** remove the %_content row at this time though.
200781*/
200782static int fts5StorageDeleteFromIndex(
200783  Fts5Storage *p,
200784  i64 iDel,
200785  sqlite3_value **apVal
200786){
200787  Fts5Config *pConfig = p->pConfig;
200788  sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
200789  int rc;                         /* Return code */
200790  int rc2;                        /* sqlite3_reset() return code */
200791  int iCol;
200792  Fts5InsertCtx ctx;
200793
200794  if( apVal==0 ){
200795    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
200796    if( rc!=SQLITE_OK ) return rc;
200797    sqlite3_bind_int64(pSeek, 1, iDel);
200798    if( sqlite3_step(pSeek)!=SQLITE_ROW ){
200799      return sqlite3_reset(pSeek);
200800    }
200801  }
200802
200803  ctx.pStorage = p;
200804  ctx.iCol = -1;
200805  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
200806  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
200807    if( pConfig->abUnindexed[iCol-1]==0 ){
200808      const char *zText;
200809      int nText;
200810      if( pSeek ){
200811        zText = (const char*)sqlite3_column_text(pSeek, iCol);
200812        nText = sqlite3_column_bytes(pSeek, iCol);
200813      }else{
200814        zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
200815        nText = sqlite3_value_bytes(apVal[iCol-1]);
200816      }
200817      ctx.szCol = 0;
200818      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
200819          zText, nText, (void*)&ctx, fts5StorageInsertCallback
200820      );
200821      p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
200822    }
200823  }
200824  p->nTotalRow--;
200825
200826  rc2 = sqlite3_reset(pSeek);
200827  if( rc==SQLITE_OK ) rc = rc2;
200828  return rc;
200829}
200830
200831
200832/*
200833** Insert a record into the %_docsize table. Specifically, do:
200834**
200835**   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
200836**
200837** If there is no %_docsize table (as happens if the columnsize=0 option
200838** is specified when the FTS5 table is created), this function is a no-op.
200839*/
200840static int fts5StorageInsertDocsize(
200841  Fts5Storage *p,                 /* Storage module to write to */
200842  i64 iRowid,                     /* id value */
200843  Fts5Buffer *pBuf                /* sz value */
200844){
200845  int rc = SQLITE_OK;
200846  if( p->pConfig->bColumnsize ){
200847    sqlite3_stmt *pReplace = 0;
200848    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
200849    if( rc==SQLITE_OK ){
200850      sqlite3_bind_int64(pReplace, 1, iRowid);
200851      sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
200852      sqlite3_step(pReplace);
200853      rc = sqlite3_reset(pReplace);
200854    }
200855  }
200856  return rc;
200857}
200858
200859/*
200860** Load the contents of the "averages" record from disk into the
200861** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
200862** argument bCache is true, set the p->bTotalsValid flag to indicate
200863** that the contents of aTotalSize[] and nTotalRow are valid until
200864** further notice.
200865**
200866** Return SQLITE_OK if successful, or an SQLite error code if an error
200867** occurs.
200868*/
200869static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
200870  int rc = SQLITE_OK;
200871  if( p->bTotalsValid==0 ){
200872    rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
200873    p->bTotalsValid = bCache;
200874  }
200875  return rc;
200876}
200877
200878/*
200879** Store the current contents of the p->nTotalRow and p->aTotalSize[]
200880** variables in the "averages" record on disk.
200881**
200882** Return SQLITE_OK if successful, or an SQLite error code if an error
200883** occurs.
200884*/
200885static int fts5StorageSaveTotals(Fts5Storage *p){
200886  int nCol = p->pConfig->nCol;
200887  int i;
200888  Fts5Buffer buf;
200889  int rc = SQLITE_OK;
200890  memset(&buf, 0, sizeof(buf));
200891
200892  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
200893  for(i=0; i<nCol; i++){
200894    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
200895  }
200896  if( rc==SQLITE_OK ){
200897    rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
200898  }
200899  sqlite3_free(buf.p);
200900
200901  return rc;
200902}
200903
200904/*
200905** Remove a row from the FTS table.
200906*/
200907static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
200908  Fts5Config *pConfig = p->pConfig;
200909  int rc;
200910  sqlite3_stmt *pDel = 0;
200911
200912  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
200913  rc = fts5StorageLoadTotals(p, 1);
200914
200915  /* Delete the index records */
200916  if( rc==SQLITE_OK ){
200917    rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
200918  }
200919
200920  /* Delete the %_docsize record */
200921  if( rc==SQLITE_OK && pConfig->bColumnsize ){
200922    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
200923    if( rc==SQLITE_OK ){
200924      sqlite3_bind_int64(pDel, 1, iDel);
200925      sqlite3_step(pDel);
200926      rc = sqlite3_reset(pDel);
200927    }
200928  }
200929
200930  /* Delete the %_content record */
200931  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
200932    if( rc==SQLITE_OK ){
200933      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
200934    }
200935    if( rc==SQLITE_OK ){
200936      sqlite3_bind_int64(pDel, 1, iDel);
200937      sqlite3_step(pDel);
200938      rc = sqlite3_reset(pDel);
200939    }
200940  }
200941
200942  return rc;
200943}
200944
200945/*
200946** Delete all entries in the FTS5 index.
200947*/
200948static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
200949  Fts5Config *pConfig = p->pConfig;
200950  int rc;
200951
200952  /* Delete the contents of the %_data and %_docsize tables. */
200953  rc = fts5ExecPrintf(pConfig->db, 0,
200954      "DELETE FROM %Q.'%q_data';"
200955      "DELETE FROM %Q.'%q_idx';",
200956      pConfig->zDb, pConfig->zName,
200957      pConfig->zDb, pConfig->zName
200958  );
200959  if( rc==SQLITE_OK && pConfig->bColumnsize ){
200960    rc = fts5ExecPrintf(pConfig->db, 0,
200961        "DELETE FROM %Q.'%q_docsize';",
200962        pConfig->zDb, pConfig->zName
200963    );
200964  }
200965
200966  /* Reinitialize the %_data table. This call creates the initial structure
200967  ** and averages records.  */
200968  if( rc==SQLITE_OK ){
200969    rc = sqlite3Fts5IndexReinit(p->pIndex);
200970  }
200971  if( rc==SQLITE_OK ){
200972    rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
200973  }
200974  return rc;
200975}
200976
200977static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
200978  Fts5Buffer buf = {0,0,0};
200979  Fts5Config *pConfig = p->pConfig;
200980  sqlite3_stmt *pScan = 0;
200981  Fts5InsertCtx ctx;
200982  int rc;
200983
200984  memset(&ctx, 0, sizeof(Fts5InsertCtx));
200985  ctx.pStorage = p;
200986  rc = sqlite3Fts5StorageDeleteAll(p);
200987  if( rc==SQLITE_OK ){
200988    rc = fts5StorageLoadTotals(p, 1);
200989  }
200990
200991  if( rc==SQLITE_OK ){
200992    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
200993  }
200994
200995  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
200996    i64 iRowid = sqlite3_column_int64(pScan, 0);
200997
200998    sqlite3Fts5BufferZero(&buf);
200999    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
201000    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
201001      ctx.szCol = 0;
201002      if( pConfig->abUnindexed[ctx.iCol]==0 ){
201003        rc = sqlite3Fts5Tokenize(pConfig,
201004            FTS5_TOKENIZE_DOCUMENT,
201005            (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
201006            sqlite3_column_bytes(pScan, ctx.iCol+1),
201007            (void*)&ctx,
201008            fts5StorageInsertCallback
201009        );
201010      }
201011      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
201012      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
201013    }
201014    p->nTotalRow++;
201015
201016    if( rc==SQLITE_OK ){
201017      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
201018    }
201019  }
201020  sqlite3_free(buf.p);
201021
201022  /* Write the averages record */
201023  if( rc==SQLITE_OK ){
201024    rc = fts5StorageSaveTotals(p);
201025  }
201026  return rc;
201027}
201028
201029static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
201030  return sqlite3Fts5IndexOptimize(p->pIndex);
201031}
201032
201033static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
201034  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
201035}
201036
201037static int sqlite3Fts5StorageReset(Fts5Storage *p){
201038  return sqlite3Fts5IndexReset(p->pIndex);
201039}
201040
201041/*
201042** Allocate a new rowid. This is used for "external content" tables when
201043** a NULL value is inserted into the rowid column. The new rowid is allocated
201044** by inserting a dummy row into the %_docsize table. The dummy will be
201045** overwritten later.
201046**
201047** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
201048** this case the user is required to provide a rowid explicitly.
201049*/
201050static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
201051  int rc = SQLITE_MISMATCH;
201052  if( p->pConfig->bColumnsize ){
201053    sqlite3_stmt *pReplace = 0;
201054    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
201055    if( rc==SQLITE_OK ){
201056      sqlite3_bind_null(pReplace, 1);
201057      sqlite3_bind_null(pReplace, 2);
201058      sqlite3_step(pReplace);
201059      rc = sqlite3_reset(pReplace);
201060    }
201061    if( rc==SQLITE_OK ){
201062      *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
201063    }
201064  }
201065  return rc;
201066}
201067
201068/*
201069** Insert a new row into the FTS content table.
201070*/
201071static int sqlite3Fts5StorageContentInsert(
201072  Fts5Storage *p,
201073  sqlite3_value **apVal,
201074  i64 *piRowid
201075){
201076  Fts5Config *pConfig = p->pConfig;
201077  int rc = SQLITE_OK;
201078
201079  /* Insert the new row into the %_content table. */
201080  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
201081    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
201082      *piRowid = sqlite3_value_int64(apVal[1]);
201083    }else{
201084      rc = fts5StorageNewRowid(p, piRowid);
201085    }
201086  }else{
201087    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
201088    int i;                        /* Counter variable */
201089    rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
201090    for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
201091      rc = sqlite3_bind_value(pInsert, i, apVal[i]);
201092    }
201093    if( rc==SQLITE_OK ){
201094      sqlite3_step(pInsert);
201095      rc = sqlite3_reset(pInsert);
201096    }
201097    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
201098  }
201099
201100  return rc;
201101}
201102
201103/*
201104** Insert new entries into the FTS index and %_docsize table.
201105*/
201106static int sqlite3Fts5StorageIndexInsert(
201107  Fts5Storage *p,
201108  sqlite3_value **apVal,
201109  i64 iRowid
201110){
201111  Fts5Config *pConfig = p->pConfig;
201112  int rc = SQLITE_OK;             /* Return code */
201113  Fts5InsertCtx ctx;              /* Tokenization callback context object */
201114  Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
201115
201116  memset(&buf, 0, sizeof(Fts5Buffer));
201117  ctx.pStorage = p;
201118  rc = fts5StorageLoadTotals(p, 1);
201119
201120  if( rc==SQLITE_OK ){
201121    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
201122  }
201123  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
201124    ctx.szCol = 0;
201125    if( pConfig->abUnindexed[ctx.iCol]==0 ){
201126      rc = sqlite3Fts5Tokenize(pConfig,
201127          FTS5_TOKENIZE_DOCUMENT,
201128          (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
201129          sqlite3_value_bytes(apVal[ctx.iCol+2]),
201130          (void*)&ctx,
201131          fts5StorageInsertCallback
201132      );
201133    }
201134    sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
201135    p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
201136  }
201137  p->nTotalRow++;
201138
201139  /* Write the %_docsize record */
201140  if( rc==SQLITE_OK ){
201141    rc = fts5StorageInsertDocsize(p, iRowid, &buf);
201142  }
201143  sqlite3_free(buf.p);
201144
201145  return rc;
201146}
201147
201148static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
201149  Fts5Config *pConfig = p->pConfig;
201150  char *zSql;
201151  int rc;
201152
201153  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
201154      pConfig->zDb, pConfig->zName, zSuffix
201155  );
201156  if( zSql==0 ){
201157    rc = SQLITE_NOMEM;
201158  }else{
201159    sqlite3_stmt *pCnt = 0;
201160    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
201161    if( rc==SQLITE_OK ){
201162      if( SQLITE_ROW==sqlite3_step(pCnt) ){
201163        *pnRow = sqlite3_column_int64(pCnt, 0);
201164      }
201165      rc = sqlite3_finalize(pCnt);
201166    }
201167  }
201168
201169  sqlite3_free(zSql);
201170  return rc;
201171}
201172
201173/*
201174** Context object used by sqlite3Fts5StorageIntegrity().
201175*/
201176typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
201177struct Fts5IntegrityCtx {
201178  i64 iRowid;
201179  int iCol;
201180  int szCol;
201181  u64 cksum;
201182  Fts5Termset *pTermset;
201183  Fts5Config *pConfig;
201184};
201185
201186
201187/*
201188** Tokenization callback used by integrity check.
201189*/
201190static int fts5StorageIntegrityCallback(
201191  void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
201192  int tflags,
201193  const char *pToken,             /* Buffer containing token */
201194  int nToken,                     /* Size of token in bytes */
201195  int iUnused1,                   /* Start offset of token */
201196  int iUnused2                    /* End offset of token */
201197){
201198  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
201199  Fts5Termset *pTermset = pCtx->pTermset;
201200  int bPresent;
201201  int ii;
201202  int rc = SQLITE_OK;
201203  int iPos;
201204  int iCol;
201205
201206  UNUSED_PARAM2(iUnused1, iUnused2);
201207  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
201208
201209  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
201210    pCtx->szCol++;
201211  }
201212
201213  switch( pCtx->pConfig->eDetail ){
201214    case FTS5_DETAIL_FULL:
201215      iPos = pCtx->szCol-1;
201216      iCol = pCtx->iCol;
201217      break;
201218
201219    case FTS5_DETAIL_COLUMNS:
201220      iPos = pCtx->iCol;
201221      iCol = 0;
201222      break;
201223
201224    default:
201225      assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
201226      iPos = 0;
201227      iCol = 0;
201228      break;
201229  }
201230
201231  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
201232  if( rc==SQLITE_OK && bPresent==0 ){
201233    pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
201234        pCtx->iRowid, iCol, iPos, 0, pToken, nToken
201235    );
201236  }
201237
201238  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
201239    const int nChar = pCtx->pConfig->aPrefix[ii];
201240    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
201241    if( nByte ){
201242      rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
201243      if( bPresent==0 ){
201244        pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
201245            pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
201246        );
201247      }
201248    }
201249  }
201250
201251  return rc;
201252}
201253
201254/*
201255** Check that the contents of the FTS index match that of the %_content
201256** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
201257** some other SQLite error code if an error occurs while attempting to
201258** determine this.
201259*/
201260static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
201261  Fts5Config *pConfig = p->pConfig;
201262  int rc;                         /* Return code */
201263  int *aColSize;                  /* Array of size pConfig->nCol */
201264  i64 *aTotalSize;                /* Array of size pConfig->nCol */
201265  Fts5IntegrityCtx ctx;
201266  sqlite3_stmt *pScan;
201267
201268  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
201269  ctx.pConfig = p->pConfig;
201270  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
201271  if( !aTotalSize ) return SQLITE_NOMEM;
201272  aColSize = (int*)&aTotalSize[pConfig->nCol];
201273  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
201274
201275  /* Generate the expected index checksum based on the contents of the
201276  ** %_content table. This block stores the checksum in ctx.cksum. */
201277  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
201278  if( rc==SQLITE_OK ){
201279    int rc2;
201280    while( SQLITE_ROW==sqlite3_step(pScan) ){
201281      int i;
201282      ctx.iRowid = sqlite3_column_int64(pScan, 0);
201283      ctx.szCol = 0;
201284      if( pConfig->bColumnsize ){
201285        rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
201286      }
201287      if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
201288        rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
201289      }
201290      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
201291        if( pConfig->abUnindexed[i] ) continue;
201292        ctx.iCol = i;
201293        ctx.szCol = 0;
201294        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
201295          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
201296        }
201297        if( rc==SQLITE_OK ){
201298          rc = sqlite3Fts5Tokenize(pConfig,
201299              FTS5_TOKENIZE_DOCUMENT,
201300              (const char*)sqlite3_column_text(pScan, i+1),
201301              sqlite3_column_bytes(pScan, i+1),
201302              (void*)&ctx,
201303              fts5StorageIntegrityCallback
201304          );
201305        }
201306        if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
201307          rc = FTS5_CORRUPT;
201308        }
201309        aTotalSize[i] += ctx.szCol;
201310        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
201311          sqlite3Fts5TermsetFree(ctx.pTermset);
201312          ctx.pTermset = 0;
201313        }
201314      }
201315      sqlite3Fts5TermsetFree(ctx.pTermset);
201316      ctx.pTermset = 0;
201317
201318      if( rc!=SQLITE_OK ) break;
201319    }
201320    rc2 = sqlite3_reset(pScan);
201321    if( rc==SQLITE_OK ) rc = rc2;
201322  }
201323
201324  /* Test that the "totals" (sometimes called "averages") record looks Ok */
201325  if( rc==SQLITE_OK ){
201326    int i;
201327    rc = fts5StorageLoadTotals(p, 0);
201328    for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
201329      if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
201330    }
201331  }
201332
201333  /* Check that the %_docsize and %_content tables contain the expected
201334  ** number of rows.  */
201335  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
201336    i64 nRow = 0;
201337    rc = fts5StorageCount(p, "content", &nRow);
201338    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
201339  }
201340  if( rc==SQLITE_OK && pConfig->bColumnsize ){
201341    i64 nRow = 0;
201342    rc = fts5StorageCount(p, "docsize", &nRow);
201343    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
201344  }
201345
201346  /* Pass the expected checksum down to the FTS index module. It will
201347  ** verify, amongst other things, that it matches the checksum generated by
201348  ** inspecting the index itself.  */
201349  if( rc==SQLITE_OK ){
201350    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
201351  }
201352
201353  sqlite3_free(aTotalSize);
201354  return rc;
201355}
201356
201357/*
201358** Obtain an SQLite statement handle that may be used to read data from the
201359** %_content table.
201360*/
201361static int sqlite3Fts5StorageStmt(
201362  Fts5Storage *p,
201363  int eStmt,
201364  sqlite3_stmt **pp,
201365  char **pzErrMsg
201366){
201367  int rc;
201368  assert( eStmt==FTS5_STMT_SCAN_ASC
201369       || eStmt==FTS5_STMT_SCAN_DESC
201370       || eStmt==FTS5_STMT_LOOKUP
201371  );
201372  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
201373  if( rc==SQLITE_OK ){
201374    assert( p->aStmt[eStmt]==*pp );
201375    p->aStmt[eStmt] = 0;
201376  }
201377  return rc;
201378}
201379
201380/*
201381** Release an SQLite statement handle obtained via an earlier call to
201382** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
201383** must match that passed to the sqlite3Fts5StorageStmt() call.
201384*/
201385static void sqlite3Fts5StorageStmtRelease(
201386  Fts5Storage *p,
201387  int eStmt,
201388  sqlite3_stmt *pStmt
201389){
201390  assert( eStmt==FTS5_STMT_SCAN_ASC
201391       || eStmt==FTS5_STMT_SCAN_DESC
201392       || eStmt==FTS5_STMT_LOOKUP
201393  );
201394  if( p->aStmt[eStmt]==0 ){
201395    sqlite3_reset(pStmt);
201396    p->aStmt[eStmt] = pStmt;
201397  }else{
201398    sqlite3_finalize(pStmt);
201399  }
201400}
201401
201402static int fts5StorageDecodeSizeArray(
201403  int *aCol, int nCol,            /* Array to populate */
201404  const u8 *aBlob, int nBlob      /* Record to read varints from */
201405){
201406  int i;
201407  int iOff = 0;
201408  for(i=0; i<nCol; i++){
201409    if( iOff>=nBlob ) return 1;
201410    iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
201411  }
201412  return (iOff!=nBlob);
201413}
201414
201415/*
201416** Argument aCol points to an array of integers containing one entry for
201417** each table column. This function reads the %_docsize record for the
201418** specified rowid and populates aCol[] with the results.
201419**
201420** An SQLite error code is returned if an error occurs, or SQLITE_OK
201421** otherwise.
201422*/
201423static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
201424  int nCol = p->pConfig->nCol;    /* Number of user columns in table */
201425  sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
201426  int rc;                         /* Return Code */
201427
201428  assert( p->pConfig->bColumnsize );
201429  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
201430  if( rc==SQLITE_OK ){
201431    int bCorrupt = 1;
201432    sqlite3_bind_int64(pLookup, 1, iRowid);
201433    if( SQLITE_ROW==sqlite3_step(pLookup) ){
201434      const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
201435      int nBlob = sqlite3_column_bytes(pLookup, 0);
201436      if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
201437        bCorrupt = 0;
201438      }
201439    }
201440    rc = sqlite3_reset(pLookup);
201441    if( bCorrupt && rc==SQLITE_OK ){
201442      rc = FTS5_CORRUPT;
201443    }
201444  }
201445
201446  return rc;
201447}
201448
201449static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
201450  int rc = fts5StorageLoadTotals(p, 0);
201451  if( rc==SQLITE_OK ){
201452    *pnToken = 0;
201453    if( iCol<0 ){
201454      int i;
201455      for(i=0; i<p->pConfig->nCol; i++){
201456        *pnToken += p->aTotalSize[i];
201457      }
201458    }else if( iCol<p->pConfig->nCol ){
201459      *pnToken = p->aTotalSize[iCol];
201460    }else{
201461      rc = SQLITE_RANGE;
201462    }
201463  }
201464  return rc;
201465}
201466
201467static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
201468  int rc = fts5StorageLoadTotals(p, 0);
201469  if( rc==SQLITE_OK ){
201470    *pnRow = p->nTotalRow;
201471  }
201472  return rc;
201473}
201474
201475/*
201476** Flush any data currently held in-memory to disk.
201477*/
201478static int sqlite3Fts5StorageSync(Fts5Storage *p){
201479  int rc = SQLITE_OK;
201480  i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
201481  if( p->bTotalsValid ){
201482    rc = fts5StorageSaveTotals(p);
201483    p->bTotalsValid = 0;
201484  }
201485  if( rc==SQLITE_OK ){
201486    rc = sqlite3Fts5IndexSync(p->pIndex);
201487  }
201488  sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
201489  return rc;
201490}
201491
201492static int sqlite3Fts5StorageRollback(Fts5Storage *p){
201493  p->bTotalsValid = 0;
201494  return sqlite3Fts5IndexRollback(p->pIndex);
201495}
201496
201497static int sqlite3Fts5StorageConfigValue(
201498  Fts5Storage *p,
201499  const char *z,
201500  sqlite3_value *pVal,
201501  int iVal
201502){
201503  sqlite3_stmt *pReplace = 0;
201504  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
201505  if( rc==SQLITE_OK ){
201506    sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
201507    if( pVal ){
201508      sqlite3_bind_value(pReplace, 2, pVal);
201509    }else{
201510      sqlite3_bind_int(pReplace, 2, iVal);
201511    }
201512    sqlite3_step(pReplace);
201513    rc = sqlite3_reset(pReplace);
201514  }
201515  if( rc==SQLITE_OK && pVal ){
201516    int iNew = p->pConfig->iCookie + 1;
201517    rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
201518    if( rc==SQLITE_OK ){
201519      p->pConfig->iCookie = iNew;
201520    }
201521  }
201522  return rc;
201523}
201524
201525/*
201526** 2014 May 31
201527**
201528** The author disclaims copyright to this source code.  In place of
201529** a legal notice, here is a blessing:
201530**
201531**    May you do good and not evil.
201532**    May you find forgiveness for yourself and forgive others.
201533**    May you share freely, never taking more than you give.
201534**
201535******************************************************************************
201536*/
201537
201538
201539/* #include "fts5Int.h" */
201540
201541/**************************************************************************
201542** Start of ascii tokenizer implementation.
201543*/
201544
201545/*
201546** For tokenizers with no "unicode" modifier, the set of token characters
201547** is the same as the set of ASCII range alphanumeric characters.
201548*/
201549static unsigned char aAsciiTokenChar[128] = {
201550  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
201551  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
201552  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
201553  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
201554  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
201555  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
201556  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
201557  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
201558};
201559
201560typedef struct AsciiTokenizer AsciiTokenizer;
201561struct AsciiTokenizer {
201562  unsigned char aTokenChar[128];
201563};
201564
201565static void fts5AsciiAddExceptions(
201566  AsciiTokenizer *p,
201567  const char *zArg,
201568  int bTokenChars
201569){
201570  int i;
201571  for(i=0; zArg[i]; i++){
201572    if( (zArg[i] & 0x80)==0 ){
201573      p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
201574    }
201575  }
201576}
201577
201578/*
201579** Delete a "ascii" tokenizer.
201580*/
201581static void fts5AsciiDelete(Fts5Tokenizer *p){
201582  sqlite3_free(p);
201583}
201584
201585/*
201586** Create an "ascii" tokenizer.
201587*/
201588static int fts5AsciiCreate(
201589  void *pUnused,
201590  const char **azArg, int nArg,
201591  Fts5Tokenizer **ppOut
201592){
201593  int rc = SQLITE_OK;
201594  AsciiTokenizer *p = 0;
201595  UNUSED_PARAM(pUnused);
201596  if( nArg%2 ){
201597    rc = SQLITE_ERROR;
201598  }else{
201599    p = sqlite3_malloc(sizeof(AsciiTokenizer));
201600    if( p==0 ){
201601      rc = SQLITE_NOMEM;
201602    }else{
201603      int i;
201604      memset(p, 0, sizeof(AsciiTokenizer));
201605      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
201606      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
201607        const char *zArg = azArg[i+1];
201608        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
201609          fts5AsciiAddExceptions(p, zArg, 1);
201610        }else
201611        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
201612          fts5AsciiAddExceptions(p, zArg, 0);
201613        }else{
201614          rc = SQLITE_ERROR;
201615        }
201616      }
201617      if( rc!=SQLITE_OK ){
201618        fts5AsciiDelete((Fts5Tokenizer*)p);
201619        p = 0;
201620      }
201621    }
201622  }
201623
201624  *ppOut = (Fts5Tokenizer*)p;
201625  return rc;
201626}
201627
201628
201629static void asciiFold(char *aOut, const char *aIn, int nByte){
201630  int i;
201631  for(i=0; i<nByte; i++){
201632    char c = aIn[i];
201633    if( c>='A' && c<='Z' ) c += 32;
201634    aOut[i] = c;
201635  }
201636}
201637
201638/*
201639** Tokenize some text using the ascii tokenizer.
201640*/
201641static int fts5AsciiTokenize(
201642  Fts5Tokenizer *pTokenizer,
201643  void *pCtx,
201644  int iUnused,
201645  const char *pText, int nText,
201646  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
201647){
201648  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
201649  int rc = SQLITE_OK;
201650  int ie;
201651  int is = 0;
201652
201653  char aFold[64];
201654  int nFold = sizeof(aFold);
201655  char *pFold = aFold;
201656  unsigned char *a = p->aTokenChar;
201657
201658  UNUSED_PARAM(iUnused);
201659
201660  while( is<nText && rc==SQLITE_OK ){
201661    int nByte;
201662
201663    /* Skip any leading divider characters. */
201664    while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
201665      is++;
201666    }
201667    if( is==nText ) break;
201668
201669    /* Count the token characters */
201670    ie = is+1;
201671    while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
201672      ie++;
201673    }
201674
201675    /* Fold to lower case */
201676    nByte = ie-is;
201677    if( nByte>nFold ){
201678      if( pFold!=aFold ) sqlite3_free(pFold);
201679      pFold = sqlite3_malloc(nByte*2);
201680      if( pFold==0 ){
201681        rc = SQLITE_NOMEM;
201682        break;
201683      }
201684      nFold = nByte*2;
201685    }
201686    asciiFold(pFold, &pText[is], nByte);
201687
201688    /* Invoke the token callback */
201689    rc = xToken(pCtx, 0, pFold, nByte, is, ie);
201690    is = ie+1;
201691  }
201692
201693  if( pFold!=aFold ) sqlite3_free(pFold);
201694  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
201695  return rc;
201696}
201697
201698/**************************************************************************
201699** Start of unicode61 tokenizer implementation.
201700*/
201701
201702
201703/*
201704** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
201705** from the sqlite3 source file utf.c. If this file is compiled as part
201706** of the amalgamation, they are not required.
201707*/
201708#ifndef SQLITE_AMALGAMATION
201709
201710static const unsigned char sqlite3Utf8Trans1[] = {
201711  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
201712  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
201713  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
201714  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
201715  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
201716  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
201717  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
201718  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
201719};
201720
201721#define READ_UTF8(zIn, zTerm, c)                           \
201722  c = *(zIn++);                                            \
201723  if( c>=0xc0 ){                                           \
201724    c = sqlite3Utf8Trans1[c-0xc0];                         \
201725    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
201726      c = (c<<6) + (0x3f & *(zIn++));                      \
201727    }                                                      \
201728    if( c<0x80                                             \
201729        || (c&0xFFFFF800)==0xD800                          \
201730        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
201731  }
201732
201733
201734#define WRITE_UTF8(zOut, c) {                          \
201735  if( c<0x00080 ){                                     \
201736    *zOut++ = (unsigned char)(c&0xFF);                 \
201737  }                                                    \
201738  else if( c<0x00800 ){                                \
201739    *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
201740    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
201741  }                                                    \
201742  else if( c<0x10000 ){                                \
201743    *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
201744    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
201745    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
201746  }else{                                               \
201747    *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
201748    *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
201749    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
201750    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
201751  }                                                    \
201752}
201753
201754#endif /* ifndef SQLITE_AMALGAMATION */
201755
201756typedef struct Unicode61Tokenizer Unicode61Tokenizer;
201757struct Unicode61Tokenizer {
201758  unsigned char aTokenChar[128];  /* ASCII range token characters */
201759  char *aFold;                    /* Buffer to fold text into */
201760  int nFold;                      /* Size of aFold[] in bytes */
201761  int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
201762  int nException;
201763  int *aiException;
201764};
201765
201766static int fts5UnicodeAddExceptions(
201767  Unicode61Tokenizer *p,          /* Tokenizer object */
201768  const char *z,                  /* Characters to treat as exceptions */
201769  int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
201770){
201771  int rc = SQLITE_OK;
201772  int n = (int)strlen(z);
201773  int *aNew;
201774
201775  if( n>0 ){
201776    aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
201777    if( aNew ){
201778      int nNew = p->nException;
201779      const unsigned char *zCsr = (const unsigned char*)z;
201780      const unsigned char *zTerm = (const unsigned char*)&z[n];
201781      while( zCsr<zTerm ){
201782        int iCode;
201783        int bToken;
201784        READ_UTF8(zCsr, zTerm, iCode);
201785        if( iCode<128 ){
201786          p->aTokenChar[iCode] = (unsigned char)bTokenChars;
201787        }else{
201788          bToken = sqlite3Fts5UnicodeIsalnum(iCode);
201789          assert( (bToken==0 || bToken==1) );
201790          assert( (bTokenChars==0 || bTokenChars==1) );
201791          if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
201792            int i;
201793            for(i=0; i<nNew; i++){
201794              if( aNew[i]>iCode ) break;
201795            }
201796            memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
201797            aNew[i] = iCode;
201798            nNew++;
201799          }
201800        }
201801      }
201802      p->aiException = aNew;
201803      p->nException = nNew;
201804    }else{
201805      rc = SQLITE_NOMEM;
201806    }
201807  }
201808
201809  return rc;
201810}
201811
201812/*
201813** Return true if the p->aiException[] array contains the value iCode.
201814*/
201815static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
201816  if( p->nException>0 ){
201817    int *a = p->aiException;
201818    int iLo = 0;
201819    int iHi = p->nException-1;
201820
201821    while( iHi>=iLo ){
201822      int iTest = (iHi + iLo) / 2;
201823      if( iCode==a[iTest] ){
201824        return 1;
201825      }else if( iCode>a[iTest] ){
201826        iLo = iTest+1;
201827      }else{
201828        iHi = iTest-1;
201829      }
201830    }
201831  }
201832
201833  return 0;
201834}
201835
201836/*
201837** Delete a "unicode61" tokenizer.
201838*/
201839static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
201840  if( pTok ){
201841    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
201842    sqlite3_free(p->aiException);
201843    sqlite3_free(p->aFold);
201844    sqlite3_free(p);
201845  }
201846  return;
201847}
201848
201849/*
201850** Create a "unicode61" tokenizer.
201851*/
201852static int fts5UnicodeCreate(
201853  void *pUnused,
201854  const char **azArg, int nArg,
201855  Fts5Tokenizer **ppOut
201856){
201857  int rc = SQLITE_OK;             /* Return code */
201858  Unicode61Tokenizer *p = 0;      /* New tokenizer object */
201859
201860  UNUSED_PARAM(pUnused);
201861
201862  if( nArg%2 ){
201863    rc = SQLITE_ERROR;
201864  }else{
201865    p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
201866    if( p ){
201867      int i;
201868      memset(p, 0, sizeof(Unicode61Tokenizer));
201869      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
201870      p->bRemoveDiacritic = 1;
201871      p->nFold = 64;
201872      p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
201873      if( p->aFold==0 ){
201874        rc = SQLITE_NOMEM;
201875      }
201876      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
201877        const char *zArg = azArg[i+1];
201878        if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
201879          if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
201880            rc = SQLITE_ERROR;
201881          }
201882          p->bRemoveDiacritic = (zArg[0]=='1');
201883        }else
201884        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
201885          rc = fts5UnicodeAddExceptions(p, zArg, 1);
201886        }else
201887        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
201888          rc = fts5UnicodeAddExceptions(p, zArg, 0);
201889        }else{
201890          rc = SQLITE_ERROR;
201891        }
201892      }
201893    }else{
201894      rc = SQLITE_NOMEM;
201895    }
201896    if( rc!=SQLITE_OK ){
201897      fts5UnicodeDelete((Fts5Tokenizer*)p);
201898      p = 0;
201899    }
201900    *ppOut = (Fts5Tokenizer*)p;
201901  }
201902  return rc;
201903}
201904
201905/*
201906** Return true if, for the purposes of tokenizing with the tokenizer
201907** passed as the first argument, codepoint iCode is considered a token
201908** character (not a separator).
201909*/
201910static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
201911  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
201912  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
201913}
201914
201915static int fts5UnicodeTokenize(
201916  Fts5Tokenizer *pTokenizer,
201917  void *pCtx,
201918  int iUnused,
201919  const char *pText, int nText,
201920  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
201921){
201922  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
201923  int rc = SQLITE_OK;
201924  unsigned char *a = p->aTokenChar;
201925
201926  unsigned char *zTerm = (unsigned char*)&pText[nText];
201927  unsigned char *zCsr = (unsigned char *)pText;
201928
201929  /* Output buffer */
201930  char *aFold = p->aFold;
201931  int nFold = p->nFold;
201932  const char *pEnd = &aFold[nFold-6];
201933
201934  UNUSED_PARAM(iUnused);
201935
201936  /* Each iteration of this loop gobbles up a contiguous run of separators,
201937  ** then the next token.  */
201938  while( rc==SQLITE_OK ){
201939    int iCode;                    /* non-ASCII codepoint read from input */
201940    char *zOut = aFold;
201941    int is;
201942    int ie;
201943
201944    /* Skip any separator characters. */
201945    while( 1 ){
201946      if( zCsr>=zTerm ) goto tokenize_done;
201947      if( *zCsr & 0x80 ) {
201948        /* A character outside of the ascii range. Skip past it if it is
201949        ** a separator character. Or break out of the loop if it is not. */
201950        is = zCsr - (unsigned char*)pText;
201951        READ_UTF8(zCsr, zTerm, iCode);
201952        if( fts5UnicodeIsAlnum(p, iCode) ){
201953          goto non_ascii_tokenchar;
201954        }
201955      }else{
201956        if( a[*zCsr] ){
201957          is = zCsr - (unsigned char*)pText;
201958          goto ascii_tokenchar;
201959        }
201960        zCsr++;
201961      }
201962    }
201963
201964    /* Run through the tokenchars. Fold them into the output buffer along
201965    ** the way.  */
201966    while( zCsr<zTerm ){
201967
201968      /* Grow the output buffer so that there is sufficient space to fit the
201969      ** largest possible utf-8 character.  */
201970      if( zOut>pEnd ){
201971        aFold = sqlite3_malloc(nFold*2);
201972        if( aFold==0 ){
201973          rc = SQLITE_NOMEM;
201974          goto tokenize_done;
201975        }
201976        zOut = &aFold[zOut - p->aFold];
201977        memcpy(aFold, p->aFold, nFold);
201978        sqlite3_free(p->aFold);
201979        p->aFold = aFold;
201980        p->nFold = nFold = nFold*2;
201981        pEnd = &aFold[nFold-6];
201982      }
201983
201984      if( *zCsr & 0x80 ){
201985        /* An non-ascii-range character. Fold it into the output buffer if
201986        ** it is a token character, or break out of the loop if it is not. */
201987        READ_UTF8(zCsr, zTerm, iCode);
201988        if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
201989 non_ascii_tokenchar:
201990          iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
201991          if( iCode ) WRITE_UTF8(zOut, iCode);
201992        }else{
201993          break;
201994        }
201995      }else if( a[*zCsr]==0 ){
201996        /* An ascii-range separator character. End of token. */
201997        break;
201998      }else{
201999 ascii_tokenchar:
202000        if( *zCsr>='A' && *zCsr<='Z' ){
202001          *zOut++ = *zCsr + 32;
202002        }else{
202003          *zOut++ = *zCsr;
202004        }
202005        zCsr++;
202006      }
202007      ie = zCsr - (unsigned char*)pText;
202008    }
202009
202010    /* Invoke the token callback */
202011    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
202012  }
202013
202014 tokenize_done:
202015  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
202016  return rc;
202017}
202018
202019/**************************************************************************
202020** Start of porter stemmer implementation.
202021*/
202022
202023/* Any tokens larger than this (in bytes) are passed through without
202024** stemming. */
202025#define FTS5_PORTER_MAX_TOKEN 64
202026
202027typedef struct PorterTokenizer PorterTokenizer;
202028struct PorterTokenizer {
202029  fts5_tokenizer tokenizer;       /* Parent tokenizer module */
202030  Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
202031  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
202032};
202033
202034/*
202035** Delete a "porter" tokenizer.
202036*/
202037static void fts5PorterDelete(Fts5Tokenizer *pTok){
202038  if( pTok ){
202039    PorterTokenizer *p = (PorterTokenizer*)pTok;
202040    if( p->pTokenizer ){
202041      p->tokenizer.xDelete(p->pTokenizer);
202042    }
202043    sqlite3_free(p);
202044  }
202045}
202046
202047/*
202048** Create a "porter" tokenizer.
202049*/
202050static int fts5PorterCreate(
202051  void *pCtx,
202052  const char **azArg, int nArg,
202053  Fts5Tokenizer **ppOut
202054){
202055  fts5_api *pApi = (fts5_api*)pCtx;
202056  int rc = SQLITE_OK;
202057  PorterTokenizer *pRet;
202058  void *pUserdata = 0;
202059  const char *zBase = "unicode61";
202060
202061  if( nArg>0 ){
202062    zBase = azArg[0];
202063  }
202064
202065  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
202066  if( pRet ){
202067    memset(pRet, 0, sizeof(PorterTokenizer));
202068    rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
202069  }else{
202070    rc = SQLITE_NOMEM;
202071  }
202072  if( rc==SQLITE_OK ){
202073    int nArg2 = (nArg>0 ? nArg-1 : 0);
202074    const char **azArg2 = (nArg2 ? &azArg[1] : 0);
202075    rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
202076  }
202077
202078  if( rc!=SQLITE_OK ){
202079    fts5PorterDelete((Fts5Tokenizer*)pRet);
202080    pRet = 0;
202081  }
202082  *ppOut = (Fts5Tokenizer*)pRet;
202083  return rc;
202084}
202085
202086typedef struct PorterContext PorterContext;
202087struct PorterContext {
202088  void *pCtx;
202089  int (*xToken)(void*, int, const char*, int, int, int);
202090  char *aBuf;
202091};
202092
202093typedef struct PorterRule PorterRule;
202094struct PorterRule {
202095  const char *zSuffix;
202096  int nSuffix;
202097  int (*xCond)(char *zStem, int nStem);
202098  const char *zOutput;
202099  int nOutput;
202100};
202101
202102#if 0
202103static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
202104  int ret = -1;
202105  int nBuf = *pnBuf;
202106  PorterRule *p;
202107
202108  for(p=aRule; p->zSuffix; p++){
202109    assert( strlen(p->zSuffix)==p->nSuffix );
202110    assert( strlen(p->zOutput)==p->nOutput );
202111    if( nBuf<p->nSuffix ) continue;
202112    if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
202113  }
202114
202115  if( p->zSuffix ){
202116    int nStem = nBuf - p->nSuffix;
202117    if( p->xCond==0 || p->xCond(aBuf, nStem) ){
202118      memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
202119      *pnBuf = nStem + p->nOutput;
202120      ret = p - aRule;
202121    }
202122  }
202123
202124  return ret;
202125}
202126#endif
202127
202128static int fts5PorterIsVowel(char c, int bYIsVowel){
202129  return (
202130      c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
202131  );
202132}
202133
202134static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
202135  int i;
202136  int bCons = bPrevCons;
202137
202138  /* Scan for a vowel */
202139  for(i=0; i<nStem; i++){
202140    if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
202141  }
202142
202143  /* Scan for a consonent */
202144  for(i++; i<nStem; i++){
202145    if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
202146  }
202147  return 0;
202148}
202149
202150/* porter rule condition: (m > 0) */
202151static int fts5Porter_MGt0(char *zStem, int nStem){
202152  return !!fts5PorterGobbleVC(zStem, nStem, 0);
202153}
202154
202155/* porter rule condition: (m > 1) */
202156static int fts5Porter_MGt1(char *zStem, int nStem){
202157  int n;
202158  n = fts5PorterGobbleVC(zStem, nStem, 0);
202159  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
202160    return 1;
202161  }
202162  return 0;
202163}
202164
202165/* porter rule condition: (m = 1) */
202166static int fts5Porter_MEq1(char *zStem, int nStem){
202167  int n;
202168  n = fts5PorterGobbleVC(zStem, nStem, 0);
202169  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
202170    return 1;
202171  }
202172  return 0;
202173}
202174
202175/* porter rule condition: (*o) */
202176static int fts5Porter_Ostar(char *zStem, int nStem){
202177  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
202178    return 0;
202179  }else{
202180    int i;
202181    int mask = 0;
202182    int bCons = 0;
202183    for(i=0; i<nStem; i++){
202184      bCons = !fts5PorterIsVowel(zStem[i], bCons);
202185      assert( bCons==0 || bCons==1 );
202186      mask = (mask << 1) + bCons;
202187    }
202188    return ((mask & 0x0007)==0x0005);
202189  }
202190}
202191
202192/* porter rule condition: (m > 1 and (*S or *T)) */
202193static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
202194  assert( nStem>0 );
202195  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
202196      && fts5Porter_MGt1(zStem, nStem);
202197}
202198
202199/* porter rule condition: (*v*) */
202200static int fts5Porter_Vowel(char *zStem, int nStem){
202201  int i;
202202  for(i=0; i<nStem; i++){
202203    if( fts5PorterIsVowel(zStem[i], i>0) ){
202204      return 1;
202205    }
202206  }
202207  return 0;
202208}
202209
202210
202211/**************************************************************************
202212***************************************************************************
202213** GENERATED CODE STARTS HERE (mkportersteps.tcl)
202214*/
202215
202216static int fts5PorterStep4(char *aBuf, int *pnBuf){
202217  int ret = 0;
202218  int nBuf = *pnBuf;
202219  switch( aBuf[nBuf-2] ){
202220
202221    case 'a':
202222      if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
202223        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
202224          *pnBuf = nBuf - 2;
202225        }
202226      }
202227      break;
202228
202229    case 'c':
202230      if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
202231        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
202232          *pnBuf = nBuf - 4;
202233        }
202234      }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
202235        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
202236          *pnBuf = nBuf - 4;
202237        }
202238      }
202239      break;
202240
202241    case 'e':
202242      if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
202243        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
202244          *pnBuf = nBuf - 2;
202245        }
202246      }
202247      break;
202248
202249    case 'i':
202250      if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
202251        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
202252          *pnBuf = nBuf - 2;
202253        }
202254      }
202255      break;
202256
202257    case 'l':
202258      if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
202259        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
202260          *pnBuf = nBuf - 4;
202261        }
202262      }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
202263        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
202264          *pnBuf = nBuf - 4;
202265        }
202266      }
202267      break;
202268
202269    case 'n':
202270      if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
202271        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
202272          *pnBuf = nBuf - 3;
202273        }
202274      }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
202275        if( fts5Porter_MGt1(aBuf, nBuf-5) ){
202276          *pnBuf = nBuf - 5;
202277        }
202278      }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
202279        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
202280          *pnBuf = nBuf - 4;
202281        }
202282      }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
202283        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
202284          *pnBuf = nBuf - 3;
202285        }
202286      }
202287      break;
202288
202289    case 'o':
202290      if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
202291        if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
202292          *pnBuf = nBuf - 3;
202293        }
202294      }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
202295        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
202296          *pnBuf = nBuf - 2;
202297        }
202298      }
202299      break;
202300
202301    case 's':
202302      if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
202303        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
202304          *pnBuf = nBuf - 3;
202305        }
202306      }
202307      break;
202308
202309    case 't':
202310      if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
202311        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
202312          *pnBuf = nBuf - 3;
202313        }
202314      }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
202315        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
202316          *pnBuf = nBuf - 3;
202317        }
202318      }
202319      break;
202320
202321    case 'u':
202322      if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
202323        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
202324          *pnBuf = nBuf - 3;
202325        }
202326      }
202327      break;
202328
202329    case 'v':
202330      if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
202331        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
202332          *pnBuf = nBuf - 3;
202333        }
202334      }
202335      break;
202336
202337    case 'z':
202338      if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
202339        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
202340          *pnBuf = nBuf - 3;
202341        }
202342      }
202343      break;
202344
202345  }
202346  return ret;
202347}
202348
202349
202350static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
202351  int ret = 0;
202352  int nBuf = *pnBuf;
202353  switch( aBuf[nBuf-2] ){
202354
202355    case 'a':
202356      if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
202357        memcpy(&aBuf[nBuf-2], "ate", 3);
202358        *pnBuf = nBuf - 2 + 3;
202359        ret = 1;
202360      }
202361      break;
202362
202363    case 'b':
202364      if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
202365        memcpy(&aBuf[nBuf-2], "ble", 3);
202366        *pnBuf = nBuf - 2 + 3;
202367        ret = 1;
202368      }
202369      break;
202370
202371    case 'i':
202372      if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
202373        memcpy(&aBuf[nBuf-2], "ize", 3);
202374        *pnBuf = nBuf - 2 + 3;
202375        ret = 1;
202376      }
202377      break;
202378
202379  }
202380  return ret;
202381}
202382
202383
202384static int fts5PorterStep2(char *aBuf, int *pnBuf){
202385  int ret = 0;
202386  int nBuf = *pnBuf;
202387  switch( aBuf[nBuf-2] ){
202388
202389    case 'a':
202390      if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
202391        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
202392          memcpy(&aBuf[nBuf-7], "ate", 3);
202393          *pnBuf = nBuf - 7 + 3;
202394        }
202395      }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
202396        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
202397          memcpy(&aBuf[nBuf-6], "tion", 4);
202398          *pnBuf = nBuf - 6 + 4;
202399        }
202400      }
202401      break;
202402
202403    case 'c':
202404      if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
202405        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
202406          memcpy(&aBuf[nBuf-4], "ence", 4);
202407          *pnBuf = nBuf - 4 + 4;
202408        }
202409      }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
202410        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
202411          memcpy(&aBuf[nBuf-4], "ance", 4);
202412          *pnBuf = nBuf - 4 + 4;
202413        }
202414      }
202415      break;
202416
202417    case 'e':
202418      if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
202419        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
202420          memcpy(&aBuf[nBuf-4], "ize", 3);
202421          *pnBuf = nBuf - 4 + 3;
202422        }
202423      }
202424      break;
202425
202426    case 'g':
202427      if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
202428        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
202429          memcpy(&aBuf[nBuf-4], "log", 3);
202430          *pnBuf = nBuf - 4 + 3;
202431        }
202432      }
202433      break;
202434
202435    case 'l':
202436      if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
202437        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
202438          memcpy(&aBuf[nBuf-3], "ble", 3);
202439          *pnBuf = nBuf - 3 + 3;
202440        }
202441      }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
202442        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
202443          memcpy(&aBuf[nBuf-4], "al", 2);
202444          *pnBuf = nBuf - 4 + 2;
202445        }
202446      }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
202447        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202448          memcpy(&aBuf[nBuf-5], "ent", 3);
202449          *pnBuf = nBuf - 5 + 3;
202450        }
202451      }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
202452        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
202453          memcpy(&aBuf[nBuf-3], "e", 1);
202454          *pnBuf = nBuf - 3 + 1;
202455        }
202456      }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
202457        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202458          memcpy(&aBuf[nBuf-5], "ous", 3);
202459          *pnBuf = nBuf - 5 + 3;
202460        }
202461      }
202462      break;
202463
202464    case 'o':
202465      if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
202466        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
202467          memcpy(&aBuf[nBuf-7], "ize", 3);
202468          *pnBuf = nBuf - 7 + 3;
202469        }
202470      }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
202471        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202472          memcpy(&aBuf[nBuf-5], "ate", 3);
202473          *pnBuf = nBuf - 5 + 3;
202474        }
202475      }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
202476        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
202477          memcpy(&aBuf[nBuf-4], "ate", 3);
202478          *pnBuf = nBuf - 4 + 3;
202479        }
202480      }
202481      break;
202482
202483    case 's':
202484      if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
202485        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202486          memcpy(&aBuf[nBuf-5], "al", 2);
202487          *pnBuf = nBuf - 5 + 2;
202488        }
202489      }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
202490        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
202491          memcpy(&aBuf[nBuf-7], "ive", 3);
202492          *pnBuf = nBuf - 7 + 3;
202493        }
202494      }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
202495        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
202496          memcpy(&aBuf[nBuf-7], "ful", 3);
202497          *pnBuf = nBuf - 7 + 3;
202498        }
202499      }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
202500        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
202501          memcpy(&aBuf[nBuf-7], "ous", 3);
202502          *pnBuf = nBuf - 7 + 3;
202503        }
202504      }
202505      break;
202506
202507    case 't':
202508      if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
202509        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202510          memcpy(&aBuf[nBuf-5], "al", 2);
202511          *pnBuf = nBuf - 5 + 2;
202512        }
202513      }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
202514        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202515          memcpy(&aBuf[nBuf-5], "ive", 3);
202516          *pnBuf = nBuf - 5 + 3;
202517        }
202518      }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
202519        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
202520          memcpy(&aBuf[nBuf-6], "ble", 3);
202521          *pnBuf = nBuf - 6 + 3;
202522        }
202523      }
202524      break;
202525
202526  }
202527  return ret;
202528}
202529
202530
202531static int fts5PorterStep3(char *aBuf, int *pnBuf){
202532  int ret = 0;
202533  int nBuf = *pnBuf;
202534  switch( aBuf[nBuf-2] ){
202535
202536    case 'a':
202537      if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
202538        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
202539          memcpy(&aBuf[nBuf-4], "ic", 2);
202540          *pnBuf = nBuf - 4 + 2;
202541        }
202542      }
202543      break;
202544
202545    case 's':
202546      if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
202547        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
202548          *pnBuf = nBuf - 4;
202549        }
202550      }
202551      break;
202552
202553    case 't':
202554      if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
202555        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202556          memcpy(&aBuf[nBuf-5], "ic", 2);
202557          *pnBuf = nBuf - 5 + 2;
202558        }
202559      }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
202560        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202561          memcpy(&aBuf[nBuf-5], "ic", 2);
202562          *pnBuf = nBuf - 5 + 2;
202563        }
202564      }
202565      break;
202566
202567    case 'u':
202568      if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
202569        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
202570          *pnBuf = nBuf - 3;
202571        }
202572      }
202573      break;
202574
202575    case 'v':
202576      if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
202577        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202578          *pnBuf = nBuf - 5;
202579        }
202580      }
202581      break;
202582
202583    case 'z':
202584      if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
202585        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
202586          memcpy(&aBuf[nBuf-5], "al", 2);
202587          *pnBuf = nBuf - 5 + 2;
202588        }
202589      }
202590      break;
202591
202592  }
202593  return ret;
202594}
202595
202596
202597static int fts5PorterStep1B(char *aBuf, int *pnBuf){
202598  int ret = 0;
202599  int nBuf = *pnBuf;
202600  switch( aBuf[nBuf-2] ){
202601
202602    case 'e':
202603      if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
202604        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
202605          memcpy(&aBuf[nBuf-3], "ee", 2);
202606          *pnBuf = nBuf - 3 + 2;
202607        }
202608      }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
202609        if( fts5Porter_Vowel(aBuf, nBuf-2) ){
202610          *pnBuf = nBuf - 2;
202611          ret = 1;
202612        }
202613      }
202614      break;
202615
202616    case 'n':
202617      if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
202618        if( fts5Porter_Vowel(aBuf, nBuf-3) ){
202619          *pnBuf = nBuf - 3;
202620          ret = 1;
202621        }
202622      }
202623      break;
202624
202625  }
202626  return ret;
202627}
202628
202629/*
202630** GENERATED CODE ENDS HERE (mkportersteps.tcl)
202631***************************************************************************
202632**************************************************************************/
202633
202634static void fts5PorterStep1A(char *aBuf, int *pnBuf){
202635  int nBuf = *pnBuf;
202636  if( aBuf[nBuf-1]=='s' ){
202637    if( aBuf[nBuf-2]=='e' ){
202638      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
202639       || (nBuf>3 && aBuf[nBuf-3]=='i' )
202640      ){
202641        *pnBuf = nBuf-2;
202642      }else{
202643        *pnBuf = nBuf-1;
202644      }
202645    }
202646    else if( aBuf[nBuf-2]!='s' ){
202647      *pnBuf = nBuf-1;
202648    }
202649  }
202650}
202651
202652static int fts5PorterCb(
202653  void *pCtx,
202654  int tflags,
202655  const char *pToken,
202656  int nToken,
202657  int iStart,
202658  int iEnd
202659){
202660  PorterContext *p = (PorterContext*)pCtx;
202661
202662  char *aBuf;
202663  int nBuf;
202664
202665  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
202666  aBuf = p->aBuf;
202667  nBuf = nToken;
202668  memcpy(aBuf, pToken, nBuf);
202669
202670  /* Step 1. */
202671  fts5PorterStep1A(aBuf, &nBuf);
202672  if( fts5PorterStep1B(aBuf, &nBuf) ){
202673    if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
202674      char c = aBuf[nBuf-1];
202675      if( fts5PorterIsVowel(c, 0)==0
202676       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
202677      ){
202678        nBuf--;
202679      }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
202680        aBuf[nBuf++] = 'e';
202681      }
202682    }
202683  }
202684
202685  /* Step 1C. */
202686  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
202687    aBuf[nBuf-1] = 'i';
202688  }
202689
202690  /* Steps 2 through 4. */
202691  fts5PorterStep2(aBuf, &nBuf);
202692  fts5PorterStep3(aBuf, &nBuf);
202693  fts5PorterStep4(aBuf, &nBuf);
202694
202695  /* Step 5a. */
202696  assert( nBuf>0 );
202697  if( aBuf[nBuf-1]=='e' ){
202698    if( fts5Porter_MGt1(aBuf, nBuf-1)
202699     || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
202700    ){
202701      nBuf--;
202702    }
202703  }
202704
202705  /* Step 5b. */
202706  if( nBuf>1 && aBuf[nBuf-1]=='l'
202707   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
202708  ){
202709    nBuf--;
202710  }
202711
202712  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
202713
202714 pass_through:
202715  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
202716}
202717
202718/*
202719** Tokenize using the porter tokenizer.
202720*/
202721static int fts5PorterTokenize(
202722  Fts5Tokenizer *pTokenizer,
202723  void *pCtx,
202724  int flags,
202725  const char *pText, int nText,
202726  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
202727){
202728  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
202729  PorterContext sCtx;
202730  sCtx.xToken = xToken;
202731  sCtx.pCtx = pCtx;
202732  sCtx.aBuf = p->aBuf;
202733  return p->tokenizer.xTokenize(
202734      p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
202735  );
202736}
202737
202738/*
202739** Register all built-in tokenizers with FTS5.
202740*/
202741static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
202742  struct BuiltinTokenizer {
202743    const char *zName;
202744    fts5_tokenizer x;
202745  } aBuiltin[] = {
202746    { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
202747    { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
202748    { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
202749  };
202750
202751  int rc = SQLITE_OK;             /* Return code */
202752  int i;                          /* To iterate through builtin functions */
202753
202754  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
202755    rc = pApi->xCreateTokenizer(pApi,
202756        aBuiltin[i].zName,
202757        (void*)pApi,
202758        &aBuiltin[i].x,
202759        0
202760    );
202761  }
202762
202763  return rc;
202764}
202765
202766
202767
202768/*
202769** 2012 May 25
202770**
202771** The author disclaims copyright to this source code.  In place of
202772** a legal notice, here is a blessing:
202773**
202774**    May you do good and not evil.
202775**    May you find forgiveness for yourself and forgive others.
202776**    May you share freely, never taking more than you give.
202777**
202778******************************************************************************
202779*/
202780
202781/*
202782** DO NOT EDIT THIS MACHINE GENERATED FILE.
202783*/
202784
202785
202786/* #include <assert.h> */
202787
202788/*
202789** Return true if the argument corresponds to a unicode codepoint
202790** classified as either a letter or a number. Otherwise false.
202791**
202792** The results are undefined if the value passed to this function
202793** is less than zero.
202794*/
202795static int sqlite3Fts5UnicodeIsalnum(int c){
202796  /* Each unsigned integer in the following array corresponds to a contiguous
202797  ** range of unicode codepoints that are not either letters or numbers (i.e.
202798  ** codepoints for which this function should return 0).
202799  **
202800  ** The most significant 22 bits in each 32-bit value contain the first
202801  ** codepoint in the range. The least significant 10 bits are used to store
202802  ** the size of the range (always at least 1). In other words, the value
202803  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
202804  ** C. It is not possible to represent a range larger than 1023 codepoints
202805  ** using this format.
202806  */
202807  static const unsigned int aEntry[] = {
202808    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
202809    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
202810    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
202811    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
202812    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
202813    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
202814    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
202815    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
202816    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
202817    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
202818    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
202819    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
202820    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
202821    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
202822    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
202823    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
202824    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
202825    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
202826    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
202827    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
202828    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
202829    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
202830    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
202831    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
202832    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
202833    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
202834    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
202835    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
202836    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
202837    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
202838    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
202839    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
202840    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
202841    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
202842    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
202843    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
202844    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
202845    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
202846    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
202847    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
202848    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
202849    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
202850    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
202851    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
202852    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
202853    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
202854    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
202855    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
202856    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
202857    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
202858    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
202859    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
202860    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
202861    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
202862    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
202863    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
202864    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
202865    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
202866    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
202867    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
202868    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
202869    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
202870    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
202871    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
202872    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
202873    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
202874    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
202875    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
202876    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
202877    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
202878    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
202879    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
202880    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
202881    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
202882    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
202883    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
202884    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
202885    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
202886    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
202887    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
202888    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
202889    0x380400F0,
202890  };
202891  static const unsigned int aAscii[4] = {
202892    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
202893  };
202894
202895  if( (unsigned int)c<128 ){
202896    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
202897  }else if( (unsigned int)c<(1<<22) ){
202898    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
202899    int iRes = 0;
202900    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
202901    int iLo = 0;
202902    while( iHi>=iLo ){
202903      int iTest = (iHi + iLo) / 2;
202904      if( key >= aEntry[iTest] ){
202905        iRes = iTest;
202906        iLo = iTest+1;
202907      }else{
202908        iHi = iTest-1;
202909      }
202910    }
202911    assert( aEntry[0]<key );
202912    assert( key>=aEntry[iRes] );
202913    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
202914  }
202915  return 1;
202916}
202917
202918
202919/*
202920** If the argument is a codepoint corresponding to a lowercase letter
202921** in the ASCII range with a diacritic added, return the codepoint
202922** of the ASCII letter only. For example, if passed 235 - "LATIN
202923** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
202924** E"). The resuls of passing a codepoint that corresponds to an
202925** uppercase letter are undefined.
202926*/
202927static int fts5_remove_diacritic(int c){
202928  unsigned short aDia[] = {
202929        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
202930     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
202931     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
202932     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
202933     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
202934     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
202935     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
202936     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
202937    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
202938    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
202939    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
202940    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
202941    62924, 63050, 63082, 63274, 63390,
202942  };
202943  char aChar[] = {
202944    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
202945    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
202946    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
202947    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
202948    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
202949    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
202950    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
202951    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
202952    'e',  'i',  'o',  'u',  'y',
202953  };
202954
202955  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
202956  int iRes = 0;
202957  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
202958  int iLo = 0;
202959  while( iHi>=iLo ){
202960    int iTest = (iHi + iLo) / 2;
202961    if( key >= aDia[iTest] ){
202962      iRes = iTest;
202963      iLo = iTest+1;
202964    }else{
202965      iHi = iTest-1;
202966    }
202967  }
202968  assert( key>=aDia[iRes] );
202969  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
202970}
202971
202972
202973/*
202974** Return true if the argument interpreted as a unicode codepoint
202975** is a diacritical modifier character.
202976*/
202977static int sqlite3Fts5UnicodeIsdiacritic(int c){
202978  unsigned int mask0 = 0x08029FDF;
202979  unsigned int mask1 = 0x000361F8;
202980  if( c<768 || c>817 ) return 0;
202981  return (c < 768+32) ?
202982      (mask0 & (1 << (c-768))) :
202983      (mask1 & (1 << (c-768-32)));
202984}
202985
202986
202987/*
202988** Interpret the argument as a unicode codepoint. If the codepoint
202989** is an upper case character that has a lower case equivalent,
202990** return the codepoint corresponding to the lower case version.
202991** Otherwise, return a copy of the argument.
202992**
202993** The results are undefined if the value passed to this function
202994** is less than zero.
202995*/
202996static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
202997  /* Each entry in the following array defines a rule for folding a range
202998  ** of codepoints to lower case. The rule applies to a range of nRange
202999  ** codepoints starting at codepoint iCode.
203000  **
203001  ** If the least significant bit in flags is clear, then the rule applies
203002  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
203003  ** need to be folded). Or, if it is set, then the rule only applies to
203004  ** every second codepoint in the range, starting with codepoint C.
203005  **
203006  ** The 7 most significant bits in flags are an index into the aiOff[]
203007  ** array. If a specific codepoint C does require folding, then its lower
203008  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
203009  **
203010  ** The contents of this array are generated by parsing the CaseFolding.txt
203011  ** file distributed as part of the "Unicode Character Database". See
203012  ** http://www.unicode.org for details.
203013  */
203014  static const struct TableEntry {
203015    unsigned short iCode;
203016    unsigned char flags;
203017    unsigned char nRange;
203018  } aEntry[] = {
203019    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
203020    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
203021    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
203022    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
203023    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
203024    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
203025    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
203026    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
203027    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
203028    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
203029    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
203030    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
203031    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
203032    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
203033    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
203034    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
203035    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
203036    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
203037    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
203038    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
203039    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
203040    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
203041    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
203042    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
203043    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
203044    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
203045    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
203046    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
203047    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
203048    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
203049    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
203050    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
203051    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
203052    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
203053    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
203054    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
203055    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
203056    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
203057    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
203058    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
203059    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
203060    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
203061    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
203062    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
203063    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
203064    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
203065    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
203066    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
203067    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
203068    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
203069    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
203070    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
203071    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
203072    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
203073    {65313, 14, 26},
203074  };
203075  static const unsigned short aiOff[] = {
203076   1,     2,     8,     15,    16,    26,    28,    32,
203077   37,    38,    40,    48,    63,    64,    69,    71,
203078   79,    80,    116,   202,   203,   205,   206,   207,
203079   209,   210,   211,   213,   214,   217,   218,   219,
203080   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
203081   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
203082   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
203083   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
203084   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
203085   65514, 65521, 65527, 65528, 65529,
203086  };
203087
203088  int ret = c;
203089
203090  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
203091
203092  if( c<128 ){
203093    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
203094  }else if( c<65536 ){
203095    const struct TableEntry *p;
203096    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
203097    int iLo = 0;
203098    int iRes = -1;
203099
203100    assert( c>aEntry[0].iCode );
203101    while( iHi>=iLo ){
203102      int iTest = (iHi + iLo) / 2;
203103      int cmp = (c - aEntry[iTest].iCode);
203104      if( cmp>=0 ){
203105        iRes = iTest;
203106        iLo = iTest+1;
203107      }else{
203108        iHi = iTest-1;
203109      }
203110    }
203111
203112    assert( iRes>=0 && c>=aEntry[iRes].iCode );
203113    p = &aEntry[iRes];
203114    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
203115      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
203116      assert( ret>0 );
203117    }
203118
203119    if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
203120  }
203121
203122  else if( c>=66560 && c<66600 ){
203123    ret = c + 40;
203124  }
203125
203126  return ret;
203127}
203128
203129/*
203130** 2015 May 30
203131**
203132** The author disclaims copyright to this source code.  In place of
203133** a legal notice, here is a blessing:
203134**
203135**    May you do good and not evil.
203136**    May you find forgiveness for yourself and forgive others.
203137**    May you share freely, never taking more than you give.
203138**
203139******************************************************************************
203140**
203141** Routines for varint serialization and deserialization.
203142*/
203143
203144
203145/* #include "fts5Int.h" */
203146
203147/*
203148** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
203149** Except, this version does handle the single byte case that the core
203150** version depends on being handled before its function is called.
203151*/
203152static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
203153  u32 a,b;
203154
203155  /* The 1-byte case. Overwhelmingly the most common. */
203156  a = *p;
203157  /* a: p0 (unmasked) */
203158  if (!(a&0x80))
203159  {
203160    /* Values between 0 and 127 */
203161    *v = a;
203162    return 1;
203163  }
203164
203165  /* The 2-byte case */
203166  p++;
203167  b = *p;
203168  /* b: p1 (unmasked) */
203169  if (!(b&0x80))
203170  {
203171    /* Values between 128 and 16383 */
203172    a &= 0x7f;
203173    a = a<<7;
203174    *v = a | b;
203175    return 2;
203176  }
203177
203178  /* The 3-byte case */
203179  p++;
203180  a = a<<14;
203181  a |= *p;
203182  /* a: p0<<14 | p2 (unmasked) */
203183  if (!(a&0x80))
203184  {
203185    /* Values between 16384 and 2097151 */
203186    a &= (0x7f<<14)|(0x7f);
203187    b &= 0x7f;
203188    b = b<<7;
203189    *v = a | b;
203190    return 3;
203191  }
203192
203193  /* A 32-bit varint is used to store size information in btrees.
203194  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
203195  ** A 3-byte varint is sufficient, for example, to record the size
203196  ** of a 1048569-byte BLOB or string.
203197  **
203198  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
203199  ** rare larger cases can be handled by the slower 64-bit varint
203200  ** routine.
203201  */
203202  {
203203    u64 v64;
203204    u8 n;
203205    p -= 2;
203206    n = sqlite3Fts5GetVarint(p, &v64);
203207    *v = (u32)v64;
203208    assert( n>3 && n<=9 );
203209    return n;
203210  }
203211}
203212
203213
203214/*
203215** Bitmasks used by sqlite3GetVarint().  These precomputed constants
203216** are defined here rather than simply putting the constant expressions
203217** inline in order to work around bugs in the RVT compiler.
203218**
203219** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
203220**
203221** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
203222*/
203223#define SLOT_2_0     0x001fc07f
203224#define SLOT_4_2_0   0xf01fc07f
203225
203226/*
203227** Read a 64-bit variable-length integer from memory starting at p[0].
203228** Return the number of bytes read.  The value is stored in *v.
203229*/
203230static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
203231  u32 a,b,s;
203232
203233  a = *p;
203234  /* a: p0 (unmasked) */
203235  if (!(a&0x80))
203236  {
203237    *v = a;
203238    return 1;
203239  }
203240
203241  p++;
203242  b = *p;
203243  /* b: p1 (unmasked) */
203244  if (!(b&0x80))
203245  {
203246    a &= 0x7f;
203247    a = a<<7;
203248    a |= b;
203249    *v = a;
203250    return 2;
203251  }
203252
203253  /* Verify that constants are precomputed correctly */
203254  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
203255  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
203256
203257  p++;
203258  a = a<<14;
203259  a |= *p;
203260  /* a: p0<<14 | p2 (unmasked) */
203261  if (!(a&0x80))
203262  {
203263    a &= SLOT_2_0;
203264    b &= 0x7f;
203265    b = b<<7;
203266    a |= b;
203267    *v = a;
203268    return 3;
203269  }
203270
203271  /* CSE1 from below */
203272  a &= SLOT_2_0;
203273  p++;
203274  b = b<<14;
203275  b |= *p;
203276  /* b: p1<<14 | p3 (unmasked) */
203277  if (!(b&0x80))
203278  {
203279    b &= SLOT_2_0;
203280    /* moved CSE1 up */
203281    /* a &= (0x7f<<14)|(0x7f); */
203282    a = a<<7;
203283    a |= b;
203284    *v = a;
203285    return 4;
203286  }
203287
203288  /* a: p0<<14 | p2 (masked) */
203289  /* b: p1<<14 | p3 (unmasked) */
203290  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
203291  /* moved CSE1 up */
203292  /* a &= (0x7f<<14)|(0x7f); */
203293  b &= SLOT_2_0;
203294  s = a;
203295  /* s: p0<<14 | p2 (masked) */
203296
203297  p++;
203298  a = a<<14;
203299  a |= *p;
203300  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
203301  if (!(a&0x80))
203302  {
203303    /* we can skip these cause they were (effectively) done above in calc'ing s */
203304    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
203305    /* b &= (0x7f<<14)|(0x7f); */
203306    b = b<<7;
203307    a |= b;
203308    s = s>>18;
203309    *v = ((u64)s)<<32 | a;
203310    return 5;
203311  }
203312
203313  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
203314  s = s<<7;
203315  s |= b;
203316  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
203317
203318  p++;
203319  b = b<<14;
203320  b |= *p;
203321  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
203322  if (!(b&0x80))
203323  {
203324    /* we can skip this cause it was (effectively) done above in calc'ing s */
203325    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
203326    a &= SLOT_2_0;
203327    a = a<<7;
203328    a |= b;
203329    s = s>>18;
203330    *v = ((u64)s)<<32 | a;
203331    return 6;
203332  }
203333
203334  p++;
203335  a = a<<14;
203336  a |= *p;
203337  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
203338  if (!(a&0x80))
203339  {
203340    a &= SLOT_4_2_0;
203341    b &= SLOT_2_0;
203342    b = b<<7;
203343    a |= b;
203344    s = s>>11;
203345    *v = ((u64)s)<<32 | a;
203346    return 7;
203347  }
203348
203349  /* CSE2 from below */
203350  a &= SLOT_2_0;
203351  p++;
203352  b = b<<14;
203353  b |= *p;
203354  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
203355  if (!(b&0x80))
203356  {
203357    b &= SLOT_4_2_0;
203358    /* moved CSE2 up */
203359    /* a &= (0x7f<<14)|(0x7f); */
203360    a = a<<7;
203361    a |= b;
203362    s = s>>4;
203363    *v = ((u64)s)<<32 | a;
203364    return 8;
203365  }
203366
203367  p++;
203368  a = a<<15;
203369  a |= *p;
203370  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
203371
203372  /* moved CSE2 up */
203373  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
203374  b &= SLOT_2_0;
203375  b = b<<8;
203376  a |= b;
203377
203378  s = s<<4;
203379  b = p[-4];
203380  b &= 0x7f;
203381  b = b>>3;
203382  s |= b;
203383
203384  *v = ((u64)s)<<32 | a;
203385
203386  return 9;
203387}
203388
203389/*
203390** The variable-length integer encoding is as follows:
203391**
203392** KEY:
203393**         A = 0xxxxxxx    7 bits of data and one flag bit
203394**         B = 1xxxxxxx    7 bits of data and one flag bit
203395**         C = xxxxxxxx    8 bits of data
203396**
203397**  7 bits - A
203398** 14 bits - BA
203399** 21 bits - BBA
203400** 28 bits - BBBA
203401** 35 bits - BBBBA
203402** 42 bits - BBBBBA
203403** 49 bits - BBBBBBA
203404** 56 bits - BBBBBBBA
203405** 64 bits - BBBBBBBBC
203406*/
203407
203408#ifdef SQLITE_NOINLINE
203409# define FTS5_NOINLINE SQLITE_NOINLINE
203410#else
203411# define FTS5_NOINLINE
203412#endif
203413
203414/*
203415** Write a 64-bit variable-length integer to memory starting at p[0].
203416** The length of data write will be between 1 and 9 bytes.  The number
203417** of bytes written is returned.
203418**
203419** A variable-length integer consists of the lower 7 bits of each byte
203420** for all bytes that have the 8th bit set and one byte with the 8th
203421** bit clear.  Except, if we get to the 9th byte, it stores the full
203422** 8 bits and is the last byte.
203423*/
203424static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
203425  int i, j, n;
203426  u8 buf[10];
203427  if( v & (((u64)0xff000000)<<32) ){
203428    p[8] = (u8)v;
203429    v >>= 8;
203430    for(i=7; i>=0; i--){
203431      p[i] = (u8)((v & 0x7f) | 0x80);
203432      v >>= 7;
203433    }
203434    return 9;
203435  }
203436  n = 0;
203437  do{
203438    buf[n++] = (u8)((v & 0x7f) | 0x80);
203439    v >>= 7;
203440  }while( v!=0 );
203441  buf[0] &= 0x7f;
203442  assert( n<=9 );
203443  for(i=0, j=n-1; j>=0; j--, i++){
203444    p[i] = buf[j];
203445  }
203446  return n;
203447}
203448
203449static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
203450  if( v<=0x7f ){
203451    p[0] = v&0x7f;
203452    return 1;
203453  }
203454  if( v<=0x3fff ){
203455    p[0] = ((v>>7)&0x7f)|0x80;
203456    p[1] = v&0x7f;
203457    return 2;
203458  }
203459  return fts5PutVarint64(p,v);
203460}
203461
203462
203463static int sqlite3Fts5GetVarintLen(u32 iVal){
203464#if 0
203465  if( iVal<(1 << 7 ) ) return 1;
203466#endif
203467  assert( iVal>=(1 << 7) );
203468  if( iVal<(1 << 14) ) return 2;
203469  if( iVal<(1 << 21) ) return 3;
203470  if( iVal<(1 << 28) ) return 4;
203471  return 5;
203472}
203473
203474
203475/*
203476** 2015 May 08
203477**
203478** The author disclaims copyright to this source code.  In place of
203479** a legal notice, here is a blessing:
203480**
203481**    May you do good and not evil.
203482**    May you find forgiveness for yourself and forgive others.
203483**    May you share freely, never taking more than you give.
203484**
203485******************************************************************************
203486**
203487** This is an SQLite virtual table module implementing direct access to an
203488** existing FTS5 index. The module may create several different types of
203489** tables:
203490**
203491** col:
203492**     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
203493**
203494**   One row for each term/column combination. The value of $doc is set to
203495**   the number of fts5 rows that contain at least one instance of term
203496**   $term within column $col. Field $cnt is set to the total number of
203497**   instances of term $term in column $col (in any row of the fts5 table).
203498**
203499** row:
203500**     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
203501**
203502**   One row for each term in the database. The value of $doc is set to
203503**   the number of fts5 rows that contain at least one instance of term
203504**   $term. Field $cnt is set to the total number of instances of term
203505**   $term in the database.
203506*/
203507
203508
203509/* #include "fts5Int.h" */
203510
203511
203512typedef struct Fts5VocabTable Fts5VocabTable;
203513typedef struct Fts5VocabCursor Fts5VocabCursor;
203514
203515struct Fts5VocabTable {
203516  sqlite3_vtab base;
203517  char *zFts5Tbl;                 /* Name of fts5 table */
203518  char *zFts5Db;                  /* Db containing fts5 table */
203519  sqlite3 *db;                    /* Database handle */
203520  Fts5Global *pGlobal;            /* FTS5 global object for this database */
203521  int eType;                      /* FTS5_VOCAB_COL or ROW */
203522};
203523
203524struct Fts5VocabCursor {
203525  sqlite3_vtab_cursor base;
203526  sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
203527  Fts5Index *pIndex;              /* Associated FTS5 index */
203528
203529  int bEof;                       /* True if this cursor is at EOF */
203530  Fts5IndexIter *pIter;           /* Term/rowid iterator object */
203531
203532  int nLeTerm;                    /* Size of zLeTerm in bytes */
203533  char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
203534
203535  /* These are used by 'col' tables only */
203536  Fts5Config *pConfig;            /* Fts5 table configuration */
203537  int iCol;
203538  i64 *aCnt;
203539  i64 *aDoc;
203540
203541  /* Output values used by 'row' and 'col' tables */
203542  i64 rowid;                      /* This table's current rowid value */
203543  Fts5Buffer term;                /* Current value of 'term' column */
203544};
203545
203546#define FTS5_VOCAB_COL    0
203547#define FTS5_VOCAB_ROW    1
203548
203549#define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
203550#define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
203551
203552/*
203553** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
203554*/
203555#define FTS5_VOCAB_TERM_EQ 0x01
203556#define FTS5_VOCAB_TERM_GE 0x02
203557#define FTS5_VOCAB_TERM_LE 0x04
203558
203559
203560/*
203561** Translate a string containing an fts5vocab table type to an
203562** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
203563** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
203564** and return SQLITE_ERROR.
203565*/
203566static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
203567  int rc = SQLITE_OK;
203568  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
203569  if( rc==SQLITE_OK ){
203570    sqlite3Fts5Dequote(zCopy);
203571    if( sqlite3_stricmp(zCopy, "col")==0 ){
203572      *peType = FTS5_VOCAB_COL;
203573    }else
203574
203575    if( sqlite3_stricmp(zCopy, "row")==0 ){
203576      *peType = FTS5_VOCAB_ROW;
203577    }else
203578    {
203579      *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
203580      rc = SQLITE_ERROR;
203581    }
203582    sqlite3_free(zCopy);
203583  }
203584
203585  return rc;
203586}
203587
203588
203589/*
203590** The xDisconnect() virtual table method.
203591*/
203592static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
203593  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
203594  sqlite3_free(pTab);
203595  return SQLITE_OK;
203596}
203597
203598/*
203599** The xDestroy() virtual table method.
203600*/
203601static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
203602  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
203603  sqlite3_free(pTab);
203604  return SQLITE_OK;
203605}
203606
203607/*
203608** This function is the implementation of both the xConnect and xCreate
203609** methods of the FTS3 virtual table.
203610**
203611** The argv[] array contains the following:
203612**
203613**   argv[0]   -> module name  ("fts5vocab")
203614**   argv[1]   -> database name
203615**   argv[2]   -> table name
203616**
203617** then:
203618**
203619**   argv[3]   -> name of fts5 table
203620**   argv[4]   -> type of fts5vocab table
203621**
203622** or, for tables in the TEMP schema only.
203623**
203624**   argv[3]   -> name of fts5 tables database
203625**   argv[4]   -> name of fts5 table
203626**   argv[5]   -> type of fts5vocab table
203627*/
203628static int fts5VocabInitVtab(
203629  sqlite3 *db,                    /* The SQLite database connection */
203630  void *pAux,                     /* Pointer to Fts5Global object */
203631  int argc,                       /* Number of elements in argv array */
203632  const char * const *argv,       /* xCreate/xConnect argument array */
203633  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
203634  char **pzErr                    /* Write any error message here */
203635){
203636  const char *azSchema[] = {
203637    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
203638    "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")"
203639  };
203640
203641  Fts5VocabTable *pRet = 0;
203642  int rc = SQLITE_OK;             /* Return code */
203643  int bDb;
203644
203645  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
203646
203647  if( argc!=5 && bDb==0 ){
203648    *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
203649    rc = SQLITE_ERROR;
203650  }else{
203651    int nByte;                      /* Bytes of space to allocate */
203652    const char *zDb = bDb ? argv[3] : argv[1];
203653    const char *zTab = bDb ? argv[4] : argv[3];
203654    const char *zType = bDb ? argv[5] : argv[4];
203655    int nDb = (int)strlen(zDb)+1;
203656    int nTab = (int)strlen(zTab)+1;
203657    int eType = 0;
203658
203659    rc = fts5VocabTableType(zType, pzErr, &eType);
203660    if( rc==SQLITE_OK ){
203661      assert( eType>=0 && eType<ArraySize(azSchema) );
203662      rc = sqlite3_declare_vtab(db, azSchema[eType]);
203663    }
203664
203665    nByte = sizeof(Fts5VocabTable) + nDb + nTab;
203666    pRet = sqlite3Fts5MallocZero(&rc, nByte);
203667    if( pRet ){
203668      pRet->pGlobal = (Fts5Global*)pAux;
203669      pRet->eType = eType;
203670      pRet->db = db;
203671      pRet->zFts5Tbl = (char*)&pRet[1];
203672      pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
203673      memcpy(pRet->zFts5Tbl, zTab, nTab);
203674      memcpy(pRet->zFts5Db, zDb, nDb);
203675      sqlite3Fts5Dequote(pRet->zFts5Tbl);
203676      sqlite3Fts5Dequote(pRet->zFts5Db);
203677    }
203678  }
203679
203680  *ppVTab = (sqlite3_vtab*)pRet;
203681  return rc;
203682}
203683
203684
203685/*
203686** The xConnect() and xCreate() methods for the virtual table. All the
203687** work is done in function fts5VocabInitVtab().
203688*/
203689static int fts5VocabConnectMethod(
203690  sqlite3 *db,                    /* Database connection */
203691  void *pAux,                     /* Pointer to tokenizer hash table */
203692  int argc,                       /* Number of elements in argv array */
203693  const char * const *argv,       /* xCreate/xConnect argument array */
203694  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
203695  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
203696){
203697  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
203698}
203699static int fts5VocabCreateMethod(
203700  sqlite3 *db,                    /* Database connection */
203701  void *pAux,                     /* Pointer to tokenizer hash table */
203702  int argc,                       /* Number of elements in argv array */
203703  const char * const *argv,       /* xCreate/xConnect argument array */
203704  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
203705  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
203706){
203707  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
203708}
203709
203710/*
203711** Implementation of the xBestIndex method.
203712*/
203713static int fts5VocabBestIndexMethod(
203714  sqlite3_vtab *pUnused,
203715  sqlite3_index_info *pInfo
203716){
203717  int i;
203718  int iTermEq = -1;
203719  int iTermGe = -1;
203720  int iTermLe = -1;
203721  int idxNum = 0;
203722  int nArg = 0;
203723
203724  UNUSED_PARAM(pUnused);
203725
203726  for(i=0; i<pInfo->nConstraint; i++){
203727    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
203728    if( p->usable==0 ) continue;
203729    if( p->iColumn==0 ){          /* term column */
203730      if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
203731      if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
203732      if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
203733      if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
203734      if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
203735    }
203736  }
203737
203738  if( iTermEq>=0 ){
203739    idxNum |= FTS5_VOCAB_TERM_EQ;
203740    pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
203741    pInfo->estimatedCost = 100;
203742  }else{
203743    pInfo->estimatedCost = 1000000;
203744    if( iTermGe>=0 ){
203745      idxNum |= FTS5_VOCAB_TERM_GE;
203746      pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
203747      pInfo->estimatedCost = pInfo->estimatedCost / 2;
203748    }
203749    if( iTermLe>=0 ){
203750      idxNum |= FTS5_VOCAB_TERM_LE;
203751      pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
203752      pInfo->estimatedCost = pInfo->estimatedCost / 2;
203753    }
203754  }
203755
203756  /* This virtual table always delivers results in ascending order of
203757  ** the "term" column (column 0). So if the user has requested this
203758  ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
203759  ** sqlite3_index_info.orderByConsumed flag to tell the core the results
203760  ** are already in sorted order.  */
203761  if( pInfo->nOrderBy==1
203762   && pInfo->aOrderBy[0].iColumn==0
203763   && pInfo->aOrderBy[0].desc==0
203764  ){
203765    pInfo->orderByConsumed = 1;
203766  }
203767
203768  pInfo->idxNum = idxNum;
203769  return SQLITE_OK;
203770}
203771
203772/*
203773** Implementation of xOpen method.
203774*/
203775static int fts5VocabOpenMethod(
203776  sqlite3_vtab *pVTab,
203777  sqlite3_vtab_cursor **ppCsr
203778){
203779  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
203780  Fts5Index *pIndex = 0;
203781  Fts5Config *pConfig = 0;
203782  Fts5VocabCursor *pCsr = 0;
203783  int rc = SQLITE_OK;
203784  sqlite3_stmt *pStmt = 0;
203785  char *zSql = 0;
203786
203787  zSql = sqlite3Fts5Mprintf(&rc,
203788      "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
203789      pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
203790  );
203791  if( zSql ){
203792    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
203793  }
203794  sqlite3_free(zSql);
203795  assert( rc==SQLITE_OK || pStmt==0 );
203796  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
203797
203798  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
203799    i64 iId = sqlite3_column_int64(pStmt, 0);
203800    pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
203801  }
203802
203803  if( rc==SQLITE_OK && pIndex==0 ){
203804    rc = sqlite3_finalize(pStmt);
203805    pStmt = 0;
203806    if( rc==SQLITE_OK ){
203807      pVTab->zErrMsg = sqlite3_mprintf(
203808          "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
203809      );
203810      rc = SQLITE_ERROR;
203811    }
203812  }
203813
203814  if( rc==SQLITE_OK ){
203815    int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
203816    pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
203817  }
203818
203819  if( pCsr ){
203820    pCsr->pIndex = pIndex;
203821    pCsr->pStmt = pStmt;
203822    pCsr->pConfig = pConfig;
203823    pCsr->aCnt = (i64*)&pCsr[1];
203824    pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
203825  }else{
203826    sqlite3_finalize(pStmt);
203827  }
203828
203829  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
203830  return rc;
203831}
203832
203833static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
203834  pCsr->rowid = 0;
203835  sqlite3Fts5IterClose(pCsr->pIter);
203836  pCsr->pIter = 0;
203837  sqlite3_free(pCsr->zLeTerm);
203838  pCsr->nLeTerm = -1;
203839  pCsr->zLeTerm = 0;
203840}
203841
203842/*
203843** Close the cursor.  For additional information see the documentation
203844** on the xClose method of the virtual table interface.
203845*/
203846static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
203847  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
203848  fts5VocabResetCursor(pCsr);
203849  sqlite3Fts5BufferFree(&pCsr->term);
203850  sqlite3_finalize(pCsr->pStmt);
203851  sqlite3_free(pCsr);
203852  return SQLITE_OK;
203853}
203854
203855
203856/*
203857** Advance the cursor to the next row in the table.
203858*/
203859static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
203860  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
203861  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
203862  int rc = SQLITE_OK;
203863  int nCol = pCsr->pConfig->nCol;
203864
203865  pCsr->rowid++;
203866
203867  if( pTab->eType==FTS5_VOCAB_COL ){
203868    for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
203869      if( pCsr->aDoc[pCsr->iCol] ) break;
203870    }
203871  }
203872
203873  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
203874    if( sqlite3Fts5IterEof(pCsr->pIter) ){
203875      pCsr->bEof = 1;
203876    }else{
203877      const char *zTerm;
203878      int nTerm;
203879
203880      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
203881      if( pCsr->nLeTerm>=0 ){
203882        int nCmp = MIN(nTerm, pCsr->nLeTerm);
203883        int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
203884        if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
203885          pCsr->bEof = 1;
203886          return SQLITE_OK;
203887        }
203888      }
203889
203890      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
203891      memset(pCsr->aCnt, 0, nCol * sizeof(i64));
203892      memset(pCsr->aDoc, 0, nCol * sizeof(i64));
203893      pCsr->iCol = 0;
203894
203895      assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
203896      while( rc==SQLITE_OK ){
203897        const u8 *pPos; int nPos;   /* Position list */
203898        i64 iPos = 0;               /* 64-bit position read from poslist */
203899        int iOff = 0;               /* Current offset within position list */
203900
203901        pPos = pCsr->pIter->pData;
203902        nPos = pCsr->pIter->nData;
203903        switch( pCsr->pConfig->eDetail ){
203904          case FTS5_DETAIL_FULL:
203905            pPos = pCsr->pIter->pData;
203906            nPos = pCsr->pIter->nData;
203907            if( pTab->eType==FTS5_VOCAB_ROW ){
203908              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
203909                pCsr->aCnt[0]++;
203910              }
203911              pCsr->aDoc[0]++;
203912            }else{
203913              int iCol = -1;
203914              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
203915                int ii = FTS5_POS2COLUMN(iPos);
203916                pCsr->aCnt[ii]++;
203917                if( iCol!=ii ){
203918                  if( ii>=nCol ){
203919                    rc = FTS5_CORRUPT;
203920                    break;
203921                  }
203922                  pCsr->aDoc[ii]++;
203923                  iCol = ii;
203924                }
203925              }
203926            }
203927            break;
203928
203929          case FTS5_DETAIL_COLUMNS:
203930            if( pTab->eType==FTS5_VOCAB_ROW ){
203931              pCsr->aDoc[0]++;
203932            }else{
203933              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
203934                assert_nc( iPos>=0 && iPos<nCol );
203935                if( iPos>=nCol ){
203936                  rc = FTS5_CORRUPT;
203937                  break;
203938                }
203939                pCsr->aDoc[iPos]++;
203940              }
203941            }
203942            break;
203943
203944          default:
203945            assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
203946            pCsr->aDoc[0]++;
203947            break;
203948        }
203949
203950        if( rc==SQLITE_OK ){
203951          rc = sqlite3Fts5IterNextScan(pCsr->pIter);
203952        }
203953
203954        if( rc==SQLITE_OK ){
203955          zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
203956          if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
203957            break;
203958          }
203959          if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
203960        }
203961      }
203962    }
203963  }
203964
203965  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
203966    while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
203967    assert( pCsr->iCol<pCsr->pConfig->nCol );
203968  }
203969  return rc;
203970}
203971
203972/*
203973** This is the xFilter implementation for the virtual table.
203974*/
203975static int fts5VocabFilterMethod(
203976  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
203977  int idxNum,                     /* Strategy index */
203978  const char *zUnused,            /* Unused */
203979  int nUnused,                    /* Number of elements in apVal */
203980  sqlite3_value **apVal           /* Arguments for the indexing scheme */
203981){
203982  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
203983  int rc = SQLITE_OK;
203984
203985  int iVal = 0;
203986  int f = FTS5INDEX_QUERY_SCAN;
203987  const char *zTerm = 0;
203988  int nTerm = 0;
203989
203990  sqlite3_value *pEq = 0;
203991  sqlite3_value *pGe = 0;
203992  sqlite3_value *pLe = 0;
203993
203994  UNUSED_PARAM2(zUnused, nUnused);
203995
203996  fts5VocabResetCursor(pCsr);
203997  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
203998  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
203999  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
204000
204001  if( pEq ){
204002    zTerm = (const char *)sqlite3_value_text(pEq);
204003    nTerm = sqlite3_value_bytes(pEq);
204004    f = 0;
204005  }else{
204006    if( pGe ){
204007      zTerm = (const char *)sqlite3_value_text(pGe);
204008      nTerm = sqlite3_value_bytes(pGe);
204009    }
204010    if( pLe ){
204011      const char *zCopy = (const char *)sqlite3_value_text(pLe);
204012      pCsr->nLeTerm = sqlite3_value_bytes(pLe);
204013      pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
204014      if( pCsr->zLeTerm==0 ){
204015        rc = SQLITE_NOMEM;
204016      }else{
204017        memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
204018      }
204019    }
204020  }
204021
204022
204023  if( rc==SQLITE_OK ){
204024    rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
204025  }
204026  if( rc==SQLITE_OK ){
204027    rc = fts5VocabNextMethod(pCursor);
204028  }
204029
204030  return rc;
204031}
204032
204033/*
204034** This is the xEof method of the virtual table. SQLite calls this
204035** routine to find out if it has reached the end of a result set.
204036*/
204037static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
204038  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204039  return pCsr->bEof;
204040}
204041
204042static int fts5VocabColumnMethod(
204043  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
204044  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
204045  int iCol                        /* Index of column to read value from */
204046){
204047  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204048  int eDetail = pCsr->pConfig->eDetail;
204049  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
204050  i64 iVal = 0;
204051
204052  if( iCol==0 ){
204053    sqlite3_result_text(
204054        pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
204055    );
204056  }else if( eType==FTS5_VOCAB_COL ){
204057    assert( iCol==1 || iCol==2 || iCol==3 );
204058    if( iCol==1 ){
204059      if( eDetail!=FTS5_DETAIL_NONE ){
204060        const char *z = pCsr->pConfig->azCol[pCsr->iCol];
204061        sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
204062      }
204063    }else if( iCol==2 ){
204064      iVal = pCsr->aDoc[pCsr->iCol];
204065    }else{
204066      iVal = pCsr->aCnt[pCsr->iCol];
204067    }
204068  }else{
204069    assert( iCol==1 || iCol==2 );
204070    if( iCol==1 ){
204071      iVal = pCsr->aDoc[0];
204072    }else{
204073      iVal = pCsr->aCnt[0];
204074    }
204075  }
204076
204077  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
204078  return SQLITE_OK;
204079}
204080
204081/*
204082** This is the xRowid method. The SQLite core calls this routine to
204083** retrieve the rowid for the current row of the result set. The
204084** rowid should be written to *pRowid.
204085*/
204086static int fts5VocabRowidMethod(
204087  sqlite3_vtab_cursor *pCursor,
204088  sqlite_int64 *pRowid
204089){
204090  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
204091  *pRowid = pCsr->rowid;
204092  return SQLITE_OK;
204093}
204094
204095static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
204096  static const sqlite3_module fts5Vocab = {
204097    /* iVersion      */ 2,
204098    /* xCreate       */ fts5VocabCreateMethod,
204099    /* xConnect      */ fts5VocabConnectMethod,
204100    /* xBestIndex    */ fts5VocabBestIndexMethod,
204101    /* xDisconnect   */ fts5VocabDisconnectMethod,
204102    /* xDestroy      */ fts5VocabDestroyMethod,
204103    /* xOpen         */ fts5VocabOpenMethod,
204104    /* xClose        */ fts5VocabCloseMethod,
204105    /* xFilter       */ fts5VocabFilterMethod,
204106    /* xNext         */ fts5VocabNextMethod,
204107    /* xEof          */ fts5VocabEofMethod,
204108    /* xColumn       */ fts5VocabColumnMethod,
204109    /* xRowid        */ fts5VocabRowidMethod,
204110    /* xUpdate       */ 0,
204111    /* xBegin        */ 0,
204112    /* xSync         */ 0,
204113    /* xCommit       */ 0,
204114    /* xRollback     */ 0,
204115    /* xFindFunction */ 0,
204116    /* xRename       */ 0,
204117    /* xSavepoint    */ 0,
204118    /* xRelease      */ 0,
204119    /* xRollbackTo   */ 0,
204120  };
204121  void *p = (void*)pGlobal;
204122
204123  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
204124}
204125
204126
204127
204128
204129
204130#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
204131
204132/************** End of fts5.c ************************************************/
204133/************** Begin file stmt.c ********************************************/
204134/*
204135** 2017-05-31
204136**
204137** The author disclaims copyright to this source code.  In place of
204138** a legal notice, here is a blessing:
204139**
204140**    May you do good and not evil.
204141**    May you find forgiveness for yourself and forgive others.
204142**    May you share freely, never taking more than you give.
204143**
204144*************************************************************************
204145**
204146** This file demonstrates an eponymous virtual table that returns information
204147** about all prepared statements for the database connection.
204148**
204149** Usage example:
204150**
204151**     .load ./stmt
204152**     .mode line
204153**     .header on
204154**     SELECT * FROM stmt;
204155*/
204156#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
204157#if !defined(SQLITEINT_H)
204158/* #include "sqlite3ext.h" */
204159#endif
204160SQLITE_EXTENSION_INIT1
204161/* #include <assert.h> */
204162/* #include <string.h> */
204163
204164#ifndef SQLITE_OMIT_VIRTUALTABLE
204165
204166/* stmt_vtab is a subclass of sqlite3_vtab which will
204167** serve as the underlying representation of a stmt virtual table
204168*/
204169typedef struct stmt_vtab stmt_vtab;
204170struct stmt_vtab {
204171  sqlite3_vtab base;  /* Base class - must be first */
204172  sqlite3 *db;        /* Database connection for this stmt vtab */
204173};
204174
204175/* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
204176** serve as the underlying representation of a cursor that scans
204177** over rows of the result
204178*/
204179typedef struct stmt_cursor stmt_cursor;
204180struct stmt_cursor {
204181  sqlite3_vtab_cursor base;  /* Base class - must be first */
204182  sqlite3 *db;               /* Database connection for this cursor */
204183  sqlite3_stmt *pStmt;       /* Statement cursor is currently pointing at */
204184  sqlite3_int64 iRowid;      /* The rowid */
204185};
204186
204187/*
204188** The stmtConnect() method is invoked to create a new
204189** stmt_vtab that describes the stmt virtual table.
204190**
204191** Think of this routine as the constructor for stmt_vtab objects.
204192**
204193** All this routine needs to do is:
204194**
204195**    (1) Allocate the stmt_vtab object and initialize all fields.
204196**
204197**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
204198**        result set of queries against stmt will look like.
204199*/
204200static int stmtConnect(
204201  sqlite3 *db,
204202  void *pAux,
204203  int argc, const char *const*argv,
204204  sqlite3_vtab **ppVtab,
204205  char **pzErr
204206){
204207  stmt_vtab *pNew;
204208  int rc;
204209
204210/* Column numbers */
204211#define STMT_COLUMN_SQL     0   /* SQL for the statement */
204212#define STMT_COLUMN_NCOL    1   /* Number of result columns */
204213#define STMT_COLUMN_RO      2   /* True if read-only */
204214#define STMT_COLUMN_BUSY    3   /* True if currently busy */
204215#define STMT_COLUMN_NSCAN   4   /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
204216#define STMT_COLUMN_NSORT   5   /* SQLITE_STMTSTATUS_SORT */
204217#define STMT_COLUMN_NAIDX   6   /* SQLITE_STMTSTATUS_AUTOINDEX */
204218#define STMT_COLUMN_NSTEP   7   /* SQLITE_STMTSTATUS_VM_STEP */
204219#define STMT_COLUMN_REPREP  8   /* SQLITE_STMTSTATUS_REPREPARE */
204220#define STMT_COLUMN_RUN     9   /* SQLITE_STMTSTATUS_RUN */
204221#define STMT_COLUMN_MEM    10   /* SQLITE_STMTSTATUS_MEMUSED */
204222
204223
204224  rc = sqlite3_declare_vtab(db,
204225     "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
204226                    "reprep,run,mem)");
204227  if( rc==SQLITE_OK ){
204228    pNew = sqlite3_malloc( sizeof(*pNew) );
204229    *ppVtab = (sqlite3_vtab*)pNew;
204230    if( pNew==0 ) return SQLITE_NOMEM;
204231    memset(pNew, 0, sizeof(*pNew));
204232    pNew->db = db;
204233  }
204234  return rc;
204235}
204236
204237/*
204238** This method is the destructor for stmt_cursor objects.
204239*/
204240static int stmtDisconnect(sqlite3_vtab *pVtab){
204241  sqlite3_free(pVtab);
204242  return SQLITE_OK;
204243}
204244
204245/*
204246** Constructor for a new stmt_cursor object.
204247*/
204248static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
204249  stmt_cursor *pCur;
204250  pCur = sqlite3_malloc( sizeof(*pCur) );
204251  if( pCur==0 ) return SQLITE_NOMEM;
204252  memset(pCur, 0, sizeof(*pCur));
204253  pCur->db = ((stmt_vtab*)p)->db;
204254  *ppCursor = &pCur->base;
204255  return SQLITE_OK;
204256}
204257
204258/*
204259** Destructor for a stmt_cursor.
204260*/
204261static int stmtClose(sqlite3_vtab_cursor *cur){
204262  sqlite3_free(cur);
204263  return SQLITE_OK;
204264}
204265
204266
204267/*
204268** Advance a stmt_cursor to its next row of output.
204269*/
204270static int stmtNext(sqlite3_vtab_cursor *cur){
204271  stmt_cursor *pCur = (stmt_cursor*)cur;
204272  pCur->iRowid++;
204273  pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
204274  return SQLITE_OK;
204275}
204276
204277/*
204278** Return values of columns for the row at which the stmt_cursor
204279** is currently pointing.
204280*/
204281static int stmtColumn(
204282  sqlite3_vtab_cursor *cur,   /* The cursor */
204283  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
204284  int i                       /* Which column to return */
204285){
204286  stmt_cursor *pCur = (stmt_cursor*)cur;
204287  switch( i ){
204288    case STMT_COLUMN_SQL: {
204289      sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
204290      break;
204291    }
204292    case STMT_COLUMN_NCOL: {
204293      sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
204294      break;
204295    }
204296    case STMT_COLUMN_RO: {
204297      sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
204298      break;
204299    }
204300    case STMT_COLUMN_BUSY: {
204301      sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
204302      break;
204303    }
204304    case STMT_COLUMN_MEM: {
204305      i = SQLITE_STMTSTATUS_MEMUSED +
204306            STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
204307      /* Fall thru */
204308    }
204309    case STMT_COLUMN_NSCAN:
204310    case STMT_COLUMN_NSORT:
204311    case STMT_COLUMN_NAIDX:
204312    case STMT_COLUMN_NSTEP:
204313    case STMT_COLUMN_REPREP:
204314    case STMT_COLUMN_RUN: {
204315      sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
204316                      i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
204317      break;
204318    }
204319  }
204320  return SQLITE_OK;
204321}
204322
204323/*
204324** Return the rowid for the current row.  In this implementation, the
204325** rowid is the same as the output value.
204326*/
204327static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
204328  stmt_cursor *pCur = (stmt_cursor*)cur;
204329  *pRowid = pCur->iRowid;
204330  return SQLITE_OK;
204331}
204332
204333/*
204334** Return TRUE if the cursor has been moved off of the last
204335** row of output.
204336*/
204337static int stmtEof(sqlite3_vtab_cursor *cur){
204338  stmt_cursor *pCur = (stmt_cursor*)cur;
204339  return pCur->pStmt==0;
204340}
204341
204342/*
204343** This method is called to "rewind" the stmt_cursor object back
204344** to the first row of output.  This method is always called at least
204345** once prior to any call to stmtColumn() or stmtRowid() or
204346** stmtEof().
204347*/
204348static int stmtFilter(
204349  sqlite3_vtab_cursor *pVtabCursor,
204350  int idxNum, const char *idxStr,
204351  int argc, sqlite3_value **argv
204352){
204353  stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
204354  pCur->pStmt = 0;
204355  pCur->iRowid = 0;
204356  return stmtNext(pVtabCursor);
204357}
204358
204359/*
204360** SQLite will invoke this method one or more times while planning a query
204361** that uses the stmt virtual table.  This routine needs to create
204362** a query plan for each invocation and compute an estimated cost for that
204363** plan.
204364*/
204365static int stmtBestIndex(
204366  sqlite3_vtab *tab,
204367  sqlite3_index_info *pIdxInfo
204368){
204369  pIdxInfo->estimatedCost = (double)500;
204370  pIdxInfo->estimatedRows = 500;
204371  return SQLITE_OK;
204372}
204373
204374/*
204375** This following structure defines all the methods for the
204376** stmt virtual table.
204377*/
204378static sqlite3_module stmtModule = {
204379  0,                         /* iVersion */
204380  0,                         /* xCreate */
204381  stmtConnect,               /* xConnect */
204382  stmtBestIndex,             /* xBestIndex */
204383  stmtDisconnect,            /* xDisconnect */
204384  0,                         /* xDestroy */
204385  stmtOpen,                  /* xOpen - open a cursor */
204386  stmtClose,                 /* xClose - close a cursor */
204387  stmtFilter,                /* xFilter - configure scan constraints */
204388  stmtNext,                  /* xNext - advance a cursor */
204389  stmtEof,                   /* xEof - check for end of scan */
204390  stmtColumn,                /* xColumn - read data */
204391  stmtRowid,                 /* xRowid - read data */
204392  0,                         /* xUpdate */
204393  0,                         /* xBegin */
204394  0,                         /* xSync */
204395  0,                         /* xCommit */
204396  0,                         /* xRollback */
204397  0,                         /* xFindMethod */
204398  0,                         /* xRename */
204399  0,                         /* xSavepoint */
204400  0,                         /* xRelease */
204401  0,                         /* xRollbackTo */
204402};
204403
204404#endif /* SQLITE_OMIT_VIRTUALTABLE */
204405
204406SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
204407  int rc = SQLITE_OK;
204408#ifndef SQLITE_OMIT_VIRTUALTABLE
204409  rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
204410#endif
204411  return rc;
204412}
204413
204414#ifndef SQLITE_CORE
204415#ifdef _WIN32
204416__declspec(dllexport)
204417#endif
204418SQLITE_API int sqlite3_stmt_init(
204419  sqlite3 *db,
204420  char **pzErrMsg,
204421  const sqlite3_api_routines *pApi
204422){
204423  int rc = SQLITE_OK;
204424  SQLITE_EXTENSION_INIT2(pApi);
204425#ifndef SQLITE_OMIT_VIRTUALTABLE
204426  rc = sqlite3StmtVtabInit(db);
204427#endif
204428  return rc;
204429}
204430#endif /* SQLITE_CORE */
204431#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
204432
204433/************** End of stmt.c ************************************************/
204434